(() => {
  var __defProp = Object.defineProperty;
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __esm = (fn2, res) => function __init() {
    return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 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 });
  };

  // node_modules/mithril/render/vnode.js
  var require_vnode = __commonJS({
    "node_modules/mithril/render/vnode.js"(exports, module) {
      "use strict";
      function Vnode(tag, key, attrs, children, text, dom) {
        return { tag, key, attrs, children, text, dom, domSize: void 0, state: void 0, events: void 0, instance: void 0 };
      }
      Vnode.normalize = function(node) {
        if (Array.isArray(node))
          return Vnode("[", void 0, void 0, Vnode.normalizeChildren(node), void 0, void 0);
        if (node == null || typeof node === "boolean")
          return null;
        if (typeof node === "object")
          return node;
        return Vnode("#", void 0, void 0, String(node), void 0, void 0);
      };
      Vnode.normalizeChildren = function(input) {
        var children = [];
        if (input.length) {
          var isKeyed = input[0] != null && input[0].key != null;
          for (var i = 1; i < input.length; i++) {
            if ((input[i] != null && input[i].key != null) !== isKeyed) {
              throw new TypeError(
                isKeyed && (input[i] != null || typeof input[i] === "boolean") ? "In fragments, vnodes must either all have keys or none have keys. You may wish to consider using an explicit keyed empty fragment, m.fragment({key: ...}), instead of a hole." : "In fragments, vnodes must either all have keys or none have keys."
              );
            }
          }
          for (var i = 0; i < input.length; i++) {
            children[i] = Vnode.normalize(input[i]);
          }
        }
        return children;
      };
      module.exports = Vnode;
    }
  });

  // node_modules/mithril/render/hyperscriptVnode.js
  var require_hyperscriptVnode = __commonJS({
    "node_modules/mithril/render/hyperscriptVnode.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      module.exports = function() {
        var attrs = arguments[this], start2 = this + 1, children;
        if (attrs == null) {
          attrs = {};
        } else if (typeof attrs !== "object" || attrs.tag != null || Array.isArray(attrs)) {
          attrs = {};
          start2 = this;
        }
        if (arguments.length === start2 + 1) {
          children = arguments[start2];
          if (!Array.isArray(children))
            children = [children];
        } else {
          children = [];
          while (start2 < arguments.length)
            children.push(arguments[start2++]);
        }
        return Vnode("", attrs.key, attrs, children);
      };
    }
  });

  // node_modules/mithril/util/hasOwn.js
  var require_hasOwn = __commonJS({
    "node_modules/mithril/util/hasOwn.js"(exports, module) {
      "use strict";
      module.exports = {}.hasOwnProperty;
    }
  });

  // node_modules/mithril/render/hyperscript.js
  var require_hyperscript = __commonJS({
    "node_modules/mithril/render/hyperscript.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      var hyperscriptVnode = require_hyperscriptVnode();
      var hasOwn = require_hasOwn();
      var selectorParser = /(?:(^|#|\.)([^#\.\[\]]+))|(\[(.+?)(?:\s*=\s*("|'|)((?:\\["'\]]|.)*?)\5)?\])/g;
      var selectorCache = {};
      function isEmpty(object) {
        for (var key in object)
          if (hasOwn.call(object, key))
            return false;
        return true;
      }
      function compileSelector(selector) {
        var match, tag = "div", classes = [], attrs = {};
        while (match = selectorParser.exec(selector)) {
          var type = match[1], value = match[2];
          if (type === "" && value !== "")
            tag = value;
          else if (type === "#")
            attrs.id = value;
          else if (type === ".")
            classes.push(value);
          else if (match[3][0] === "[") {
            var attrValue = match[6];
            if (attrValue)
              attrValue = attrValue.replace(/\\(["'])/g, "$1").replace(/\\\\/g, "\\");
            if (match[4] === "class")
              classes.push(attrValue);
            else
              attrs[match[4]] = attrValue === "" ? attrValue : attrValue || true;
          }
        }
        if (classes.length > 0)
          attrs.className = classes.join(" ");
        return selectorCache[selector] = { tag, attrs };
      }
      function execSelector(state, vnode) {
        var attrs = vnode.attrs;
        var hasClass = hasOwn.call(attrs, "class");
        var className = hasClass ? attrs.class : attrs.className;
        vnode.tag = state.tag;
        vnode.attrs = {};
        if (!isEmpty(state.attrs) && !isEmpty(attrs)) {
          var newAttrs = {};
          for (var key in attrs) {
            if (hasOwn.call(attrs, key))
              newAttrs[key] = attrs[key];
          }
          attrs = newAttrs;
        }
        for (var key in state.attrs) {
          if (hasOwn.call(state.attrs, key) && key !== "className" && !hasOwn.call(attrs, key)) {
            attrs[key] = state.attrs[key];
          }
        }
        if (className != null || state.attrs.className != null)
          attrs.className = className != null ? state.attrs.className != null ? String(state.attrs.className) + " " + String(className) : className : state.attrs.className != null ? state.attrs.className : null;
        if (hasClass)
          attrs.class = null;
        for (var key in attrs) {
          if (hasOwn.call(attrs, key) && key !== "key") {
            vnode.attrs = attrs;
            break;
          }
        }
        return vnode;
      }
      function hyperscript(selector) {
        if (selector == null || typeof selector !== "string" && typeof selector !== "function" && typeof selector.view !== "function") {
          throw Error("The selector must be either a string or a component.");
        }
        var vnode = hyperscriptVnode.apply(1, arguments);
        if (typeof selector === "string") {
          vnode.children = Vnode.normalizeChildren(vnode.children);
          if (selector !== "[")
            return execSelector(selectorCache[selector] || compileSelector(selector), vnode);
        }
        vnode.tag = selector;
        return vnode;
      }
      module.exports = hyperscript;
    }
  });

  // node_modules/mithril/render/trust.js
  var require_trust = __commonJS({
    "node_modules/mithril/render/trust.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      module.exports = function(html) {
        if (html == null)
          html = "";
        return Vnode("<", void 0, void 0, html, void 0, void 0);
      };
    }
  });

  // node_modules/mithril/render/fragment.js
  var require_fragment = __commonJS({
    "node_modules/mithril/render/fragment.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      var hyperscriptVnode = require_hyperscriptVnode();
      module.exports = function() {
        var vnode = hyperscriptVnode.apply(0, arguments);
        vnode.tag = "[";
        vnode.children = Vnode.normalizeChildren(vnode.children);
        return vnode;
      };
    }
  });

  // node_modules/mithril/hyperscript.js
  var require_hyperscript2 = __commonJS({
    "node_modules/mithril/hyperscript.js"(exports, module) {
      "use strict";
      var hyperscript = require_hyperscript();
      hyperscript.trust = require_trust();
      hyperscript.fragment = require_fragment();
      module.exports = hyperscript;
    }
  });

  // node_modules/mithril/promise/polyfill.js
  var require_polyfill = __commonJS({
    "node_modules/mithril/promise/polyfill.js"(exports, module) {
      "use strict";
      var PromisePolyfill = function(executor) {
        if (!(this instanceof PromisePolyfill))
          throw new Error("Promise must be called with 'new'.");
        if (typeof executor !== "function")
          throw new TypeError("executor must be a function.");
        var self2 = this, resolvers = [], rejectors = [], resolveCurrent = handler(resolvers, true), rejectCurrent = handler(rejectors, false);
        var instance = self2._instance = { resolvers, rejectors };
        var callAsync = typeof setImmediate === "function" ? setImmediate : setTimeout;
        function handler(list, shouldAbsorb) {
          return function execute(value) {
            var then;
            try {
              if (shouldAbsorb && value != null && (typeof value === "object" || typeof value === "function") && typeof (then = value.then) === "function") {
                if (value === self2)
                  throw new TypeError("Promise can't be resolved with itself.");
                executeOnce(then.bind(value));
              } else {
                callAsync(function() {
                  if (!shouldAbsorb && list.length === 0)
                    console.error("Possible unhandled promise rejection:", value);
                  for (var i = 0; i < list.length; i++)
                    list[i](value);
                  resolvers.length = 0, rejectors.length = 0;
                  instance.state = shouldAbsorb;
                  instance.retry = function() {
                    execute(value);
                  };
                });
              }
            } catch (e) {
              rejectCurrent(e);
            }
          };
        }
        function executeOnce(then) {
          var runs = 0;
          function run(fn2) {
            return function(value) {
              if (runs++ > 0)
                return;
              fn2(value);
            };
          }
          var onerror = run(rejectCurrent);
          try {
            then(run(resolveCurrent), onerror);
          } catch (e) {
            onerror(e);
          }
        }
        executeOnce(executor);
      };
      PromisePolyfill.prototype.then = function(onFulfilled, onRejection) {
        var self2 = this, instance = self2._instance;
        function handle(callback, list, next, state) {
          list.push(function(value) {
            if (typeof callback !== "function")
              next(value);
            else
              try {
                resolveNext(callback(value));
              } catch (e) {
                if (rejectNext)
                  rejectNext(e);
              }
          });
          if (typeof instance.retry === "function" && state === instance.state)
            instance.retry();
        }
        var resolveNext, rejectNext;
        var promise = new PromisePolyfill(function(resolve, reject) {
          resolveNext = resolve, rejectNext = reject;
        });
        handle(onFulfilled, instance.resolvers, resolveNext, true), handle(onRejection, instance.rejectors, rejectNext, false);
        return promise;
      };
      PromisePolyfill.prototype.catch = function(onRejection) {
        return this.then(null, onRejection);
      };
      PromisePolyfill.prototype.finally = function(callback) {
        return this.then(
          function(value) {
            return PromisePolyfill.resolve(callback()).then(function() {
              return value;
            });
          },
          function(reason) {
            return PromisePolyfill.resolve(callback()).then(function() {
              return PromisePolyfill.reject(reason);
            });
          }
        );
      };
      PromisePolyfill.resolve = function(value) {
        if (value instanceof PromisePolyfill)
          return value;
        return new PromisePolyfill(function(resolve) {
          resolve(value);
        });
      };
      PromisePolyfill.reject = function(value) {
        return new PromisePolyfill(function(resolve, reject) {
          reject(value);
        });
      };
      PromisePolyfill.all = function(list) {
        return new PromisePolyfill(function(resolve, reject) {
          var total = list.length, count = 0, values = [];
          if (list.length === 0)
            resolve([]);
          else
            for (var i = 0; i < list.length; i++) {
              (function(i2) {
                function consume(value) {
                  count++;
                  values[i2] = value;
                  if (count === total)
                    resolve(values);
                }
                if (list[i2] != null && (typeof list[i2] === "object" || typeof list[i2] === "function") && typeof list[i2].then === "function") {
                  list[i2].then(consume, reject);
                } else
                  consume(list[i2]);
              })(i);
            }
        });
      };
      PromisePolyfill.race = function(list) {
        return new PromisePolyfill(function(resolve, reject) {
          for (var i = 0; i < list.length; i++) {
            list[i].then(resolve, reject);
          }
        });
      };
      module.exports = PromisePolyfill;
    }
  });

  // node_modules/mithril/promise/promise.js
  var require_promise = __commonJS({
    "node_modules/mithril/promise/promise.js"(exports, module) {
      "use strict";
      var PromisePolyfill = require_polyfill();
      if (typeof window !== "undefined") {
        if (typeof window.Promise === "undefined") {
          window.Promise = PromisePolyfill;
        } else if (!window.Promise.prototype.finally) {
          window.Promise.prototype.finally = PromisePolyfill.prototype.finally;
        }
        module.exports = window.Promise;
      } else if (typeof global !== "undefined") {
        if (typeof global.Promise === "undefined") {
          global.Promise = PromisePolyfill;
        } else if (!global.Promise.prototype.finally) {
          global.Promise.prototype.finally = PromisePolyfill.prototype.finally;
        }
        module.exports = global.Promise;
      } else {
        module.exports = PromisePolyfill;
      }
    }
  });

  // node_modules/mithril/render/render.js
  var require_render = __commonJS({
    "node_modules/mithril/render/render.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      module.exports = function($window) {
        var $doc = $window && $window.document;
        var currentRedraw;
        var nameSpace = {
          svg: "http://www.w3.org/2000/svg",
          math: "http://www.w3.org/1998/Math/MathML"
        };
        function getNameSpace(vnode) {
          return vnode.attrs && vnode.attrs.xmlns || nameSpace[vnode.tag];
        }
        function checkState(vnode, original) {
          if (vnode.state !== original)
            throw new Error("'vnode.state' must not be modified.");
        }
        function callHook(vnode) {
          var original = vnode.state;
          try {
            return this.apply(original, arguments);
          } finally {
            checkState(vnode, original);
          }
        }
        function activeElement() {
          try {
            return $doc.activeElement;
          } catch (e) {
            return null;
          }
        }
        function createNodes(parent, vnodes, start2, end2, hooks, nextSibling, ns) {
          for (var i = start2; i < end2; i++) {
            var vnode = vnodes[i];
            if (vnode != null) {
              createNode(parent, vnode, hooks, ns, nextSibling);
            }
          }
        }
        function createNode(parent, vnode, hooks, ns, nextSibling) {
          var tag = vnode.tag;
          if (typeof tag === "string") {
            vnode.state = {};
            if (vnode.attrs != null)
              initLifecycle(vnode.attrs, vnode, hooks);
            switch (tag) {
              case "#":
                createText(parent, vnode, nextSibling);
                break;
              case "<":
                createHTML(parent, vnode, ns, nextSibling);
                break;
              case "[":
                createFragment(parent, vnode, hooks, ns, nextSibling);
                break;
              default:
                createElement(parent, vnode, hooks, ns, nextSibling);
            }
          } else
            createComponent(parent, vnode, hooks, ns, nextSibling);
        }
        function createText(parent, vnode, nextSibling) {
          vnode.dom = $doc.createTextNode(vnode.children);
          insertNode(parent, vnode.dom, nextSibling);
        }
        var possibleParents = { caption: "table", thead: "table", tbody: "table", tfoot: "table", tr: "tbody", th: "tr", td: "tr", colgroup: "table", col: "colgroup" };
        function createHTML(parent, vnode, ns, nextSibling) {
          var match = vnode.children.match(/^\s*?<(\w+)/im) || [];
          var temp = $doc.createElement(possibleParents[match[1]] || "div");
          if (ns === "http://www.w3.org/2000/svg") {
            temp.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg">' + vnode.children + "</svg>";
            temp = temp.firstChild;
          } else {
            temp.innerHTML = vnode.children;
          }
          vnode.dom = temp.firstChild;
          vnode.domSize = temp.childNodes.length;
          vnode.instance = [];
          var fragment = $doc.createDocumentFragment();
          var child;
          while (child = temp.firstChild) {
            vnode.instance.push(child);
            fragment.appendChild(child);
          }
          insertNode(parent, fragment, nextSibling);
        }
        function createFragment(parent, vnode, hooks, ns, nextSibling) {
          var fragment = $doc.createDocumentFragment();
          if (vnode.children != null) {
            var children = vnode.children;
            createNodes(fragment, children, 0, children.length, hooks, null, ns);
          }
          vnode.dom = fragment.firstChild;
          vnode.domSize = fragment.childNodes.length;
          insertNode(parent, fragment, nextSibling);
        }
        function createElement(parent, vnode, hooks, ns, nextSibling) {
          var tag = vnode.tag;
          var attrs = vnode.attrs;
          var is = attrs && attrs.is;
          ns = getNameSpace(vnode) || ns;
          var element = ns ? is ? $doc.createElementNS(ns, tag, { is }) : $doc.createElementNS(ns, tag) : is ? $doc.createElement(tag, { is }) : $doc.createElement(tag);
          vnode.dom = element;
          if (attrs != null) {
            setAttrs(vnode, attrs, ns);
          }
          insertNode(parent, element, nextSibling);
          if (!maybeSetContentEditable(vnode)) {
            if (vnode.children != null) {
              var children = vnode.children;
              createNodes(element, children, 0, children.length, hooks, null, ns);
              if (vnode.tag === "select" && attrs != null)
                setLateSelectAttrs(vnode, attrs);
            }
          }
        }
        function initComponent(vnode, hooks) {
          var sentinel;
          if (typeof vnode.tag.view === "function") {
            vnode.state = Object.create(vnode.tag);
            sentinel = vnode.state.view;
            if (sentinel.$$reentrantLock$$ != null)
              return;
            sentinel.$$reentrantLock$$ = true;
          } else {
            vnode.state = void 0;
            sentinel = vnode.tag;
            if (sentinel.$$reentrantLock$$ != null)
              return;
            sentinel.$$reentrantLock$$ = true;
            vnode.state = vnode.tag.prototype != null && typeof vnode.tag.prototype.view === "function" ? new vnode.tag(vnode) : vnode.tag(vnode);
          }
          initLifecycle(vnode.state, vnode, hooks);
          if (vnode.attrs != null)
            initLifecycle(vnode.attrs, vnode, hooks);
          vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode));
          if (vnode.instance === vnode)
            throw Error("A view cannot return the vnode it received as argument");
          sentinel.$$reentrantLock$$ = null;
        }
        function createComponent(parent, vnode, hooks, ns, nextSibling) {
          initComponent(vnode, hooks);
          if (vnode.instance != null) {
            createNode(parent, vnode.instance, hooks, ns, nextSibling);
            vnode.dom = vnode.instance.dom;
            vnode.domSize = vnode.dom != null ? vnode.instance.domSize : 0;
          } else {
            vnode.domSize = 0;
          }
        }
        function updateNodes(parent, old, vnodes, hooks, nextSibling, ns) {
          if (old === vnodes || old == null && vnodes == null)
            return;
          else if (old == null || old.length === 0)
            createNodes(parent, vnodes, 0, vnodes.length, hooks, nextSibling, ns);
          else if (vnodes == null || vnodes.length === 0)
            removeNodes(parent, old, 0, old.length);
          else {
            var isOldKeyed = old[0] != null && old[0].key != null;
            var isKeyed = vnodes[0] != null && vnodes[0].key != null;
            var start2 = 0, oldStart = 0;
            if (!isOldKeyed)
              while (oldStart < old.length && old[oldStart] == null)
                oldStart++;
            if (!isKeyed)
              while (start2 < vnodes.length && vnodes[start2] == null)
                start2++;
            if (isOldKeyed !== isKeyed) {
              removeNodes(parent, old, oldStart, old.length);
              createNodes(parent, vnodes, start2, vnodes.length, hooks, nextSibling, ns);
            } else if (!isKeyed) {
              var commonLength = old.length < vnodes.length ? old.length : vnodes.length;
              start2 = start2 < oldStart ? start2 : oldStart;
              for (; start2 < commonLength; start2++) {
                o = old[start2];
                v = vnodes[start2];
                if (o === v || o == null && v == null)
                  continue;
                else if (o == null)
                  createNode(parent, v, hooks, ns, getNextSibling(old, start2 + 1, nextSibling));
                else if (v == null)
                  removeNode(parent, o);
                else
                  updateNode(parent, o, v, hooks, getNextSibling(old, start2 + 1, nextSibling), ns);
              }
              if (old.length > commonLength)
                removeNodes(parent, old, start2, old.length);
              if (vnodes.length > commonLength)
                createNodes(parent, vnodes, start2, vnodes.length, hooks, nextSibling, ns);
            } else {
              var oldEnd = old.length - 1, end2 = vnodes.length - 1, map, o, v, oe, ve, topSibling;
              while (oldEnd >= oldStart && end2 >= start2) {
                oe = old[oldEnd];
                ve = vnodes[end2];
                if (oe.key !== ve.key)
                  break;
                if (oe !== ve)
                  updateNode(parent, oe, ve, hooks, nextSibling, ns);
                if (ve.dom != null)
                  nextSibling = ve.dom;
                oldEnd--, end2--;
              }
              while (oldEnd >= oldStart && end2 >= start2) {
                o = old[oldStart];
                v = vnodes[start2];
                if (o.key !== v.key)
                  break;
                oldStart++, start2++;
                if (o !== v)
                  updateNode(parent, o, v, hooks, getNextSibling(old, oldStart, nextSibling), ns);
              }
              while (oldEnd >= oldStart && end2 >= start2) {
                if (start2 === end2)
                  break;
                if (o.key !== ve.key || oe.key !== v.key)
                  break;
                topSibling = getNextSibling(old, oldStart, nextSibling);
                moveNodes(parent, oe, topSibling);
                if (oe !== v)
                  updateNode(parent, oe, v, hooks, topSibling, ns);
                if (++start2 <= --end2)
                  moveNodes(parent, o, nextSibling);
                if (o !== ve)
                  updateNode(parent, o, ve, hooks, nextSibling, ns);
                if (ve.dom != null)
                  nextSibling = ve.dom;
                oldStart++;
                oldEnd--;
                oe = old[oldEnd];
                ve = vnodes[end2];
                o = old[oldStart];
                v = vnodes[start2];
              }
              while (oldEnd >= oldStart && end2 >= start2) {
                if (oe.key !== ve.key)
                  break;
                if (oe !== ve)
                  updateNode(parent, oe, ve, hooks, nextSibling, ns);
                if (ve.dom != null)
                  nextSibling = ve.dom;
                oldEnd--, end2--;
                oe = old[oldEnd];
                ve = vnodes[end2];
              }
              if (start2 > end2)
                removeNodes(parent, old, oldStart, oldEnd + 1);
              else if (oldStart > oldEnd)
                createNodes(parent, vnodes, start2, end2 + 1, hooks, nextSibling, ns);
              else {
                var originalNextSibling = nextSibling, vnodesLength = end2 - start2 + 1, oldIndices = new Array(vnodesLength), li = 0, i = 0, pos = 2147483647, matched = 0, map, lisIndices;
                for (i = 0; i < vnodesLength; i++)
                  oldIndices[i] = -1;
                for (i = end2; i >= start2; i--) {
                  if (map == null)
                    map = getKeyMap(old, oldStart, oldEnd + 1);
                  ve = vnodes[i];
                  var oldIndex = map[ve.key];
                  if (oldIndex != null) {
                    pos = oldIndex < pos ? oldIndex : -1;
                    oldIndices[i - start2] = oldIndex;
                    oe = old[oldIndex];
                    old[oldIndex] = null;
                    if (oe !== ve)
                      updateNode(parent, oe, ve, hooks, nextSibling, ns);
                    if (ve.dom != null)
                      nextSibling = ve.dom;
                    matched++;
                  }
                }
                nextSibling = originalNextSibling;
                if (matched !== oldEnd - oldStart + 1)
                  removeNodes(parent, old, oldStart, oldEnd + 1);
                if (matched === 0)
                  createNodes(parent, vnodes, start2, end2 + 1, hooks, nextSibling, ns);
                else {
                  if (pos === -1) {
                    lisIndices = makeLisIndices(oldIndices);
                    li = lisIndices.length - 1;
                    for (i = end2; i >= start2; i--) {
                      v = vnodes[i];
                      if (oldIndices[i - start2] === -1)
                        createNode(parent, v, hooks, ns, nextSibling);
                      else {
                        if (lisIndices[li] === i - start2)
                          li--;
                        else
                          moveNodes(parent, v, nextSibling);
                      }
                      if (v.dom != null)
                        nextSibling = vnodes[i].dom;
                    }
                  } else {
                    for (i = end2; i >= start2; i--) {
                      v = vnodes[i];
                      if (oldIndices[i - start2] === -1)
                        createNode(parent, v, hooks, ns, nextSibling);
                      if (v.dom != null)
                        nextSibling = vnodes[i].dom;
                    }
                  }
                }
              }
            }
          }
        }
        function updateNode(parent, old, vnode, hooks, nextSibling, ns) {
          var oldTag = old.tag, tag = vnode.tag;
          if (oldTag === tag) {
            vnode.state = old.state;
            vnode.events = old.events;
            if (shouldNotUpdate(vnode, old))
              return;
            if (typeof oldTag === "string") {
              if (vnode.attrs != null) {
                updateLifecycle(vnode.attrs, vnode, hooks);
              }
              switch (oldTag) {
                case "#":
                  updateText(old, vnode);
                  break;
                case "<":
                  updateHTML(parent, old, vnode, ns, nextSibling);
                  break;
                case "[":
                  updateFragment(parent, old, vnode, hooks, nextSibling, ns);
                  break;
                default:
                  updateElement(old, vnode, hooks, ns);
              }
            } else
              updateComponent(parent, old, vnode, hooks, nextSibling, ns);
          } else {
            removeNode(parent, old);
            createNode(parent, vnode, hooks, ns, nextSibling);
          }
        }
        function updateText(old, vnode) {
          if (old.children.toString() !== vnode.children.toString()) {
            old.dom.nodeValue = vnode.children;
          }
          vnode.dom = old.dom;
        }
        function updateHTML(parent, old, vnode, ns, nextSibling) {
          if (old.children !== vnode.children) {
            removeHTML(parent, old);
            createHTML(parent, vnode, ns, nextSibling);
          } else {
            vnode.dom = old.dom;
            vnode.domSize = old.domSize;
            vnode.instance = old.instance;
          }
        }
        function updateFragment(parent, old, vnode, hooks, nextSibling, ns) {
          updateNodes(parent, old.children, vnode.children, hooks, nextSibling, ns);
          var domSize = 0, children = vnode.children;
          vnode.dom = null;
          if (children != null) {
            for (var i = 0; i < children.length; i++) {
              var child = children[i];
              if (child != null && child.dom != null) {
                if (vnode.dom == null)
                  vnode.dom = child.dom;
                domSize += child.domSize || 1;
              }
            }
            if (domSize !== 1)
              vnode.domSize = domSize;
          }
        }
        function updateElement(old, vnode, hooks, ns) {
          var element = vnode.dom = old.dom;
          ns = getNameSpace(vnode) || ns;
          if (vnode.tag === "textarea") {
            if (vnode.attrs == null)
              vnode.attrs = {};
          }
          updateAttrs(vnode, old.attrs, vnode.attrs, ns);
          if (!maybeSetContentEditable(vnode)) {
            updateNodes(element, old.children, vnode.children, hooks, null, ns);
          }
        }
        function updateComponent(parent, old, vnode, hooks, nextSibling, ns) {
          vnode.instance = Vnode.normalize(callHook.call(vnode.state.view, vnode));
          if (vnode.instance === vnode)
            throw Error("A view cannot return the vnode it received as argument");
          updateLifecycle(vnode.state, vnode, hooks);
          if (vnode.attrs != null)
            updateLifecycle(vnode.attrs, vnode, hooks);
          if (vnode.instance != null) {
            if (old.instance == null)
              createNode(parent, vnode.instance, hooks, ns, nextSibling);
            else
              updateNode(parent, old.instance, vnode.instance, hooks, nextSibling, ns);
            vnode.dom = vnode.instance.dom;
            vnode.domSize = vnode.instance.domSize;
          } else if (old.instance != null) {
            removeNode(parent, old.instance);
            vnode.dom = void 0;
            vnode.domSize = 0;
          } else {
            vnode.dom = old.dom;
            vnode.domSize = old.domSize;
          }
        }
        function getKeyMap(vnodes, start2, end2) {
          var map = /* @__PURE__ */ Object.create(null);
          for (; start2 < end2; start2++) {
            var vnode = vnodes[start2];
            if (vnode != null) {
              var key = vnode.key;
              if (key != null)
                map[key] = start2;
            }
          }
          return map;
        }
        var lisTemp = [];
        function makeLisIndices(a) {
          var result = [0];
          var u = 0, v = 0, i = 0;
          var il = lisTemp.length = a.length;
          for (var i = 0; i < il; i++)
            lisTemp[i] = a[i];
          for (var i = 0; i < il; ++i) {
            if (a[i] === -1)
              continue;
            var j = result[result.length - 1];
            if (a[j] < a[i]) {
              lisTemp[i] = j;
              result.push(i);
              continue;
            }
            u = 0;
            v = result.length - 1;
            while (u < v) {
              var c = (u >>> 1) + (v >>> 1) + (u & v & 1);
              if (a[result[c]] < a[i]) {
                u = c + 1;
              } else {
                v = c;
              }
            }
            if (a[i] < a[result[u]]) {
              if (u > 0)
                lisTemp[i] = result[u - 1];
              result[u] = i;
            }
          }
          u = result.length;
          v = result[u - 1];
          while (u-- > 0) {
            result[u] = v;
            v = lisTemp[v];
          }
          lisTemp.length = 0;
          return result;
        }
        function getNextSibling(vnodes, i, nextSibling) {
          for (; i < vnodes.length; i++) {
            if (vnodes[i] != null && vnodes[i].dom != null)
              return vnodes[i].dom;
          }
          return nextSibling;
        }
        function moveNodes(parent, vnode, nextSibling) {
          var frag = $doc.createDocumentFragment();
          moveChildToFrag(parent, frag, vnode);
          insertNode(parent, frag, nextSibling);
        }
        function moveChildToFrag(parent, frag, vnode) {
          while (vnode.dom != null && vnode.dom.parentNode === parent) {
            if (typeof vnode.tag !== "string") {
              vnode = vnode.instance;
              if (vnode != null)
                continue;
            } else if (vnode.tag === "<") {
              for (var i = 0; i < vnode.instance.length; i++) {
                frag.appendChild(vnode.instance[i]);
              }
            } else if (vnode.tag !== "[") {
              frag.appendChild(vnode.dom);
            } else if (vnode.children.length === 1) {
              vnode = vnode.children[0];
              if (vnode != null)
                continue;
            } else {
              for (var i = 0; i < vnode.children.length; i++) {
                var child = vnode.children[i];
                if (child != null)
                  moveChildToFrag(parent, frag, child);
              }
            }
            break;
          }
        }
        function insertNode(parent, dom, nextSibling) {
          if (nextSibling != null)
            parent.insertBefore(dom, nextSibling);
          else
            parent.appendChild(dom);
        }
        function maybeSetContentEditable(vnode) {
          if (vnode.attrs == null || vnode.attrs.contenteditable == null && // attribute
          vnode.attrs.contentEditable == null)
            return false;
          var children = vnode.children;
          if (children != null && children.length === 1 && children[0].tag === "<") {
            var content = children[0].children;
            if (vnode.dom.innerHTML !== content)
              vnode.dom.innerHTML = content;
          } else if (children != null && children.length !== 0)
            throw new Error("Child node of a contenteditable must be trusted.");
          return true;
        }
        function removeNodes(parent, vnodes, start2, end2) {
          for (var i = start2; i < end2; i++) {
            var vnode = vnodes[i];
            if (vnode != null)
              removeNode(parent, vnode);
          }
        }
        function removeNode(parent, vnode) {
          var mask = 0;
          var original = vnode.state;
          var stateResult, attrsResult;
          if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeremove === "function") {
            var result = callHook.call(vnode.state.onbeforeremove, vnode);
            if (result != null && typeof result.then === "function") {
              mask = 1;
              stateResult = result;
            }
          }
          if (vnode.attrs && typeof vnode.attrs.onbeforeremove === "function") {
            var result = callHook.call(vnode.attrs.onbeforeremove, vnode);
            if (result != null && typeof result.then === "function") {
              mask |= 2;
              attrsResult = result;
            }
          }
          checkState(vnode, original);
          if (!mask) {
            onremove(vnode);
            removeChild(parent, vnode);
          } else {
            if (stateResult != null) {
              var next = function() {
                if (mask & 1) {
                  mask &= 2;
                  if (!mask)
                    reallyRemove();
                }
              };
              stateResult.then(next, next);
            }
            if (attrsResult != null) {
              var next = function() {
                if (mask & 2) {
                  mask &= 1;
                  if (!mask)
                    reallyRemove();
                }
              };
              attrsResult.then(next, next);
            }
          }
          function reallyRemove() {
            checkState(vnode, original);
            onremove(vnode);
            removeChild(parent, vnode);
          }
        }
        function removeHTML(parent, vnode) {
          for (var i = 0; i < vnode.instance.length; i++) {
            parent.removeChild(vnode.instance[i]);
          }
        }
        function removeChild(parent, vnode) {
          while (vnode.dom != null && vnode.dom.parentNode === parent) {
            if (typeof vnode.tag !== "string") {
              vnode = vnode.instance;
              if (vnode != null)
                continue;
            } else if (vnode.tag === "<") {
              removeHTML(parent, vnode);
            } else {
              if (vnode.tag !== "[") {
                parent.removeChild(vnode.dom);
                if (!Array.isArray(vnode.children))
                  break;
              }
              if (vnode.children.length === 1) {
                vnode = vnode.children[0];
                if (vnode != null)
                  continue;
              } else {
                for (var i = 0; i < vnode.children.length; i++) {
                  var child = vnode.children[i];
                  if (child != null)
                    removeChild(parent, child);
                }
              }
            }
            break;
          }
        }
        function onremove(vnode) {
          if (typeof vnode.tag !== "string" && typeof vnode.state.onremove === "function")
            callHook.call(vnode.state.onremove, vnode);
          if (vnode.attrs && typeof vnode.attrs.onremove === "function")
            callHook.call(vnode.attrs.onremove, vnode);
          if (typeof vnode.tag !== "string") {
            if (vnode.instance != null)
              onremove(vnode.instance);
          } else {
            var children = vnode.children;
            if (Array.isArray(children)) {
              for (var i = 0; i < children.length; i++) {
                var child = children[i];
                if (child != null)
                  onremove(child);
              }
            }
          }
        }
        function setAttrs(vnode, attrs, ns) {
          if (vnode.tag === "input" && attrs.type != null)
            vnode.dom.setAttribute("type", attrs.type);
          var isFileInput = attrs != null && vnode.tag === "input" && attrs.type === "file";
          for (var key in attrs) {
            setAttr(vnode, key, null, attrs[key], ns, isFileInput);
          }
        }
        function setAttr(vnode, key, old, value, ns, isFileInput) {
          if (key === "key" || key === "is" || value == null || isLifecycleMethod(key) || old === value && !isFormAttribute(vnode, key) && typeof value !== "object" || key === "type" && vnode.tag === "input")
            return;
          if (key[0] === "o" && key[1] === "n")
            return updateEvent(vnode, key, value);
          if (key.slice(0, 6) === "xlink:")
            vnode.dom.setAttributeNS("http://www.w3.org/1999/xlink", key.slice(6), value);
          else if (key === "style")
            updateStyle(vnode.dom, old, value);
          else if (hasPropertyKey(vnode, key, ns)) {
            if (key === "value") {
              if ((vnode.tag === "input" || vnode.tag === "textarea") && vnode.dom.value === "" + value && (isFileInput || vnode.dom === activeElement()))
                return;
              if (vnode.tag === "select" && old !== null && vnode.dom.value === "" + value)
                return;
              if (vnode.tag === "option" && old !== null && vnode.dom.value === "" + value)
                return;
              if (isFileInput && "" + value !== "") {
                console.error("`value` is read-only on file inputs!");
                return;
              }
            }
            vnode.dom[key] = value;
          } else {
            if (typeof value === "boolean") {
              if (value)
                vnode.dom.setAttribute(key, "");
              else
                vnode.dom.removeAttribute(key);
            } else
              vnode.dom.setAttribute(key === "className" ? "class" : key, value);
          }
        }
        function removeAttr(vnode, key, old, ns) {
          if (key === "key" || key === "is" || old == null || isLifecycleMethod(key))
            return;
          if (key[0] === "o" && key[1] === "n")
            updateEvent(vnode, key, void 0);
          else if (key === "style")
            updateStyle(vnode.dom, old, null);
          else if (hasPropertyKey(vnode, key, ns) && key !== "className" && key !== "title" && !(key === "value" && (vnode.tag === "option" || vnode.tag === "select" && vnode.dom.selectedIndex === -1 && vnode.dom === activeElement())) && !(vnode.tag === "input" && key === "type")) {
            vnode.dom[key] = null;
          } else {
            var nsLastIndex = key.indexOf(":");
            if (nsLastIndex !== -1)
              key = key.slice(nsLastIndex + 1);
            if (old !== false)
              vnode.dom.removeAttribute(key === "className" ? "class" : key);
          }
        }
        function setLateSelectAttrs(vnode, attrs) {
          if ("value" in attrs) {
            if (attrs.value === null) {
              if (vnode.dom.selectedIndex !== -1)
                vnode.dom.value = null;
            } else {
              var normalized = "" + attrs.value;
              if (vnode.dom.value !== normalized || vnode.dom.selectedIndex === -1) {
                vnode.dom.value = normalized;
              }
            }
          }
          if ("selectedIndex" in attrs)
            setAttr(vnode, "selectedIndex", null, attrs.selectedIndex, void 0);
        }
        function updateAttrs(vnode, old, attrs, ns) {
          if (old && old === attrs) {
            console.warn("Don't reuse attrs object, use new object for every redraw, this will throw in next major");
          }
          if (attrs != null) {
            if (vnode.tag === "input" && attrs.type != null)
              vnode.dom.setAttribute("type", attrs.type);
            var isFileInput = vnode.tag === "input" && attrs.type === "file";
            for (var key in attrs) {
              setAttr(vnode, key, old && old[key], attrs[key], ns, isFileInput);
            }
          }
          var val;
          if (old != null) {
            for (var key in old) {
              if ((val = old[key]) != null && (attrs == null || attrs[key] == null)) {
                removeAttr(vnode, key, val, ns);
              }
            }
          }
        }
        function isFormAttribute(vnode, attr) {
          return attr === "value" || attr === "checked" || attr === "selectedIndex" || attr === "selected" && vnode.dom === activeElement() || vnode.tag === "option" && vnode.dom.parentNode === $doc.activeElement;
        }
        function isLifecycleMethod(attr) {
          return attr === "oninit" || attr === "oncreate" || attr === "onupdate" || attr === "onremove" || attr === "onbeforeremove" || attr === "onbeforeupdate";
        }
        function hasPropertyKey(vnode, key, ns) {
          return ns === void 0 && // If it's a custom element, just keep it.
          (vnode.tag.indexOf("-") > -1 || vnode.attrs != null && vnode.attrs.is || // If it's a normal element, let's try to avoid a few browser bugs.
          key !== "href" && key !== "list" && key !== "form" && key !== "width" && key !== "height") && key in vnode.dom;
        }
        var uppercaseRegex = /[A-Z]/g;
        function toLowerCase(capital) {
          return "-" + capital.toLowerCase();
        }
        function normalizeKey(key) {
          return key[0] === "-" && key[1] === "-" ? key : key === "cssFloat" ? "float" : key.replace(uppercaseRegex, toLowerCase);
        }
        function updateStyle(element, old, style) {
          if (old === style) {
          } else if (style == null) {
            element.style.cssText = "";
          } else if (typeof style !== "object") {
            element.style.cssText = style;
          } else if (old == null || typeof old !== "object") {
            element.style.cssText = "";
            for (var key in style) {
              var value = style[key];
              if (value != null)
                element.style.setProperty(normalizeKey(key), String(value));
            }
          } else {
            for (var key in style) {
              var value = style[key];
              if (value != null && (value = String(value)) !== String(old[key])) {
                element.style.setProperty(normalizeKey(key), value);
              }
            }
            for (var key in old) {
              if (old[key] != null && style[key] == null) {
                element.style.removeProperty(normalizeKey(key));
              }
            }
          }
        }
        function EventDict() {
          this._ = currentRedraw;
        }
        EventDict.prototype = /* @__PURE__ */ Object.create(null);
        EventDict.prototype.handleEvent = function(ev) {
          var handler = this["on" + ev.type];
          var result;
          if (typeof handler === "function")
            result = handler.call(ev.currentTarget, ev);
          else if (typeof handler.handleEvent === "function")
            handler.handleEvent(ev);
          if (this._ && ev.redraw !== false)
            (0, this._)();
          if (result === false) {
            ev.preventDefault();
            ev.stopPropagation();
          }
        };
        function updateEvent(vnode, key, value) {
          if (vnode.events != null) {
            vnode.events._ = currentRedraw;
            if (vnode.events[key] === value)
              return;
            if (value != null && (typeof value === "function" || typeof value === "object")) {
              if (vnode.events[key] == null)
                vnode.dom.addEventListener(key.slice(2), vnode.events, false);
              vnode.events[key] = value;
            } else {
              if (vnode.events[key] != null)
                vnode.dom.removeEventListener(key.slice(2), vnode.events, false);
              vnode.events[key] = void 0;
            }
          } else if (value != null && (typeof value === "function" || typeof value === "object")) {
            vnode.events = new EventDict();
            vnode.dom.addEventListener(key.slice(2), vnode.events, false);
            vnode.events[key] = value;
          }
        }
        function initLifecycle(source, vnode, hooks) {
          if (typeof source.oninit === "function")
            callHook.call(source.oninit, vnode);
          if (typeof source.oncreate === "function")
            hooks.push(callHook.bind(source.oncreate, vnode));
        }
        function updateLifecycle(source, vnode, hooks) {
          if (typeof source.onupdate === "function")
            hooks.push(callHook.bind(source.onupdate, vnode));
        }
        function shouldNotUpdate(vnode, old) {
          do {
            if (vnode.attrs != null && typeof vnode.attrs.onbeforeupdate === "function") {
              var force = callHook.call(vnode.attrs.onbeforeupdate, vnode, old);
              if (force !== void 0 && !force)
                break;
            }
            if (typeof vnode.tag !== "string" && typeof vnode.state.onbeforeupdate === "function") {
              var force = callHook.call(vnode.state.onbeforeupdate, vnode, old);
              if (force !== void 0 && !force)
                break;
            }
            return false;
          } while (false);
          vnode.dom = old.dom;
          vnode.domSize = old.domSize;
          vnode.instance = old.instance;
          vnode.attrs = old.attrs;
          vnode.children = old.children;
          vnode.text = old.text;
          return true;
        }
        var currentDOM;
        return function(dom, vnodes, redraw) {
          if (!dom)
            throw new TypeError("DOM element being rendered to does not exist.");
          if (currentDOM != null && dom.contains(currentDOM)) {
            throw new TypeError("Node is currently being rendered to and thus is locked.");
          }
          var prevRedraw = currentRedraw;
          var prevDOM = currentDOM;
          var hooks = [];
          var active = activeElement();
          var namespace = dom.namespaceURI;
          currentDOM = dom;
          currentRedraw = typeof redraw === "function" ? redraw : void 0;
          try {
            if (dom.vnodes == null)
              dom.textContent = "";
            vnodes = Vnode.normalizeChildren(Array.isArray(vnodes) ? vnodes : [vnodes]);
            updateNodes(dom, dom.vnodes, vnodes, hooks, null, namespace === "http://www.w3.org/1999/xhtml" ? void 0 : namespace);
            dom.vnodes = vnodes;
            if (active != null && activeElement() !== active && typeof active.focus === "function")
              active.focus();
            for (var i = 0; i < hooks.length; i++)
              hooks[i]();
          } finally {
            currentRedraw = prevRedraw;
            currentDOM = prevDOM;
          }
        };
      };
    }
  });

  // node_modules/mithril/render.js
  var require_render2 = __commonJS({
    "node_modules/mithril/render.js"(exports, module) {
      "use strict";
      module.exports = require_render()(typeof window !== "undefined" ? window : null);
    }
  });

  // node_modules/mithril/api/mount-redraw.js
  var require_mount_redraw = __commonJS({
    "node_modules/mithril/api/mount-redraw.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      module.exports = function(render, schedule, console2) {
        var subscriptions = [];
        var pending = false;
        var offset2 = -1;
        function sync() {
          for (offset2 = 0; offset2 < subscriptions.length; offset2 += 2) {
            try {
              render(subscriptions[offset2], Vnode(subscriptions[offset2 + 1]), redraw);
            } catch (e) {
              console2.error(e);
            }
          }
          offset2 = -1;
        }
        function redraw() {
          if (!pending) {
            pending = true;
            schedule(function() {
              pending = false;
              sync();
            });
          }
        }
        redraw.sync = sync;
        function mount(root, component) {
          if (component != null && component.view == null && typeof component !== "function") {
            throw new TypeError("m.mount expects a component, not a vnode.");
          }
          var index = subscriptions.indexOf(root);
          if (index >= 0) {
            subscriptions.splice(index, 2);
            if (index <= offset2)
              offset2 -= 2;
            render(root, []);
          }
          if (component != null) {
            subscriptions.push(root, component);
            render(root, Vnode(component), redraw);
          }
        }
        return { mount, redraw };
      };
    }
  });

  // node_modules/mithril/mount-redraw.js
  var require_mount_redraw2 = __commonJS({
    "node_modules/mithril/mount-redraw.js"(exports, module) {
      "use strict";
      var render = require_render2();
      module.exports = require_mount_redraw()(render, typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : null, typeof console !== "undefined" ? console : null);
    }
  });

  // node_modules/mithril/querystring/build.js
  var require_build = __commonJS({
    "node_modules/mithril/querystring/build.js"(exports, module) {
      "use strict";
      module.exports = function(object) {
        if (Object.prototype.toString.call(object) !== "[object Object]")
          return "";
        var args = [];
        for (var key in object) {
          destructure(key, object[key]);
        }
        return args.join("&");
        function destructure(key2, value) {
          if (Array.isArray(value)) {
            for (var i = 0; i < value.length; i++) {
              destructure(key2 + "[" + i + "]", value[i]);
            }
          } else if (Object.prototype.toString.call(value) === "[object Object]") {
            for (var i in value) {
              destructure(key2 + "[" + i + "]", value[i]);
            }
          } else
            args.push(encodeURIComponent(key2) + (value != null && value !== "" ? "=" + encodeURIComponent(value) : ""));
        }
      };
    }
  });

  // node_modules/mithril/util/assign.js
  var require_assign = __commonJS({
    "node_modules/mithril/util/assign.js"(exports, module) {
      "use strict";
      var hasOwn = require_hasOwn();
      module.exports = Object.assign || function(target, source) {
        for (var key in source) {
          if (hasOwn.call(source, key))
            target[key] = source[key];
        }
      };
    }
  });

  // node_modules/mithril/pathname/build.js
  var require_build2 = __commonJS({
    "node_modules/mithril/pathname/build.js"(exports, module) {
      "use strict";
      var buildQueryString = require_build();
      var assign = require_assign();
      module.exports = function(template, params) {
        if (/:([^\/\.-]+)(\.{3})?:/.test(template)) {
          throw new SyntaxError("Template parameter names must be separated by either a '/', '-', or '.'.");
        }
        if (params == null)
          return template;
        var queryIndex = template.indexOf("?");
        var hashIndex = template.indexOf("#");
        var queryEnd = hashIndex < 0 ? template.length : hashIndex;
        var pathEnd = queryIndex < 0 ? queryEnd : queryIndex;
        var path = template.slice(0, pathEnd);
        var query = {};
        assign(query, params);
        var resolved = path.replace(/:([^\/\.-]+)(\.{3})?/g, function(m3, key, variadic) {
          delete query[key];
          if (params[key] == null)
            return m3;
          return variadic ? params[key] : encodeURIComponent(String(params[key]));
        });
        var newQueryIndex = resolved.indexOf("?");
        var newHashIndex = resolved.indexOf("#");
        var newQueryEnd = newHashIndex < 0 ? resolved.length : newHashIndex;
        var newPathEnd = newQueryIndex < 0 ? newQueryEnd : newQueryIndex;
        var result = resolved.slice(0, newPathEnd);
        if (queryIndex >= 0)
          result += template.slice(queryIndex, queryEnd);
        if (newQueryIndex >= 0)
          result += (queryIndex < 0 ? "?" : "&") + resolved.slice(newQueryIndex, newQueryEnd);
        var querystring = buildQueryString(query);
        if (querystring)
          result += (queryIndex < 0 && newQueryIndex < 0 ? "?" : "&") + querystring;
        if (hashIndex >= 0)
          result += template.slice(hashIndex);
        if (newHashIndex >= 0)
          result += (hashIndex < 0 ? "" : "&") + resolved.slice(newHashIndex);
        return result;
      };
    }
  });

  // node_modules/mithril/request/request.js
  var require_request = __commonJS({
    "node_modules/mithril/request/request.js"(exports, module) {
      "use strict";
      var buildPathname = require_build2();
      var hasOwn = require_hasOwn();
      module.exports = function($window, Promise2, oncompletion) {
        var callbackCount = 0;
        function PromiseProxy(executor) {
          return new Promise2(executor);
        }
        PromiseProxy.prototype = Promise2.prototype;
        PromiseProxy.__proto__ = Promise2;
        function makeRequest(factory) {
          return function(url, args) {
            if (typeof url !== "string") {
              args = url;
              url = url.url;
            } else if (args == null)
              args = {};
            var promise = new Promise2(function(resolve, reject) {
              factory(buildPathname(url, args.params), args, function(data) {
                if (typeof args.type === "function") {
                  if (Array.isArray(data)) {
                    for (var i = 0; i < data.length; i++) {
                      data[i] = new args.type(data[i]);
                    }
                  } else
                    data = new args.type(data);
                }
                resolve(data);
              }, reject);
            });
            if (args.background === true)
              return promise;
            var count = 0;
            function complete() {
              if (--count === 0 && typeof oncompletion === "function")
                oncompletion();
            }
            return wrap(promise);
            function wrap(promise2) {
              var then = promise2.then;
              promise2.constructor = PromiseProxy;
              promise2.then = function() {
                count++;
                var next = then.apply(promise2, arguments);
                next.then(complete, function(e) {
                  complete();
                  if (count === 0)
                    throw e;
                });
                return wrap(next);
              };
              return promise2;
            }
          };
        }
        function hasHeader(args, name) {
          for (var key in args.headers) {
            if (hasOwn.call(args.headers, key) && key.toLowerCase() === name)
              return true;
          }
          return false;
        }
        return {
          request: makeRequest(function(url, args, resolve, reject) {
            var method = args.method != null ? args.method.toUpperCase() : "GET";
            var body = args.body;
            var assumeJSON = (args.serialize == null || args.serialize === JSON.serialize) && !(body instanceof $window.FormData || body instanceof $window.URLSearchParams);
            var responseType = args.responseType || (typeof args.extract === "function" ? "" : "json");
            var xhr = new $window.XMLHttpRequest(), aborted = false, isTimeout = false;
            var original = xhr, replacedAbort;
            var abort = xhr.abort;
            xhr.abort = function() {
              aborted = true;
              abort.call(this);
            };
            xhr.open(method, url, args.async !== false, typeof args.user === "string" ? args.user : void 0, typeof args.password === "string" ? args.password : void 0);
            if (assumeJSON && body != null && !hasHeader(args, "content-type")) {
              xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            }
            if (typeof args.deserialize !== "function" && !hasHeader(args, "accept")) {
              xhr.setRequestHeader("Accept", "application/json, text/*");
            }
            if (args.withCredentials)
              xhr.withCredentials = args.withCredentials;
            if (args.timeout)
              xhr.timeout = args.timeout;
            xhr.responseType = responseType;
            for (var key in args.headers) {
              if (hasOwn.call(args.headers, key)) {
                xhr.setRequestHeader(key, args.headers[key]);
              }
            }
            xhr.onreadystatechange = function(ev) {
              if (aborted)
                return;
              if (ev.target.readyState === 4) {
                try {
                  var success = ev.target.status >= 200 && ev.target.status < 300 || ev.target.status === 304 || /^file:\/\//i.test(url);
                  var response = ev.target.response, message;
                  if (responseType === "json") {
                    if (!ev.target.responseType && typeof args.extract !== "function") {
                      try {
                        response = JSON.parse(ev.target.responseText);
                      } catch (e) {
                        response = null;
                      }
                    }
                  } else if (!responseType || responseType === "text") {
                    if (response == null)
                      response = ev.target.responseText;
                  }
                  if (typeof args.extract === "function") {
                    response = args.extract(ev.target, args);
                    success = true;
                  } else if (typeof args.deserialize === "function") {
                    response = args.deserialize(response);
                  }
                  if (success)
                    resolve(response);
                  else {
                    var completeErrorResponse = function() {
                      try {
                        message = ev.target.responseText;
                      } catch (e) {
                        message = response;
                      }
                      var error = new Error(message);
                      error.code = ev.target.status;
                      error.response = response;
                      reject(error);
                    };
                    if (xhr.status === 0) {
                      setTimeout(function() {
                        if (isTimeout)
                          return;
                        completeErrorResponse();
                      });
                    } else
                      completeErrorResponse();
                  }
                } catch (e) {
                  reject(e);
                }
              }
            };
            xhr.ontimeout = function(ev) {
              isTimeout = true;
              var error = new Error("Request timed out");
              error.code = ev.target.status;
              reject(error);
            };
            if (typeof args.config === "function") {
              xhr = args.config(xhr, args, url) || xhr;
              if (xhr !== original) {
                replacedAbort = xhr.abort;
                xhr.abort = function() {
                  aborted = true;
                  replacedAbort.call(this);
                };
              }
            }
            if (body == null)
              xhr.send();
            else if (typeof args.serialize === "function")
              xhr.send(args.serialize(body));
            else if (body instanceof $window.FormData || body instanceof $window.URLSearchParams)
              xhr.send(body);
            else
              xhr.send(JSON.stringify(body));
          }),
          jsonp: makeRequest(function(url, args, resolve, reject) {
            var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++;
            var script = $window.document.createElement("script");
            $window[callbackName] = function(data) {
              delete $window[callbackName];
              script.parentNode.removeChild(script);
              resolve(data);
            };
            script.onerror = function() {
              delete $window[callbackName];
              script.parentNode.removeChild(script);
              reject(new Error("JSONP request failed"));
            };
            script.src = url + (url.indexOf("?") < 0 ? "?" : "&") + encodeURIComponent(args.callbackKey || "callback") + "=" + encodeURIComponent(callbackName);
            $window.document.documentElement.appendChild(script);
          })
        };
      };
    }
  });

  // node_modules/mithril/request.js
  var require_request2 = __commonJS({
    "node_modules/mithril/request.js"(exports, module) {
      "use strict";
      var PromisePolyfill = require_promise();
      var mountRedraw = require_mount_redraw2();
      module.exports = require_request()(typeof window !== "undefined" ? window : null, PromisePolyfill, mountRedraw.redraw);
    }
  });

  // node_modules/mithril/querystring/parse.js
  var require_parse = __commonJS({
    "node_modules/mithril/querystring/parse.js"(exports, module) {
      "use strict";
      function decodeURIComponentSave(str) {
        try {
          return decodeURIComponent(str);
        } catch (err) {
          return str;
        }
      }
      module.exports = function(string) {
        if (string === "" || string == null)
          return {};
        if (string.charAt(0) === "?")
          string = string.slice(1);
        var entries = string.split("&"), counters = {}, data = {};
        for (var i = 0; i < entries.length; i++) {
          var entry = entries[i].split("=");
          var key = decodeURIComponentSave(entry[0]);
          var value = entry.length === 2 ? decodeURIComponentSave(entry[1]) : "";
          if (value === "true")
            value = true;
          else if (value === "false")
            value = false;
          var levels = key.split(/\]\[?|\[/);
          var cursor = data;
          if (key.indexOf("[") > -1)
            levels.pop();
          for (var j = 0; j < levels.length; j++) {
            var level = levels[j], nextLevel = levels[j + 1];
            var isNumber = nextLevel == "" || !isNaN(parseInt(nextLevel, 10));
            if (level === "") {
              var key = levels.slice(0, j).join();
              if (counters[key] == null) {
                counters[key] = Array.isArray(cursor) ? cursor.length : 0;
              }
              level = counters[key]++;
            } else if (level === "__proto__")
              break;
            if (j === levels.length - 1)
              cursor[level] = value;
            else {
              var desc = Object.getOwnPropertyDescriptor(cursor, level);
              if (desc != null)
                desc = desc.value;
              if (desc == null)
                cursor[level] = desc = isNumber ? [] : {};
              cursor = desc;
            }
          }
        }
        return data;
      };
    }
  });

  // node_modules/mithril/pathname/parse.js
  var require_parse2 = __commonJS({
    "node_modules/mithril/pathname/parse.js"(exports, module) {
      "use strict";
      var parseQueryString = require_parse();
      module.exports = function(url) {
        var queryIndex = url.indexOf("?");
        var hashIndex = url.indexOf("#");
        var queryEnd = hashIndex < 0 ? url.length : hashIndex;
        var pathEnd = queryIndex < 0 ? queryEnd : queryIndex;
        var path = url.slice(0, pathEnd).replace(/\/{2,}/g, "/");
        if (!path)
          path = "/";
        else {
          if (path[0] !== "/")
            path = "/" + path;
          if (path.length > 1 && path[path.length - 1] === "/")
            path = path.slice(0, -1);
        }
        return {
          path,
          params: queryIndex < 0 ? {} : parseQueryString(url.slice(queryIndex + 1, queryEnd))
        };
      };
    }
  });

  // node_modules/mithril/pathname/compileTemplate.js
  var require_compileTemplate = __commonJS({
    "node_modules/mithril/pathname/compileTemplate.js"(exports, module) {
      "use strict";
      var parsePathname = require_parse2();
      module.exports = function(template) {
        var templateData = parsePathname(template);
        var templateKeys = Object.keys(templateData.params);
        var keys = [];
        var regexp = new RegExp("^" + templateData.path.replace(
          // I escape literal text so people can use things like `:file.:ext` or
          // `:lang-:locale` in routes. This is all merged into one pass so I
          // don't also accidentally escape `-` and make it harder to detect it to
          // ban it from template parameters.
          /:([^\/.-]+)(\.{3}|\.(?!\.)|-)?|[\\^$*+.()|\[\]{}]/g,
          function(m3, key, extra) {
            if (key == null)
              return "\\" + m3;
            keys.push({ k: key, r: extra === "..." });
            if (extra === "...")
              return "(.*)";
            if (extra === ".")
              return "([^/]+)\\.";
            return "([^/]+)" + (extra || "");
          }
        ) + "$");
        return function(data) {
          for (var i = 0; i < templateKeys.length; i++) {
            if (templateData.params[templateKeys[i]] !== data.params[templateKeys[i]])
              return false;
          }
          if (!keys.length)
            return regexp.test(data.path);
          var values = regexp.exec(data.path);
          if (values == null)
            return false;
          for (var i = 0; i < keys.length; i++) {
            data.params[keys[i].k] = keys[i].r ? values[i + 1] : decodeURIComponent(values[i + 1]);
          }
          return true;
        };
      };
    }
  });

  // node_modules/mithril/util/censor.js
  var require_censor = __commonJS({
    "node_modules/mithril/util/censor.js"(exports, module) {
      "use strict";
      var hasOwn = require_hasOwn();
      var magic = new RegExp("^(?:key|oninit|oncreate|onbeforeupdate|onupdate|onbeforeremove|onremove)$");
      module.exports = function(attrs, extras) {
        var result = {};
        if (extras != null) {
          for (var key in attrs) {
            if (hasOwn.call(attrs, key) && !magic.test(key) && extras.indexOf(key) < 0) {
              result[key] = attrs[key];
            }
          }
        } else {
          for (var key in attrs) {
            if (hasOwn.call(attrs, key) && !magic.test(key)) {
              result[key] = attrs[key];
            }
          }
        }
        return result;
      };
    }
  });

  // node_modules/mithril/api/router.js
  var require_router = __commonJS({
    "node_modules/mithril/api/router.js"(exports, module) {
      "use strict";
      var Vnode = require_vnode();
      var m3 = require_hyperscript();
      var Promise2 = require_promise();
      var buildPathname = require_build2();
      var parsePathname = require_parse2();
      var compileTemplate = require_compileTemplate();
      var assign = require_assign();
      var censor = require_censor();
      var sentinel = {};
      function decodeURIComponentSave(component) {
        try {
          return decodeURIComponent(component);
        } catch (e) {
          return component;
        }
      }
      module.exports = function($window, mountRedraw) {
        var callAsync = $window == null ? null : typeof $window.setImmediate === "function" ? $window.setImmediate : $window.setTimeout;
        var p = Promise2.resolve();
        var scheduled = false;
        var ready = false;
        var state = 0;
        var compiled, fallbackRoute;
        var currentResolver = sentinel, component, attrs, currentPath, lastUpdate;
        var RouterRoot = {
          onbeforeupdate: function() {
            state = state ? 2 : 1;
            return !(!state || sentinel === currentResolver);
          },
          onremove: function() {
            $window.removeEventListener("popstate", fireAsync, false);
            $window.removeEventListener("hashchange", resolveRoute, false);
          },
          view: function() {
            if (!state || sentinel === currentResolver)
              return;
            var vnode = [Vnode(component, attrs.key, attrs)];
            if (currentResolver)
              vnode = currentResolver.render(vnode[0]);
            return vnode;
          }
        };
        var SKIP = route.SKIP = {};
        function resolveRoute() {
          scheduled = false;
          var prefix = $window.location.hash;
          if (route.prefix[0] !== "#") {
            prefix = $window.location.search + prefix;
            if (route.prefix[0] !== "?") {
              prefix = $window.location.pathname + prefix;
              if (prefix[0] !== "/")
                prefix = "/" + prefix;
            }
          }
          var path = prefix.concat().replace(/(?:%[a-f89][a-f0-9])+/gim, decodeURIComponentSave).slice(route.prefix.length);
          var data = parsePathname(path);
          assign(data.params, $window.history.state);
          function reject(e) {
            console.error(e);
            setPath(fallbackRoute, null, { replace: true });
          }
          loop(0);
          function loop(i) {
            for (; i < compiled.length; i++) {
              if (compiled[i].check(data)) {
                var payload = compiled[i].component;
                var matchedRoute = compiled[i].route;
                var localComp = payload;
                var update = lastUpdate = function(comp) {
                  if (update !== lastUpdate)
                    return;
                  if (comp === SKIP)
                    return loop(i + 1);
                  component = comp != null && (typeof comp.view === "function" || typeof comp === "function") ? comp : "div";
                  attrs = data.params, currentPath = path, lastUpdate = null;
                  currentResolver = payload.render ? payload : null;
                  if (state === 2)
                    mountRedraw.redraw();
                  else {
                    state = 2;
                    mountRedraw.redraw.sync();
                  }
                };
                if (payload.view || typeof payload === "function") {
                  payload = {};
                  update(localComp);
                } else if (payload.onmatch) {
                  p.then(function() {
                    return payload.onmatch(data.params, path, matchedRoute);
                  }).then(update, path === fallbackRoute ? null : reject);
                } else
                  update("div");
                return;
              }
            }
            if (path === fallbackRoute) {
              throw new Error("Could not resolve default route " + fallbackRoute + ".");
            }
            setPath(fallbackRoute, null, { replace: true });
          }
        }
        function fireAsync() {
          if (!scheduled) {
            scheduled = true;
            callAsync(resolveRoute);
          }
        }
        function setPath(path, data, options) {
          path = buildPathname(path, data);
          if (ready) {
            fireAsync();
            var state2 = options ? options.state : null;
            var title = options ? options.title : null;
            if (options && options.replace)
              $window.history.replaceState(state2, title, route.prefix + path);
            else
              $window.history.pushState(state2, title, route.prefix + path);
          } else {
            $window.location.href = route.prefix + path;
          }
        }
        function route(root, defaultRoute, routes) {
          if (!root)
            throw new TypeError("DOM element being rendered to does not exist.");
          compiled = Object.keys(routes).map(function(route2) {
            if (route2[0] !== "/")
              throw new SyntaxError("Routes must start with a '/'.");
            if (/:([^\/\.-]+)(\.{3})?:/.test(route2)) {
              throw new SyntaxError("Route parameter names must be separated with either '/', '.', or '-'.");
            }
            return {
              route: route2,
              component: routes[route2],
              check: compileTemplate(route2)
            };
          });
          fallbackRoute = defaultRoute;
          if (defaultRoute != null) {
            var defaultData = parsePathname(defaultRoute);
            if (!compiled.some(function(i) {
              return i.check(defaultData);
            })) {
              throw new ReferenceError("Default route doesn't match any known routes.");
            }
          }
          if (typeof $window.history.pushState === "function") {
            $window.addEventListener("popstate", fireAsync, false);
          } else if (route.prefix[0] === "#") {
            $window.addEventListener("hashchange", resolveRoute, false);
          }
          ready = true;
          mountRedraw.mount(root, RouterRoot);
          resolveRoute();
        }
        route.set = function(path, data, options) {
          if (lastUpdate != null) {
            options = options || {};
            options.replace = true;
          }
          lastUpdate = null;
          setPath(path, data, options);
        };
        route.get = function() {
          return currentPath;
        };
        route.prefix = "#!";
        route.Link = {
          view: function(vnode) {
            var child = m3(
              vnode.attrs.selector || "a",
              censor(vnode.attrs, ["options", "params", "selector", "onclick"]),
              vnode.children
            );
            var options, onclick, href;
            if (child.attrs.disabled = Boolean(child.attrs.disabled)) {
              child.attrs.href = null;
              child.attrs["aria-disabled"] = "true";
            } else {
              options = vnode.attrs.options;
              onclick = vnode.attrs.onclick;
              href = buildPathname(child.attrs.href, vnode.attrs.params);
              child.attrs.href = route.prefix + href;
              child.attrs.onclick = function(e) {
                var result;
                if (typeof onclick === "function") {
                  result = onclick.call(e.currentTarget, e);
                } else if (onclick == null || typeof onclick !== "object") {
                } else if (typeof onclick.handleEvent === "function") {
                  onclick.handleEvent(e);
                }
                if (
                  // Skip if `onclick` prevented default
                  result !== false && !e.defaultPrevented && // Ignore everything but left clicks
                  (e.button === 0 || e.which === 0 || e.which === 1) && // Let the browser handle `target=_blank`, etc.
                  (!e.currentTarget.target || e.currentTarget.target === "_self") && // No modifier keys
                  !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey
                ) {
                  e.preventDefault();
                  e.redraw = false;
                  route.set(href, null, options);
                }
              };
            }
            return child;
          }
        };
        route.param = function(key) {
          return attrs && key != null ? attrs[key] : attrs;
        };
        return route;
      };
    }
  });

  // node_modules/mithril/route.js
  var require_route = __commonJS({
    "node_modules/mithril/route.js"(exports, module) {
      "use strict";
      var mountRedraw = require_mount_redraw2();
      module.exports = require_router()(typeof window !== "undefined" ? window : null, mountRedraw);
    }
  });

  // node_modules/mithril/index.js
  var require_mithril = __commonJS({
    "node_modules/mithril/index.js"(exports, module) {
      "use strict";
      var hyperscript = require_hyperscript2();
      var request = require_request2();
      var mountRedraw = require_mount_redraw2();
      var m3 = function m4() {
        return hyperscript.apply(this, arguments);
      };
      m3.m = hyperscript;
      m3.trust = hyperscript.trust;
      m3.fragment = hyperscript.fragment;
      m3.Fragment = "[";
      m3.mount = mountRedraw.mount;
      m3.route = require_route();
      m3.render = require_render2();
      m3.redraw = mountRedraw.redraw;
      m3.request = request.request;
      m3.jsonp = request.jsonp;
      m3.parseQueryString = require_parse();
      m3.buildQueryString = require_build();
      m3.parsePathname = require_parse2();
      m3.buildPathname = require_build2();
      m3.vnode = require_vnode();
      m3.PromisePolyfill = require_polyfill();
      m3.censor = require_censor();
      module.exports = m3;
    }
  });

  // app/authentication.js
  var require_authentication = __commonJS({
    "app/authentication.js"(exports, module) {
      var m3 = require_mithril();
      var storageName = "nfp_sites_filadelfia_web_logintoken";
      var Authentication2 = {
        currentUser: null,
        isAdmin: false,
        loadingListeners: [],
        authListeners: [],
        updateToken: function(token) {
          if (!token)
            return Authentication2.clearToken();
          localStorage.setItem(storageName, token);
          Authentication2.currentUser = JSON.parse(atob(token.split(".")[1]));
          if (Authentication2.authListeners.length) {
            Authentication2.authListeners.forEach(function(x) {
              x(Authentication2.currentUser);
            });
          }
        },
        clearToken: function() {
          Authentication2.currentUser = null;
          localStorage.removeItem(storageName);
          Authentication2.isAdmin = false;
        },
        addEvent: function(event) {
          Authentication2.authListeners.push(event);
        },
        setAdmin: function(item) {
          Authentication2.isAdmin = item;
        },
        getToken: function() {
          return localStorage.getItem(storageName);
        },
        getTokenDecoded: function() {
          let token = Authentication2.getToken();
          var base64Url = token.split(".")[1];
          var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
          var jsonPayload = decodeURIComponent(window.atob(base64).split("").map(function(c) {
            return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
          }).join(""));
          return JSON.parse(jsonPayload);
        },
        requiresLogin: function() {
          if (Authentication2.currentUser)
            return;
          m3.route.set("/login");
        },
        requiresNotLogin: function() {
          if (!Authentication2.currentUser)
            return;
          m3.route.set("/");
        }
      };
      Authentication2.updateToken(localStorage.getItem(storageName));
      window.Authentication = Authentication2;
      module.exports = Authentication2;
    }
  });

  // app/lang.js
  var require_lang = __commonJS({
    "app/lang.js"(exports, module) {
      var out = {
        currentlang: "en"
      };
      var i18n = {
        lang_change_long: [
          "Skipta yfir \xE1 \xEDslensku",
          "Change to english"
        ],
        lang_current: [
          "en",
          "is"
        ],
        header_title: [
          "F\xEDladelfia archival center",
          "F\xEDladelfia myndhvelfing"
        ],
        header_logout: [
          "Log out",
          "Skr\xE1 \xFAt"
        ],
        title: [
          "Title",
          "Titill"
        ],
        date: [
          "Date",
          "Dagsetning"
        ],
        language: [
          "EN",
          "IS"
        ],
        upload_goto: [
          "Upload",
          "Upphla\xF0a"
        ],
        login_error: [
          "Error while logging in: {0}",
          "Villa vi\xF0 innskr\xE1ningu: {0}"
        ],
        login_error_auth: [
          "Unknown error from server. Try again later.",
          "\xD3\xFEekkt villa fr\xE1 vef\xFEj\xF3ni. Reyndu aftur seinna."
        ],
        login_missing_email: [
          "Email is missing",
          "Email e\xF0a nafn vantar"
        ],
        login_missing_password: [
          "Password is missing",
          "Lykilor\xF0 vantar"
        ],
        login_email: [
          "Email or name",
          "Email e\xF0a nafn"
        ],
        login_password: [
          "Password",
          "Lykilor\xF0"
        ],
        login_submit: [
          "Log in",
          "Skr\xE1 inn"
        ],
        logout: [
          "Log out",
          "Skr\xE1 \xFAt"
        ],
        upload_missing_title: [
          "Title is missing",
          "Titill vantar"
        ],
        upload_missing_date: [
          "Date is missing",
          "Dagsetning vantar"
        ],
        upload_missing_file: [
          "Video file missing",
          "Myndaskr\xE1 vantar"
        ],
        upload_missing_banner: [
          "Poster image missing",
          "Mynd vantar"
        ],
        upload_error: [
          "Error while uploading: {0}",
          "Villa vi\xF0 a\xF0 hla\xF0a upp myndefni: {0}"
        ],
        unsplash: [
          "Photo by {0} on {1}",
          "Mynd eftir {0} fr\xE1 {1}"
        ],
        api_down: [
          "No internet or browser blocked the request.",
          "Ekkert net e\xF0a vafri blocka\xF0i fyrirspurn."
        ],
        edit: [
          "Edit",
          "Breyta"
        ],
        delete: [
          "Delete",
          "Ey\xF0a"
        ],
        article_speaker: [
          "Speaker",
          "R\xE6\xF0uma\xF0ur"
        ],
        delete_error: [
          "Error while deleting: {0}",
          "Villa vi\xF0 a\xF0 ey\xF0a efni: {0}"
        ],
        article_error: [
          "Error while saving: {0}",
          "Villa vi\xF0 a\xF0 vista: {0}"
        ],
        months: {
          "1": [
            "January",
            "Jan\xFAar"
          ],
          "2": [
            "February",
            "Febr\xFAar"
          ],
          "3": [
            "March",
            "Mars"
          ],
          "4": [
            "April",
            "Apr\xEDl"
          ],
          "5": [
            "May",
            "Ma\xED"
          ],
          "6": [
            "June",
            "J\xFAn\xED"
          ],
          "7": [
            "July",
            "J\xFAl\xED"
          ],
          "8": [
            "August",
            "\xC1g\xFAst"
          ],
          "9": [
            "September",
            "September"
          ],
          "10": [
            "Oktober",
            "Okt\xF3ber"
          ],
          "11": [
            "November",
            "N\xF3vember"
          ],
          "12": [
            "December",
            "Desember"
          ]
        }
      };
      var langs = {
        "en": 0,
        "is": 1
      };
      var regexNumber = new RegExp("^\\d+$");
      out.printdate = function(date) {
        let day = date.getDate().toString();
        if (out.currentlang === "en") {
          let last = day[day.length - 1];
          if (last === "1") {
            day += "st";
          } else if (last === "2") {
            day += "nd";
          } else if (last === "3") {
            day += "rd";
          } else {
            day += "th";
          }
        } else {
          day += ".";
        }
        return `${day} ${out.months[date.getMonth() + 1]} ${date.getFullYear()}, ${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
      };
      out.langset = function(lang) {
        out.currentlang = lang;
        let index = langs[lang];
        for (let key of Object.keys(i18n)) {
          if (!Array.isArray(i18n[key])) {
            out[key] = {};
            for (let subKey of Object.keys(i18n[key])) {
              out[key][subKey] = i18n[key][subKey][index];
            }
          } else {
            out[key] = i18n[key][index];
          }
        }
      };
      out.langtoggle = function() {
        out.langset(out.currentlang === "en" ? "is" : "en");
        return false;
      };
      out.format = function(str, ...args) {
        return out.mformat(str, ...args).join("");
      };
      out.mformat = function(str, ...args) {
        let split = (str || "").split(/\{|\}/);
        return split.map(function(item) {
          if (regexNumber.test(item)) {
            return args[Number(item)] || item;
          }
          return item;
        });
      };
      out.langset("is");
      module.exports = out;
    }
  });

  // app/api.js
  var require_api = __commonJS({
    "app/api.js"(exports, module) {
      var Authentication2 = require_authentication();
      var lang = require_lang();
      function safeParseReponse(str, status, url) {
        if (status === 0) {
          return new Error(lang.api_down);
        }
        if (str.slice(0, 9) === "<!doctype") {
          if (status === 500) {
            return new Error("Server is temporarily down, try again later.");
          }
          return new Error("Expected JSON but got HTML (" + status + ": " + url.split("?")[0] + ")");
        }
        if (!str) {
          return {};
        }
        try {
          return JSON.parse(str);
        } catch (err) {
          return new Error("Unexpected non-JSON response: " + err.message);
        }
      }
      var api = {
        loading: false,
        sendRequest: function(options, isPagination) {
          api.loading = true;
          let token = Authentication2.getToken();
          let pagination = isPagination;
          if (token) {
            options.headers = options.headers || {};
            options.headers["Authorization"] = "Bearer " + token;
          }
          options.extract = function(xhr) {
            let out = safeParseReponse(xhr.responseText, xhr.status, this.url);
            if (out instanceof Error) {
              throw out;
            }
            if (xhr.status >= 300) {
              if (out.message) {
                throw out;
              }
              console.error("Got error " + xhr.status + " but no error message:", out);
              throw new Error("Unknown or empty response from server.");
            }
            if (pagination) {
              let headers = {};
              xhr.getAllResponseHeaders().split("\r\n").forEach(function(item) {
                let splitted = item.split(": ");
                headers[splitted[0]] = splitted[1];
              });
              out = {
                headers: headers || {},
                data: out
              };
            }
            return out;
          };
          return m.request(options).then(function(res) {
            api.loading = false;
            window.requestAnimationFrame(m.redraw.bind(m));
            return res;
          }).catch(function(error) {
            api.loading = false;
            window.requestAnimationFrame(m.redraw.bind(m));
            if (error.status === 403) {
              Authentication2.clearToken();
              m.route.set("/", { redirect: m.route.get() });
            }
            if (error.response && error.response.status) {
              return Promise.reject(error.response);
            }
            return Promise.reject(error);
          });
        },
        uploadBanner: function(bannerFile, token) {
          var data = new FormData();
          data.append("file", bannerFile);
          data.append("preview", JSON.stringify({
            "out": "base64",
            "format": "avif",
            "resize": {
              "width": 360,
              "height": 203,
              "fit": "cover",
              "withoutEnlargement": true,
              "kernel": "mitchell"
            },
            "avif": {
              "quality": 50,
              "effort": 9
            }
          }));
          data.append("medium", JSON.stringify({
            "format": "avif",
            "resize": {
              "width": 1280,
              "height": 720,
              "fit": "cover",
              "withoutEnlargement": true,
              "kernel": "mitchell"
            },
            "avif": {
              "quality": 75,
              "effort": 3
            }
          }));
          return api.sendRequest({
            method: "POST",
            url: token.resize + "?token=" + token.token,
            body: data
          }).then((banner) => {
            api.sendRequest({
              method: "DELETE",
              url: token.delete + banner.filename + "?token=" + token.token
            }).catch((err) => console.error(err));
            return {
              file: banner,
              size: bannerFile.size,
              medium: {
                filename: banner.medium.filename,
                path: banner.medium.path
              },
              preview: {
                base64: banner.preview.base64
              }
            };
          });
        },
        prettyFormatBytes: function(bytes) {
          if (bytes < 1024) {
            return `${bytes} B`;
          }
          if (bytes < 1024 * 1024) {
            return `${(bytes / 1024).toFixed(1)} KB`;
          }
          if (bytes < 1024 * 1024 * 1024) {
            return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
          }
        },
        uploadFileProgress: function(options, file, reporter) {
          api.loading = true;
          return new Promise(function(res, rej) {
            let report = reporter || function() {
            };
            let formdata = new FormData();
            formdata.append("file", file);
            let request = new XMLHttpRequest();
            let finished = false;
            let lastMarker = /* @__PURE__ */ new Date();
            let lastMarkerLoaded = 0;
            let lastMarkerSpeed = "...";
            request.abortRequest = function() {
              finished = true;
              request.abort();
            };
            request.upload.addEventListener("progress", function(e) {
              let check = /* @__PURE__ */ new Date();
              if (check - lastMarker >= 1e3) {
                let loaded = e.loaded - lastMarkerLoaded;
                lastMarkerSpeed = api.prettyFormatBytes(loaded / ((check - lastMarker) / 1e3));
                lastMarker = check;
                lastMarkerLoaded = e.loaded;
              }
              report(request, Math.min(e.loaded / file.size * 100, 100), lastMarkerSpeed);
            });
            request.addEventListener("abort", function(e) {
              finished = true;
              window.requestAnimationFrame(m.redraw.bind(m));
              rej();
            });
            request.addEventListener("readystatechange", function(e) {
              if (finished)
                return;
              if (request.readyState !== 4)
                return;
              finished = true;
              let out = safeParseReponse(request.responseText, request.status, options.url);
              if (out instanceof Error || request.status >= 300) {
                return rej(out);
              }
              return res(out);
            });
            request.open(options.method || "POST", options.url);
            request.send(formdata);
            report(request, 0);
          }).then(function(res) {
            api.loading = false;
            window.requestAnimationFrame(m.redraw.bind(m));
            return res;
          }, function(err) {
            api.loading = false;
            window.requestAnimationFrame(m.redraw.bind(m));
            return Promise.reject(err);
          });
        }
      };
      module.exports = api;
    }
  });

  // app/videos.js
  var require_videos = __commonJS({
    "app/videos.js"(exports) {
      var m3 = require_mithril();
      var api = require_api();
      var Tree = [];
      var Articles = [];
      exports.Tree = Tree;
      exports.Articles = Articles;
      exports.loading = false;
      exports.error = "";
      exports.year = null;
      exports.month = null;
      var matcher = /\/(\d+)(\/\d+)?/;
      function calculateActiveBranches() {
        let path = matcher.exec(m3.route.get());
        if (path && path[1] !== exports.year?.title) {
          for (let year of Tree) {
            if (year.title === path[1]) {
              exports.year = year;
              break;
            }
          }
        } else if (!path && m3.route.get() === "/") {
          exports.year = Tree[Tree.length - 1];
        } else if (!path) {
          exports.year = null;
        }
        if (path && exports.year && path[2]) {
          exports.month = exports.year.branches[Number(path[2].slice(1)) - 1] || null;
        } else if (!path?.[2]) {
          exports.month = null;
        }
      }
      function rebuildTree() {
        Tree.splice(0, Tree.length);
        if (!Articles.length)
          return;
        let startYear = Articles[0].publish_at;
        let target = /* @__PURE__ */ new Date();
        let articleIndex = 0;
        for (let year = startYear.getFullYear(); year <= target.getFullYear(); year++) {
          let branchYear = {
            title: year.toString(),
            type: "year",
            branches: [],
            videos: []
          };
          Tree.push(branchYear);
          let lastMonth = year === target.getFullYear() ? target.getMonth() + 1 : 12;
          for (let month = 1; month <= lastMonth; month++) {
            let branchMonth = {
              title: month.toString(),
              type: "month",
              branches: [],
              videos: []
            };
            branchYear.branches.push(branchMonth);
            let start2 = new Date(year, month - 1);
            let end2 = new Date(year, month);
            for (; Articles[articleIndex] && Articles[articleIndex].publish_at >= start2 && Articles[articleIndex].publish_at < end2; articleIndex++) {
              branchYear.videos.push(Articles[articleIndex]);
              branchMonth.videos.push(Articles[articleIndex]);
            }
          }
        }
      }
      function removeArticle(id) {
        let index = Articles.findIndex((article) => article.id === id);
        if (index >= 0) {
          Articles.splice(index, 1);
          rebuildTree();
        }
      }
      function refreshTree() {
        exports.error = "";
        if (exports.loading)
          return Promise.resolve();
        exports.loading = true;
        m3.redraw();
        return api.sendRequest({
          method: "GET",
          url: "/api/articles"
        }).then((result) => {
          result.videos.forEach((video) => {
            video.publish_at = new Date(video.publish_at);
            video.path_short = video.path.split("-")[2];
          });
          Articles.splice(0, Articles.length);
          Articles.push.apply(Articles, result.videos);
          rebuildTree();
        }, (err) => {
          exports.error = "Error fetching videos: " + err.message;
        }).then(() => {
          exports.loading = false;
          m3.redraw();
        });
      }
      exports.removeArticle = removeArticle;
      exports.rebuildTree = rebuildTree;
      exports.refreshTree = refreshTree;
      exports.calculateActiveBranches = calculateActiveBranches;
    }
  });

  // app/header.js
  var require_header = __commonJS({
    "app/header.js"(exports, module) {
      var m3 = require_mithril();
      var videos = require_videos();
      var Authentication2 = require_authentication();
      var lang = require_lang();
      var Menu = {
        oninit: function(vnode) {
          this.currentActive = "home";
          this.loading = false;
          if (!videos.Tree.length) {
            videos.refreshTree();
          }
          this.onbeforeupdate();
        },
        onbeforeupdate: function() {
          videos.calculateActiveBranches();
          let currentPath = m3.route.get();
        },
        logOut: function() {
          Authentication2.clearToken();
          m3.route.set("/");
        },
        view: function() {
          let tree = videos.Tree;
          let last = videos.Tree[videos.Tree.length - 1];
          let hasId = m3.route.param("id");
          return [
            m3("nav", [
              m3("h4", m3(
                m3.route.Link,
                { href: "/" },
                lang.header_title
                /* Filadelfia archival center */
              )),
              m3("a.link.changelang", { onclick: lang.langtoggle }, lang.lang_current),
              Authentication2.currentUser?.rank >= 100 ? m3(m3.route.Link, { class: "upload", href: "/upload" }, lang.upload_goto) : null,
              Authentication2.currentUser ? m3(m3.route.Link, { class: "link", href: "/logout" }, lang.logout) : m3(m3.route.Link, { class: "upload", href: "/login" }, lang.login_submit)
              // Upload,
              // m('button.logout', { onclick: this.logOut }, lang.header_logout), // Log out
            ]),
            videos.error ? m3("div.error", { onclick: videos.refreshTree }, [
              videos.error,
              m3("br"),
              "Click here to try again"
            ]) : null,
            !videos.error ? [
              m3(".nav", m3(".inner", tree.map((year) => {
                return m3(m3.route.Link, {
                  class: [
                    videos.year === year ? "active" : "",
                    !year.videos.length ? "empty" : ""
                  ].join(" "),
                  href: ["", videos.year !== year && year !== last || hasId ? year.title : ""].filter((x) => x).join("/") || "/"
                }, year.title);
              }))),
              videos.year ? m3(".nav", m3(".inner", videos.year.branches.map((month) => {
                return m3(m3.route.Link, {
                  class: [
                    videos.month === month ? "active" : "",
                    !month.videos.length ? "empty" : ""
                  ].join(" "),
                  href: ["", videos.year.title, videos.month !== month || hasId ? month.title : null].filter((x) => x).join("/")
                }, lang.months[month.title]);
              }))) : null
            ] : null
          ];
        }
      };
      module.exports = Menu;
    }
  });

  // node_modules/@popperjs/core/lib/enums.js
  var top, bottom, right, left, auto, basePlacements, start, end, clippingParents, viewport, popper, reference, variationPlacements, placements, beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite, modifierPhases;
  var init_enums = __esm({
    "node_modules/@popperjs/core/lib/enums.js"() {
      top = "top";
      bottom = "bottom";
      right = "right";
      left = "left";
      auto = "auto";
      basePlacements = [top, bottom, right, left];
      start = "start";
      end = "end";
      clippingParents = "clippingParents";
      viewport = "viewport";
      popper = "popper";
      reference = "reference";
      variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) {
        return acc.concat([placement + "-" + start, placement + "-" + end]);
      }, []);
      placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) {
        return acc.concat([placement, placement + "-" + start, placement + "-" + end]);
      }, []);
      beforeRead = "beforeRead";
      read = "read";
      afterRead = "afterRead";
      beforeMain = "beforeMain";
      main = "main";
      afterMain = "afterMain";
      beforeWrite = "beforeWrite";
      write = "write";
      afterWrite = "afterWrite";
      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;
  }
  var init_getNodeName = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getNodeName.js"() {
    }
  });

  // 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;
  }
  var init_getWindow = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getWindow.js"() {
    }
  });

  // 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;
  }
  var init_instanceOf = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/instanceOf.js"() {
      init_getWindow();
    }
  });

  // 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;
  var init_applyStyles = __esm({
    "node_modules/@popperjs/core/lib/modifiers/applyStyles.js"() {
      init_getNodeName();
      init_instanceOf();
      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];
  }
  var init_getBasePlacement = __esm({
    "node_modules/@popperjs/core/lib/utils/getBasePlacement.js"() {
    }
  });

  // node_modules/@popperjs/core/lib/utils/math.js
  var max, min, round;
  var init_math = __esm({
    "node_modules/@popperjs/core/lib/utils/math.js"() {
      max = Math.max;
      min = Math.min;
      round = Math.round;
    }
  });

  // node_modules/@popperjs/core/lib/utils/userAgent.js
  function getUAString() {
    var uaData = navigator.userAgentData;
    if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
      return uaData.brands.map(function(item) {
        return item.brand + "/" + item.version;
      }).join(" ");
    }
    return navigator.userAgent;
  }
  var init_userAgent = __esm({
    "node_modules/@popperjs/core/lib/utils/userAgent.js"() {
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js
  function isLayoutViewport() {
    return !/^((?!chrome|android).)*safari/i.test(getUAString());
  }
  var init_isLayoutViewport = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js"() {
      init_userAgent();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
  function getBoundingClientRect(element, includeScale, isFixedStrategy) {
    if (includeScale === void 0) {
      includeScale = false;
    }
    if (isFixedStrategy === void 0) {
      isFixedStrategy = false;
    }
    var clientRect = element.getBoundingClientRect();
    var scaleX = 1;
    var scaleY = 1;
    if (includeScale && isHTMLElement(element)) {
      scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1;
      scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1;
    }
    var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport;
    var addVisualOffsets = !isLayoutViewport() && isFixedStrategy;
    var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX;
    var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY;
    var width = clientRect.width / scaleX;
    var height = clientRect.height / scaleY;
    return {
      width,
      height,
      top: y,
      right: x + width,
      bottom: y + height,
      left: x,
      x,
      y
    };
  }
  var init_getBoundingClientRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js"() {
      init_instanceOf();
      init_math();
      init_getWindow();
      init_isLayoutViewport();
    }
  });

  // 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
    };
  }
  var init_getLayoutRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js"() {
      init_getBoundingClientRect();
    }
  });

  // 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;
  }
  var init_contains = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/contains.js"() {
      init_instanceOf();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
  function getComputedStyle(element) {
    return getWindow(element).getComputedStyle(element);
  }
  var init_getComputedStyle = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js"() {
      init_getWindow();
    }
  });

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

  // node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
  function getDocumentElement(element) {
    return ((isElement(element) ? element.ownerDocument : (
      // $FlowFixMe[prop-missing]
      element.document
    )) || window.document).documentElement;
  }
  var init_getDocumentElement = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js"() {
      init_instanceOf();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
  function getParentNode(element) {
    if (getNodeName(element) === "html") {
      return element;
    }
    return (
      // this is a quicker (but less type safe) way to save quite some bytes from the bundle
      // $FlowFixMe[incompatible-return]
      // $FlowFixMe[prop-missing]
      element.assignedSlot || // step into the shadow DOM of the parent of a slotted node
      element.parentNode || // DOM Element detected
      (isShadowRoot(element) ? element.host : null) || // ShadowRoot detected
      // $FlowFixMe[incompatible-call]: HTMLElement is a Node
      getDocumentElement(element)
    );
  }
  var init_getParentNode = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getParentNode.js"() {
      init_getNodeName();
      init_getDocumentElement();
      init_instanceOf();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
  function getTrueOffsetParent(element) {
    if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837
    getComputedStyle(element).position === "fixed") {
      return null;
    }
    return element.offsetParent;
  }
  function getContainingBlock(element) {
    var isFirefox = /firefox/i.test(getUAString());
    var isIE = /Trident/i.test(getUAString());
    if (isIE && isHTMLElement(element)) {
      var elementCss = getComputedStyle(element);
      if (elementCss.position === "fixed") {
        return null;
      }
    }
    var currentNode = getParentNode(element);
    if (isShadowRoot(currentNode)) {
      currentNode = currentNode.host;
    }
    while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
      var css2 = getComputedStyle(currentNode);
      if (css2.transform !== "none" || css2.perspective !== "none" || css2.contain === "paint" || ["transform", "perspective"].indexOf(css2.willChange) !== -1 || isFirefox && css2.willChange === "filter" || isFirefox && css2.filter && css2.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) && getComputedStyle(offsetParent).position === "static") {
      offsetParent = getTrueOffsetParent(offsetParent);
    }
    if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) {
      return window2;
    }
    return offsetParent || getContainingBlock(element) || window2;
  }
  var init_getOffsetParent = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js"() {
      init_getWindow();
      init_getNodeName();
      init_getComputedStyle();
      init_instanceOf();
      init_isTableElement();
      init_getParentNode();
      init_userAgent();
    }
  });

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

  // 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 v = within(min2, value, max2);
    return v > max2 ? max2 : v;
  }
  var init_within = __esm({
    "node_modules/@popperjs/core/lib/utils/within.js"() {
      init_math();
    }
  });

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

  // node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
  function mergePaddingObject(paddingObject) {
    return Object.assign({}, getFreshSideObject(), paddingObject);
  }
  var init_mergePaddingObject = __esm({
    "node_modules/@popperjs/core/lib/utils/mergePaddingObject.js"() {
      init_getFreshSideObject();
    }
  });

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

  // node_modules/@popperjs/core/lib/modifiers/arrow.js
  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 (!contains(state.elements.popper, arrowElement)) {
      return;
    }
    state.elements.arrow = arrowElement;
  }
  var toPaddingObject, arrow_default;
  var init_arrow = __esm({
    "node_modules/@popperjs/core/lib/modifiers/arrow.js"() {
      init_getBasePlacement();
      init_getLayoutRect();
      init_contains();
      init_getOffsetParent();
      init_getMainAxisFromPlacement();
      init_within();
      init_mergePaddingObject();
      init_expandToHashMap();
      init_enums();
      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));
      };
      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];
  }
  var init_getVariation = __esm({
    "node_modules/@popperjs/core/lib/utils/getVariation.js"() {
    }
  });

  // node_modules/@popperjs/core/lib/modifiers/computeStyles.js
  function roundOffsetsByDPR(_ref, win) {
    var x = _ref.x, y = _ref.y;
    var dpr = win.devicePixelRatio || 1;
    return {
      x: round(x * dpr) / dpr || 0,
      y: round(y * 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, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y;
    var _ref3 = typeof roundOffsets === "function" ? roundOffsets({
      x,
      y
    }) : {
      x,
      y
    };
    x = _ref3.x;
    y = _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 (getComputedStyle(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 && offsetParent === win && win.visualViewport ? win.visualViewport.height : (
          // $FlowFixMe[prop-missing]
          offsetParent[heightProp]
        );
        y -= offsetY - popperRect.height;
        y *= gpuAcceleration ? 1 : -1;
      }
      if (placement === left || (placement === top || placement === bottom) && variation === end) {
        sideX = right;
        var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : (
          // $FlowFixMe[prop-missing]
          offsetParent[widthProp]
        );
        x -= offsetX - popperRect.width;
        x *= gpuAcceleration ? 1 : -1;
      }
    }
    var commonStyles = Object.assign({
      position
    }, adaptive && unsetSides);
    var _ref4 = roundOffsets === true ? roundOffsetsByDPR({
      x,
      y
    }, getWindow(popper2)) : {
      x,
      y
    };
    x = _ref4.x;
    y = _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(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
    }
    return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "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;
    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 unsetSides, computeStyles_default;
  var init_computeStyles = __esm({
    "node_modules/@popperjs/core/lib/modifiers/computeStyles.js"() {
      init_enums();
      init_getOffsetParent();
      init_getWindow();
      init_getDocumentElement();
      init_getComputedStyle();
      init_getBasePlacement();
      init_getVariation();
      init_math();
      unsetSides = {
        top: "auto",
        right: "auto",
        bottom: "auto",
        left: "auto"
      };
      computeStyles_default = {
        name: "computeStyles",
        enabled: true,
        phase: "beforeWrite",
        fn: computeStyles,
        data: {}
      };
    }
  });

  // node_modules/@popperjs/core/lib/modifiers/eventListeners.js
  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 passive, eventListeners_default;
  var init_eventListeners = __esm({
    "node_modules/@popperjs/core/lib/modifiers/eventListeners.js"() {
      init_getWindow();
      passive = {
        passive: true
      };
      eventListeners_default = {
        name: "eventListeners",
        enabled: true,
        phase: "write",
        fn: function fn() {
        },
        effect: effect3,
        data: {}
      };
    }
  });

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

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

  // 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
    };
  }
  var init_getWindowScroll = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js"() {
      init_getWindow();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
  function getWindowScrollBarX(element) {
    return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
  }
  var init_getWindowScrollBarX = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js"() {
      init_getBoundingClientRect();
      init_getDocumentElement();
      init_getWindowScroll();
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
  function getViewportRect(element, strategy) {
    var win = getWindow(element);
    var html = getDocumentElement(element);
    var visualViewport = win.visualViewport;
    var width = html.clientWidth;
    var height = html.clientHeight;
    var x = 0;
    var y = 0;
    if (visualViewport) {
      width = visualViewport.width;
      height = visualViewport.height;
      var layoutViewport = isLayoutViewport();
      if (layoutViewport || !layoutViewport && strategy === "fixed") {
        x = visualViewport.offsetLeft;
        y = visualViewport.offsetTop;
      }
    }
    return {
      width,
      height,
      x: x + getWindowScrollBarX(element),
      y
    };
  }
  var init_getViewportRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js"() {
      init_getWindow();
      init_getDocumentElement();
      init_getWindowScrollBarX();
      init_isLayoutViewport();
    }
  });

  // 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 x = -winScroll.scrollLeft + getWindowScrollBarX(element);
    var y = -winScroll.scrollTop;
    if (getComputedStyle(body || html).direction === "rtl") {
      x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
    }
    return {
      width,
      height,
      x,
      y
    };
  }
  var init_getDocumentRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js"() {
      init_getDocumentElement();
      init_getComputedStyle();
      init_getWindowScrollBarX();
      init_getWindowScroll();
      init_math();
    }
  });

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

  // 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));
  }
  var init_getScrollParent = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js"() {
      init_getParentNode();
      init_isScrollParent();
      init_getNodeName();
      init_instanceOf();
    }
  });

  // 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 : (
      // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here
      updatedList.concat(listScrollParents(getParentNode(target)))
    );
  }
  var init_listScrollParents = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js"() {
      init_getScrollParent();
      init_getParentNode();
      init_getWindow();
      init_isScrollParent();
    }
  });

  // 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
    });
  }
  var init_rectToClientRect = __esm({
    "node_modules/@popperjs/core/lib/utils/rectToClientRect.js"() {
    }
  });

  // node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
  function getInnerBoundingClientRect(element, strategy) {
    var rect = getBoundingClientRect(element, false, strategy === "fixed");
    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, strategy) {
    return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
  }
  function getClippingParents(element) {
    var clippingParents2 = listScrollParents(getParentNode(element));
    var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(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, strategy) {
    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, strategy);
      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, strategy));
    clippingRect.width = clippingRect.right - clippingRect.left;
    clippingRect.height = clippingRect.bottom - clippingRect.top;
    clippingRect.x = clippingRect.left;
    clippingRect.y = clippingRect.top;
    return clippingRect;
  }
  var init_getClippingRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js"() {
      init_enums();
      init_getViewportRect();
      init_getDocumentRect();
      init_listScrollParents();
      init_getOffsetParent();
      init_getDocumentElement();
      init_getComputedStyle();
      init_instanceOf();
      init_getBoundingClientRect();
      init_getParentNode();
      init_contains();
      init_getNodeName();
      init_rectToClientRect();
      init_math();
    }
  });

  // 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 start:
          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;
  }
  var init_computeOffsets = __esm({
    "node_modules/@popperjs/core/lib/utils/computeOffsets.js"() {
      init_getBasePlacement();
      init_getVariation();
      init_getMainAxisFromPlacement();
      init_enums();
    }
  });

  // 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$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _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, strategy);
    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;
  }
  var init_detectOverflow = __esm({
    "node_modules/@popperjs/core/lib/utils/detectOverflow.js"() {
      init_getClippingRect();
      init_getDocumentElement();
      init_getBoundingClientRect();
      init_computeOffsets();
      init_rectToClientRect();
      init_enums();
      init_instanceOf();
      init_mergePaddingObject();
      init_expandToHashMap();
    }
  });

  // 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;
    }
    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(a, b) {
      return overflows[a] - overflows[b];
    });
  }
  var init_computeAutoPlacement = __esm({
    "node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js"() {
      init_getVariation();
      init_enums();
      init_detectOverflow();
      init_getBasePlacement();
    }
  });

  // 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 i = 0; i < placements2.length; i++) {
      var placement = placements2[i];
      var _basePlacement = getBasePlacement(placement);
      var isStartVariation = getVariation(placement) === start;
      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(_i2) {
        var fittingPlacement = placements2.find(function(placement2) {
          var checks2 = checksMap.get(placement2);
          if (checks2) {
            return checks2.slice(0, _i2).every(function(check) {
              return check;
            });
          }
        });
        if (fittingPlacement) {
          firstFittingPlacement = fittingPlacement;
          return "break";
        }
      };
      for (var _i = numberOfChecks; _i > 0; _i--) {
        var _ret = _loop(_i);
        if (_ret === "break")
          break;
      }
    }
    if (state.placement !== firstFittingPlacement) {
      state.modifiersData[name]._skip = true;
      state.placement = firstFittingPlacement;
      state.reset = true;
    }
  }
  var flip_default;
  var init_flip = __esm({
    "node_modules/@popperjs/core/lib/modifiers/flip.js"() {
      init_getOppositePlacement();
      init_getBasePlacement();
      init_getOppositeVariationPlacement();
      init_detectOverflow();
      init_computeAutoPlacement();
      init_enums();
      init_getVariation();
      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;
  var init_hide = __esm({
    "node_modules/@popperjs/core/lib/modifiers/hide.js"() {
      init_enums();
      init_detectOverflow();
      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], x = _data$state$placement.x, y = _data$state$placement.y;
    if (state.modifiersData.popperOffsets != null) {
      state.modifiersData.popperOffsets.x += x;
      state.modifiersData.popperOffsets.y += y;
    }
    state.modifiersData[name] = data;
  }
  var offset_default;
  var init_offset = __esm({
    "node_modules/@popperjs/core/lib/modifiers/offset.js"() {
      init_getBasePlacement();
      init_enums();
      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;
  var init_popperOffsets = __esm({
    "node_modules/@popperjs/core/lib/modifiers/popperOffsets.js"() {
      init_computeOffsets();
      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";
  }
  var init_getAltAxis = __esm({
    "node_modules/@popperjs/core/lib/utils/getAltAxis.js"() {
    }
  });

  // 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 === start ? referenceRect[len] : popperRect[len];
      var maxLen = variation === start ? -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;
  var init_preventOverflow = __esm({
    "node_modules/@popperjs/core/lib/modifiers/preventOverflow.js"() {
      init_enums();
      init_getBasePlacement();
      init_getMainAxisFromPlacement();
      init_getAltAxis();
      init_within();
      init_getLayoutRect();
      init_getOffsetParent();
      init_detectOverflow();
      init_getVariation();
      init_getFreshSideObject();
      init_math();
      preventOverflow_default = {
        name: "preventOverflow",
        enabled: true,
        phase: "main",
        fn: preventOverflow,
        requiresIfExists: ["offset"]
      };
    }
  });

  // node_modules/@popperjs/core/lib/modifiers/index.js
  var init_modifiers = __esm({
    "node_modules/@popperjs/core/lib/modifiers/index.js"() {
      init_applyStyles();
      init_arrow();
      init_computeStyles();
      init_eventListeners();
      init_flip();
      init_hide();
      init_offset();
      init_popperOffsets();
      init_preventOverflow();
    }
  });

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

  // 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);
    }
  }
  var init_getNodeScroll = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js"() {
      init_getWindowScroll();
      init_getWindow();
      init_instanceOf();
      init_getHTMLElementScroll();
    }
  });

  // 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, isFixed);
    var scroll = {
      scrollLeft: 0,
      scrollTop: 0
    };
    var offsets = {
      x: 0,
      y: 0
    };
    if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
      if (getNodeName(offsetParent) !== "body" || // https://github.com/popperjs/popper-core/issues/1078
      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
    };
  }
  var init_getCompositeRect = __esm({
    "node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js"() {
      init_getBoundingClientRect();
      init_getNodeScroll();
      init_getNodeName();
      init_instanceOf();
      init_getWindowScrollBarX();
      init_getDocumentElement();
      init_isScrollParent();
      init_math();
    }
  });

  // node_modules/@popperjs/core/lib/utils/orderModifiers.js
  function order(modifiers) {
    var map = /* @__PURE__ */ new Map();
    var visited = /* @__PURE__ */ new Set();
    var result = [];
    modifiers.forEach(function(modifier) {
      map.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 = map.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;
      }));
    }, []);
  }
  var init_orderModifiers = __esm({
    "node_modules/@popperjs/core/lib/utils/orderModifiers.js"() {
      init_enums();
    }
  });

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

  // 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];
    });
  }
  var init_mergeByName = __esm({
    "node_modules/@popperjs/core/lib/utils/mergeByName.js"() {
    }
  });

  // node_modules/@popperjs/core/lib/createPopper.js
  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, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
    return function createPopper4(reference2, popper2, options) {
      if (options === void 0) {
        options = defaultOptions;
      }
      var state = {
        placement: "bottom",
        orderedModifiers: [],
        options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
        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({}, defaultOptions, 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(m3) {
            return m3.enabled;
          });
          runModifierEffects();
          return instance.update();
        },
        // Sync update – it will always be executed, even if not necessary. This
        // is useful for low frequency updates where sync behavior simplifies the
        // logic.
        // For high frequency updates (e.g. `resize` and `scroll` events), always
        // prefer the async Popper#update method
        forceUpdate: function forceUpdate() {
          if (isDestroyed) {
            return;
          }
          var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
          if (!areValidElements(reference3, popper3)) {
            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);
          });
          for (var index = 0; index < state.orderedModifiers.length; index++) {
            if (state.reset === true) {
              state.reset = false;
              index = -1;
              continue;
            }
            var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name;
            if (typeof fn2 === "function") {
              state = fn2({
                state,
                options: _options,
                name,
                instance
              }) || state;
            }
          }
        },
        // Async and optimistically optimized update – it will not be executed if
        // not necessary (debounced to run at most once-per-tick)
        update: debounce(function() {
          return new Promise(function(resolve) {
            instance.forceUpdate();
            resolve(state);
          });
        }),
        destroy: function destroy() {
          cleanupModifierEffects();
          isDestroyed = true;
        }
      };
      if (!areValidElements(reference2, popper2)) {
        return instance;
      }
      instance.setOptions(options).then(function(state2) {
        if (!isDestroyed && options.onFirstUpdate) {
          options.onFirstUpdate(state2);
        }
      });
      function runModifierEffects() {
        state.orderedModifiers.forEach(function(_ref) {
          var name = _ref.name, _ref$options = _ref.options, options2 = _ref$options === void 0 ? {} : _ref$options, effect4 = _ref.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(fn2) {
          return fn2();
        });
        effectCleanupFns = [];
      }
      return instance;
    };
  }
  var DEFAULT_OPTIONS, createPopper;
  var init_createPopper = __esm({
    "node_modules/@popperjs/core/lib/createPopper.js"() {
      init_getCompositeRect();
      init_getLayoutRect();
      init_listScrollParents();
      init_getOffsetParent();
      init_orderModifiers();
      init_debounce();
      init_mergeByName();
      init_detectOverflow();
      init_instanceOf();
      DEFAULT_OPTIONS = {
        placement: "bottom",
        modifiers: [],
        strategy: "absolute"
      };
      createPopper = /* @__PURE__ */ popperGenerator();
    }
  });

  // node_modules/@popperjs/core/lib/popper-lite.js
  var defaultModifiers, createPopper2;
  var init_popper_lite = __esm({
    "node_modules/@popperjs/core/lib/popper-lite.js"() {
      init_createPopper();
      init_eventListeners();
      init_popperOffsets();
      init_computeStyles();
      init_applyStyles();
      defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default];
      createPopper2 = /* @__PURE__ */ popperGenerator({
        defaultModifiers
      });
    }
  });

  // node_modules/@popperjs/core/lib/popper.js
  var defaultModifiers2, createPopper3;
  var init_popper = __esm({
    "node_modules/@popperjs/core/lib/popper.js"() {
      init_createPopper();
      init_eventListeners();
      init_popperOffsets();
      init_computeStyles();
      init_applyStyles();
      init_offset();
      init_flip();
      init_preventOverflow();
      init_arrow();
      init_hide();
      init_modifiers();
      defaultModifiers2 = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default];
      createPopper3 = /* @__PURE__ */ popperGenerator({
        defaultModifiers: defaultModifiers2
      });
    }
  });

  // 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: () => start,
    top: () => top,
    variationPlacements: () => variationPlacements,
    viewport: () => viewport,
    write: () => write
  });
  var init_lib = __esm({
    "node_modules/@popperjs/core/lib/index.js"() {
      init_enums();
      init_modifiers();
      init_createPopper();
      init_popper();
      init_popper_lite();
    }
  });

  // node_modules/@eonasdan/tempus-dominus/dist/js/tempus-dominus.js
  var require_tempus_dominus = __commonJS({
    "node_modules/@eonasdan/tempus-dominus/dist/js/tempus-dominus.js"(exports, module) {
      (function(global2, factory) {
        typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.tempusDominus = {}));
      })(exports, function(exports2) {
        "use strict";
        class TdError extends Error {
        }
        class ErrorMessages {
          constructor() {
            this.base = "TD:";
            this.failedToSetInvalidDate = "Failed to set invalid date";
            this.failedToParseInput = "Failed parse input field";
          }
          //#region out to console
          /**
           * Throws an error indicating that a key in the options object is invalid.
           * @param optionName
           */
          unexpectedOption(optionName) {
            const error = new TdError(`${this.base} Unexpected option: ${optionName} does not match a known option.`);
            error.code = 1;
            throw error;
          }
          /**
           * Throws an error indicating that one more keys in the options object is invalid.
           * @param optionName
           */
          unexpectedOptions(optionName) {
            const error = new TdError(`${this.base}: ${optionName.join(", ")}`);
            error.code = 1;
            throw error;
          }
          /**
           * Throws an error when an option is provide an unsupported value.
           * For example a value of 'cheese' for toolbarPlacement which only supports
           * 'top', 'bottom', 'default'.
           * @param optionName
           * @param badValue
           * @param validOptions
           */
          unexpectedOptionValue(optionName, badValue, validOptions) {
            const error = new TdError(`${this.base} Unexpected option value: ${optionName} does not accept a value of "${badValue}". Valid values are: ${validOptions.join(", ")}`);
            error.code = 2;
            throw error;
          }
          /**
           * Throws an error when an option value is the wrong type.
           * For example a string value was provided to multipleDates which only
           * supports true or false.
           * @param optionName
           * @param badType
           * @param expectedType
           */
          typeMismatch(optionName, badType, expectedType) {
            const error = new TdError(`${this.base} Mismatch types: ${optionName} has a type of ${badType} instead of the required ${expectedType}`);
            error.code = 3;
            throw error;
          }
          /**
           * Throws an error when an option value is  outside of the expected range.
           * For example restrictions.daysOfWeekDisabled excepts a value between 0 and 6.
           * @param optionName
           * @param lower
           * @param upper
           */
          numbersOutOfRange(optionName, lower, upper) {
            const error = new TdError(`${this.base} ${optionName} expected an array of number between ${lower} and ${upper}.`);
            error.code = 4;
            throw error;
          }
          /**
           * Throws an error when a value for a date options couldn't be parsed. Either
           * the option was an invalid string or an invalid Date object.
           * @param optionName
           * @param date
           * @param soft If true, logs a warning instead of an error.
           */
          //eslint-disable-next-line @typescript-eslint/no-explicit-any
          failedToParseDate(optionName, date, soft = false) {
            const error = new TdError(`${this.base} Could not correctly parse "${date}" to a date for ${optionName}.`);
            error.code = 5;
            if (!soft)
              throw error;
            console.warn(error);
          }
          /**
           * Throws when an element to attach to was not provided in the constructor.
           */
          mustProvideElement() {
            const error = new TdError(`${this.base} No element was provided.`);
            error.code = 6;
            throw error;
          }
          /**
           * Throws if providing an array for the events to subscribe method doesn't have
           * the same number of callbacks. E.g., subscribe([1,2], [1])
           */
          subscribeMismatch() {
            const error = new TdError(`${this.base} The subscribed events does not match the number of callbacks`);
            error.code = 7;
            throw error;
          }
          /**
           * Throws if the configuration has conflicting rules e.g. minDate is after maxDate
           */
          conflictingConfiguration(message) {
            const error = new TdError(`${this.base} A configuration value conflicts with another rule. ${message}`);
            error.code = 8;
            throw error;
          }
          /**
           * customDateFormat errors
           */
          customDateFormatError(message) {
            const error = new TdError(`${this.base} Custom Date Format: ${message}`);
            error.code = 9;
            throw error;
          }
          /**
           * Logs a warning if a date option value is provided as a string, instead of
           * a date/datetime object.
           */
          dateString() {
            console.warn(`${this.base} Using a string for date options is not recommended unless you specify an ISO string or use the customDateFormat plugin.`);
          }
          deprecatedWarning(message, remediation) {
            console.warn(`${this.base} Warning ${message} is deprecated and will be removed in a future version. ${remediation}`);
          }
          throwError(message) {
            const error = new TdError(`${this.base} ${message}`);
            error.code = 9;
            throw error;
          }
        }
        const NAME = "tempus-dominus", dataKey = "td";
        class Events {
          constructor() {
            this.key = `.${dataKey}`;
            this.change = `change${this.key}`;
            this.update = `update${this.key}`;
            this.error = `error${this.key}`;
            this.show = `show${this.key}`;
            this.hide = `hide${this.key}`;
            this.blur = `blur${this.key}`;
            this.focus = `focus${this.key}`;
            this.keyup = `keyup${this.key}`;
            this.keydown = `keydown${this.key}`;
          }
        }
        class Css {
          constructor() {
            this.widget = `${NAME}-widget`;
            this.calendarHeader = "calendar-header";
            this.switch = "picker-switch";
            this.toolbar = "toolbar";
            this.noHighlight = "no-highlight";
            this.sideBySide = "timepicker-sbs";
            this.previous = "previous";
            this.next = "next";
            this.disabled = "disabled";
            this.old = "old";
            this.new = "new";
            this.active = "active";
            this.dateContainer = "date-container";
            this.decadesContainer = `${this.dateContainer}-decades`;
            this.decade = "decade";
            this.yearsContainer = `${this.dateContainer}-years`;
            this.year = "year";
            this.monthsContainer = `${this.dateContainer}-months`;
            this.month = "month";
            this.daysContainer = `${this.dateContainer}-days`;
            this.day = "day";
            this.calendarWeeks = "cw";
            this.dayOfTheWeek = "dow";
            this.today = "today";
            this.weekend = "weekend";
            this.rangeIn = "range-in";
            this.rangeStart = "range-start";
            this.rangeEnd = "range-end";
            this.timeContainer = "time-container";
            this.separator = "separator";
            this.clockContainer = `${this.timeContainer}-clock`;
            this.hourContainer = `${this.timeContainer}-hour`;
            this.minuteContainer = `${this.timeContainer}-minute`;
            this.secondContainer = `${this.timeContainer}-second`;
            this.hour = "hour";
            this.minute = "minute";
            this.second = "second";
            this.toggleMeridiem = "toggleMeridiem";
            this.show = "show";
            this.collapsing = "td-collapsing";
            this.collapse = "td-collapse";
            this.inline = "inline";
            this.lightTheme = "light";
            this.darkTheme = "dark";
            this.isDarkPreferredQuery = "(prefers-color-scheme: dark)";
          }
        }
        class Namespace {
        }
        Namespace.NAME = NAME;
        Namespace.dataKey = dataKey;
        Namespace.events = new Events();
        Namespace.css = new Css();
        Namespace.errorMessages = new ErrorMessages();
        const DefaultFormatLocalization = {
          dateFormats: {
            LTS: "h:mm:ss T",
            LT: "h:mm T",
            L: "MM/dd/yyyy",
            LL: "MMMM d, yyyy",
            LLL: "MMMM d, yyyy h:mm T",
            LLLL: "dddd, MMMM d, yyyy h:mm T"
          },
          format: "L LT",
          locale: "default",
          hourCycle: void 0,
          ordinal: (n) => {
            const s = ["th", "st", "nd", "rd"];
            const v = n % 100;
            return `[${n}${s[(v - 20) % 10] || s[v] || s[0]}]`;
          }
        };
        var DefaultFormatLocalization$1 = { ...DefaultFormatLocalization };
        exports2.Unit = void 0;
        (function(Unit) {
          Unit["seconds"] = "seconds";
          Unit["minutes"] = "minutes";
          Unit["hours"] = "hours";
          Unit["date"] = "date";
          Unit["month"] = "month";
          Unit["year"] = "year";
        })(exports2.Unit || (exports2.Unit = {}));
        const twoDigitTemplate = {
          month: "2-digit",
          day: "2-digit",
          year: "numeric",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit"
        };
        const getFormatByUnit = (unit) => {
          switch (unit) {
            case "date":
              return { dateStyle: "short" };
            case "month":
              return {
                month: "numeric",
                year: "numeric"
              };
            case "year":
              return { year: "numeric" };
          }
        };
        const guessHourCycle = (locale2) => {
          if (!locale2)
            return "h12";
          const template = {
            hour: "2-digit",
            minute: "2-digit",
            numberingSystem: "latn"
          };
          const dt = new DateTime().setLocalization({ locale: locale2 });
          dt.hours = 0;
          const start2 = dt.parts(void 0, template).hour;
          if (start2 === "12")
            return "h12";
          if (start2 === "24")
            return "h24";
          dt.hours = 23;
          const end2 = dt.parts(void 0, template).hour;
          if (start2 === "00" && end2 === "11")
            return "h11";
          if (start2 === "00" && end2 === "23")
            return "h23";
          console.warn(`couldn't determine hour cycle for ${locale2}. start: ${start2}. end: ${end2}`);
          return void 0;
        };
        class DateTime extends Date {
          constructor() {
            super(...arguments);
            this.localization = DefaultFormatLocalization$1;
            this.nonLeapLadder = [
              0,
              31,
              59,
              90,
              120,
              151,
              181,
              212,
              243,
              273,
              304,
              334
            ];
            this.leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
            this.dateTimeRegex = //is regex cannot be simplified beyond what it already is
            /(\[[^[\]]*])|y{1,4}|M{1,4}|d{1,4}|H{1,2}|h{1,2}|t|T|m{1,2}|s{1,2}|f{3}/g;
            this.formattingTokens = /(\[[^[\]]*])|([-_:/.,()\s]+)|(T|t|yyyy|yy?|MM?M?M?|Do|dd?|hh?|HH?|mm?|ss?)/g;
            this.match2 = /\d\d/;
            this.match3 = /\d{3}/;
            this.match4 = /\d{4}/;
            this.match1to2 = /\d\d?/;
            this.matchSigned = /[+-]?\d+/;
            this.matchOffset = /[+-]\d\d:?(\d\d)?|Z/;
            this.matchWord = /[^\d_:/,\-()\s]+/;
            this.zoneExpressions = [
              this.matchOffset,
              (obj, input) => {
                obj.offset = this.offsetFromString(input);
              }
            ];
            this.expressions = {
              t: {
                pattern: void 0,
                parser: (obj, input) => {
                  obj.afternoon = this.meridiemMatch(input);
                }
              },
              T: {
                pattern: void 0,
                parser: (obj, input) => {
                  obj.afternoon = this.meridiemMatch(input);
                }
              },
              fff: {
                pattern: this.match3,
                parser: (obj, input) => {
                  obj.milliseconds = +input;
                }
              },
              s: {
                pattern: this.match1to2,
                parser: this.addInput("seconds")
              },
              ss: {
                pattern: this.match1to2,
                parser: this.addInput("seconds")
              },
              m: {
                pattern: this.match1to2,
                parser: this.addInput("minutes")
              },
              mm: {
                pattern: this.match1to2,
                parser: this.addInput("minutes")
              },
              H: {
                pattern: this.match1to2,
                parser: this.addInput("hours")
              },
              h: {
                pattern: this.match1to2,
                parser: this.addInput("hours")
              },
              HH: {
                pattern: this.match1to2,
                parser: this.addInput("hours")
              },
              hh: {
                pattern: this.match1to2,
                parser: this.addInput("hours")
              },
              d: {
                pattern: this.match1to2,
                parser: this.addInput("day")
              },
              dd: {
                pattern: this.match2,
                parser: this.addInput("day")
              },
              Do: {
                pattern: this.matchWord,
                parser: (obj, input) => {
                  obj.day = +(input.match(/\d+/)[0] || 1);
                  if (!this.localization.ordinal)
                    return;
                  for (let i = 1; i <= 31; i += 1) {
                    if (this.localization.ordinal(i).replace(/[[\]]/g, "") === input) {
                      obj.day = i;
                    }
                  }
                }
              },
              M: {
                pattern: this.match1to2,
                parser: this.addInput("month")
              },
              MM: {
                pattern: this.match2,
                parser: this.addInput("month")
              },
              MMM: {
                pattern: this.matchWord,
                parser: (obj, input) => {
                  const months = this.getAllMonths();
                  const monthsShort = this.getAllMonths("short");
                  const matchIndex = (monthsShort || months.map((_) => _.slice(0, 3))).indexOf(input) + 1;
                  if (matchIndex < 1) {
                    throw new Error();
                  }
                  obj.month = matchIndex % 12 || matchIndex;
                }
              },
              MMMM: {
                pattern: this.matchWord,
                parser: (obj, input) => {
                  const months = this.getAllMonths();
                  const matchIndex = months.indexOf(input) + 1;
                  if (matchIndex < 1) {
                    throw new Error();
                  }
                  obj.month = matchIndex % 12 || matchIndex;
                }
              },
              y: {
                pattern: this.matchSigned,
                parser: this.addInput("year")
              },
              yy: {
                pattern: this.match2,
                parser: (obj, input) => {
                  obj.year = this.parseTwoDigitYear(+input);
                }
              },
              yyyy: {
                pattern: this.match4,
                parser: this.addInput("year")
              }
              // z: this.zoneExpressions,
              // zz: this.zoneExpressions,
              // zzz: this.zoneExpressions
            };
          }
          /**
           * Chainable way to set the {@link locale}
           * @param value
           * @deprecated use setLocalization with a FormatLocalization object instead
           */
          setLocale(value) {
            if (!this.localization) {
              this.localization = DefaultFormatLocalization$1;
              this.localization.locale = value;
            }
            return this;
          }
          /**
           * Chainable way to set the {@link localization}
           * @param value
           */
          setLocalization(value) {
            this.localization = value;
            return this;
          }
          /**
           * Converts a plain JS date object to a DateTime object.
           * Doing this allows access to format, etc.
           * @param  date
           * @param locale this parameter is deprecated. Use formatLocalization instead.
           * @param formatLocalization
           */
          static convert(date, locale2 = "default", formatLocalization = void 0) {
            if (!date)
              throw new Error(`A date is required`);
            if (!formatLocalization) {
              formatLocalization = DefaultFormatLocalization$1;
              formatLocalization.locale = locale2;
            }
            return new DateTime(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()).setLocalization(formatLocalization);
          }
          /**
           * Native date manipulations are not pure functions. This function creates a duplicate of the DateTime object.
           */
          get clone() {
            return new DateTime(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.getMilliseconds()).setLocalization(this.localization);
          }
          static isValid(d) {
            if (d === void 0 || JSON.stringify(d) === "null")
              return false;
            if (d.constructor.name === DateTime.name)
              return true;
            return false;
          }
          /**
           * Sets the current date to the start of the {@link unit} provided
           * Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).startOf('month')
           * would return April 1, 2021, 12:00:00.000 AM (midnight)
           * @param unit
           * @param startOfTheWeek Allows for the changing the start of the week.
           */
          startOf(unit, startOfTheWeek = 0) {
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            switch (unit) {
              case "seconds":
                this.setMilliseconds(0);
                break;
              case "minutes":
                this.setSeconds(0, 0);
                break;
              case "hours":
                this.setMinutes(0, 0, 0);
                break;
              case "date":
                this.setHours(0, 0, 0, 0);
                break;
              case "weekDay": {
                this.startOf(exports2.Unit.date);
                if (this.weekDay === startOfTheWeek)
                  break;
                const goBack = (this.weekDay - startOfTheWeek + 7) % 7;
                this.manipulate(goBack * -1, exports2.Unit.date);
                break;
              }
              case "month":
                this.startOf(exports2.Unit.date);
                this.setDate(1);
                break;
              case "year":
                this.startOf(exports2.Unit.date);
                this.setMonth(0, 1);
                break;
            }
            return this;
          }
          /**
           * Sets the current date to the end of the {@link unit} provided
           * Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).endOf('month')
           * would return April 30, 2021, 11:59:59.999 PM
           * @param unit
           * @param startOfTheWeek
           */
          endOf(unit, startOfTheWeek = 0) {
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            switch (unit) {
              case "seconds":
                this.setMilliseconds(999);
                break;
              case "minutes":
                this.setSeconds(59, 999);
                break;
              case "hours":
                this.setMinutes(59, 59, 999);
                break;
              case "date":
                this.setHours(23, 59, 59, 999);
                break;
              case "weekDay": {
                this.endOf(exports2.Unit.date);
                const endOfWeek = 6 + startOfTheWeek;
                if (this.weekDay === endOfWeek)
                  break;
                this.manipulate(endOfWeek - this.weekDay, exports2.Unit.date);
                break;
              }
              case "month":
                this.endOf(exports2.Unit.date);
                this.manipulate(1, exports2.Unit.month);
                this.setDate(0);
                break;
              case "year":
                this.endOf(exports2.Unit.date);
                this.setMonth(11, 31);
                break;
            }
            return this;
          }
          /**
           * Change a {@link unit} value. Value can be positive or negative
           * Example: Consider a date of "April 30, 2021, 11:45:32.984 AM" => new DateTime(2021, 3, 30, 11, 45, 32, 984).manipulate(1, 'month')
           * would return May 30, 2021, 11:45:32.984 AM
           * @param value A positive or negative number
           * @param unit
           */
          manipulate(value, unit) {
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            this[unit] += value;
            return this;
          }
          /**
           * Return true if {@link compare} is before this date
           * @param compare The Date/DateTime to compare
           * @param unit If provided, uses {@link startOf} for
           * comparison.
           */
          isBefore(compare, unit) {
            if (!DateTime.isValid(compare))
              return false;
            if (!unit)
              return this.valueOf() < compare.valueOf();
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            return this.clone.startOf(unit).valueOf() < compare.clone.startOf(unit).valueOf();
          }
          /**
           * Return true if {@link compare} is after this date
           * @param compare The Date/DateTime to compare
           * @param unit If provided, uses {@link startOf} for
           * comparison.
           */
          isAfter(compare, unit) {
            if (!DateTime.isValid(compare))
              return false;
            if (!unit)
              return this.valueOf() > compare.valueOf();
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            return this.clone.startOf(unit).valueOf() > compare.clone.startOf(unit).valueOf();
          }
          /**
           * Return true if {@link compare} is same this date
           * @param compare The Date/DateTime to compare
           * @param unit If provided, uses {@link startOf} for
           * comparison.
           */
          isSame(compare, unit) {
            if (!DateTime.isValid(compare))
              return false;
            if (!unit)
              return this.valueOf() === compare.valueOf();
            if (this[unit] === void 0)
              throw new Error(`Unit '${unit}' is not valid`);
            compare = DateTime.convert(compare);
            return this.clone.startOf(unit).valueOf() === compare.startOf(unit).valueOf();
          }
          /**
           * Check if this is between two other DateTimes, optionally looking at unit scale. The match is exclusive.
           * @param left
           * @param right
           * @param unit.
           * @param inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion.
           * If the inclusivity parameter is used, both indicators must be passed.
           */
          isBetween(left2, right2, unit, inclusivity = "()") {
            if (!DateTime.isValid(left2) || !DateTime.isValid(right2))
              return false;
            if (unit && this[unit] === void 0) {
              throw new Error(`Unit '${unit}' is not valid`);
            }
            const leftInclusivity = inclusivity[0] === "(";
            const rightInclusivity = inclusivity[1] === ")";
            const isLeftInRange = leftInclusivity ? this.isAfter(left2, unit) : !this.isBefore(left2, unit);
            const isRightInRange = rightInclusivity ? this.isBefore(right2, unit) : !this.isAfter(right2, unit);
            return isLeftInRange && isRightInRange;
          }
          /**
           * Returns flattened object of the date. Does not include literals
           * @param locale
           * @param template
           */
          parts(locale2 = this.localization.locale, template = { dateStyle: "full", timeStyle: "long" }) {
            const parts = {};
            new Intl.DateTimeFormat(locale2, template).formatToParts(this).filter((x) => x.type !== "literal").forEach((x) => parts[x.type] = x.value);
            return parts;
          }
          /**
           * Shortcut to Date.getSeconds()
           */
          get seconds() {
            return this.getSeconds();
          }
          /**
           * Shortcut to Date.setSeconds()
           */
          set seconds(value) {
            this.setSeconds(value);
          }
          /**
           * Returns two digit hours
           */
          get secondsFormatted() {
            return this.parts(void 0, twoDigitTemplate).second;
          }
          /**
           * Shortcut to Date.getMinutes()
           */
          get minutes() {
            return this.getMinutes();
          }
          /**
           * Shortcut to Date.setMinutes()
           */
          set minutes(value) {
            this.setMinutes(value);
          }
          /**
           * Returns two digit minutes
           */
          get minutesFormatted() {
            return this.parts(void 0, twoDigitTemplate).minute;
          }
          /**
           * Shortcut to Date.getHours()
           */
          get hours() {
            return this.getHours();
          }
          /**
           * Shortcut to Date.setHours()
           */
          set hours(value) {
            this.setHours(value);
          }
          /**
           * Returns two digit hour, e.g. 01...10
           * @param hourCycle Providing an hour cycle will change 00 to 24 depending on the given value.
           */
          getHoursFormatted(hourCycle = "h12") {
            return this.parts(void 0, { ...twoDigitTemplate, hourCycle }).hour;
          }
          /**
           * Get the meridiem of the date. E.g. AM or PM.
           * If the {@link locale} provides a "dayPeriod" then this will be returned,
           * otherwise it will return AM or PM.
           * @param locale
           */
          meridiem(locale2 = this.localization.locale) {
            return new Intl.DateTimeFormat(locale2, {
              hour: "numeric",
              hour12: true
            }).formatToParts(this).find((p) => p.type === "dayPeriod")?.value;
          }
          /**
           * Shortcut to Date.getDate()
           */
          get date() {
            return this.getDate();
          }
          /**
           * Shortcut to Date.setDate()
           */
          set date(value) {
            this.setDate(value);
          }
          /**
           * Return two digit date
           */
          get dateFormatted() {
            return this.parts(void 0, twoDigitTemplate).day;
          }
          /**
           * Shortcut to Date.getDay()
           */
          get weekDay() {
            return this.getDay();
          }
          /**
           * Shortcut to Date.getMonth()
           */
          get month() {
            return this.getMonth();
          }
          /**
           * Shortcut to Date.setMonth()
           */
          set month(value) {
            const targetMonth = new Date(this.year, value + 1);
            targetMonth.setDate(0);
            const endOfMonth = targetMonth.getDate();
            if (this.date > endOfMonth) {
              this.date = endOfMonth;
            }
            this.setMonth(value);
          }
          /**
           * Return two digit, human expected month. E.g. January = 1, December = 12
           */
          get monthFormatted() {
            return this.parts(void 0, twoDigitTemplate).month;
          }
          /**
           * Shortcut to Date.getFullYear()
           */
          get year() {
            return this.getFullYear();
          }
          /**
           * Shortcut to Date.setFullYear()
           */
          set year(value) {
            this.setFullYear(value);
          }
          // borrowed a bunch of stuff from Luxon
          /**
           * Gets the week of the year
           */
          get week() {
            const ordinal = this.computeOrdinal(), weekday = this.getUTCDay();
            let weekNumber = Math.floor((ordinal - weekday + 10) / 7);
            if (weekNumber < 1) {
              weekNumber = this.weeksInWeekYear();
            } else if (weekNumber > this.weeksInWeekYear()) {
              weekNumber = 1;
            }
            return weekNumber;
          }
          /**
           * Returns the number of weeks in the year
           */
          weeksInWeekYear() {
            const p1 = (this.year + Math.floor(this.year / 4) - Math.floor(this.year / 100) + Math.floor(this.year / 400)) % 7, last = this.year - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7;
            return p1 === 4 || p2 === 3 ? 53 : 52;
          }
          /**
           * Returns true or false depending on if the year is a leap year or not.
           */
          get isLeapYear() {
            return this.year % 4 === 0 && (this.year % 100 !== 0 || this.year % 400 === 0);
          }
          computeOrdinal() {
            return this.date + (this.isLeapYear ? this.leapLadder : this.nonLeapLadder)[this.month];
          }
          /**
           * Returns a list of month values based on the current locale
           */
          getAllMonths(format = "long") {
            const applyFormat = new Intl.DateTimeFormat(this.localization.locale, {
              month: format
            }).format;
            return [...Array(12).keys()].map((m3) => applyFormat(new Date(2021, m3)));
          }
          /**
           * Replaces an expanded token set (e.g. LT/LTS)
           */
          replaceTokens(formatStr, formats) {
            return formatStr.replace(/(\[[^[\]]*])|(LTS?|l{1,4}|L{1,4})/g, (_, a, b) => {
              const B = b && b.toUpperCase();
              return a || formats[B] || DefaultFormatLocalization$1.dateFormats[B];
            });
          }
          parseTwoDigitYear(input) {
            return input + (input > 68 ? 1900 : 2e3);
          }
          offsetFromString(input) {
            if (!input)
              return 0;
            if (input === "Z")
              return 0;
            const [first, second, third] = input.match(/([+-]|\d\d)/g);
            const minutes = +second * 60 + (+third || 0);
            const signed = first === "+" ? -minutes : minutes;
            return minutes === 0 ? 0 : signed;
          }
          /**
           * z = -4, zz = -04, zzz = -0400
           * @param date
           * @param style
           * @private
           */
          zoneInformation(date, style) {
            let name = date.parts(this.localization.locale, { timeZoneName: "longOffset" }).timeZoneName.replace("GMT", "").replace(":", "");
            const negative = name.includes("-");
            name = name.replace("-", "");
            if (style === "z")
              name = name.substring(1, 2);
            else if (style === "zz")
              name = name.substring(0, 2);
            return `${negative ? "-" : ""}${name}`;
          }
          addInput(property) {
            return (obj, input) => {
              obj[property] = +input;
            };
          }
          getLocaleAfternoon() {
            return new Intl.DateTimeFormat(this.localization.locale, {
              hour: "numeric",
              hour12: true
            }).formatToParts(new Date(2022, 3, 4, 13)).find((p) => p.type === "dayPeriod")?.value?.replace(/\s+/g, " ");
          }
          meridiemMatch(input) {
            return input.toLowerCase() === this.getLocaleAfternoon().toLowerCase();
          }
          correctHours(time) {
            const { afternoon } = time;
            if (afternoon !== void 0) {
              const { hours } = time;
              if (afternoon) {
                if (hours < 12) {
                  time.hours += 12;
                }
              } else if (hours === 12) {
                time.hours = 0;
              }
              delete time.afternoon;
            }
          }
          makeParser(format) {
            format = this.replaceTokens(format, this.localization.dateFormats);
            const matchArray = format.match(this.formattingTokens);
            const { length } = matchArray;
            const expressionArray = [];
            for (let i = 0; i < length; i += 1) {
              const token = matchArray[i];
              const expression = this.expressions[token];
              if (expression?.parser) {
                expressionArray[i] = expression;
              } else {
                expressionArray[i] = token.replace(/^\[[^[\]]*]$/g, "");
              }
            }
            return (input) => {
              const time = {
                hours: 0,
                minutes: 0,
                seconds: 0,
                milliseconds: 0
              };
              for (let i = 0, start2 = 0; i < length; i += 1) {
                const token = expressionArray[i];
                if (typeof token === "string") {
                  start2 += token.length;
                } else {
                  const part = input.slice(start2);
                  let value = part;
                  if (token.pattern) {
                    const match = token.pattern.exec(part);
                    value = match[0];
                  }
                  token.parser.call(this, time, value);
                  input = input.replace(value, "");
                }
              }
              this.correctHours(time);
              return time;
            };
          }
          /**
           * Attempts to create a DateTime from a string.
           * @param input date as string
           * @param localization provides the date template the string is in via the format property
           */
          //eslint-disable-next-line @typescript-eslint/no-unused-vars
          static fromString(input, localization) {
            if (!localization?.format) {
              Namespace.errorMessages.customDateFormatError("No format was provided");
            }
            try {
              const dt = new DateTime();
              dt.setLocalization(localization);
              if (["x", "X"].indexOf(localization.format) > -1)
                return new DateTime((localization.format === "X" ? 1e3 : 1) * +input);
              input = input.replace(/\s+/g, " ");
              const parser = dt.makeParser(localization.format);
              const { year, month, day, hours, minutes, seconds, milliseconds, zone } = parser(input);
              const d = day || (!year && !month ? dt.getDate() : 1);
              const y = year || dt.getFullYear();
              let M = 0;
              if (!(year && !month)) {
                M = month > 0 ? month - 1 : dt.getMonth();
              }
              if (zone) {
                return new DateTime(Date.UTC(y, M, d, hours, minutes, seconds, milliseconds + zone.offset * 60 * 1e3));
              }
              return new DateTime(y, M, d, hours, minutes, seconds, milliseconds);
            } catch (e) {
              Namespace.errorMessages.customDateFormatError(`Unable to parse provided input: ${input}, format: ${localization.format}`);
            }
          }
          /**
           * Returns a string format.
           * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
           * for valid templates and locale objects
           * @param template An optional object. If provided, method will use Intl., otherwise the localizations format properties
           * @param locale Can be a string or an array of strings. Uses browser defaults otherwise.
           */
          format(template, locale2 = this.localization.locale) {
            if (template && typeof template === "object")
              return new Intl.DateTimeFormat(locale2, template).format(this);
            const formatString = this.replaceTokens(
              //try template first
              template || //otherwise try localization format
              this.localization.format || //otherwise try date + time
              `${DefaultFormatLocalization$1.dateFormats.L}, ${DefaultFormatLocalization$1.dateFormats.LT}`,
              this.localization.dateFormats
            );
            const formatter = (template2) => new Intl.DateTimeFormat(this.localization.locale, template2).format(this);
            if (!this.localization.hourCycle)
              this.localization.hourCycle = guessHourCycle(this.localization.locale);
            const HHCycle = this.localization.hourCycle.startsWith("h1") ? "h24" : this.localization.hourCycle;
            const hhCycle = this.localization.hourCycle.startsWith("h2") ? "h12" : this.localization.hourCycle;
            const matches = {
              y: this.year,
              yy: formatter({ year: "2-digit" }),
              yyyy: this.year,
              M: formatter({ month: "numeric" }),
              MM: this.monthFormatted,
              MMM: this.getAllMonths("short")[this.getMonth()],
              MMMM: this.getAllMonths()[this.getMonth()],
              d: this.date,
              dd: this.dateFormatted,
              ddd: formatter({ weekday: "short" }),
              dddd: formatter({ weekday: "long" }),
              H: this.getHours(),
              HH: this.getHoursFormatted(HHCycle),
              h: this.hours > 12 ? this.hours - 12 : this.hours,
              hh: this.getHoursFormatted(hhCycle),
              t: this.meridiem(),
              T: this.meridiem().toUpperCase(),
              m: this.minutes,
              mm: this.minutesFormatted,
              s: this.seconds,
              ss: this.secondsFormatted,
              fff: this.getMilliseconds()
              // z: this.zoneInformation(dateTime, 'z'), //-4
              // zz: this.zoneInformation(dateTime, 'zz'), //-04
              // zzz: this.zoneInformation(dateTime, 'zzz') //-0400
            };
            return formatString.replace(this.dateTimeRegex, (match, $1) => {
              return $1 || matches[match];
            }).replace(/\[/g, "").replace(/]/g, "");
          }
        }
        class ServiceLocator {
          constructor() {
            this.cache = /* @__PURE__ */ new Map();
          }
          locate(identifier) {
            const service = this.cache.get(identifier);
            if (service)
              return service;
            const value = new identifier();
            this.cache.set(identifier, value);
            return value;
          }
        }
        const setupServiceLocator = () => {
          serviceLocator = new ServiceLocator();
        };
        let serviceLocator;
        const CalendarModes = [
          {
            name: "calendar",
            className: Namespace.css.daysContainer,
            unit: exports2.Unit.month,
            step: 1
          },
          {
            name: "months",
            className: Namespace.css.monthsContainer,
            unit: exports2.Unit.year,
            step: 1
          },
          {
            name: "years",
            className: Namespace.css.yearsContainer,
            unit: exports2.Unit.year,
            step: 10
          },
          {
            name: "decades",
            className: Namespace.css.decadesContainer,
            unit: exports2.Unit.year,
            step: 100
          }
        ];
        class OptionsStore {
          constructor() {
            this._currentCalendarViewMode = 0;
            this._viewDate = new DateTime();
            this.minimumCalendarViewMode = 0;
            this.currentView = "calendar";
          }
          get currentCalendarViewMode() {
            return this._currentCalendarViewMode;
          }
          set currentCalendarViewMode(value) {
            this._currentCalendarViewMode = value;
            this.currentView = CalendarModes[value].name;
          }
          get viewDate() {
            return this._viewDate;
          }
          set viewDate(v) {
            this._viewDate = v;
            if (this.options)
              this.options.viewDate = v;
          }
          /**
           * When switching back to the calendar from the clock,
           * this sets currentView to the correct calendar view.
           */
          refreshCurrentView() {
            this.currentView = CalendarModes[this.currentCalendarViewMode].name;
          }
          get isTwelveHour() {
            return ["h12", "h11"].includes(this.options.localization.hourCycle);
          }
        }
        class Validation {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
          }
          /**
           * Checks to see if the target date is valid based on the rules provided in the options.
           * Granularity can be provided to check portions of the date instead of the whole.
           * @param targetDate
           * @param granularity
           */
          isValid(targetDate, granularity) {
            if (!this._enabledDisabledDatesIsValid(granularity, targetDate))
              return false;
            if (granularity !== exports2.Unit.month && granularity !== exports2.Unit.year && this.optionsStore.options.restrictions.daysOfWeekDisabled?.length > 0 && this.optionsStore.options.restrictions.daysOfWeekDisabled.indexOf(targetDate.weekDay) !== -1)
              return false;
            if (!this._minMaxIsValid(granularity, targetDate))
              return false;
            if (granularity === exports2.Unit.hours || granularity === exports2.Unit.minutes || granularity === exports2.Unit.seconds) {
              if (!this._enabledDisabledHoursIsValid(targetDate))
                return false;
              if (this.optionsStore.options.restrictions.disabledTimeIntervals?.filter((internal) => targetDate.isBetween(internal.from, internal.to)).length !== 0)
                return false;
            }
            return true;
          }
          _enabledDisabledDatesIsValid(granularity, targetDate) {
            if (granularity !== exports2.Unit.date)
              return true;
            if (this.optionsStore.options.restrictions.disabledDates.length > 0 && this._isInDisabledDates(targetDate)) {
              return false;
            }
            if (this.optionsStore.options.restrictions.enabledDates.length > 0 && !this._isInEnabledDates(targetDate)) {
              return false;
            }
            return true;
          }
          /**
           * Checks to see if the disabledDates option is in use and returns true (meaning invalid)
           * if the `testDate` is with in the array. Granularity is by date.
           * @param testDate
           * @private
           */
          _isInDisabledDates(testDate) {
            if (!this.optionsStore.options.restrictions.disabledDates || this.optionsStore.options.restrictions.disabledDates.length === 0)
              return false;
            return !!this.optionsStore.options.restrictions.disabledDates.find((x) => x.isSame(testDate, exports2.Unit.date));
          }
          /**
           * Checks to see if the enabledDates option is in use and returns true (meaning valid)
           * if the `testDate` is with in the array. Granularity is by date.
           * @param testDate
           * @private
           */
          _isInEnabledDates(testDate) {
            if (!this.optionsStore.options.restrictions.enabledDates || this.optionsStore.options.restrictions.enabledDates.length === 0)
              return true;
            return !!this.optionsStore.options.restrictions.enabledDates.find((x) => x.isSame(testDate, exports2.Unit.date));
          }
          _minMaxIsValid(granularity, targetDate) {
            if (this.optionsStore.options.restrictions.minDate && targetDate.isBefore(this.optionsStore.options.restrictions.minDate, granularity)) {
              return false;
            }
            if (this.optionsStore.options.restrictions.maxDate && targetDate.isAfter(this.optionsStore.options.restrictions.maxDate, granularity)) {
              return false;
            }
            return true;
          }
          _enabledDisabledHoursIsValid(targetDate) {
            if (this.optionsStore.options.restrictions.disabledHours.length > 0 && this._isInDisabledHours(targetDate)) {
              return false;
            }
            if (this.optionsStore.options.restrictions.enabledHours.length > 0 && !this._isInEnabledHours(targetDate)) {
              return false;
            }
            return true;
          }
          /**
           * Checks to see if the disabledHours option is in use and returns true (meaning invalid)
           * if the `testDate` is with in the array. Granularity is by hours.
           * @param testDate
           * @private
           */
          _isInDisabledHours(testDate) {
            if (!this.optionsStore.options.restrictions.disabledHours || this.optionsStore.options.restrictions.disabledHours.length === 0)
              return false;
            const formattedDate = testDate.hours;
            return this.optionsStore.options.restrictions.disabledHours.includes(formattedDate);
          }
          /**
           * Checks to see if the enabledHours option is in use and returns true (meaning valid)
           * if the `testDate` is with in the array. Granularity is by hours.
           * @param testDate
           * @private
           */
          _isInEnabledHours(testDate) {
            if (!this.optionsStore.options.restrictions.enabledHours || this.optionsStore.options.restrictions.enabledHours.length === 0)
              return true;
            const formattedDate = testDate.hours;
            return this.optionsStore.options.restrictions.enabledHours.includes(formattedDate);
          }
          dateRangeIsValid(dates, index, target) {
            if (!this.optionsStore.options.dateRange)
              return true;
            if (dates.length !== 2 && index !== 1)
              return true;
            const start2 = dates[0].clone;
            if (start2.isSame(target, exports2.Unit.date))
              return true;
            start2.manipulate(1, exports2.Unit.date);
            while (!start2.isSame(target, exports2.Unit.date)) {
              const valid = this.isValid(start2, exports2.Unit.date);
              if (!valid)
                return false;
              start2.manipulate(1, exports2.Unit.date);
            }
            return true;
          }
        }
        class EventEmitter {
          constructor() {
            this.subscribers = [];
          }
          subscribe(callback) {
            this.subscribers.push(callback);
            return this.unsubscribe.bind(this, this.subscribers.length - 1);
          }
          unsubscribe(index) {
            this.subscribers.splice(index, 1);
          }
          emit(value) {
            this.subscribers.forEach((callback) => {
              callback(value);
            });
          }
          destroy() {
            this.subscribers = null;
            this.subscribers = [];
          }
        }
        class EventEmitters {
          constructor() {
            this.triggerEvent = new EventEmitter();
            this.viewUpdate = new EventEmitter();
            this.updateDisplay = new EventEmitter();
            this.action = new EventEmitter();
            this.updateViewDate = new EventEmitter();
          }
          destroy() {
            this.triggerEvent.destroy();
            this.viewUpdate.destroy();
            this.updateDisplay.destroy();
            this.action.destroy();
            this.updateViewDate.destroy();
          }
        }
        const defaultEnLocalization = {
          clear: "Clear selection",
          close: "Close the picker",
          dateFormats: DefaultFormatLocalization$1.dateFormats,
          dayViewHeaderFormat: { month: "long", year: "2-digit" },
          decrementHour: "Decrement Hour",
          decrementMinute: "Decrement Minute",
          decrementSecond: "Decrement Second",
          format: DefaultFormatLocalization$1.format,
          hourCycle: DefaultFormatLocalization$1.hourCycle,
          incrementHour: "Increment Hour",
          incrementMinute: "Increment Minute",
          incrementSecond: "Increment Second",
          locale: DefaultFormatLocalization$1.locale,
          maxWeekdayLength: 0,
          nextCentury: "Next Century",
          nextDecade: "Next Decade",
          nextMonth: "Next Month",
          nextYear: "Next Year",
          ordinal: DefaultFormatLocalization$1.ordinal,
          pickHour: "Pick Hour",
          pickMinute: "Pick Minute",
          pickSecond: "Pick Second",
          previousCentury: "Previous Century",
          previousDecade: "Previous Decade",
          previousMonth: "Previous Month",
          previousYear: "Previous Year",
          selectDate: "Select Date",
          selectDecade: "Select Decade",
          selectMonth: "Select Month",
          selectTime: "Select Time",
          selectYear: "Select Year",
          startOfTheWeek: 0,
          today: "Go to today",
          toggleMeridiem: "Toggle Meridiem"
        };
        const DefaultOptions = {
          allowInputToggle: false,
          container: void 0,
          dateRange: false,
          debug: false,
          defaultDate: void 0,
          display: {
            icons: {
              type: "icons",
              time: "fa-solid fa-clock",
              date: "fa-solid fa-calendar",
              up: "fa-solid fa-arrow-up",
              down: "fa-solid fa-arrow-down",
              previous: "fa-solid fa-chevron-left",
              next: "fa-solid fa-chevron-right",
              today: "fa-solid fa-calendar-check",
              clear: "fa-solid fa-trash",
              close: "fa-solid fa-xmark"
            },
            sideBySide: false,
            calendarWeeks: false,
            viewMode: "calendar",
            toolbarPlacement: "bottom",
            keepOpen: false,
            buttons: {
              today: false,
              clear: false,
              close: false
            },
            components: {
              calendar: true,
              date: true,
              month: true,
              year: true,
              decades: true,
              clock: true,
              hours: true,
              minutes: true,
              seconds: false,
              useTwentyfourHour: void 0
            },
            inline: false,
            theme: "auto",
            placement: "bottom"
          },
          keepInvalid: false,
          localization: defaultEnLocalization,
          meta: {},
          multipleDates: false,
          multipleDatesSeparator: "; ",
          promptTimeOnDateChange: false,
          promptTimeOnDateChangeTransitionDelay: 200,
          restrictions: {
            minDate: void 0,
            maxDate: void 0,
            disabledDates: [],
            enabledDates: [],
            daysOfWeekDisabled: [],
            disabledTimeIntervals: [],
            disabledHours: [],
            enabledHours: []
          },
          stepping: 1,
          useCurrent: true,
          viewDate: new DateTime()
        };
        const DefaultEnLocalization = { ...defaultEnLocalization };
        function tryConvertToDateTime(d, localization) {
          if (!d)
            return null;
          if (d.constructor.name === DateTime.name)
            return d;
          if (d.constructor.name === Date.name) {
            return DateTime.convert(d);
          }
          if (typeof d === "string") {
            const dateTime = DateTime.fromString(d, localization);
            if (JSON.stringify(dateTime) === "null") {
              return null;
            }
            return dateTime;
          }
          return null;
        }
        function convertToDateTime(d, optionName, localization) {
          if (typeof d === "string" && optionName !== "input") {
            Namespace.errorMessages.dateString();
          }
          const converted = tryConvertToDateTime(d, localization);
          if (!converted) {
            Namespace.errorMessages.failedToParseDate(optionName, d, optionName === "input");
          }
          return converted;
        }
        function typeCheckDateArray(optionName, value, providedType, localization = DefaultFormatLocalization$1) {
          if (!Array.isArray(value)) {
            Namespace.errorMessages.typeMismatch(optionName, providedType, "array of DateTime or Date");
          }
          for (let i = 0; i < value.length; i++) {
            const d = value[i];
            const dateTime = convertToDateTime(d, optionName, localization);
            dateTime.setLocalization(localization);
            value[i] = dateTime;
          }
        }
        function typeCheckNumberArray(optionName, value, providedType) {
          if (!Array.isArray(value) || value.some((x) => typeof x !== "number")) {
            Namespace.errorMessages.typeMismatch(optionName, providedType, "array of numbers");
          }
        }
        function mandatoryDate(key) {
          return ({ value, providedType, localization }) => {
            const dateTime = convertToDateTime(value, key, localization);
            if (dateTime !== void 0) {
              dateTime.setLocalization(localization);
              return dateTime;
            }
          };
        }
        function optionalDate(key) {
          const mandatory = mandatoryDate(key);
          return (args) => {
            if (args.value === void 0) {
              return args.value;
            }
            return mandatory(args);
          };
        }
        function numbersInRange(key, lower, upper) {
          return ({ value, providedType }) => {
            if (value === void 0) {
              return [];
            }
            typeCheckNumberArray(key, value, providedType);
            if (value.some((x) => x < lower || x > upper))
              Namespace.errorMessages.numbersOutOfRange(key, lower, upper);
            return value;
          };
        }
        function validHourRange(key) {
          return numbersInRange(key, 0, 23);
        }
        function validDateArray(key) {
          return ({ value, providedType, localization }) => {
            if (value === void 0) {
              return [];
            }
            typeCheckDateArray(key, value, providedType, localization);
            return value;
          };
        }
        function validKeyOption(keyOptions) {
          return ({ value, path }) => {
            if (!keyOptions.includes(value))
              Namespace.errorMessages.unexpectedOptionValue(path.substring(1), value, keyOptions);
            return value;
          };
        }
        const optionProcessors = Object.freeze({
          defaultDate: mandatoryDate("defaultDate"),
          viewDate: mandatoryDate("viewDate"),
          minDate: optionalDate("restrictions.minDate"),
          maxDate: optionalDate("restrictions.maxDate"),
          disabledHours: validHourRange("restrictions.disabledHours"),
          enabledHours: validHourRange("restrictions.enabledHours"),
          disabledDates: validDateArray("restrictions.disabledDates"),
          enabledDates: validDateArray("restrictions.enabledDates"),
          daysOfWeekDisabled: numbersInRange("restrictions.daysOfWeekDisabled", 0, 6),
          disabledTimeIntervals: ({ key, value, providedType, localization }) => {
            if (value === void 0) {
              return [];
            }
            if (!Array.isArray(value)) {
              Namespace.errorMessages.typeMismatch(key, providedType, "array of { from: DateTime|Date, to: DateTime|Date }");
            }
            const valueObject = value;
            for (let i = 0; i < valueObject.length; i++) {
              Object.keys(valueObject[i]).forEach((vk) => {
                const subOptionName = `${key}[${i}].${vk}`;
                const d = valueObject[i][vk];
                const dateTime = convertToDateTime(d, subOptionName, localization);
                dateTime.setLocalization(localization);
                valueObject[i][vk] = dateTime;
              });
            }
            return valueObject;
          },
          toolbarPlacement: validKeyOption(["top", "bottom", "default"]),
          type: validKeyOption(["icons", "sprites"]),
          viewMode: validKeyOption([
            "clock",
            "calendar",
            "months",
            "years",
            "decades"
          ]),
          theme: validKeyOption(["light", "dark", "auto"]),
          placement: validKeyOption(["top", "bottom"]),
          meta: ({ value }) => value,
          dayViewHeaderFormat: ({ value }) => value,
          container: ({ value, path }) => {
            if (value && !(value instanceof HTMLElement || value instanceof Element || value?.appendChild)) {
              Namespace.errorMessages.typeMismatch(path.substring(1), typeof value, "HTMLElement");
            }
            return value;
          },
          useTwentyfourHour: ({ value, path, providedType, defaultType }) => {
            Namespace.errorMessages.deprecatedWarning("useTwentyfourHour", 'Please use "options.localization.hourCycle" instead');
            if (value === void 0 || providedType === "boolean")
              return value;
            Namespace.errorMessages.typeMismatch(path, providedType, defaultType);
          },
          hourCycle: validKeyOption(["h11", "h12", "h23", "h24"])
        });
        const defaultProcessor = ({ value, defaultType, providedType, path }) => {
          switch (defaultType) {
            case "boolean":
              return value === "true" || value === true;
            case "number":
              return +value;
            case "string":
              return value.toString();
            case "object":
              return {};
            case "function":
              return value;
            default:
              Namespace.errorMessages.typeMismatch(path, providedType, defaultType);
          }
        };
        function processKey(args) {
          return (optionProcessors[args.key] || defaultProcessor)(args);
        }
        class OptionConverter {
          static deepCopy(input) {
            const o = {};
            Object.keys(input).forEach((key) => {
              const inputElement = input[key];
              if (inputElement instanceof DateTime) {
                o[key] = inputElement.clone;
                return;
              } else if (inputElement instanceof Date) {
                o[key] = new Date(inputElement.valueOf());
                return;
              }
              o[key] = inputElement;
              if (typeof inputElement !== "object" || inputElement instanceof HTMLElement || inputElement instanceof Element)
                return;
              if (!Array.isArray(inputElement)) {
                o[key] = OptionConverter.deepCopy(inputElement);
              }
            });
            return o;
          }
          /**
           * Finds value out of an object based on a string, period delimited, path
           * @param paths
           * @param obj
           */
          static objectPath(paths, obj) {
            if (paths.charAt(0) === ".")
              paths = paths.slice(1);
            if (!paths)
              return obj;
            return paths.split(".").reduce((value, key) => OptionConverter.isValue(value) || OptionConverter.isValue(value[key]) ? value[key] : void 0, obj);
          }
          /**
           * The spread operator caused sub keys to be missing after merging.
           * This is to fix that issue by using spread on the child objects first.
           * Also handles complex options like disabledDates
           * @param provided An option from new providedOptions
           * @param copyTo Destination object. This was added to prevent reference copies
           * @param localization
           * @param path
           */
          static spread(provided, copyTo, localization, path = "") {
            const defaultOptions = OptionConverter.objectPath(path, DefaultOptions);
            const unsupportedOptions = Object.keys(provided).filter((x) => !Object.keys(defaultOptions).includes(x));
            if (unsupportedOptions.length > 0) {
              const flattenedOptions = OptionConverter.getFlattenDefaultOptions();
              const errors = unsupportedOptions.map((x) => {
                let error = `"${path}.${x}" in not a known option.`;
                const didYouMean = flattenedOptions.find((y) => y.includes(x));
                if (didYouMean)
                  error += ` Did you mean "${didYouMean}"?`;
                return error;
              });
              Namespace.errorMessages.unexpectedOptions(errors);
            }
            Object.keys(provided).filter((key) => key !== "__proto__" && key !== "constructor").forEach((key) => {
              path += `.${key}`;
              if (path.charAt(0) === ".")
                path = path.slice(1);
              const defaultOptionValue = defaultOptions[key];
              const providedType = typeof provided[key];
              const defaultType = typeof defaultOptionValue;
              const value = provided[key];
              if (value === void 0 || value === null) {
                copyTo[key] = value;
                path = path.substring(0, path.lastIndexOf(`.${key}`));
                return;
              }
              if (typeof defaultOptionValue === "object" && !Array.isArray(provided[key]) && !(defaultOptionValue instanceof Date || OptionConverter.ignoreProperties.includes(key))) {
                OptionConverter.spread(provided[key], copyTo[key], localization, path);
              } else {
                copyTo[key] = OptionConverter.processKey(key, value, providedType, defaultType, path, localization);
              }
              path = path.substring(0, path.lastIndexOf(`.${key}`));
            });
          }
          static processKey(key, value, providedType, defaultType, path, localization) {
            return processKey({
              key,
              value,
              providedType,
              defaultType,
              path,
              localization
            });
          }
          static _mergeOptions(providedOptions, mergeTo) {
            const newConfig = OptionConverter.deepCopy(mergeTo);
            const localization = mergeTo.localization?.locale !== "default" ? mergeTo.localization : providedOptions?.localization || DefaultOptions.localization;
            OptionConverter.spread(providedOptions, newConfig, localization, "");
            return newConfig;
          }
          static _dataToOptions(element, options) {
            const eData = JSON.parse(JSON.stringify(element.dataset));
            if (eData?.tdTargetInput)
              delete eData.tdTargetInput;
            if (eData?.tdTargetToggle)
              delete eData.tdTargetToggle;
            if (!eData || Object.keys(eData).length === 0 || eData.constructor !== DOMStringMap)
              return options;
            const dataOptions = {};
            const objectToNormalized = (object) => {
              const lowered = {};
              Object.keys(object).forEach((x) => {
                lowered[x.toLowerCase()] = x;
              });
              return lowered;
            };
            const normalizeObject = this.normalizeObject(objectToNormalized);
            const optionsLower = objectToNormalized(options);
            Object.keys(eData).filter((x) => x.startsWith(Namespace.dataKey)).map((x) => x.substring(2)).forEach((key) => {
              let keyOption = optionsLower[key.toLowerCase()];
              if (key.includes("_")) {
                const split = key.split("_");
                keyOption = optionsLower[split[0].toLowerCase()];
                if (keyOption !== void 0 && options[keyOption].constructor === Object) {
                  dataOptions[keyOption] = normalizeObject(split, 1, options[keyOption], eData[`td${key}`]);
                }
              } else if (keyOption !== void 0) {
                dataOptions[keyOption] = eData[`td${key}`];
              }
            });
            return this._mergeOptions(dataOptions, options);
          }
          //todo clean this up
          static normalizeObject(objectToNormalized) {
            const normalizeObject = (split, index, optionSubgroup, value) => {
              const normalizedOptions = objectToNormalized(optionSubgroup);
              const keyOption = normalizedOptions[split[index].toLowerCase()];
              const internalObject = {};
              if (keyOption === void 0)
                return internalObject;
              if (optionSubgroup[keyOption].constructor === Object) {
                index++;
                internalObject[keyOption] = normalizeObject(split, index, optionSubgroup[keyOption], value);
              } else {
                internalObject[keyOption] = value;
              }
              return internalObject;
            };
            return normalizeObject;
          }
          /**
           * Attempts to prove `d` is a DateTime or Date or can be converted into one.
           * @param d If a string will attempt creating a date from it.
           * @param localization object containing locale and format settings. Only used with the custom formats
           * @private
           */
          static _dateTypeCheck(d, localization) {
            return tryConvertToDateTime(d, localization);
          }
          /**
           * Type checks that `value` is an array of Date or DateTime
           * @param optionName Provides text to error messages e.g. disabledDates
           * @param value Option value
           * @param providedType Used to provide text to error messages
           * @param localization
           */
          static _typeCheckDateArray(optionName, value, providedType, localization) {
            return typeCheckDateArray(optionName, value, providedType, localization);
          }
          /**
           * Type checks that `value` is an array of numbers
           * @param optionName Provides text to error messages e.g. disabledDates
           * @param value Option value
           * @param providedType Used to provide text to error messages
           */
          static _typeCheckNumberArray(optionName, value, providedType) {
            return typeCheckNumberArray(optionName, value, providedType);
          }
          /**
           * Attempts to convert `d` to a DateTime object
           * @param d value to convert
           * @param optionName Provides text to error messages e.g. disabledDates
           * @param localization object containing locale and format settings. Only used with the custom formats
           */
          static dateConversion(d, optionName, localization) {
            return convertToDateTime(d, optionName, localization);
          }
          static getFlattenDefaultOptions() {
            if (this._flattenDefaults)
              return this._flattenDefaults;
            const deepKeys = (t, pre = []) => {
              if (Array.isArray(t))
                return [];
              if (Object(t) === t) {
                return Object.entries(t).flatMap(([k, v]) => deepKeys(v, [...pre, k]));
              } else {
                return pre.join(".");
              }
            };
            this._flattenDefaults = deepKeys(DefaultOptions);
            return this._flattenDefaults;
          }
          /**
           * Some options conflict like min/max date. Verify that these kinds of options
           * are set correctly.
           * @param config
           */
          static _validateConflicts(config) {
            if (config.display.sideBySide && (!config.display.components.clock || !(config.display.components.hours || config.display.components.minutes || config.display.components.seconds))) {
              Namespace.errorMessages.conflictingConfiguration("Cannot use side by side mode without the clock components");
            }
            if (config.restrictions.minDate && config.restrictions.maxDate) {
              if (config.restrictions.minDate.isAfter(config.restrictions.maxDate)) {
                Namespace.errorMessages.conflictingConfiguration("minDate is after maxDate");
              }
              if (config.restrictions.maxDate.isBefore(config.restrictions.minDate)) {
                Namespace.errorMessages.conflictingConfiguration("maxDate is before minDate");
              }
            }
            if (config.multipleDates && config.dateRange) {
              Namespace.errorMessages.conflictingConfiguration('Cannot uss option "multipleDates" with "dateRange"');
            }
          }
        }
        OptionConverter.ignoreProperties = [
          "meta",
          "dayViewHeaderFormat",
          "container",
          "dateForms",
          "ordinal"
        ];
        OptionConverter.isValue = (a) => a != null;
        class Dates {
          constructor() {
            this._dates = [];
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.validation = serviceLocator.locate(Validation);
            this._eventEmitters = serviceLocator.locate(EventEmitters);
          }
          /**
           * Returns the array of selected dates
           */
          get picked() {
            return [...this._dates];
          }
          /**
           * Returns the last picked value.
           */
          get lastPicked() {
            return this._dates[this.lastPickedIndex]?.clone;
          }
          /**
           * Returns the length of picked dates -1 or 0 if none are selected.
           */
          get lastPickedIndex() {
            if (this._dates.length === 0)
              return 0;
            return this._dates.length - 1;
          }
          /**
           * Formats a DateTime object to a string. Used when setting the input value.
           * @param date
           */
          formatInput(date) {
            if (!date)
              return "";
            date.localization = this.optionsStore.options.localization;
            return date.format();
          }
          /**
           * parse the value into a DateTime object.
           * this can be overwritten to supply your own parsing.
           */
          //eslint-disable-next-line @typescript-eslint/no-explicit-any
          parseInput(value) {
            return OptionConverter.dateConversion(value, "input", this.optionsStore.options.localization);
          }
          /**
           * Tries to convert the provided value to a DateTime object.
           * If value is null|undefined then clear the value of the provided index (or 0).
           * @param value Value to convert or null|undefined
           * @param index When using multidates this is the index in the array
           */
          //eslint-disable-next-line @typescript-eslint/no-explicit-any
          setFromInput(value, index) {
            if (!value) {
              this.setValue(void 0, index);
              return;
            }
            const converted = this.parseInput(value);
            if (converted) {
              converted.setLocalization(this.optionsStore.options.localization);
              this.setValue(converted, index);
            }
          }
          /**
           * Adds a new DateTime to selected dates array
           * @param date
           */
          add(date) {
            this._dates.push(date);
          }
          /**
           * Returns true if the `targetDate` is part of the selected dates array.
           * If `unit` is provided then a granularity to that unit will be used.
           * @param targetDate
           * @param unit
           */
          isPicked(targetDate, unit) {
            if (!DateTime.isValid(targetDate))
              return false;
            if (!unit)
              return this._dates.find((x) => x.isSame(targetDate)) !== void 0;
            const format = getFormatByUnit(unit);
            const innerDateFormatted = targetDate.format(format);
            return this._dates.map((x) => x.format(format)).find((x) => x === innerDateFormatted) !== void 0;
          }
          /**
           * Returns the index at which `targetDate` is in the array.
           * This is used for updating or removing a date when multi-date is used
           * If `unit` is provided then a granularity to that unit will be used.
           * @param targetDate
           * @param unit
           */
          pickedIndex(targetDate, unit) {
            if (!DateTime.isValid(targetDate))
              return -1;
            if (!unit)
              return this._dates.map((x) => x.valueOf()).indexOf(targetDate.valueOf());
            const format = getFormatByUnit(unit);
            const innerDateFormatted = targetDate.format(format);
            return this._dates.map((x) => x.format(format)).indexOf(innerDateFormatted);
          }
          /**
           * Clears all selected dates.
           */
          clear() {
            this.optionsStore.unset = true;
            this._eventEmitters.triggerEvent.emit({
              type: Namespace.events.change,
              date: void 0,
              oldDate: this.lastPicked,
              isClear: true,
              isValid: true
            });
            this._dates = [];
            if (this.optionsStore.input)
              this.optionsStore.input.value = "";
            this._eventEmitters.updateDisplay.emit("all");
          }
          /**
           * Find the "book end" years given a `year` and a `factor`
           * @param factor e.g. 100 for decades
           * @param year e.g. 2021
           */
          static getStartEndYear(factor, year) {
            const step = factor / 10, startYear = Math.floor(year / factor) * factor, endYear = startYear + step * 9, focusValue = Math.floor(year / step) * step;
            return [startYear, endYear, focusValue];
          }
          updateInput(target) {
            if (!this.optionsStore.input)
              return;
            let newValue = this.formatInput(target);
            if (this.optionsStore.options.multipleDates || this.optionsStore.options.dateRange) {
              newValue = this._dates.map((d) => this.formatInput(d)).join(this.optionsStore.options.multipleDatesSeparator);
            }
            if (this.optionsStore.input.value != newValue)
              this.optionsStore.input.value = newValue;
          }
          /**
           * Attempts to either clear or set the `target` date at `index`.
           * If the `target` is null then the date will be cleared.
           * If multi-date is being used then it will be removed from the array.
           * If `target` is valid and multi-date is used then if `index` is
           * provided the date at that index will be replaced, otherwise it is appended.
           * @param target
           * @param index
           */
          setValue(target, index) {
            const noIndex = typeof index === "undefined", isClear = !target && noIndex;
            let oldDate = this.optionsStore.unset ? null : this._dates[index]?.clone;
            if (!oldDate && !this.optionsStore.unset && noIndex && isClear) {
              oldDate = this.lastPicked;
            }
            if (target && oldDate?.isSame(target)) {
              this.updateInput(target);
              return;
            }
            if (!target) {
              this._setValueNull(isClear, index, oldDate);
              return;
            }
            index = index || 0;
            target = target.clone;
            if (this.optionsStore.options.stepping !== 1) {
              target.minutes = Math.round(target.minutes / this.optionsStore.options.stepping) * this.optionsStore.options.stepping;
              target.startOf(exports2.Unit.minutes);
            }
            const onUpdate = (isValid) => {
              this._dates[index] = target;
              this._eventEmitters.updateViewDate.emit(target.clone);
              this.updateInput(target);
              this.optionsStore.unset = false;
              this._eventEmitters.updateDisplay.emit("all");
              this._eventEmitters.triggerEvent.emit({
                type: Namespace.events.change,
                date: target,
                oldDate,
                isClear,
                isValid
              });
            };
            if (this.validation.isValid(target) && this.validation.dateRangeIsValid(this.picked, index, target)) {
              onUpdate(true);
              return;
            }
            if (this.optionsStore.options.keepInvalid) {
              onUpdate(false);
            }
            this._eventEmitters.triggerEvent.emit({
              type: Namespace.events.error,
              reason: Namespace.errorMessages.failedToSetInvalidDate,
              date: target,
              oldDate
            });
          }
          _setValueNull(isClear, index, oldDate) {
            if (!this.optionsStore.options.multipleDates || this._dates.length === 1 || isClear) {
              this.optionsStore.unset = true;
              this._dates = [];
            } else {
              this._dates.splice(index, 1);
            }
            this.updateInput();
            this._eventEmitters.triggerEvent.emit({
              type: Namespace.events.change,
              date: void 0,
              oldDate,
              isClear,
              isValid: true
            });
            this._eventEmitters.updateDisplay.emit("all");
          }
        }
        var ActionTypes;
        (function(ActionTypes2) {
          ActionTypes2["next"] = "next";
          ActionTypes2["previous"] = "previous";
          ActionTypes2["changeCalendarView"] = "changeCalendarView";
          ActionTypes2["selectMonth"] = "selectMonth";
          ActionTypes2["selectYear"] = "selectYear";
          ActionTypes2["selectDecade"] = "selectDecade";
          ActionTypes2["selectDay"] = "selectDay";
          ActionTypes2["selectHour"] = "selectHour";
          ActionTypes2["selectMinute"] = "selectMinute";
          ActionTypes2["selectSecond"] = "selectSecond";
          ActionTypes2["incrementHours"] = "incrementHours";
          ActionTypes2["incrementMinutes"] = "incrementMinutes";
          ActionTypes2["incrementSeconds"] = "incrementSeconds";
          ActionTypes2["decrementHours"] = "decrementHours";
          ActionTypes2["decrementMinutes"] = "decrementMinutes";
          ActionTypes2["decrementSeconds"] = "decrementSeconds";
          ActionTypes2["toggleMeridiem"] = "toggleMeridiem";
          ActionTypes2["togglePicker"] = "togglePicker";
          ActionTypes2["showClock"] = "showClock";
          ActionTypes2["showHours"] = "showHours";
          ActionTypes2["showMinutes"] = "showMinutes";
          ActionTypes2["showSeconds"] = "showSeconds";
          ActionTypes2["clear"] = "clear";
          ActionTypes2["close"] = "close";
          ActionTypes2["today"] = "today";
        })(ActionTypes || (ActionTypes = {}));
        var ActionTypes$1 = ActionTypes;
        class DateDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.daysContainer);
            container.append(...this._daysOfTheWeek());
            if (this.optionsStore.options.display.calendarWeeks) {
              const div = document.createElement("div");
              div.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
              container.appendChild(div);
            }
            const { rangeHoverEvent, rangeHoverOutEvent } = this.handleMouseEvents(container);
            for (let i = 0; i < 42; i++) {
              if (i !== 0 && i % 7 === 0) {
                if (this.optionsStore.options.display.calendarWeeks) {
                  const div2 = document.createElement("div");
                  div2.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
                  container.appendChild(div2);
                }
              }
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectDay);
              container.appendChild(div);
              if (matchMedia("(hover: hover)").matches && this.optionsStore.options.dateRange) {
                div.addEventListener("mouseover", rangeHoverEvent);
                div.addEventListener("mouseout", rangeHoverOutEvent);
              }
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const container = widget.getElementsByClassName(Namespace.css.daysContainer)[0];
            this._updateCalendarView(container);
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.month).startOf("weekDay", this.optionsStore.options.localization.startOfTheWeek).manipulate(12, exports2.Unit.hours);
            this._handleCalendarWeeks(container, innerDate.clone);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectDay}"]`).forEach((element) => {
              const classes = [];
              classes.push(Namespace.css.day);
              if (innerDate.isBefore(this.optionsStore.viewDate, exports2.Unit.month)) {
                classes.push(Namespace.css.old);
              }
              if (innerDate.isAfter(this.optionsStore.viewDate, exports2.Unit.month)) {
                classes.push(Namespace.css.new);
              }
              if (!this.optionsStore.unset && !this.optionsStore.options.dateRange && this.dates.isPicked(innerDate, exports2.Unit.date)) {
                classes.push(Namespace.css.active);
              }
              if (!this.validation.isValid(innerDate, exports2.Unit.date)) {
                classes.push(Namespace.css.disabled);
              }
              if (innerDate.isSame(new DateTime(), exports2.Unit.date)) {
                classes.push(Namespace.css.today);
              }
              if (innerDate.weekDay === 0 || innerDate.weekDay === 6) {
                classes.push(Namespace.css.weekend);
              }
              this._handleDateRange(innerDate, classes);
              paint(exports2.Unit.date, innerDate, classes, element);
              element.classList.remove(...element.classList);
              element.classList.add(...classes);
              element.setAttribute("data-value", this._dateToDataValue(innerDate));
              element.setAttribute("data-day", `${innerDate.date}`);
              element.innerText = innerDate.parts(void 0, {
                day: "numeric"
              }).day;
              innerDate.manipulate(1, exports2.Unit.date);
            });
          }
          _dateToDataValue(date) {
            if (!DateTime.isValid(date))
              return "";
            return `${date.year}-${date.monthFormatted}-${date.dateFormatted}`;
          }
          _handleDateRange(innerDate, classes) {
            const rangeStart = this.dates.picked[0];
            const rangeEnd = this.dates.picked[1];
            if (this.optionsStore.options.dateRange) {
              if (innerDate.isBetween(rangeStart, rangeEnd, exports2.Unit.date)) {
                classes.push(Namespace.css.rangeIn);
              }
              if (innerDate.isSame(rangeStart, exports2.Unit.date)) {
                classes.push(Namespace.css.rangeStart);
              }
              if (innerDate.isSame(rangeEnd, exports2.Unit.date)) {
                classes.push(Namespace.css.rangeEnd);
              }
            }
          }
          handleMouseEvents(container) {
            const rangeHoverEvent = (e) => {
              const currentTarget = e?.currentTarget;
              if (this.dates.picked.length !== 1 || currentTarget.classList.contains(Namespace.css.disabled))
                return;
              const allDays = [...container.querySelectorAll(".day")];
              const attributeValue = currentTarget.getAttribute("data-value");
              const innerDate = DateTime.fromString(attributeValue, {
                format: "yyyy-MM-dd"
              });
              const dayIndex = allDays.findIndex((e2) => e2.getAttribute("data-value") === attributeValue);
              const rangeStart = this.dates.picked[0];
              const rangeEnd = this.dates.picked[1];
              const rangeStartFormatted = this._dateToDataValue(rangeStart);
              const rangeStartIndex = allDays.findIndex((e2) => e2.getAttribute("data-value") === rangeStartFormatted);
              const rangeStartElement = allDays[rangeStartIndex];
              if (!innerDate.isSame(rangeStart, exports2.Unit.date)) {
                currentTarget.classList.remove(Namespace.css.rangeStart);
              }
              if (!innerDate.isSame(rangeEnd, exports2.Unit.date)) {
                currentTarget.classList.remove(Namespace.css.rangeEnd);
              }
              let lambda;
              if (innerDate.isBefore(rangeStart)) {
                currentTarget.classList.add(Namespace.css.rangeStart);
                rangeStartElement?.classList.remove(Namespace.css.rangeStart);
                rangeStartElement?.classList.add(Namespace.css.rangeEnd);
                lambda = (_, index) => index > dayIndex && index < rangeStartIndex;
              } else {
                currentTarget.classList.add(Namespace.css.rangeEnd);
                rangeStartElement?.classList.remove(Namespace.css.rangeEnd);
                rangeStartElement?.classList.add(Namespace.css.rangeStart);
                lambda = (_, index) => index < dayIndex && index > rangeStartIndex;
              }
              allDays.filter(lambda).forEach((e2) => {
                e2.classList.add(Namespace.css.rangeIn);
              });
            };
            const rangeHoverOutEvent = (e) => {
              const allDays = [...container.querySelectorAll(".day")];
              if (this.dates.picked.length === 1)
                allDays.forEach((e2) => e2.classList.remove(Namespace.css.rangeIn));
              if (this.dates.picked.length !== 1)
                return;
              const currentTarget = e?.currentTarget;
              const innerDate = new DateTime(currentTarget.getAttribute("data-value"));
              if (!innerDate.isSame(this.dates.picked[0], exports2.Unit.date)) {
                currentTarget.classList.remove(Namespace.css.rangeStart);
              }
              if (!innerDate.isSame(this.dates.picked[1], exports2.Unit.date)) {
                currentTarget.classList.remove(Namespace.css.rangeEnd);
              }
            };
            return { rangeHoverEvent, rangeHoverOutEvent };
          }
          _updateCalendarView(container) {
            if (this.optionsStore.currentView !== "calendar")
              return;
            const [previous, switcher, next] = container.parentElement.getElementsByClassName(Namespace.css.calendarHeader)[0].getElementsByTagName("div");
            switcher.setAttribute(Namespace.css.daysContainer, this.optionsStore.viewDate.format(this.optionsStore.options.localization.dayViewHeaderFormat));
            this.optionsStore.options.display.components.month ? switcher.classList.remove(Namespace.css.disabled) : switcher.classList.add(Namespace.css.disabled);
            this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.month), exports2.Unit.month) ? previous.classList.remove(Namespace.css.disabled) : previous.classList.add(Namespace.css.disabled);
            this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(1, exports2.Unit.month), exports2.Unit.month) ? next.classList.remove(Namespace.css.disabled) : next.classList.add(Namespace.css.disabled);
          }
          /***
           * Generates a html row that contains the days of the week.
           * @private
           */
          _daysOfTheWeek() {
            const innerDate = this.optionsStore.viewDate.clone.startOf("weekDay", this.optionsStore.options.localization.startOfTheWeek).startOf(exports2.Unit.date);
            const row = [];
            document.createElement("div");
            if (this.optionsStore.options.display.calendarWeeks) {
              const htmlDivElement = document.createElement("div");
              htmlDivElement.classList.add(Namespace.css.calendarWeeks, Namespace.css.noHighlight);
              htmlDivElement.innerText = "#";
              row.push(htmlDivElement);
            }
            for (let i = 0; i < 7; i++) {
              const htmlDivElement = document.createElement("div");
              htmlDivElement.classList.add(Namespace.css.dayOfTheWeek, Namespace.css.noHighlight);
              let weekDay = innerDate.format({ weekday: "short" });
              if (this.optionsStore.options.localization.maxWeekdayLength > 0)
                weekDay = weekDay.substring(0, this.optionsStore.options.localization.maxWeekdayLength);
              htmlDivElement.innerText = weekDay;
              innerDate.manipulate(1, exports2.Unit.date);
              row.push(htmlDivElement);
            }
            return row;
          }
          _handleCalendarWeeks(container, innerDate) {
            [...container.querySelectorAll(`.${Namespace.css.calendarWeeks}`)].filter((e) => e.innerText !== "#").forEach((element) => {
              element.innerText = `${innerDate.week}`;
              innerDate.manipulate(7, exports2.Unit.date);
            });
          }
        }
        class MonthDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.monthsContainer);
            for (let i = 0; i < 12; i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectMonth);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const container = widget.getElementsByClassName(Namespace.css.monthsContainer)[0];
            if (this.optionsStore.currentView === "months") {
              const [previous, switcher, next] = container.parentElement.getElementsByClassName(Namespace.css.calendarHeader)[0].getElementsByTagName("div");
              switcher.setAttribute(Namespace.css.monthsContainer, this.optionsStore.viewDate.format({ year: "numeric" }));
              this.optionsStore.options.display.components.year ? switcher.classList.remove(Namespace.css.disabled) : switcher.classList.add(Namespace.css.disabled);
              this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.year), exports2.Unit.year) ? previous.classList.remove(Namespace.css.disabled) : previous.classList.add(Namespace.css.disabled);
              this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(1, exports2.Unit.year), exports2.Unit.year) ? next.classList.remove(Namespace.css.disabled) : next.classList.add(Namespace.css.disabled);
            }
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.year);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectMonth}"]`).forEach((containerClone, index) => {
              const classes = [];
              classes.push(Namespace.css.month);
              if (!this.optionsStore.unset && this.dates.isPicked(innerDate, exports2.Unit.month)) {
                classes.push(Namespace.css.active);
              }
              if (!this.validation.isValid(innerDate, exports2.Unit.month)) {
                classes.push(Namespace.css.disabled);
              }
              paint(exports2.Unit.month, innerDate, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${index}`);
              containerClone.innerText = `${innerDate.format({ month: "short" })}`;
              innerDate.manipulate(1, exports2.Unit.month);
            });
          }
        }
        class YearDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.yearsContainer);
            for (let i = 0; i < 12; i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectYear);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            this._startYear = this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.year);
            this._endYear = this.optionsStore.viewDate.clone.manipulate(10, exports2.Unit.year);
            const container = widget.getElementsByClassName(Namespace.css.yearsContainer)[0];
            if (this.optionsStore.currentView === "years") {
              const [previous, switcher, next] = container.parentElement.getElementsByClassName(Namespace.css.calendarHeader)[0].getElementsByTagName("div");
              switcher.setAttribute(Namespace.css.yearsContainer, `${this._startYear.format({ year: "numeric" })}-${this._endYear.format({
                year: "numeric"
              })}`);
              this.optionsStore.options.display.components.decades ? switcher.classList.remove(Namespace.css.disabled) : switcher.classList.add(Namespace.css.disabled);
              this.validation.isValid(this._startYear, exports2.Unit.year) ? previous.classList.remove(Namespace.css.disabled) : previous.classList.add(Namespace.css.disabled);
              this.validation.isValid(this._endYear, exports2.Unit.year) ? next.classList.remove(Namespace.css.disabled) : next.classList.add(Namespace.css.disabled);
            }
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.year).manipulate(-1, exports2.Unit.year);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectYear}"]`).forEach((containerClone) => {
              const classes = [];
              classes.push(Namespace.css.year);
              if (!this.optionsStore.unset && this.dates.isPicked(innerDate, exports2.Unit.year)) {
                classes.push(Namespace.css.active);
              }
              if (!this.validation.isValid(innerDate, exports2.Unit.year)) {
                classes.push(Namespace.css.disabled);
              }
              paint(exports2.Unit.year, innerDate, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${innerDate.year}`);
              containerClone.innerText = innerDate.format({ year: "numeric" });
              innerDate.manipulate(1, exports2.Unit.year);
            });
          }
        }
        class DecadeDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.decadesContainer);
            for (let i = 0; i < 12; i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectDecade);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const [start2, end2] = Dates.getStartEndYear(100, this.optionsStore.viewDate.year);
            this._startDecade = this.optionsStore.viewDate.clone.startOf(exports2.Unit.year);
            this._startDecade.year = start2;
            this._endDecade = this.optionsStore.viewDate.clone.startOf(exports2.Unit.year);
            this._endDecade.year = end2;
            const container = widget.getElementsByClassName(Namespace.css.decadesContainer)[0];
            const [previous, switcher, next] = container.parentElement.getElementsByClassName(Namespace.css.calendarHeader)[0].getElementsByTagName("div");
            if (this.optionsStore.currentView === "decades") {
              switcher.setAttribute(Namespace.css.decadesContainer, `${this._startDecade.format({
                year: "numeric"
              })}-${this._endDecade.format({ year: "numeric" })}`);
              this.validation.isValid(this._startDecade, exports2.Unit.year) ? previous.classList.remove(Namespace.css.disabled) : previous.classList.add(Namespace.css.disabled);
              this.validation.isValid(this._endDecade, exports2.Unit.year) ? next.classList.remove(Namespace.css.disabled) : next.classList.add(Namespace.css.disabled);
            }
            const pickedYears = this.dates.picked.map((x) => x.year);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectDecade}"]`).forEach((containerClone, index) => {
              if (index === 0) {
                containerClone.classList.add(Namespace.css.old);
                if (this._startDecade.year - 10 < 0) {
                  containerClone.textContent = " ";
                  previous.classList.add(Namespace.css.disabled);
                  containerClone.classList.add(Namespace.css.disabled);
                  containerClone.setAttribute("data-value", "");
                  return;
                } else {
                  containerClone.innerText = this._startDecade.clone.manipulate(-10, exports2.Unit.year).format({ year: "numeric" });
                  containerClone.setAttribute("data-value", `${this._startDecade.year}`);
                  return;
                }
              }
              const classes = [];
              classes.push(Namespace.css.decade);
              const startDecadeYear = this._startDecade.year;
              const endDecadeYear = this._startDecade.year + 9;
              if (!this.optionsStore.unset && pickedYears.filter((x) => x >= startDecadeYear && x <= endDecadeYear).length > 0) {
                classes.push(Namespace.css.active);
              }
              paint("decade", this._startDecade, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${this._startDecade.year}`);
              containerClone.innerText = `${this._startDecade.format({
                year: "numeric"
              })}`;
              this._startDecade.manipulate(10, exports2.Unit.year);
            });
          }
        }
        class TimeDisplay {
          constructor() {
            this._gridColumns = "";
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the clock display
           * @private
           */
          getPicker(iconTag) {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.clockContainer);
            container.append(...this._grid(iconTag));
            return container;
          }
          /**
           * Populates the various elements with in the clock display
           * like the current hour and if the manipulation icons are enabled.
           * @private
           */
          _update(widget) {
            const timesDiv = widget.getElementsByClassName(Namespace.css.clockContainer)[0];
            let lastPicked = this.dates.lastPicked?.clone;
            if (!lastPicked && this.optionsStore.options.useCurrent)
              lastPicked = this.optionsStore.viewDate.clone;
            timesDiv.querySelectorAll(".disabled").forEach((element) => element.classList.remove(Namespace.css.disabled));
            if (this.optionsStore.options.display.components.hours) {
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(1, exports2.Unit.hours), exports2.Unit.hours)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.incrementHours}]`).classList.add(Namespace.css.disabled);
              }
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.hours), exports2.Unit.hours)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.decrementHours}]`).classList.add(Namespace.css.disabled);
              }
              timesDiv.querySelector(`[data-time-component=${exports2.Unit.hours}]`).innerText = lastPicked ? lastPicked.getHoursFormatted(this.optionsStore.options.localization.hourCycle) : "--";
            }
            if (this.optionsStore.options.display.components.minutes) {
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(1, exports2.Unit.minutes), exports2.Unit.minutes)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.incrementMinutes}]`).classList.add(Namespace.css.disabled);
              }
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.minutes), exports2.Unit.minutes)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.decrementMinutes}]`).classList.add(Namespace.css.disabled);
              }
              timesDiv.querySelector(`[data-time-component=${exports2.Unit.minutes}]`).innerText = lastPicked ? lastPicked.minutesFormatted : "--";
            }
            if (this.optionsStore.options.display.components.seconds) {
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(1, exports2.Unit.seconds), exports2.Unit.seconds)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.incrementSeconds}]`).classList.add(Namespace.css.disabled);
              }
              if (!this.validation.isValid(this.optionsStore.viewDate.clone.manipulate(-1, exports2.Unit.seconds), exports2.Unit.seconds)) {
                timesDiv.querySelector(`[data-action=${ActionTypes$1.decrementSeconds}]`).classList.add(Namespace.css.disabled);
              }
              timesDiv.querySelector(`[data-time-component=${exports2.Unit.seconds}]`).innerText = lastPicked ? lastPicked.secondsFormatted : "--";
            }
            if (this.optionsStore.isTwelveHour) {
              const toggle = timesDiv.querySelector(`[data-action=${ActionTypes$1.toggleMeridiem}]`);
              const meridiemDate = (lastPicked || this.optionsStore.viewDate).clone;
              toggle.innerText = meridiemDate.meridiem();
              if (!this.validation.isValid(meridiemDate.manipulate(meridiemDate.hours >= 12 ? -12 : 12, exports2.Unit.hours))) {
                toggle.classList.add(Namespace.css.disabled);
              } else {
                toggle.classList.remove(Namespace.css.disabled);
              }
            }
            timesDiv.style.gridTemplateAreas = `"${this._gridColumns}"`;
          }
          /**
           * Creates the table for the clock display depending on what options are selected.
           * @private
           */
          _grid(iconTag) {
            this._gridColumns = "";
            const top2 = [], middle = [], bottom2 = [], separator = document.createElement("div"), upIcon = iconTag(this.optionsStore.options.display.icons.up), downIcon = iconTag(this.optionsStore.options.display.icons.down);
            separator.classList.add(Namespace.css.separator, Namespace.css.noHighlight);
            const separatorColon = separator.cloneNode(true);
            separatorColon.innerHTML = ":";
            const getSeparator = (colon = false) => {
              return colon ? separatorColon.cloneNode(true) : separator.cloneNode(true);
            };
            if (this.optionsStore.options.display.components.hours) {
              let divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.incrementHour);
              divElement.setAttribute("data-action", ActionTypes$1.incrementHours);
              divElement.appendChild(upIcon.cloneNode(true));
              top2.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.pickHour);
              divElement.setAttribute("data-action", ActionTypes$1.showHours);
              divElement.setAttribute("data-time-component", exports2.Unit.hours);
              middle.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.decrementHour);
              divElement.setAttribute("data-action", ActionTypes$1.decrementHours);
              divElement.appendChild(downIcon.cloneNode(true));
              bottom2.push(divElement);
              this._gridColumns += "a";
            }
            if (this.optionsStore.options.display.components.minutes) {
              this._gridColumns += " a";
              if (this.optionsStore.options.display.components.hours) {
                top2.push(getSeparator());
                middle.push(getSeparator(true));
                bottom2.push(getSeparator());
                this._gridColumns += " a";
              }
              let divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.incrementMinute);
              divElement.setAttribute("data-action", ActionTypes$1.incrementMinutes);
              divElement.appendChild(upIcon.cloneNode(true));
              top2.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.pickMinute);
              divElement.setAttribute("data-action", ActionTypes$1.showMinutes);
              divElement.setAttribute("data-time-component", exports2.Unit.minutes);
              middle.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.decrementMinute);
              divElement.setAttribute("data-action", ActionTypes$1.decrementMinutes);
              divElement.appendChild(downIcon.cloneNode(true));
              bottom2.push(divElement);
            }
            if (this.optionsStore.options.display.components.seconds) {
              this._gridColumns += " a";
              if (this.optionsStore.options.display.components.minutes) {
                top2.push(getSeparator());
                middle.push(getSeparator(true));
                bottom2.push(getSeparator());
                this._gridColumns += " a";
              }
              let divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.incrementSecond);
              divElement.setAttribute("data-action", ActionTypes$1.incrementSeconds);
              divElement.appendChild(upIcon.cloneNode(true));
              top2.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.pickSecond);
              divElement.setAttribute("data-action", ActionTypes$1.showSeconds);
              divElement.setAttribute("data-time-component", exports2.Unit.seconds);
              middle.push(divElement);
              divElement = document.createElement("div");
              divElement.setAttribute("title", this.optionsStore.options.localization.decrementSecond);
              divElement.setAttribute("data-action", ActionTypes$1.decrementSeconds);
              divElement.appendChild(downIcon.cloneNode(true));
              bottom2.push(divElement);
            }
            if (this.optionsStore.isTwelveHour) {
              this._gridColumns += " a";
              let divElement = getSeparator();
              top2.push(divElement);
              const button = document.createElement("button");
              button.setAttribute("type", "button");
              button.setAttribute("title", this.optionsStore.options.localization.toggleMeridiem);
              button.setAttribute("data-action", ActionTypes$1.toggleMeridiem);
              button.setAttribute("tabindex", "-1");
              if (Namespace.css.toggleMeridiem.includes(",")) {
                button.classList.add(...Namespace.css.toggleMeridiem.split(","));
              } else
                button.classList.add(Namespace.css.toggleMeridiem);
              divElement = document.createElement("div");
              divElement.classList.add(Namespace.css.noHighlight);
              divElement.appendChild(button);
              middle.push(divElement);
              divElement = getSeparator();
              bottom2.push(divElement);
            }
            this._gridColumns = this._gridColumns.trim();
            return [...top2, ...middle, ...bottom2];
          }
        }
        class HourDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.hourContainer);
            for (let i = 0; i < (this.optionsStore.isTwelveHour ? 12 : 24); i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectHour);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const container = widget.getElementsByClassName(Namespace.css.hourContainer)[0];
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.date);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectHour}"]`).forEach((containerClone) => {
              const classes = [];
              classes.push(Namespace.css.hour);
              if (!this.validation.isValid(innerDate, exports2.Unit.hours)) {
                classes.push(Namespace.css.disabled);
              }
              paint(exports2.Unit.hours, innerDate, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${innerDate.hours}`);
              containerClone.innerText = innerDate.getHoursFormatted(this.optionsStore.options.localization.hourCycle);
              innerDate.manipulate(1, exports2.Unit.hours);
            });
          }
        }
        class MinuteDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.minuteContainer);
            const step = this.optionsStore.options.stepping === 1 ? 5 : this.optionsStore.options.stepping;
            for (let i = 0; i < 60 / step; i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectMinute);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const container = widget.getElementsByClassName(Namespace.css.minuteContainer)[0];
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.hours);
            const step = this.optionsStore.options.stepping === 1 ? 5 : this.optionsStore.options.stepping;
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectMinute}"]`).forEach((containerClone) => {
              const classes = [];
              classes.push(Namespace.css.minute);
              if (!this.validation.isValid(innerDate, exports2.Unit.minutes)) {
                classes.push(Namespace.css.disabled);
              }
              paint(exports2.Unit.minutes, innerDate, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${innerDate.minutes}`);
              containerClone.innerText = innerDate.minutesFormatted;
              innerDate.manipulate(step, exports2.Unit.minutes);
            });
          }
        }
        class secondDisplay {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.validation = serviceLocator.locate(Validation);
          }
          /**
           * Build the container html for the display
           * @private
           */
          getPicker() {
            const container = document.createElement("div");
            container.classList.add(Namespace.css.secondContainer);
            for (let i = 0; i < 12; i++) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.selectSecond);
              container.appendChild(div);
            }
            return container;
          }
          /**
           * Populates the grid and updates enabled states
           * @private
           */
          _update(widget, paint) {
            const container = widget.getElementsByClassName(Namespace.css.secondContainer)[0];
            const innerDate = this.optionsStore.viewDate.clone.startOf(exports2.Unit.minutes);
            container.querySelectorAll(`[data-action="${ActionTypes$1.selectSecond}"]`).forEach((containerClone) => {
              const classes = [];
              classes.push(Namespace.css.second);
              if (!this.validation.isValid(innerDate, exports2.Unit.seconds)) {
                classes.push(Namespace.css.disabled);
              }
              paint(exports2.Unit.seconds, innerDate, classes, containerClone);
              containerClone.classList.remove(...containerClone.classList);
              containerClone.classList.add(...classes);
              containerClone.setAttribute("data-value", `${innerDate.seconds}`);
              containerClone.innerText = innerDate.secondsFormatted;
              innerDate.manipulate(5, exports2.Unit.seconds);
            });
          }
        }
        class Collapse {
          /**
           * Flips the show/hide state of `target`
           * @param target html element to affect.
           */
          static toggle(target) {
            if (target.classList.contains(Namespace.css.show)) {
              this.hide(target);
            } else {
              this.show(target);
            }
          }
          /**
           * Skips any animation or timeouts and immediately set the element to show.
           * @param target
           */
          static showImmediately(target) {
            target.classList.remove(Namespace.css.collapsing);
            target.classList.add(Namespace.css.collapse, Namespace.css.show);
            target.style.height = "";
          }
          /**
           * If `target` is not already showing, then show after the animation.
           * @param target
           */
          static show(target) {
            if (target.classList.contains(Namespace.css.collapsing) || target.classList.contains(Namespace.css.show))
              return;
            const complete = () => {
              Collapse.showImmediately(target);
            };
            target.style.height = "0";
            target.classList.remove(Namespace.css.collapse);
            target.classList.add(Namespace.css.collapsing);
            setTimeout(complete, this.getTransitionDurationFromElement(target));
            target.style.height = `${target.scrollHeight}px`;
          }
          /**
           * Skips any animation or timeouts and immediately set the element to hide.
           * @param target
           */
          static hideImmediately(target) {
            if (!target)
              return;
            target.classList.remove(Namespace.css.collapsing, Namespace.css.show);
            target.classList.add(Namespace.css.collapse);
          }
          /**
           * If `target` is not already hidden, then hide after the animation.
           * @param target HTML Element
           */
          static hide(target) {
            if (target.classList.contains(Namespace.css.collapsing) || !target.classList.contains(Namespace.css.show))
              return;
            const complete = () => {
              Collapse.hideImmediately(target);
            };
            target.style.height = `${target.getBoundingClientRect()["height"]}px`;
            const reflow = (element) => element.offsetHeight;
            reflow(target);
            target.classList.remove(Namespace.css.collapse, Namespace.css.show);
            target.classList.add(Namespace.css.collapsing);
            target.style.height = "";
            setTimeout(complete, this.getTransitionDurationFromElement(target));
          }
        }
        Collapse.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)) * 1e3;
        };
        class Display {
          constructor() {
            this._isVisible = false;
            this._documentClickEvent = (e) => {
              if (this.optionsStore.options.debug || window.debug)
                return;
              if (this._isVisible && !e.composedPath().includes(this.widget) && // click inside the widget
              !e.composedPath()?.includes(this.optionsStore.element)) {
                this.hide();
              }
            };
            this._actionsClickEvent = (e) => {
              this._eventEmitters.action.emit({ e });
            };
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.validation = serviceLocator.locate(Validation);
            this.dates = serviceLocator.locate(Dates);
            this.dateDisplay = serviceLocator.locate(DateDisplay);
            this.monthDisplay = serviceLocator.locate(MonthDisplay);
            this.yearDisplay = serviceLocator.locate(YearDisplay);
            this.decadeDisplay = serviceLocator.locate(DecadeDisplay);
            this.timeDisplay = serviceLocator.locate(TimeDisplay);
            this.hourDisplay = serviceLocator.locate(HourDisplay);
            this.minuteDisplay = serviceLocator.locate(MinuteDisplay);
            this.secondDisplay = serviceLocator.locate(secondDisplay);
            this._eventEmitters = serviceLocator.locate(EventEmitters);
            this._widget = void 0;
            this._eventEmitters.updateDisplay.subscribe((result) => {
              this._update(result);
            });
          }
          /**
           * Returns the widget body or undefined
           * @private
           */
          get widget() {
            return this._widget;
          }
          get dateContainer() {
            return this.widget?.querySelector(`div.${Namespace.css.dateContainer}`);
          }
          get timeContainer() {
            return this.widget?.querySelector(`div.${Namespace.css.timeContainer}`);
          }
          /**
           * Returns this visible state of the picker (shown)
           */
          get isVisible() {
            return this._isVisible;
          }
          /**
           * Updates the table for a particular unit. Used when an option as changed or
           * whenever the class list might need to be refreshed.
           * @param unit
           * @private
           */
          _update(unit) {
            if (!this.widget)
              return;
            switch (unit) {
              case exports2.Unit.seconds:
                this.secondDisplay._update(this.widget, this.paint);
                break;
              case exports2.Unit.minutes:
                this.minuteDisplay._update(this.widget, this.paint);
                break;
              case exports2.Unit.hours:
                this.hourDisplay._update(this.widget, this.paint);
                break;
              case exports2.Unit.date:
                this.dateDisplay._update(this.widget, this.paint);
                break;
              case exports2.Unit.month:
                this.monthDisplay._update(this.widget, this.paint);
                break;
              case exports2.Unit.year:
                this.yearDisplay._update(this.widget, this.paint);
                break;
              case "decade":
                this.decadeDisplay._update(this.widget, this.paint);
                break;
              case "clock":
                if (!this._hasTime)
                  break;
                this.timeDisplay._update(this.widget);
                this._update(exports2.Unit.hours);
                this._update(exports2.Unit.minutes);
                this._update(exports2.Unit.seconds);
                break;
              case "calendar":
                this._update(exports2.Unit.date);
                this._update(exports2.Unit.year);
                this._update(exports2.Unit.month);
                this.decadeDisplay._update(this.widget, this.paint);
                this._updateCalendarHeader();
                break;
              case "all":
                if (this._hasTime) {
                  this._update("clock");
                }
                if (this._hasDate) {
                  this._update("calendar");
                }
            }
          }
          // noinspection JSUnusedLocalSymbols
          /**
           * Allows developers to add/remove classes from an element.
           * @param _unit
           * @param _date
           * @param _classes
           * @param _element
           */
          /* eslint-disable @typescript-eslint/no-unused-vars */
          paint(_unit, _date, _classes, _element) {
          }
          /**
           * Shows the picker and creates a Popper instance if needed.
           * Add document click event to hide when clicking outside the picker.
           * fires Events#show
           */
          show() {
            if (this.widget == void 0) {
              this._showSetDefaultIfNeeded();
              this._buildWidget();
              this._updateTheme();
              this._showSetupViewMode();
              if (!this.optionsStore.options.display.inline) {
                const container = this.optionsStore.options?.container || document.body;
                const placement = this.optionsStore.options?.display?.placement || "bottom";
                container.appendChild(this.widget);
                this.createPopup(this.optionsStore.element, this.widget, {
                  modifiers: [{ name: "eventListeners", enabled: true }],
                  //#2400
                  placement: document.documentElement.dir === "rtl" ? `${placement}-end` : `${placement}-start`
                }).then();
              } else {
                this.optionsStore.element.appendChild(this.widget);
              }
              if (this.optionsStore.options.display.viewMode == "clock") {
                this._eventEmitters.action.emit({
                  e: null,
                  action: ActionTypes$1.showClock
                });
              }
              this.widget.querySelectorAll("[data-action]").forEach((element) => element.addEventListener("click", this._actionsClickEvent));
              if (this._hasTime && this.optionsStore.options.display.sideBySide) {
                this.timeDisplay._update(this.widget);
                this.widget.getElementsByClassName(Namespace.css.clockContainer)[0].style.display = "grid";
              }
            }
            this.widget.classList.add(Namespace.css.show);
            if (!this.optionsStore.options.display.inline) {
              this.updatePopup();
              document.addEventListener("click", this._documentClickEvent);
            }
            this._eventEmitters.triggerEvent.emit({ type: Namespace.events.show });
            this._isVisible = true;
          }
          _showSetupViewMode() {
            const onlyClock = this._hasTime && !this._hasDate;
            if (onlyClock) {
              this.optionsStore.currentView = "clock";
              this._eventEmitters.action.emit({
                e: null,
                action: ActionTypes$1.showClock
              });
            } else if (!this.optionsStore.currentCalendarViewMode) {
              this.optionsStore.currentCalendarViewMode = this.optionsStore.minimumCalendarViewMode;
            }
            if (!onlyClock && this.optionsStore.options.display.viewMode !== "clock") {
              if (this._hasTime) {
                if (!this.optionsStore.options.display.sideBySide) {
                  Collapse.hideImmediately(this.timeContainer);
                } else {
                  Collapse.show(this.timeContainer);
                }
              }
              Collapse.show(this.dateContainer);
            }
            if (this._hasDate) {
              this._showMode();
            }
          }
          _showSetDefaultIfNeeded() {
            if (this.dates.picked.length != 0)
              return;
            if (this.optionsStore.options.useCurrent && !this.optionsStore.options.defaultDate) {
              const date = new DateTime().setLocalization(this.optionsStore.options.localization);
              if (!this.optionsStore.options.keepInvalid) {
                let tries = 0;
                let direction = 1;
                if (this.optionsStore.options.restrictions.maxDate?.isBefore(date)) {
                  direction = -1;
                }
                while (!this.validation.isValid(date) && tries > 31) {
                  date.manipulate(direction, exports2.Unit.date);
                  tries++;
                }
              }
              this.dates.setValue(date);
            }
            if (this.optionsStore.options.defaultDate) {
              this.dates.setValue(this.optionsStore.options.defaultDate);
            }
          }
          async createPopup(element, widget, options) {
            let createPopperFunction;
            if (window?.Popper) {
              createPopperFunction = window?.Popper?.createPopper;
            } else {
              const { createPopper: createPopper4 } = await Promise.resolve().then(() => (init_lib(), lib_exports));
              createPopperFunction = createPopper4;
            }
            if (createPopperFunction) {
              this._popperInstance = createPopperFunction(element, widget, options);
            }
          }
          updatePopup() {
            this._popperInstance?.update();
          }
          /**
           * Changes the calendar view mode. E.g. month <-> year
           * @param direction -/+ number to move currentViewMode
           * @private
           */
          _showMode(direction) {
            if (!this.widget) {
              return;
            }
            if (direction) {
              const max2 = Math.max(this.optionsStore.minimumCalendarViewMode, Math.min(3, this.optionsStore.currentCalendarViewMode + direction));
              if (this.optionsStore.currentCalendarViewMode == max2)
                return;
              this.optionsStore.currentCalendarViewMode = max2;
            }
            this.widget.querySelectorAll(`.${Namespace.css.dateContainer} > div:not(.${Namespace.css.calendarHeader}), .${Namespace.css.timeContainer} > div:not(.${Namespace.css.clockContainer})`).forEach((e) => e.style.display = "none");
            const datePickerMode = CalendarModes[this.optionsStore.currentCalendarViewMode];
            const picker = this.widget.querySelector(`.${datePickerMode.className}`);
            switch (datePickerMode.className) {
              case Namespace.css.decadesContainer:
                this.decadeDisplay._update(this.widget, this.paint);
                break;
              case Namespace.css.yearsContainer:
                this.yearDisplay._update(this.widget, this.paint);
                break;
              case Namespace.css.monthsContainer:
                this.monthDisplay._update(this.widget, this.paint);
                break;
              case Namespace.css.daysContainer:
                this.dateDisplay._update(this.widget, this.paint);
                break;
            }
            picker.style.display = "grid";
            if (this.optionsStore.options.display.sideBySide)
              this.widget.querySelectorAll(`.${Namespace.css.clockContainer}`)[0].style.display = "grid";
            this._updateCalendarHeader();
            this._eventEmitters.viewUpdate.emit();
          }
          /**
           * Changes the theme. E.g. light, dark or auto
           * @param theme the theme name
           * @private
           */
          _updateTheme(theme) {
            if (!this.widget) {
              return;
            }
            if (theme) {
              if (this.optionsStore.options.display.theme === theme)
                return;
              this.optionsStore.options.display.theme = theme;
            }
            this.widget.classList.remove("light", "dark");
            this.widget.classList.add(this._getThemeClass());
            if (this.optionsStore.options.display.theme === "auto") {
              window.matchMedia(Namespace.css.isDarkPreferredQuery).addEventListener("change", () => this._updateTheme());
            } else {
              window.matchMedia(Namespace.css.isDarkPreferredQuery).removeEventListener("change", () => this._updateTheme());
            }
          }
          _getThemeClass() {
            const currentTheme = this.optionsStore.options.display.theme || "auto";
            const isDarkMode = window.matchMedia && window.matchMedia(Namespace.css.isDarkPreferredQuery).matches;
            switch (currentTheme) {
              case "light":
                return Namespace.css.lightTheme;
              case "dark":
                return Namespace.css.darkTheme;
              case "auto":
                return isDarkMode ? Namespace.css.darkTheme : Namespace.css.lightTheme;
            }
          }
          _updateCalendarHeader() {
            if (!this._hasDate)
              return;
            const showing = [
              ...this.widget.querySelector(`.${Namespace.css.dateContainer} div[style*="display: grid"]`).classList
            ].find((x) => x.startsWith(Namespace.css.dateContainer));
            const [previous, switcher, next] = this.widget.getElementsByClassName(Namespace.css.calendarHeader)[0].getElementsByTagName("div");
            switch (showing) {
              case Namespace.css.decadesContainer:
                previous.setAttribute("title", this.optionsStore.options.localization.previousCentury);
                switcher.setAttribute("title", "");
                next.setAttribute("title", this.optionsStore.options.localization.nextCentury);
                break;
              case Namespace.css.yearsContainer:
                previous.setAttribute("title", this.optionsStore.options.localization.previousDecade);
                switcher.setAttribute("title", this.optionsStore.options.localization.selectDecade);
                next.setAttribute("title", this.optionsStore.options.localization.nextDecade);
                break;
              case Namespace.css.monthsContainer:
                previous.setAttribute("title", this.optionsStore.options.localization.previousYear);
                switcher.setAttribute("title", this.optionsStore.options.localization.selectYear);
                next.setAttribute("title", this.optionsStore.options.localization.nextYear);
                break;
              case Namespace.css.daysContainer:
                previous.setAttribute("title", this.optionsStore.options.localization.previousMonth);
                switcher.setAttribute("title", this.optionsStore.options.localization.selectMonth);
                next.setAttribute("title", this.optionsStore.options.localization.nextMonth);
                switcher.setAttribute(showing, this.optionsStore.viewDate.format(this.optionsStore.options.localization.dayViewHeaderFormat));
                break;
            }
            switcher.innerText = switcher.getAttribute(showing);
          }
          /**
           * Hides the picker if needed.
           * Remove document click event to hide when clicking outside the picker.
           * fires Events#hide
           */
          hide() {
            if (!this.widget || !this._isVisible)
              return;
            this.widget.classList.remove(Namespace.css.show);
            if (this._isVisible) {
              this._eventEmitters.triggerEvent.emit({
                type: Namespace.events.hide,
                date: this.optionsStore.unset ? null : this.dates.lastPicked?.clone
              });
              this._isVisible = false;
            }
            document.removeEventListener("click", this._documentClickEvent);
          }
          /**
           * Toggles the picker's open state. Fires a show/hide event depending.
           */
          toggle() {
            return this._isVisible ? this.hide() : this.show();
          }
          /**
           * Removes document and data-action click listener and reset the widget
           * @private
           */
          _dispose() {
            document.removeEventListener("click", this._documentClickEvent);
            if (!this.widget)
              return;
            this.widget.querySelectorAll("[data-action]").forEach((element) => element.removeEventListener("click", this._actionsClickEvent));
            this.widget.parentNode.removeChild(this.widget);
            this._widget = void 0;
          }
          /**
           * Builds the widgets html template.
           * @private
           */
          _buildWidget() {
            const template = document.createElement("div");
            template.classList.add(Namespace.css.widget);
            const dateView = document.createElement("div");
            dateView.classList.add(Namespace.css.dateContainer);
            dateView.append(this.getHeadTemplate(), this.decadeDisplay.getPicker(), this.yearDisplay.getPicker(), this.monthDisplay.getPicker(), this.dateDisplay.getPicker());
            const timeView = document.createElement("div");
            timeView.classList.add(Namespace.css.timeContainer);
            timeView.appendChild(this.timeDisplay.getPicker(this._iconTag.bind(this)));
            timeView.appendChild(this.hourDisplay.getPicker());
            timeView.appendChild(this.minuteDisplay.getPicker());
            timeView.appendChild(this.secondDisplay.getPicker());
            const toolbar = document.createElement("div");
            toolbar.classList.add(Namespace.css.toolbar);
            toolbar.append(...this.getToolbarElements());
            if (this.optionsStore.options.display.inline) {
              template.classList.add(Namespace.css.inline);
            }
            if (this.optionsStore.options.display.calendarWeeks) {
              template.classList.add("calendarWeeks");
            }
            if (this.optionsStore.options.display.sideBySide && this._hasDateAndTime) {
              this._buildWidgetSideBySide(template, dateView, timeView, toolbar);
              return;
            }
            if (this.optionsStore.options.display.toolbarPlacement === "top") {
              template.appendChild(toolbar);
            }
            const setupComponentView = (hasFirst, hasSecond, element, shouldShow) => {
              if (!hasFirst)
                return;
              if (hasSecond) {
                element.classList.add(Namespace.css.collapse);
                if (shouldShow)
                  element.classList.add(Namespace.css.show);
              }
              template.appendChild(element);
            };
            setupComponentView(this._hasDate, this._hasTime, dateView, this.optionsStore.options.display.viewMode !== "clock");
            setupComponentView(this._hasTime, this._hasDate, timeView, this.optionsStore.options.display.viewMode === "clock");
            if (this.optionsStore.options.display.toolbarPlacement === "bottom") {
              template.appendChild(toolbar);
            }
            const arrow2 = document.createElement("div");
            arrow2.classList.add("arrow");
            arrow2.setAttribute("data-popper-arrow", "");
            template.appendChild(arrow2);
            this._widget = template;
          }
          _buildWidgetSideBySide(template, dateView, timeView, toolbar) {
            template.classList.add(Namespace.css.sideBySide);
            if (this.optionsStore.options.display.toolbarPlacement === "top") {
              template.appendChild(toolbar);
            }
            const row = document.createElement("div");
            row.classList.add("td-row");
            dateView.classList.add("td-half");
            timeView.classList.add("td-half");
            row.appendChild(dateView);
            row.appendChild(timeView);
            template.appendChild(row);
            if (this.optionsStore.options.display.toolbarPlacement === "bottom") {
              template.appendChild(toolbar);
            }
            this._widget = template;
          }
          /**
           * Returns true if the hours, minutes, or seconds component is turned on
           */
          get _hasTime() {
            return this.optionsStore.options.display.components.clock && (this.optionsStore.options.display.components.hours || this.optionsStore.options.display.components.minutes || this.optionsStore.options.display.components.seconds);
          }
          /**
           * Returns true if the year, month, or date component is turned on
           */
          get _hasDate() {
            return this.optionsStore.options.display.components.calendar && (this.optionsStore.options.display.components.year || this.optionsStore.options.display.components.month || this.optionsStore.options.display.components.date);
          }
          get _hasDateAndTime() {
            return this._hasDate && this._hasTime;
          }
          /**
           * Get the toolbar html based on options like buttons => today
           * @private
           */
          getToolbarElements() {
            const toolbar = [];
            if (this.optionsStore.options.display.buttons.today) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.today);
              div.setAttribute("title", this.optionsStore.options.localization.today);
              div.appendChild(this._iconTag(this.optionsStore.options.display.icons.today));
              toolbar.push(div);
            }
            if (!this.optionsStore.options.display.sideBySide && this._hasDate && this._hasTime) {
              let title, icon;
              if (this.optionsStore.options.display.viewMode === "clock") {
                title = this.optionsStore.options.localization.selectDate;
                icon = this.optionsStore.options.display.icons.date;
              } else {
                title = this.optionsStore.options.localization.selectTime;
                icon = this.optionsStore.options.display.icons.time;
              }
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.togglePicker);
              div.setAttribute("title", title);
              div.appendChild(this._iconTag(icon));
              toolbar.push(div);
            }
            if (this.optionsStore.options.display.buttons.clear) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.clear);
              div.setAttribute("title", this.optionsStore.options.localization.clear);
              div.appendChild(this._iconTag(this.optionsStore.options.display.icons.clear));
              toolbar.push(div);
            }
            if (this.optionsStore.options.display.buttons.close) {
              const div = document.createElement("div");
              div.setAttribute("data-action", ActionTypes$1.close);
              div.setAttribute("title", this.optionsStore.options.localization.close);
              div.appendChild(this._iconTag(this.optionsStore.options.display.icons.close));
              toolbar.push(div);
            }
            return toolbar;
          }
          /***
           * Builds the base header template with next and previous icons
           * @private
           */
          getHeadTemplate() {
            const calendarHeader = document.createElement("div");
            calendarHeader.classList.add(Namespace.css.calendarHeader);
            const previous = document.createElement("div");
            previous.classList.add(Namespace.css.previous);
            previous.setAttribute("data-action", ActionTypes$1.previous);
            previous.appendChild(this._iconTag(this.optionsStore.options.display.icons.previous));
            const switcher = document.createElement("div");
            switcher.classList.add(Namespace.css.switch);
            switcher.setAttribute("data-action", ActionTypes$1.changeCalendarView);
            const next = document.createElement("div");
            next.classList.add(Namespace.css.next);
            next.setAttribute("data-action", ActionTypes$1.next);
            next.appendChild(this._iconTag(this.optionsStore.options.display.icons.next));
            calendarHeader.append(previous, switcher, next);
            return calendarHeader;
          }
          /**
           * Builds an icon tag as either an `<i>`
           * or with icons => type is `sprites` then a svg tag instead
           * @param iconClass
           * @private
           */
          _iconTag(iconClass) {
            if (this.optionsStore.options.display.icons.type === "sprites") {
              const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
              const icon2 = document.createElementNS("http://www.w3.org/2000/svg", "use");
              icon2.setAttribute("xlink:href", iconClass);
              icon2.setAttribute("href", iconClass);
              svg.appendChild(icon2);
              return svg;
            }
            const icon = document.createElement("i");
            icon.classList.add(...iconClass.split(" "));
            return icon;
          }
          /**
           * Causes the widget to get rebuilt on next show. If the picker is already open
           * then hide and reshow it.
           * @private
           */
          _rebuild() {
            const wasVisible = this._isVisible;
            this._dispose();
            if (wasVisible)
              this.show();
          }
          refreshCurrentView() {
            if (!this._isVisible)
              this._dispose();
            switch (this.optionsStore.currentView) {
              case "clock":
                this._update("clock");
                break;
              case "calendar":
                this._update(exports2.Unit.date);
                break;
              case "months":
                this._update(exports2.Unit.month);
                break;
              case "years":
                this._update(exports2.Unit.year);
                break;
              case "decades":
                this._update("decade");
                break;
            }
          }
        }
        class Actions {
          constructor() {
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.dates = serviceLocator.locate(Dates);
            this.validation = serviceLocator.locate(Validation);
            this.display = serviceLocator.locate(Display);
            this._eventEmitters = serviceLocator.locate(EventEmitters);
            this._eventEmitters.action.subscribe((result) => {
              this.do(result.e, result.action);
            });
          }
          /**
           * Performs the selected `action`. See ActionTypes
           * @param e This is normally a click event
           * @param action If not provided, then look for a [data-action]
           */
          //eslint-disable-next-line @typescript-eslint/no-explicit-any
          do(e, action) {
            const currentTarget = e?.currentTarget;
            if (currentTarget?.classList?.contains(Namespace.css.disabled))
              return;
            action = action || currentTarget?.dataset?.action;
            const lastPicked = (this.dates.lastPicked || this.optionsStore.viewDate).clone;
            switch (action) {
              case ActionTypes$1.next:
              case ActionTypes$1.previous:
                this.handleNextPrevious(action);
                break;
              case ActionTypes$1.changeCalendarView:
                this.display._showMode(1);
                this.display._updateCalendarHeader();
                break;
              case ActionTypes$1.selectMonth:
              case ActionTypes$1.selectYear:
              case ActionTypes$1.selectDecade:
                this.handleSelectCalendarMode(action, currentTarget);
                break;
              case ActionTypes$1.selectDay:
                this.handleSelectDay(currentTarget);
                break;
              case ActionTypes$1.selectHour: {
                let hour = +currentTarget.dataset.value;
                if (lastPicked.hours >= 12 && this.optionsStore.isTwelveHour)
                  hour += 12;
                lastPicked.hours = hour;
                this.dates.setValue(lastPicked, this.dates.lastPickedIndex);
                this.hideOrClock(e);
                break;
              }
              case ActionTypes$1.selectMinute: {
                lastPicked.minutes = +currentTarget.dataset.value;
                this.dates.setValue(lastPicked, this.dates.lastPickedIndex);
                this.hideOrClock(e);
                break;
              }
              case ActionTypes$1.selectSecond: {
                lastPicked.seconds = +currentTarget.dataset.value;
                this.dates.setValue(lastPicked, this.dates.lastPickedIndex);
                this.hideOrClock(e);
                break;
              }
              case ActionTypes$1.incrementHours:
                this.manipulateAndSet(lastPicked, exports2.Unit.hours);
                break;
              case ActionTypes$1.incrementMinutes:
                this.manipulateAndSet(lastPicked, exports2.Unit.minutes, this.optionsStore.options.stepping);
                break;
              case ActionTypes$1.incrementSeconds:
                this.manipulateAndSet(lastPicked, exports2.Unit.seconds);
                break;
              case ActionTypes$1.decrementHours:
                this.manipulateAndSet(lastPicked, exports2.Unit.hours, -1);
                break;
              case ActionTypes$1.decrementMinutes:
                this.manipulateAndSet(lastPicked, exports2.Unit.minutes, this.optionsStore.options.stepping * -1);
                break;
              case ActionTypes$1.decrementSeconds:
                this.manipulateAndSet(lastPicked, exports2.Unit.seconds, -1);
                break;
              case ActionTypes$1.toggleMeridiem:
                this.manipulateAndSet(lastPicked, exports2.Unit.hours, this.dates.lastPicked.hours >= 12 ? -12 : 12);
                break;
              case ActionTypes$1.togglePicker:
                this.handleToggle(currentTarget);
                break;
              case ActionTypes$1.showClock:
              case ActionTypes$1.showHours:
              case ActionTypes$1.showMinutes:
              case ActionTypes$1.showSeconds:
                if (!this.optionsStore.options.display.sideBySide && this.optionsStore.currentView !== "clock") {
                  Collapse.hideImmediately(this.display.dateContainer);
                  Collapse.showImmediately(this.display.timeContainer);
                }
                this.handleShowClockContainers(action);
                break;
              case ActionTypes$1.clear:
                this.dates.setValue(null);
                this.display._updateCalendarHeader();
                break;
              case ActionTypes$1.close:
                this.display.hide();
                break;
              case ActionTypes$1.today: {
                const today = new DateTime().setLocalization(this.optionsStore.options.localization);
                this._eventEmitters.updateViewDate.emit(today);
                if (this.validation.isValid(today, exports2.Unit.date))
                  this.dates.setValue(today, this.dates.lastPickedIndex);
                break;
              }
            }
          }
          handleShowClockContainers(action) {
            if (!this.display._hasTime) {
              Namespace.errorMessages.throwError("Cannot show clock containers when time is disabled.");
              return;
            }
            this.optionsStore.currentView = "clock";
            this.display.widget.querySelectorAll(`.${Namespace.css.timeContainer} > div`).forEach((htmlElement) => htmlElement.style.display = "none");
            let classToUse = "";
            switch (action) {
              case ActionTypes$1.showClock:
                classToUse = Namespace.css.clockContainer;
                this.display._update("clock");
                break;
              case ActionTypes$1.showHours:
                classToUse = Namespace.css.hourContainer;
                this.display._update(exports2.Unit.hours);
                break;
              case ActionTypes$1.showMinutes:
                classToUse = Namespace.css.minuteContainer;
                this.display._update(exports2.Unit.minutes);
                break;
              case ActionTypes$1.showSeconds:
                classToUse = Namespace.css.secondContainer;
                this.display._update(exports2.Unit.seconds);
                break;
            }
            this.display.widget.getElementsByClassName(classToUse)[0].style.display = "grid";
          }
          handleNextPrevious(action) {
            const { unit, step } = CalendarModes[this.optionsStore.currentCalendarViewMode];
            if (action === ActionTypes$1.next)
              this.optionsStore.viewDate.manipulate(step, unit);
            else
              this.optionsStore.viewDate.manipulate(step * -1, unit);
            this._eventEmitters.viewUpdate.emit();
            this.display._showMode();
          }
          /**
           * After setting the value it will either show the clock or hide the widget.
           * @param e
           */
          hideOrClock(e) {
            if (!this.optionsStore.isTwelveHour && !this.optionsStore.options.display.components.minutes && !this.optionsStore.options.display.keepOpen && !this.optionsStore.options.display.inline) {
              this.display.hide();
            } else {
              this.do(e, ActionTypes$1.showClock);
            }
          }
          /**
           * Common function to manipulate {@link lastPicked} by `unit`.
           * @param lastPicked
           * @param unit
           * @param value Value to change by
           */
          manipulateAndSet(lastPicked, unit, value = 1) {
            const newDate = lastPicked.manipulate(value, unit);
            if (this.validation.isValid(newDate, unit)) {
              this.dates.setValue(newDate, this.dates.lastPickedIndex);
            }
          }
          handleSelectCalendarMode(action, currentTarget) {
            const value = +currentTarget.dataset.value;
            switch (action) {
              case ActionTypes$1.selectMonth:
                this.optionsStore.viewDate.month = value;
                break;
              case ActionTypes$1.selectYear:
              case ActionTypes$1.selectDecade:
                this.optionsStore.viewDate.year = value;
                break;
            }
            if (this.optionsStore.currentCalendarViewMode === this.optionsStore.minimumCalendarViewMode) {
              this.dates.setValue(this.optionsStore.viewDate, this.dates.lastPickedIndex);
              if (!this.optionsStore.options.display.inline) {
                this.display.hide();
              }
            } else {
              this.display._showMode(-1);
            }
          }
          handleToggle(currentTarget) {
            if (currentTarget.getAttribute("title") === this.optionsStore.options.localization.selectDate) {
              currentTarget.setAttribute("title", this.optionsStore.options.localization.selectTime);
              currentTarget.innerHTML = this.display._iconTag(this.optionsStore.options.display.icons.time).outerHTML;
              this.display._updateCalendarHeader();
              this.optionsStore.refreshCurrentView();
            } else {
              currentTarget.setAttribute("title", this.optionsStore.options.localization.selectDate);
              currentTarget.innerHTML = this.display._iconTag(this.optionsStore.options.display.icons.date).outerHTML;
              if (this.display._hasTime) {
                this.handleShowClockContainers(ActionTypes$1.showClock);
                this.display._update("clock");
              }
            }
            this.display.widget.querySelectorAll(`.${Namespace.css.dateContainer}, .${Namespace.css.timeContainer}`).forEach((htmlElement) => Collapse.toggle(htmlElement));
            this._eventEmitters.viewUpdate.emit();
          }
          handleSelectDay(currentTarget) {
            const day = this.optionsStore.viewDate.clone;
            if (currentTarget.classList.contains(Namespace.css.old)) {
              day.manipulate(-1, exports2.Unit.month);
            }
            if (currentTarget.classList.contains(Namespace.css.new)) {
              day.manipulate(1, exports2.Unit.month);
            }
            day.date = +currentTarget.dataset.day;
            if (this.optionsStore.options.dateRange)
              this.handleDateRange(day);
            else if (this.optionsStore.options.multipleDates) {
              this.handleMultiDate(day);
            } else {
              this.dates.setValue(day, this.dates.lastPickedIndex);
            }
            if (!this.display._hasTime && !this.optionsStore.options.display.keepOpen && !this.optionsStore.options.display.inline && !this.optionsStore.options.multipleDates && !this.optionsStore.options.dateRange) {
              this.display.hide();
            }
          }
          handleMultiDate(day) {
            let index = this.dates.pickedIndex(day, exports2.Unit.date);
            console.log(index);
            if (index !== -1) {
              this.dates.setValue(null, index);
            } else {
              index = this.dates.lastPickedIndex + 1;
              if (this.dates.picked.length === 0)
                index = 0;
              this.dates.setValue(day, index);
            }
          }
          handleDateRange(day) {
            switch (this.dates.picked.length) {
              case 2: {
                this.dates.clear();
                break;
              }
              case 1: {
                const other = this.dates.picked[0];
                if (day.getTime() === other.getTime()) {
                  this.dates.clear();
                  break;
                }
                if (day.isBefore(other)) {
                  this.dates.setValue(day, 0);
                  this.dates.setValue(other, 1);
                  return;
                } else {
                  this.dates.setValue(day, 1);
                  return;
                }
              }
            }
            this.dates.setValue(day, 0);
          }
        }
        class TempusDominus {
          constructor(element, options = {}) {
            this._subscribers = {};
            this._isDisabled = false;
            this._inputChangeEvent = (event) => {
              const internallyTriggered = event?.detail;
              if (internallyTriggered)
                return;
              const setViewDate = () => {
                if (this.dates.lastPicked)
                  this.optionsStore.viewDate = this.dates.lastPicked.clone;
              };
              const value = this.optionsStore.input.value;
              if (this.optionsStore.options.multipleDates || this.optionsStore.options.dateRange) {
                try {
                  const valueSplit = value.split(this.optionsStore.options.multipleDatesSeparator);
                  for (let i = 0; i < valueSplit.length; i++) {
                    this.dates.setFromInput(valueSplit[i], i);
                  }
                  setViewDate();
                } catch {
                  console.warn("TD: Something went wrong trying to set the multipleDates values from the input field.");
                }
              } else {
                this.dates.setFromInput(value, 0);
                setViewDate();
              }
            };
            this._toggleClickEvent = () => {
              if (this.optionsStore.element?.disabled || this.optionsStore.input?.disabled || //if we just have the input and allow input toggle is enabled, then don't cause a toggle
              this._toggle.nodeName === "INPUT" && this._toggle?.type === "text" && this.optionsStore.options.allowInputToggle)
                return;
              this.toggle();
            };
            this._openClickEvent = () => {
              if (this.optionsStore.element?.disabled || this.optionsStore.input?.disabled)
                return;
              if (!this.display.isVisible)
                this.show();
            };
            setupServiceLocator();
            this._eventEmitters = serviceLocator.locate(EventEmitters);
            this.optionsStore = serviceLocator.locate(OptionsStore);
            this.display = serviceLocator.locate(Display);
            this.dates = serviceLocator.locate(Dates);
            this.actions = serviceLocator.locate(Actions);
            if (!element) {
              Namespace.errorMessages.mustProvideElement();
            }
            this.optionsStore.element = element;
            this._initializeOptions(options, DefaultOptions, true);
            this.optionsStore.viewDate.setLocalization(this.optionsStore.options.localization);
            this.optionsStore.unset = true;
            this._initializeInput();
            this._initializeToggle();
            if (this.optionsStore.options.display.inline)
              this.display.show();
            this._eventEmitters.triggerEvent.subscribe((e) => {
              this._triggerEvent(e);
            });
            this._eventEmitters.viewUpdate.subscribe(() => {
              this._viewUpdate();
            });
            this._eventEmitters.updateViewDate.subscribe((dateTime) => {
              this.viewDate = dateTime;
            });
          }
          get viewDate() {
            return this.optionsStore.viewDate;
          }
          set viewDate(value) {
            this.optionsStore.viewDate = value;
            this.optionsStore.viewDate.setLocalization(this.optionsStore.options.localization);
            this.display._update(this.optionsStore.currentView === "clock" ? "clock" : "calendar");
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Update the picker options. If `reset` is provide `options` will be merged with DefaultOptions instead.
           * @param options
           * @param reset
           * @public
           */
          updateOptions(options, reset = false) {
            if (reset)
              this._initializeOptions(options, DefaultOptions);
            else
              this._initializeOptions(options, this.optionsStore.options);
            this.optionsStore.viewDate.setLocalization(this.optionsStore.options.localization);
            this.display.refreshCurrentView();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Toggles the picker open or closed. If the picker is disabled, nothing will happen.
           * @public
           */
          toggle() {
            if (this._isDisabled)
              return;
            this.display.toggle();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Shows the picker unless the picker is disabled.
           * @public
           */
          show() {
            if (this._isDisabled)
              return;
            this.display.show();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Hides the picker unless the picker is disabled.
           * @public
           */
          hide() {
            this.display.hide();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Disables the picker and the target input field.
           * @public
           */
          disable() {
            this._isDisabled = true;
            this.optionsStore.input?.setAttribute("disabled", "disabled");
            this.display.hide();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Enables the picker and the target input field.
           * @public
           */
          enable() {
            this._isDisabled = false;
            this.optionsStore.input?.removeAttribute("disabled");
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Clears all the selected dates
           * @public
           */
          clear() {
            this.optionsStore.input.value = "";
            this.dates.clear();
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Allows for a direct subscription to picker events, without having to use addEventListener on the element.
           * @param eventTypes See Namespace.Events
           * @param callbacks Function to call when event is triggered
           * @public
           */
          subscribe(eventTypes, callbacks) {
            if (typeof eventTypes === "string") {
              eventTypes = [eventTypes];
            }
            let callBackArray;
            if (!Array.isArray(callbacks)) {
              callBackArray = [callbacks];
            } else {
              callBackArray = callbacks;
            }
            if (eventTypes.length !== callBackArray.length) {
              Namespace.errorMessages.subscribeMismatch();
            }
            const returnArray = [];
            for (let i = 0; i < eventTypes.length; i++) {
              const eventType = eventTypes[i];
              if (!Array.isArray(this._subscribers[eventType])) {
                this._subscribers[eventType] = [];
              }
              this._subscribers[eventType].push(callBackArray[i]);
              returnArray.push({
                unsubscribe: this._unsubscribe.bind(this, eventType, this._subscribers[eventType].length - 1)
              });
              if (eventTypes.length === 1) {
                return returnArray[0];
              }
            }
            return returnArray;
          }
          // noinspection JSUnusedGlobalSymbols
          /**
           * Hides the picker and removes event listeners
           */
          dispose() {
            this.display.hide();
            this.display._dispose();
            this._eventEmitters.destroy();
            this.optionsStore.input?.removeEventListener("change", this._inputChangeEvent);
            if (this.optionsStore.options.allowInputToggle) {
              this.optionsStore.input?.removeEventListener("click", this._openClickEvent);
              this.optionsStore.input?.removeEventListener("focus", this._openClickEvent);
            }
            this._toggle?.removeEventListener("click", this._toggleClickEvent);
            this._subscribers = {};
          }
          /**
           * Updates the options to use the provided language.
           * THe language file must be loaded first.
           * @param language
           */
          locale(language) {
            const asked = loadedLocales[language];
            if (!asked)
              return;
            this.updateOptions({
              localization: asked
            });
          }
          /**
           * Triggers an event like ChangeEvent when the picker has updated the value
           * of a selected date.
           * @param event Accepts a BaseEvent object.
           * @private
           */
          _triggerEvent(event) {
            event.viewMode = this.optionsStore.currentView;
            const isChangeEvent = event.type === Namespace.events.change;
            if (isChangeEvent) {
              const { date, oldDate, isClear } = event;
              if (date && oldDate && date.isSame(oldDate) || !isClear && !date && !oldDate) {
                return;
              }
              this._handleAfterChangeEvent(event);
              this.optionsStore.input?.dispatchEvent(
                //eslint-disable-next-line @typescript-eslint/no-explicit-any
                new CustomEvent("change", { detail: event })
              );
            }
            this.optionsStore.element.dispatchEvent(
              //eslint-disable-next-line @typescript-eslint/no-explicit-any
              new CustomEvent(event.type, { detail: event })
            );
            if (window.jQuery) {
              const $ = window.jQuery;
              if (isChangeEvent && this.optionsStore.input) {
                $(this.optionsStore.input).trigger(event);
              } else {
                $(this.optionsStore.element).trigger(event);
              }
            }
            this._publish(event);
          }
          _publish(event) {
            if (!Array.isArray(this._subscribers[event.type])) {
              return;
            }
            this._subscribers[event.type].forEach((callback) => {
              callback(event);
            });
          }
          /**
           * Fires a ViewUpdate event when, for example, the month view is changed.
           * @private
           */
          _viewUpdate() {
            this._triggerEvent({
              type: Namespace.events.update,
              viewDate: this.optionsStore.viewDate.clone
            });
          }
          _unsubscribe(eventName, index) {
            this._subscribers[eventName].splice(index, 1);
          }
          /**
           * Merges two Option objects together and validates options type
           * @param config new Options
           * @param mergeTo Options to merge into
           * @param includeDataset When true, the elements data-td attributes will be included in the
           * @private
           */
          _initializeOptions(config, mergeTo, includeDataset = false) {
            let newConfig = OptionConverter.deepCopy(config);
            newConfig = OptionConverter._mergeOptions(newConfig, mergeTo);
            if (includeDataset)
              newConfig = OptionConverter._dataToOptions(this.optionsStore.element, newConfig);
            OptionConverter._validateConflicts(newConfig);
            newConfig.viewDate = newConfig.viewDate.setLocalization(newConfig.localization);
            if (!this.optionsStore.viewDate.isSame(newConfig.viewDate)) {
              this.optionsStore.viewDate = newConfig.viewDate;
            }
            if (newConfig.display.components.year) {
              this.optionsStore.minimumCalendarViewMode = 2;
            }
            if (newConfig.display.components.month) {
              this.optionsStore.minimumCalendarViewMode = 1;
            }
            if (newConfig.display.components.date) {
              this.optionsStore.minimumCalendarViewMode = 0;
            }
            this.optionsStore.currentCalendarViewMode = Math.max(this.optionsStore.minimumCalendarViewMode, this.optionsStore.currentCalendarViewMode);
            if (CalendarModes[this.optionsStore.currentCalendarViewMode].name !== newConfig.display.viewMode) {
              this.optionsStore.currentCalendarViewMode = Math.max(CalendarModes.findIndex((x) => x.name === newConfig.display.viewMode), this.optionsStore.minimumCalendarViewMode);
            }
            if (this.display?.isVisible) {
              this.display._update("all");
            }
            if (newConfig.display.components.useTwentyfourHour && newConfig.localization.hourCycle === void 0)
              newConfig.localization.hourCycle = "h24";
            else if (newConfig.localization.hourCycle === void 0) {
              newConfig.localization.hourCycle = guessHourCycle(newConfig.localization.locale);
            }
            this.optionsStore.options = newConfig;
            if (newConfig.restrictions.maxDate && this.viewDate.isAfter(newConfig.restrictions.maxDate))
              this.viewDate = newConfig.restrictions.maxDate;
            if (newConfig.restrictions.minDate && this.viewDate.isBefore(newConfig.restrictions.minDate))
              this.viewDate = newConfig.restrictions.minDate;
          }
          /**
           * Checks if an input field is being used, attempts to locate one and sets an
           * event listener if found.
           * @private
           */
          _initializeInput() {
            if (this.optionsStore.element.tagName == "INPUT") {
              this.optionsStore.input = this.optionsStore.element;
            } else {
              const query = this.optionsStore.element.dataset.tdTargetInput;
              if (query == void 0 || query == "nearest") {
                this.optionsStore.input = this.optionsStore.element.querySelector("input");
              } else {
                this.optionsStore.input = this.optionsStore.element.querySelector(query);
              }
            }
            if (!this.optionsStore.input)
              return;
            if (!this.optionsStore.input.value && this.optionsStore.options.defaultDate)
              this.optionsStore.input.value = this.dates.formatInput(this.optionsStore.options.defaultDate);
            this.optionsStore.input.addEventListener("change", this._inputChangeEvent);
            if (this.optionsStore.options.allowInputToggle) {
              this.optionsStore.input.addEventListener("click", this._openClickEvent);
              this.optionsStore.input.addEventListener("focus", this._openClickEvent);
            }
            if (this.optionsStore.input.value) {
              this._inputChangeEvent();
            }
          }
          /**
           * Attempts to locate a toggle for the picker and sets an event listener
           * @private
           */
          _initializeToggle() {
            if (this.optionsStore.options.display.inline)
              return;
            let query = this.optionsStore.element.dataset.tdTargetToggle;
            if (query == "nearest") {
              query = '[data-td-toggle="datetimepicker"]';
            }
            this._toggle = query == void 0 ? this.optionsStore.element : this.optionsStore.element.querySelector(query);
            this._toggle.addEventListener("click", this._toggleClickEvent);
          }
          /**
           * If the option is enabled this will render the clock view after a date pick.
           * @param e change event
           * @private
           */
          _handleAfterChangeEvent(e) {
            if (
              // options is disabled
              !this.optionsStore.options.promptTimeOnDateChange || this.optionsStore.options.multipleDates || this.optionsStore.options.display.inline || this.optionsStore.options.display.sideBySide || // time is disabled
              !this.display._hasTime || // clock component is already showing
              this.display.widget?.getElementsByClassName(Namespace.css.show)[0].classList.contains(Namespace.css.timeContainer)
            )
              return;
            if (!e.oldDate && this.optionsStore.options.useCurrent || e.oldDate && e.date?.isSame(e.oldDate)) {
              return;
            }
            clearTimeout(this._currentPromptTimeTimeout);
            this._currentPromptTimeTimeout = setTimeout(() => {
              if (this.display.widget) {
                this._eventEmitters.action.emit({
                  e: {
                    currentTarget: this.display.widget.querySelector('[data-action="togglePicker"]')
                  },
                  action: ActionTypes$1.togglePicker
                });
              }
            }, this.optionsStore.options.promptTimeOnDateChangeTransitionDelay);
          }
        }
        const loadedLocales = {};
        const loadLocale = (l) => {
          if (loadedLocales[l.name])
            return;
          loadedLocales[l.name] = l.localization;
        };
        const locale = (l) => {
          const asked = loadedLocales[l];
          if (!asked)
            return;
          DefaultOptions.localization = asked;
        };
        const extend = function(plugin, option = void 0) {
          if (!plugin)
            return tempusDominus;
          if (!plugin.installed) {
            plugin(option, { TempusDominus, Dates, Display, DateTime, Namespace }, tempusDominus);
            plugin.installed = true;
          }
          return tempusDominus;
        };
        const version = "6.7.19";
        const tempusDominus = {
          TempusDominus,
          extend,
          loadLocale,
          locale,
          Namespace,
          DefaultOptions,
          DateTime,
          Unit: exports2.Unit,
          version,
          DefaultEnLocalization
        };
        exports2.DateTime = DateTime;
        exports2.DefaultEnLocalization = DefaultEnLocalization;
        exports2.DefaultOptions = DefaultOptions;
        exports2.Namespace = Namespace;
        exports2.TempusDominus = TempusDominus;
        exports2.extend = extend;
        exports2.loadLocale = loadLocale;
        exports2.locale = locale;
        exports2.version = version;
        Object.defineProperty(exports2, "__esModule", { value: true });
      });
    }
  });

  // app/input.js
  var require_input = __commonJS({
    "app/input.js"(exports, module) {
      var m3 = require_mithril();
      var api = require_api();
      var tempus = require_tempus_dominus();
      var tempusLocalization = {
        locale: "is",
        startOfTheWeek: 0,
        hourCycle: "h23",
        dateFormats: {
          LTS: "H:mm:ss",
          LT: "H:mm",
          L: "dd.MM.yyyy",
          LL: "d [de] MMMM [de] yyyy",
          LLL: "d [de] MMMM [de] yyyy H:mm",
          LLLL: "dddd, d [de] MMMM [de] yyyy H:mm"
        }
      };
      var Input = {
        oninit: function(vnode) {
          this.tempus = null;
          this.subscription = null;
          this.input = null;
          this.preview = null;
        },
        onremove: function(vnode) {
          if (this.subscription)
            this.subscription.unsubscribe();
          if (this.tempus) {
            this.tempus.dispose();
            this.tempus = null;
          }
          if (this.preview) {
            this.preview.clear();
          }
        },
        onupdate: function(vnode) {
          if (this.tempus && vnode.attrs.form[vnode.attrs.formKey]) {
            if (vnode.attrs.form[vnode.attrs.formKey].getTime() !== this.tempus.viewDate?.getTime()) {
              this.tempus.dates.setValue(new tempus.DateTime(vnode.attrs.form[vnode.attrs.formKey]));
            }
          }
        },
        imageChanged: function(vnode, e) {
          let file = e.currentTarget.files?.[0] || null;
          this.updateValue(vnode, file);
          if (this.preview) {
            this.preview.clear();
            this.preview = null;
          }
          if (!file)
            return;
          if (file.type.startsWith("image")) {
            this.preview = {
              file,
              preview: URL.createObjectURL(file),
              clear: function() {
                URL.revokeObjectURL(this.preview);
              }
            };
          }
        },
        updateValue: function(vnode, value) {
          vnode.attrs.form[vnode.attrs.formKey] = value;
          if (typeof vnode.attrs.oninput === "function") {
            vnode.attrs.oninput(vnode.attrs.form[vnode.attrs.formKey]);
          }
          return false;
        },
        getInput: function(vnode) {
          switch (vnode.attrs.utility) {
            case "file":
              return m3("div.form-row", [
                m3("input", {
                  type: "text",
                  disabled: api.loading,
                  value: vnode.attrs.form[vnode.attrs.formKey]?.name || ""
                }),
                m3("button.fal", { class: vnode.attrs.button || "file" }),
                m3("input.cover", {
                  type: "file",
                  accept: vnode.attrs.accept,
                  disabled: api.loading,
                  oninput: (e) => this.updateValue(vnode, e.currentTarget.files?.[0] || null)
                })
              ]);
            case "datetime":
              return m3("div.form-row", [
                m3("input", {
                  type: "text",
                  disabled: api.loading,
                  oncreate: (e) => {
                    this.tempus = new tempus.TempusDominus(e.dom, {
                      localization: tempusLocalization
                    });
                    this.tempus.dates.setValue(new tempus.DateTime(vnode.attrs.form[vnode.attrs.formKey]));
                    this.subscription = this.tempus.subscribe(tempus.Namespace.events.change, (e2) => {
                      this.updateValue(vnode, e2.date);
                    });
                  }
                }),
                m3("button.fal.fa-calendar", {
                  onclick: () => {
                    this.tempus.toggle();
                    return false;
                  }
                })
              ]);
            case "image":
              let imageLink = this.preview && this.preview.preview || vnode.attrs.form[vnode.attrs.formKey];
              return m3("div.form-row.image-banner", {
                style: {
                  "background-image": typeof imageLink === "string" ? 'url("' + imageLink + '")' : null
                }
              }, [
                m3("input.cover", {
                  type: "file",
                  accept: vnode.attrs.accept,
                  disabled: api.loading,
                  onchange: this.imageChanged.bind(this, vnode)
                })
              ]);
            default:
              return m3("input", {
                disabled: api.loading,
                type: vnode.attrs.type || "text",
                value: vnode.attrs.form[vnode.attrs.formKey],
                oninput: (e) => this.updateValue(vnode, e.currentTarget.value)
              });
          }
        },
        view: function(vnode) {
          return [
            vnode.attrs.label ? m3("label", vnode.attrs.label) : null,
            this.getInput(vnode)
          ];
        }
      };
      module.exports = Input;
    }
  });

  // app/page_login.js
  var require_page_login = __commonJS({
    "app/page_login.js"(exports, module) {
      var m3 = require_mithril();
      var Authentication2 = require_authentication();
      var api = require_api();
      var Input = require_input();
      var lang = require_lang();
      var videos = require_videos();
      var Login2 = {
        oninit: function(vnode) {
          this.redirect = vnode.attrs.redirect || "";
          Authentication2.requiresNotLogin();
          this.error = "";
          this.form = {
            email: "",
            password: ""
          };
        },
        loginuser: function(vnode, e) {
          e.preventDefault();
          this.error = "";
          if (!this.form.email)
            this.error = lang.login_missing_email;
          if (!this.form.password)
            this.error = lang.login_missing_password;
          if (this.error)
            return false;
          api.sendRequest({
            method: "POST",
            url: "/api/authentication/login",
            body: this.form
          }).then((result) => {
            if (!result.token)
              return Promise.reject(new Error(lang.login_error_auth));
            Authentication2.updateToken(result.token);
            m3.route.set(this.redirect || "/");
            videos.refreshTree();
          }).catch((error) => {
            this.error = lang.format(lang.login_error, error.message);
            this.form.password = "";
          });
          return false;
        },
        view: function(vnode) {
          return [
            m3("div.page.page-login", [
              m3("div.modal", [
                m3("form", {
                  onsubmit: this.loginuser.bind(this, vnode)
                }, [
                  m3(
                    "h3",
                    lang.header_title
                    /* Filadelfia archival center */
                  ),
                  this.error ? m3("p.error", this.error) : null,
                  m3(Input, {
                    label: lang.login_email,
                    // Email or name
                    form: this.form,
                    formKey: "email"
                  }),
                  m3(Input, {
                    label: lang.login_password,
                    // Password
                    type: "password",
                    form: this.form,
                    formKey: "password"
                  }),
                  m3("input.spinner", {
                    hidden: api.loading,
                    type: "submit",
                    value: lang.login_submit
                    // Log in
                  }),
                  api.loading ? m3("div.loading-spinner") : null
                ])
              ]),
              m3("footer", lang.mformat(
                lang.unsplash,
                // Photo by X on Y
                m3("a", { href: "https://unsplash.com/@franhotchin?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash", target: "_blank" }, "Francesca Hotchin"),
                m3("a", { href: "https://unsplash.com/photos/landscape-photo-of-mountain-covered-with-snow-FN-cedy6NHA?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash", target: "_blank" }, "Unsplash")
              ))
            ])
          ];
        }
      };
      module.exports = Login2;
    }
  });

  // app/page_logout.js
  var require_page_logout = __commonJS({
    "app/page_logout.js"(exports, module) {
      var m3 = require_mithril();
      var Authentication2 = require_authentication();
      var Logout2 = {
        oninit: function(vnode) {
          Authentication2.clearToken();
          m3.route.set(vnode.attrs.redirect || "/");
        },
        view: function(vnode) {
          return [];
        }
      };
      module.exports = Logout2;
    }
  });

  // app/page_browse.js
  var require_page_browse = __commonJS({
    "app/page_browse.js"(exports, module) {
      var m3 = require_mithril();
      var api = require_api();
      var Authentication2 = require_authentication();
      var videos = require_videos();
      var lang = require_lang();
      var Browse2 = {
        oninit: function(vnode) {
        },
        mArticles: function(vnode, articles) {
          return articles.map((article) => {
            return m3(m3.route.Link, {
              href: ["", article.publish_at.getFullYear(), article.publish_at.getMonth() + 1, article.path_short].join("/"),
              style: article.avif_preview ? `background-image: url('${article.avif_preview}')` : null
            }, [
              m3("span", lang.printdate(article.publish_at)),
              m3("span", article.name)
            ]);
          });
        },
        mMonth: function(vnode, year) {
          return year.branches.map((month) => {
            return [
              m3(".gallery-month", lang.months[month.title]),
              m3(".group", this.mArticles(vnode, month.videos))
            ];
          });
        },
        view: function(vnode) {
          let articles = videos.month?.videos || videos.year?.videos || videos.Articles;
          return [
            api.loading ? m3("div.loading-spinner") : null,
            videos.error ? m3("div.full-error", { onclick: videos.refreshTree }, [
              videos.error,
              m3("br"),
              "Click here to try again"
            ]) : null,
            m3(".gallery", [
              videos.month ? m3(".group", this.mArticles(vnode, articles)) : null,
              videos.year && !videos.month ? this.mMonth(vnode, videos.year) : null,
              !videos.year ? videos.Tree.slice(-1).map((year) => {
                return [
                  m3(".gallery-year", year.title),
                  this.mMonth(vnode, year)
                ];
              }) : null
            ])
          ];
        }
      };
      module.exports = Browse2;
    }
  });

  // app/page_upload.js
  var require_page_upload = __commonJS({
    "app/page_upload.js"(exports, module) {
      var m3 = require_mithril();
      var Authentication2 = require_authentication();
      var api = require_api();
      var Input = require_input();
      var lang = require_lang();
      var videos = require_videos();
      var Upload2 = {
        oninit: function(vnode) {
          Authentication2.requiresLogin();
          this.error = "";
          let d = /* @__PURE__ */ new Date();
          d.setDate(d.getDate() - d.getDay());
          d.setHours(11);
          d.setMinutes(0);
          d.setSeconds(0);
          d.setMilliseconds(0);
          this.cacheVideo = null;
          this.cacheImage = null;
          this.uploading = null;
          this.form = {
            title: "Sunnudagssamkoma",
            date: d,
            file: null,
            banner: null,
            metadata: {
              speaker: ""
            }
          };
        },
        uploadvideo: function(vnode, e) {
          this.error = "";
          if (!this.form.title)
            this.error = lang.upload_missing_title;
          if (!this.form.date)
            this.error = lang.upload_missing_date;
          if (!this.form.file)
            this.error = lang.upload_missing_file;
          if (!this.form.banner)
            this.error = lang.upload_missing_banner;
          if (this.error)
            return false;
          api.sendRequest({
            method: "GET",
            url: "/api/auth/uploadToken"
          }).then((res) => {
            if (this.cacheImage?.file === this.form.banner) {
              return this.cacheImage;
            }
            return api.uploadBanner(this.form.banner, res).then((imageData) => {
              this.cacheImage = imageData;
              return res;
            });
          }).then((res) => {
            if (this.cacheVideo?.file === this.form.file) {
              return this.cacheVideo;
            }
            return api.uploadFileProgress({
              url: res.path + "?token=" + res.token
            }, this.form.file, (xhr, progress, perSecond) => {
              this.uploading = {
                progress,
                xhr,
                perSecond
              };
              m3.redraw();
            });
          }).then((res) => {
            this.cacheVideo = {
              file: this.form.file,
              filename: res.filename,
              path: res.path
            };
            this.uploading = null;
            return api.sendRequest({
              method: "PUT",
              url: "/api/auth/articles/0",
              body: {
                name: this.form.title,
                page_id: "null",
                path: this.form.date.toISOString().replace("T", "_").replace(/:/g, "").split(".")[0],
                content: JSON.stringify(this.form.metadata),
                publish_at: this.form.date,
                admin_id: Authentication2.getTokenDecoded().user_id,
                is_featured: false,
                media: {
                  filename: res.filename,
                  path: res.path,
                  type: this.form.file.type,
                  size: this.form.file.size
                },
                banner: {
                  filename: this.cacheImage.medium.filename,
                  path: this.cacheImage.medium.path,
                  type: "image/avif",
                  size: this.cacheImage.size,
                  preview: {
                    base64: this.cacheImage.preview.base64
                  }
                }
              }
            });
          }).then((res) => {
            videos.refreshTree();
            m3.route.set("/");
          }).catch((error) => {
            this.uploading = null;
            if (!error)
              return;
            this.error = lang.format(lang.upload_error, error.message);
          });
          return false;
        },
        cancelUpload(e) {
          e.stopPropagation();
          this.uploading.xhr.abortRequest();
          this.uploading = null;
          return false;
        },
        filechanged(file) {
          if (!file || !file.name)
            return;
          let matches = /^(\d{4})-(\d\d)-(\d\d)_(\d\d)-(\d\d)/.exec(file.name);
          if (!matches)
            return;
          var date = /* @__PURE__ */ new Date(matches.slice(1, 4).join("-") + "T" + matches.slice(4, 6).join(":") + ":00");
          if (isNaN(date.getTime()))
            return;
          if (date.getMinutes() >= 30 || date.getHours() === 10) {
            date.setHours(date.getHours() + 1);
          }
          date.setMinutes(0);
          this.form.date = date;
        },
        view: function(vnode) {
          return [
            m3("div.page.page-upload", [
              m3("div.modal", [
                m3("form", {
                  onsubmit: this.uploadvideo.bind(this, vnode)
                }, [
                  m3("h3", "Upload new video"),
                  this.error ? m3("p.error", this.error) : null,
                  m3(Input, {
                    label: "Title",
                    form: this.form,
                    formKey: "title"
                  }),
                  m3(Input, {
                    label: "Date (dd.mm.yyyy)",
                    type: "text",
                    utility: "datetime",
                    form: this.form,
                    formKey: "date"
                  }),
                  m3(Input, {
                    label: "Video",
                    type: "file",
                    accept: ".webm",
                    utility: "file",
                    button: "fa-video",
                    form: this.form,
                    formKey: "file",
                    oninput: (file) => this.filechanged(file)
                  }),
                  m3(Input, {
                    label: "Mynd",
                    type: "file",
                    accept: "image/*",
                    utility: "image",
                    form: this.form,
                    formKey: "banner"
                  }),
                  m3("p.separator", "Optional"),
                  m3(Input, {
                    label: "Speaker",
                    form: this.form.metadata,
                    formKey: "speaker"
                  }),
                  m3("input.spinner", {
                    hidden: api.loading,
                    type: "submit",
                    value: "Begin upload"
                  }),
                  api.loading ? m3("div.loading-spinner") : null,
                  this.uploading ? [
                    m3("p", `${Math.floor(this.uploading.progress)}% (${this.uploading.perSecond}/s)`),
                    m3(".loading-bar", { style: `--progress: ${this.uploading.progress}%` }),
                    m3("button.button.button-alert", {
                      onclick: this.cancelUpload.bind(this)
                    }, "Cancel upload")
                  ] : null
                ])
              ]),
              m3("footer", lang.mformat(
                lang.unsplash,
                // Photo by X on Y
                m3("a", { href: "https://unsplash.com/@franhotchin?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash", target: "_blank" }, "Francesca Hotchin"),
                m3("a", { href: "https://unsplash.com/photos/landscape-photo-of-mountain-covered-with-snow-FN-cedy6NHA?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash", target: "_blank" }, "Unsplash")
              ))
            ])
          ];
        }
      };
      module.exports = Upload2;
    }
  });

  // app/holdbutton.js
  var require_holdbutton = __commonJS({
    "app/holdbutton.js"(exports, module) {
      var m3 = require_mithril();
      var HoldButton = {
        oninit: function(vnode) {
          this.timer = null;
          this.holding = false;
          this.windowBlur = () => {
            this.timerStop();
            m3.redraw();
          };
          window.addEventListener("blur", this.windowBlur);
        },
        onremove: function(vnode) {
          this.timerStop();
          window.removeEventListener("blur", this.windowBlur);
        },
        keydown(vnode, e) {
          if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
            this.timerStart(vnode);
            m3.redraw();
          }
        },
        keyup(e) {
          if (e.key === " " || e.key === "Enter" || e.key === "Spacebar") {
            this.timerStop();
            m3.redraw();
          }
        },
        timerStart(vnode) {
          if (this.timer)
            return;
          this.timer = setTimeout(this.timerConfirmed.bind(this), 2e3, vnode);
          this.holding = true;
        },
        timerStop() {
          clearTimeout(this.timer);
          this.timer = null;
          this.holding = false;
        },
        timerConfirmed(vnode) {
          this.timerStop();
          vnode.attrs.onclick();
          m3.redraw();
        },
        view: function(vnode) {
          return m3("button.holdbutton", {
            style: "--hold-bg: var(--error-bg); --hold-color: var(--error); --hold-fill: var(--error);",
            hidden: vnode.attrs.hidden,
            class: (vnode.attrs.class || "") + (this.holding ? " holdbutton-active" : ""),
            onpointerdown: this.timerStart.bind(this, vnode),
            onpointerup: this.timerStop.bind(this),
            onpointerleave: this.timerStop.bind(this),
            onkeydown: this.keydown.bind(this, vnode),
            onkeyup: this.keyup.bind(this),
            onclick: (e) => {
              return false;
            }
          }, m3("div.inner", vnode.attrs.text));
        }
      };
      module.exports = HoldButton;
    }
  });

  // app/page_article.js
  var require_page_article = __commonJS({
    "app/page_article.js"(exports, module) {
      var m3 = require_mithril();
      var api = require_api();
      var Authentication2 = require_authentication();
      var Input = require_input();
      var lang = require_lang();
      var videos = require_videos();
      var HoldButton = require_holdbutton();
      var Article2 = {
        oninit: function(vnode) {
          this.error = "";
          this.path = "";
          this.data = null;
          this.editing = false;
          this.cacheImage = null;
          this.form = {
            title: "Sunnudagssamkoma",
            date: /* @__PURE__ */ new Date(),
            banner: null,
            metadata: {
              speaker: ""
            }
          };
          this.onbeforeupdate(vnode);
        },
        onbeforeupdate: function(vnode) {
          let path = m3.route.param("year").padStart(4, "0") + "-" + m3.route.param("month").padStart(2, "0") + "-" + m3.route.param("path");
          if (this.path === path)
            return;
          this.fetchArticle(vnode, path);
        },
        fetchArticle: function(vnode, path) {
          this.error = "";
          this.data = null;
          this.path = path;
          this.cacheImage = null;
          this.editing = false;
          api.sendRequest({
            method: "GET",
            url: "/api/articles/" + this.path
          }).then((result) => {
            this.data = result.article;
            this.gotArticle(vnode);
          }, (err) => {
            this.error = err.message;
          });
        },
        gotArticle: function(vnode) {
          if (!this.data) {
            return this.error = "Article not found";
          }
          this.form.title = this.data.name;
          this.form.date = new Date(this.data.publish_at);
          this.form.banner = this.data.banner_path;
          this.form.metadata.speaker = this.data.content.speaker;
        },
        updatevideo: function(vnode, e) {
          this.error = "";
          if (!this.form.title)
            this.error = lang.upload_missing_title;
          if (!this.form.date)
            this.error = lang.upload_missing_date;
          if (this.error)
            return false;
          let promise = Promise.resolve();
          if (Authentication2.currentUser && (typeof this.form.banner !== "string" && this.cacheImage?.file !== this.form.banner)) {
            promise = api.sendRequest({
              method: "GET",
              url: "/api/auth/uploadToken"
            }).then((res) => {
              return api.uploadBanner(this.form.banner, res).then((imageData) => {
                this.cacheImage = imageData;
                if (this.data.banner_path) {
                  api.sendRequest({
                    method: "DELETE",
                    url: res.delete + this.data.banner_path.slice(this.data.banner_path.lastIndexOf("/") + 1) + "?token=" + res.token
                  }).catch((err) => console.error(err));
                }
                return res;
              });
            });
          }
          promise.then(() => {
            return api.sendRequest({
              method: "PUT",
              url: "/api/auth/articles/" + this.data.id,
              body: {
                name: this.form.title,
                page_id: "null",
                path: this.form.date.toISOString().replace("T", "_").replace(/:/g, "").split(".")[0],
                content: JSON.stringify(this.form.metadata),
                publish_at: this.form.date,
                admin_id: Authentication2.getTokenDecoded().user_id,
                is_featured: false,
                media: null,
                banner: this.cacheImage ? {
                  filename: this.cacheImage.medium.filename,
                  path: this.cacheImage.medium.path,
                  type: "image/avif",
                  size: this.cacheImage.size,
                  preview: {
                    base64: this.cacheImage.preview.base64
                  }
                } : null
              }
            });
          }).then((res) => {
            this.fetchArticle(vnode, this.path);
          }).catch((error) => {
            console.error(error);
            this.error = lang.format(lang.article_error, error.message);
          });
          return false;
        },
        deletevideo: function(vnode) {
          api.sendRequest({
            method: "GET",
            url: "/api/auth/uploadToken",
            body: this.form
          }).then((res) => {
            return Promise.all([
              this.data.banner_path ? api.sendRequest({
                method: "DELETE",
                url: res.delete + this.data.banner_path.slice(this.data.banner_path.lastIndexOf("/") + 1) + "?token=" + res.token
              }).catch((err) => console.error(err)) : Promise.resolve(),
              this.data.media_path ? api.sendRequest({
                method: "DELETE",
                url: res.delete + this.data.media_path.slice(this.data.media_path.lastIndexOf("/") + 1) + "?token=" + res.token
              }).catch((err) => console.error(err)) : Promise.resolve()
            ]);
          }).then(() => {
            return api.sendRequest({
              method: "DELETE",
              url: "/api/auth/articles/" + this.data.id
            });
          }).then((res) => {
            videos.removeArticle(this.data.id);
            m3.route.set("/");
          }).catch((error) => {
            if (!error)
              return;
            this.error = lang.format(lang.delete_error, error.message);
          });
        },
        view: function(vnode) {
          return [
            api.loading && !this.data ? m3("div.loading-spinner") : null,
            this.data ? [
              this.data.media_path ? [
                m3(".player", [
                  m3("video", {
                    crossorigin: "",
                    controls: true,
                    preload: "none",
                    poster: this.data.banner_path || "/assets/placeholder.avif"
                  }, [
                    m3("source", {
                      src: this.data.media_path
                    })
                  ])
                ])
              ] : null,
              this.editing ? m3("form.article", {
                onsubmit: this.updatevideo.bind(this, vnode)
              }, [
                m3("div.form-row", [
                  m3("div.form-columns", [
                    m3(Input, {
                      label: "",
                      type: "file",
                      accept: "image/*",
                      utility: "image",
                      form: this.form,
                      formKey: "banner"
                    })
                  ]),
                  m3("div.form-columns.article-name", [
                    m3(Input, {
                      label: "Title",
                      form: this.form,
                      formKey: "title"
                    }),
                    m3(Input, {
                      label: "Date (dd.mm.yyyy)",
                      type: "text",
                      utility: "datetime",
                      form: this.form,
                      formKey: "date"
                    })
                  ])
                ]),
                m3("p.separator", "Optional"),
                m3(Input, {
                  label: "Speaker",
                  form: this.form.metadata,
                  formKey: "speaker"
                }),
                this.error ? m3("div.full-error", this.error) : null,
                m3("div.row", [
                  m3("input.spinner", {
                    hidden: api.loading,
                    type: "submit",
                    value: lang.edit
                  }),
                  m3("div.filler", {
                    hidden: api.loading
                  }),
                  api.loading ? m3("div.loading-spinner") : null,
                  m3(HoldButton, {
                    class: "button spinner",
                    onclick: () => this.deletevideo(vnode),
                    hidden: api.loading,
                    text: lang.delete
                  })
                ])
              ]) : m3("div.article", [
                m3("h1", this.data.name),
                m3("p", [
                  lang.printdate(this.form.date)
                ]),
                m3("div.table", [
                  m3("div.table-row", [
                    m3("div.table-item", lang.article_speaker),
                    m3("div.table-item", this.data.content.speaker || "...")
                  ])
                ]),
                Authentication2.currentUser?.rank >= 10 ? m3("button.button", { onclick: () => this.editing = true }, lang.edit) : null
              ])
            ] : [
              this.error ? m3("div.full-error", this.error) : null
            ]
          ];
        }
      };
      module.exports = Article2;
    }
  });

  // app/index.js
  var m2 = require_mithril();
  var Authentication = require_authentication();
  var Header = require_header();
  var Login = require_page_login();
  var Logout = require_page_logout();
  var Browse = require_page_browse();
  var Upload = require_page_upload();
  var Article = require_page_article();
  window.m = m2;
  var css = [
    "/assets/app.css?v=2",
    "/assets/tempus-dominus.css",
    "/assets/fontawesome.css"
  ];
  for (let item of css) {
    fileref = document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", item);
    document.head.appendChild(fileref);
  }
  var fileref;
  m2.route.setOrig = m2.route.set;
  m2.route.set = function(path, data, options) {
    m2.route.setOrig(path, data, options);
    window.scrollTo(0, 0);
  };
  m2.route.linkOrig = m2.route.link;
  m2.route.link = function(vnode) {
    m2.route.linkOrig(vnode);
    window.scrollTo(0, 0);
  };
  m2.route.prefix = "";
  var allRoutes = {
    "/": Browse,
    "/login": Login,
    "/logout": Logout,
    "/upload": Upload,
    "/:year": Browse,
    "/:year/:month": Browse,
    "/:year/:month/:path": Article
  };
  var AVIF = new Image();
  AVIF.onload = AVIF.onerror = function() {
    window.supportsavif = AVIF.height === 2;
    document.body.className = document.body.className + " " + (window.supportsavif ? "avifsupport" : "jpegonly");
    m2.mount(document.getElementById("header"), Header);
    m2.route(document.getElementById("main"), "/", allRoutes);
  };
  AVIF.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAABAA0ABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgAPkgIaDQgMgkf8AAAQAAAr3A=";
})();
/*! Bundled license information:

@eonasdan/tempus-dominus/dist/js/tempus-dominus.js:
  (*!
    * Tempus Dominus v6.7.19 (https://getdatepicker.com/)
    * Copyright 2013-2023 Jonathan Peterson
    * Licensed under MIT (https://github.com/Eonasdan/tempus-dominus/blob/master/LICENSE)
    *)
*/
