const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./auto-render-DTMSUk0Z-BeunX3LV.js","./katex-BnZ5CZRo-BMBmxj1Y.js","./mermaid.core-vMMZVCDT-alxhRXoZ.js","./index-Bq2njFOY.js","./index-JtiO_h80.css","./i18n-CGlVUOvE.js","./i18n-DmEW90TJ.css","./utils.svelte-Bi9ASwv9.js","./index-DnoGeqVF.js","./dsv-BhAd467f.js","./props-o1aFOJaB.js","./misc-D8a4ZbMA.js","./index-By61_kAe.js","./Upload-xR3P-2U5.js","./snippet-BG7qkY_1.js","./actions-CgRQ2lHA.js","./Upload-B9AbOy1B.css","./ScrollFade.svelte_svelte_type_style_lang-D0JPkGar.js","./ScrollFade-DXC81vHi.css","./MarkdownCode.svelte_svelte_type_style_lang-B29zDiob.js","./prism-python-NrKIQnfs.js","./MarkdownCode-hl0Esrgh.css","./html-Bwif0JPw.js","./input-CXpCw23l.js","./event-modifiers-DanhKw3_.js","./MarkdownCode-BYKuypS7.js","./StreamingBar.svelte_svelte_type_style_lang-DWGn5tT_.js","./StreamingBar-M0OJiclA.css","./Checkbox-dsIC6373.js","./Checkbox-CJBAs2gn.css","./size-CWi277d_.js","./Check-BKMHx_DF.js","./DropdownArrow-3lFHYtTD.js","./Copy-BQlJe6-D.js","./FullscreenButton-C6RgeACK.js","./Maximize-2N5airbC.js","./Example-CSyNUPmz.js","./Example-B0qjHn8W.css"])))=>i.map(i=>d[i]);
import { j as get, w as writable$1, p as prop, e as init$1, b as set_class, a as set_attribute, h as clsx, i as if_block, d as bind_this, f as set_style$1, s as slot, k as each, t as remove_input_defaults, F as set_value, u as index, q as store_get, m as setup_stores, r as rest_props } from './i18n-CGlVUOvE.js';
import { ag as __vitePreload, aw as setContext$1, I as tick$1, M as push, Y as legacy_pre_effect, y as deep_read_state, Z as get$1, _ as legacy_pre_effect_reset, t as template_effect, U as event, a as append$1, O as pop, a0 as mutable_source, P as flushSync, Q as child, R as from_html, $ as set, T as reset, a1 as createEventDispatcher$1, N as first_child, S as sibling, u as effect, w as untrack, aj as remove_textarea_child, a3 as comment, ae as derived_safe_equal, a4 as text$1, X as set_text, f as from_svg, a8 as onMount$1, ar as mutate, af as onDestroy$1, aA as afterUpdate$1, av as $window, ad as user_effect } from './index-Bq2njFOY.js';
import { G as Gradio } from './utils.svelte-Bi9ASwv9.js';
import { d as dequal$2 } from './index-DnoGeqVF.js';
import { d as dsvFormat$1 } from './dsv-BhAd467f.js';
import { b as bind_prop } from './props-o1aFOJaB.js';
import { b as bubble_event } from './misc-D8a4ZbMA.js';
import { d as dequal$3 } from './index-By61_kAe.js';
import { U as Upload } from './Upload-xR3P-2U5.js';
import { c as component, I as IconButton$1 } from './ScrollFade.svelte_svelte_type_style_lang-D0JPkGar.js';
import './MarkdownCode.svelte_svelte_type_style_lang-B29zDiob.js';
import { h as html$1 } from './html-Bwif0JPw.js';
import { a as action } from './actions-CgRQ2lHA.js';
import { b as bind_value } from './input-CXpCw23l.js';
import { s as stopPropagation, p as preventDefault } from './event-modifiers-DanhKw3_.js';
import { M as MarkdownCode$1 } from './MarkdownCode-BYKuypS7.js';
import './StreamingBar.svelte_svelte_type_style_lang-DWGn5tT_.js';
import { C as Checkbox$1 } from './Checkbox-dsIC6373.js';
import { b as bind_element_size, a as bind_resize_observer } from './size-CWi277d_.js';
import { C as Check$1 } from './Check-BKMHx_DF.js';
import { D as DropdownArrow$1 } from './DropdownArrow-3lFHYtTD.js';
import { C as Copy$1 } from './Copy-BQlJe6-D.js';
import { F as FullscreenButton$1 } from './FullscreenButton-C6RgeACK.js';
import Example from './Example-CSyNUPmz.js';

var __defProp = Object.defineProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var _Marked_instances, parseMarkdown_fn, onError_fn, _currentLine;
function noop() {
}
const identity = (x) => x;
function assign(tar, src) {
  for (const k in src) tar[k] = src[k];
  return (
    /** @type {T & S} */
    tar
  );
}
function run(fn) {
  return fn();
}
function blank_object() {
  return /* @__PURE__ */ Object.create(null);
}
function run_all(fns) {
  fns.forEach(run);
}
function is_function(thing) {
  return typeof thing === "function";
}
function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || a && typeof a === "object" || typeof a === "function";
}
let src_url_equal_anchor;
function src_url_equal(element_src, url) {
  if (element_src === url) return true;
  if (!src_url_equal_anchor) {
    src_url_equal_anchor = document.createElement("a");
  }
  src_url_equal_anchor.href = url;
  return element_src === src_url_equal_anchor.href;
}
function is_empty(obj) {
  return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
  if (store == null) {
    for (const callback of callbacks) {
      callback(void 0);
    }
    return noop;
  }
  const unsub = store.subscribe(...callbacks);
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function get_store_value(store) {
  let value;
  subscribe(store, (_) => value = _)();
  return value;
}
function component_subscribe(component, store, callback) {
  component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
  if (definition) {
    const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
    return definition[0](slot_ctx);
  }
}
function get_slot_context(definition, ctx, $$scope, fn) {
  return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
  if (definition[2] && fn) {
    const lets = definition[2](fn(dirty));
    if ($$scope.dirty === void 0) {
      return lets;
    }
    if (typeof lets === "object") {
      const merged = [];
      const len = Math.max($$scope.dirty.length, lets.length);
      for (let i = 0; i < len; i += 1) {
        merged[i] = $$scope.dirty[i] | lets[i];
      }
      return merged;
    }
    return $$scope.dirty | lets;
  }
  return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
  if (slot_changes) {
    const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
    slot.p(slot_context, slot_changes);
  }
}
function get_all_dirty_from_scope($$scope) {
  if ($$scope.ctx.length > 32) {
    const dirty = [];
    const length = $$scope.ctx.length / 32;
    for (let i = 0; i < length; i++) {
      dirty[i] = -1;
    }
    return dirty;
  }
  return -1;
}
function exclude_internal_props(props) {
  const result = {};
  for (const k in props) if (k[0] !== "$") result[k] = props[k];
  return result;
}
function compute_rest_props(props, keys) {
  const rest = {};
  keys = new Set(keys);
  for (const k in props) if (!keys.has(k) && k[0] !== "$") rest[k] = props[k];
  return rest;
}
function null_to_empty(value) {
  return value == null ? "" : value;
}
function action_destroyer(action_result) {
  return action_result && is_function(action_result.destroy) ? action_result.destroy : noop;
}
const is_client = typeof window !== "undefined";
let now = is_client ? () => window.performance.now() : () => Date.now();
let raf$1 = is_client ? (cb) => requestAnimationFrame(cb) : noop;
const tasks = /* @__PURE__ */ new Set();
function run_tasks(now2) {
  tasks.forEach((task) => {
    if (!task.c(now2)) {
      tasks.delete(task);
      task.f();
    }
  });
  if (tasks.size !== 0) raf$1(run_tasks);
}
function loop(callback) {
  let task;
  if (tasks.size === 0) raf$1(run_tasks);
  return {
    promise: new Promise((fulfill) => {
      tasks.add(task = { c: callback, f: fulfill });
    }),
    abort() {
      tasks.delete(task);
    }
  };
}
const globals = typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : (
  // @ts-ignore Node typings have this
  global
);
class ResizeObserverSingleton {
  /** @param {ResizeObserverOptions} options */
  constructor(options) {
    /**
     * @private
     * @readonly
     * @type {WeakMap<Element, import('./private.js').Listener>}
     */
    __publicField(this, "_listeners", "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0);
    /**
     * @private
     * @type {ResizeObserver}
     */
    __publicField(this, "_observer");
    /** @type {ResizeObserverOptions} */
    __publicField(this, "options");
    this.options = options;
  }
  /**
   * @param {Element} element
   * @param {import('./private.js').Listener} listener
   * @returns {() => void}
   */
  observe(element2, listener) {
    this._listeners.set(element2, listener);
    this._getObserver().observe(element2, this.options);
    return () => {
      this._listeners.delete(element2);
      this._observer.unobserve(element2);
    };
  }
  /**
   * @private
   */
  _getObserver() {
    return this._observer ?? (this._observer = new ResizeObserver((entries) => {
      var _a;
      for (const entry of entries) {
        ResizeObserverSingleton.entries.set(entry.target, entry);
        (_a = this._listeners.get(entry.target)) == null ? void 0 : _a(entry);
      }
    }));
  }
}
ResizeObserverSingleton.entries = "WeakMap" in globals ? /* @__PURE__ */ new WeakMap() : void 0;
function append(target, node) {
  target.appendChild(node);
}
function get_root_for_style(node) {
  if (!node) return document;
  const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  if (root && /** @type {ShadowRoot} */
  root.host) {
    return (
      /** @type {ShadowRoot} */
      root
    );
  }
  return node.ownerDocument;
}
function append_empty_stylesheet(node) {
  const style_element = element("style");
  style_element.textContent = "/* empty */";
  append_stylesheet(get_root_for_style(node), style_element);
  return style_element.sheet;
}
function append_stylesheet(node, style) {
  append(
    /** @type {Document} */
    node.head || node,
    style
  );
  return style.sheet;
}
function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}
function detach(node) {
  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }
}
function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) {
    if (iterations[i]) iterations[i].d(detaching);
  }
}
function element(name) {
  return document.createElement(name);
}
function svg_element(name) {
  return document.createElementNS("http://www.w3.org/2000/svg", name);
}
function text(data) {
  return document.createTextNode(data);
}
function space() {
  return text(" ");
}
function empty() {
  return text("");
}
function listen(node, event, handler, options) {
  node.addEventListener(event, handler, options);
  return () => node.removeEventListener(event, handler, options);
}
function prevent_default(fn) {
  return function(event) {
    event.preventDefault();
    return fn.call(this, event);
  };
}
function stop_propagation(fn) {
  return function(event) {
    event.stopPropagation();
    return fn.call(this, event);
  };
}
function attr(node, attribute, value) {
  if (value == null) node.removeAttribute(attribute);
  else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);
}
const always_set_through_set_attribute = ["width", "height"];
function set_attributes(node, attributes) {
  const descriptors = Object.getOwnPropertyDescriptors(node.__proto__);
  for (const key in attributes) {
    if (attributes[key] == null) {
      node.removeAttribute(key);
    } else if (key === "style") {
      node.style.cssText = attributes[key];
    } else if (key === "__value") {
      node.value = node[key] = attributes[key];
    } else if (descriptors[key] && descriptors[key].set && always_set_through_set_attribute.indexOf(key) === -1) {
      node[key] = attributes[key];
    } else {
      attr(node, key, attributes[key]);
    }
  }
}
function set_custom_element_data_map(node, data_map) {
  Object.keys(data_map).forEach((key) => {
    set_custom_element_data(node, key, data_map[key]);
  });
}
function set_custom_element_data(node, prop, value) {
  const lower = prop.toLowerCase();
  if (lower in node) {
    node[lower] = typeof node[lower] === "boolean" && value === "" ? true : value;
  } else if (prop in node) {
    node[prop] = typeof node[prop] === "boolean" && value === "" ? true : value;
  } else {
    attr(node, prop, value);
  }
}
function set_dynamic_element_data(tag2) {
  return /-/.test(tag2) ? set_custom_element_data_map : set_attributes;
}
function children(element2) {
  return Array.from(element2.childNodes);
}
function set_data(text2, data) {
  data = "" + data;
  if (text2.data === data) return;
  text2.data = /** @type {string} */
  data;
}
function set_input_value(input, value) {
  input.value = value == null ? "" : value;
}
function set_style(node, key, value, important) {
  if (value == null) {
    node.style.removeProperty(key);
  } else {
    node.style.setProperty(key, value, "");
  }
}
let crossorigin;
function is_crossorigin() {
  if (crossorigin === void 0) {
    crossorigin = false;
    try {
      if (typeof window !== "undefined" && window.parent) {
        void window.parent.document;
      }
    } catch (error) {
      crossorigin = true;
    }
  }
  return crossorigin;
}
function add_iframe_resize_listener(node, fn) {
  const computed_style = getComputedStyle(node);
  if (computed_style.position === "static") {
    node.style.position = "relative";
  }
  const iframe = element("iframe");
  iframe.setAttribute(
    "style",
    "display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; border: 0; opacity: 0; pointer-events: none; z-index: -1;"
  );
  iframe.setAttribute("aria-hidden", "true");
  iframe.tabIndex = -1;
  const crossorigin2 = is_crossorigin();
  let unsubscribe;
  if (crossorigin2) {
    iframe.src = "data:text/html,<script>onresize=function(){parent.postMessage(0,'*')}<\/script>";
    unsubscribe = listen(
      window,
      "message",
      /** @param {MessageEvent} event */
      (event) => {
        if (event.source === iframe.contentWindow) fn();
      }
    );
  } else {
    iframe.src = "about:blank";
    iframe.onload = () => {
      unsubscribe = listen(iframe.contentWindow, "resize", fn);
      fn();
    };
  }
  append(node, iframe);
  return () => {
    if (crossorigin2) {
      unsubscribe();
    } else if (unsubscribe && iframe.contentWindow) {
      unsubscribe();
    }
    detach(iframe);
  };
}
const resize_observer_content_box = /* @__PURE__ */ new ResizeObserverSingleton({
  box: "content-box"
});
function toggle_class(element2, name, toggle) {
  element2.classList.toggle(name, !!toggle);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
  return new CustomEvent(type, { detail, bubbles, cancelable });
}
class HtmlTag {
  constructor(is_svg = false) {
    /**
     * @private
     * @default false
     */
    __publicField(this, "is_svg", false);
    /** parent for creating node */
    __publicField(this, "e");
    /** html tag nodes */
    __publicField(this, "n");
    /** target */
    __publicField(this, "t");
    /** anchor */
    __publicField(this, "a");
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  c(html2) {
    this.h(html2);
  }
  /**
   * @param {string} html
   * @param {HTMLElement | SVGElement} target
   * @param {HTMLElement | SVGElement} anchor
   * @returns {void}
   */
  m(html2, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg)
        this.e = svg_element(
          /** @type {keyof SVGElementTagNameMap} */
          target.nodeName
        );
      else
        this.e = element(
          /** @type {keyof HTMLElementTagNameMap} */
          target.nodeType === 11 ? "TEMPLATE" : target.nodeName
        );
      this.t = target.tagName !== "TEMPLATE" ? target : (
        /** @type {HTMLTemplateElement} */
        target.content
      );
      this.c(html2);
    }
    this.i(anchor);
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  h(html2) {
    this.e.innerHTML = html2;
    this.n = Array.from(
      this.e.nodeName === "TEMPLATE" ? this.e.content.childNodes : this.e.childNodes
    );
  }
  /**
   * @returns {void} */
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) {
      insert(this.t, this.n[i], anchor);
    }
  }
  /**
   * @param {string} html
   * @returns {void}
   */
  p(html2) {
    this.d();
    this.h(html2);
    this.i(this.a);
  }
  /**
   * @returns {void} */
  d() {
    this.n.forEach(detach);
  }
}
function construct_svelte_component(component, props) {
  return new component(props);
}
const managed_styles = /* @__PURE__ */ new Map();
let active = 0;
function hash(str) {
  let hash2 = 5381;
  let i = str.length;
  while (i--) hash2 = (hash2 << 5) - hash2 ^ str.charCodeAt(i);
  return hash2 >>> 0;
}
function create_style_information(doc, node) {
  const info = { stylesheet: append_empty_stylesheet(node), rules: {} };
  managed_styles.set(doc, info);
  return info;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
  const step = 16.666 / duration;
  let keyframes = "{\n";
  for (let p = 0; p <= 1; p += step) {
    const t = a + (b - a) * ease(p);
    keyframes += p * 100 + `%{${fn(t, 1 - t)}}
`;
  }
  const rule = keyframes + `100% {${fn(b, 1 - b)}}
}`;
  const name = `__svelte_${hash(rule)}_${uid}`;
  const doc = get_root_for_style(node);
  const { stylesheet, rules } = managed_styles.get(doc) || create_style_information(doc, node);
  if (!rules[name]) {
    rules[name] = true;
    stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
  }
  const animation = node.style.animation || "";
  node.style.animation = `${animation ? `${animation}, ` : ""}${name} ${duration}ms linear ${delay}ms 1 both`;
  active += 1;
  return name;
}
function delete_rule(node, name) {
  const previous = (node.style.animation || "").split(", ");
  const next = previous.filter(
    name ? (anim) => anim.indexOf(name) < 0 : (anim) => anim.indexOf("__svelte") === -1
    // remove all Svelte animations
  );
  const deleted = previous.length - next.length;
  if (deleted) {
    node.style.animation = next.join(", ");
    active -= deleted;
    if (!active) clear_rules();
  }
}
function clear_rules() {
  raf$1(() => {
    if (active) return;
    managed_styles.forEach((info) => {
      const { ownerNode } = info.stylesheet;
      if (ownerNode) detach(ownerNode);
    });
    managed_styles.clear();
  });
}
let current_component;
function set_current_component(component) {
  current_component = component;
}
function get_current_component() {
  if (!current_component) throw new Error("Function called outside component initialization");
  return current_component;
}
function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}
function afterUpdate(fn) {
  get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
  get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
  const component = get_current_component();
  return (type, detail, { cancelable = false } = {}) => {
    const callbacks = component.$$.callbacks[type];
    if (callbacks) {
      const event = custom_event(
        /** @type {string} */
        type,
        detail,
        { cancelable }
      );
      callbacks.slice().forEach((fn) => {
        fn.call(component, event);
      });
      return !event.defaultPrevented;
    }
    return true;
  };
}
function setContext(key, context) {
  get_current_component().$$.context.set(key, context);
  return context;
}
function bubble(component, event) {
  const callbacks = component.$$.callbacks[event.type];
  if (callbacks) {
    callbacks.slice().forEach((fn) => fn.call(this, event));
  }
}
const dirty_components = [];
const binding_callbacks = [];
let render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = /* @__PURE__ */ Promise.resolve();
let update_scheduled = false;
function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}
function tick() {
  schedule_update();
  return resolved_promise;
}
function add_render_callback(fn) {
  render_callbacks.push(fn);
}
function add_flush_callback(fn) {
  flush_callbacks.push(fn);
}
const seen_callbacks = /* @__PURE__ */ new Set();
let flushidx = 0;
function flush() {
  if (flushidx !== 0) {
    return;
  }
  const saved_component = current_component;
  do {
    try {
      while (flushidx < dirty_components.length) {
        const component = dirty_components[flushidx];
        flushidx++;
        set_current_component(component);
        update(component.$$);
      }
    } catch (e) {
      dirty_components.length = 0;
      flushidx = 0;
      throw e;
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    while (binding_callbacks.length) binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  while (flush_callbacks.length) {
    flush_callbacks.pop()();
  }
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}
function update($$) {
  if ($$.fragment !== null) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [-1];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}
function flush_render_callbacks(fns) {
  const filtered = [];
  const targets = [];
  render_callbacks.forEach((c) => fns.indexOf(c) === -1 ? filtered.push(c) : targets.push(c));
  targets.forEach((c) => c());
  render_callbacks = filtered;
}
let promise;
function wait() {
  if (!promise) {
    promise = Promise.resolve();
    promise.then(() => {
      promise = null;
    });
  }
  return promise;
}
function dispatch(node, direction, kind) {
  node.dispatchEvent(custom_event(`${"intro"}${kind}`));
}
const outroing = /* @__PURE__ */ new Set();
let outros;
function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
    // parent group
  };
}
function check_outros() {
  if (!outros.r) {
    run_all(outros.c);
  }
  outros = outros.p;
}
function transition_in(block2, local) {
  if (block2 && block2.i) {
    outroing.delete(block2);
    block2.i(local);
  }
}
function transition_out(block2, local, detach2, callback) {
  if (block2 && block2.o) {
    if (outroing.has(block2)) return;
    outroing.add(block2);
    outros.c.push(() => {
      outroing.delete(block2);
      if (callback) {
        if (detach2) block2.d(1);
        callback();
      }
    });
    block2.o(local);
  } else if (callback) {
    callback();
  }
}
const null_transition = { duration: 0 };
function create_in_transition(node, fn, params) {
  const options = { direction: "in" };
  let config = fn(node, params, options);
  let running = false;
  let animation_name;
  let task;
  let uid = 0;
  function cleanup() {
    if (animation_name) delete_rule(node, animation_name);
  }
  function go() {
    const {
      delay = 0,
      duration = 300,
      easing = identity,
      tick: tick2 = noop,
      css
    } = config || null_transition;
    if (css) animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
    tick2(0, 1);
    const start_time = now() + delay;
    const end_time = start_time + duration;
    if (task) task.abort();
    running = true;
    add_render_callback(() => dispatch(node, true, "start"));
    task = loop((now2) => {
      if (running) {
        if (now2 >= end_time) {
          tick2(1, 0);
          dispatch(node, true, "end");
          cleanup();
          return running = false;
        }
        if (now2 >= start_time) {
          const t = easing((now2 - start_time) / duration);
          tick2(t, 1 - t);
        }
      }
      return running;
    });
  }
  let started = false;
  return {
    start() {
      if (started) return;
      started = true;
      delete_rule(node);
      if (is_function(config)) {
        config = config(options);
        wait().then(go);
      } else {
        go();
      }
    },
    invalidate() {
      started = false;
    },
    end() {
      if (running) {
        cleanup();
        running = false;
      }
    }
  };
}
function ensure_array_like(array_like_or_iterator) {
  return (array_like_or_iterator == null ? void 0 : array_like_or_iterator.length) !== void 0 ? array_like_or_iterator : Array.from(array_like_or_iterator);
}
function outro_and_destroy_block(block2, lookup) {
  transition_out(block2, 1, 1, () => {
    lookup.delete(block2.key);
  });
}
function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list2, lookup, node, destroy, create_each_block2, next, get_context) {
  let o = old_blocks.length;
  let n = list2.length;
  let i = o;
  const old_indexes = {};
  while (i--) old_indexes[old_blocks[i].key] = i;
  const new_blocks = [];
  const new_lookup = /* @__PURE__ */ new Map();
  const deltas = /* @__PURE__ */ new Map();
  const updates = [];
  i = n;
  while (i--) {
    const child_ctx = get_context(ctx, list2, i);
    const key = get_key(child_ctx);
    let block2 = lookup.get(key);
    if (!block2) {
      block2 = create_each_block2(key, child_ctx);
      block2.c();
    } else {
      updates.push(() => block2.p(child_ctx, dirty));
    }
    new_lookup.set(key, new_blocks[i] = block2);
    if (key in old_indexes) deltas.set(key, Math.abs(i - old_indexes[key]));
  }
  const will_move = /* @__PURE__ */ new Set();
  const did_move = /* @__PURE__ */ new Set();
  function insert2(block2) {
    transition_in(block2, 1);
    block2.m(node, next);
    lookup.set(block2.key, block2);
    next = block2.first;
    n--;
  }
  while (o && n) {
    const new_block = new_blocks[n - 1];
    const old_block = old_blocks[o - 1];
    const new_key = new_block.key;
    const old_key = old_block.key;
    if (new_block === old_block) {
      next = new_block.first;
      o--;
      n--;
    } else if (!new_lookup.has(old_key)) {
      destroy(old_block, lookup);
      o--;
    } else if (!lookup.has(new_key) || will_move.has(new_key)) {
      insert2(new_block);
    } else if (did_move.has(old_key)) {
      o--;
    } else if (deltas.get(new_key) > deltas.get(old_key)) {
      did_move.add(new_key);
      insert2(new_block);
    } else {
      will_move.add(old_key);
      o--;
    }
  }
  while (o--) {
    const old_block = old_blocks[o];
    if (!new_lookup.has(old_block.key)) destroy(old_block, lookup);
  }
  while (n) insert2(new_blocks[n - 1]);
  run_all(updates);
  return new_blocks;
}
function get_spread_update(levels, updates) {
  const update2 = {};
  const to_null_out = {};
  const accounted_for = { $$scope: 1 };
  let i = levels.length;
  while (i--) {
    const o = levels[i];
    const n = updates[i];
    if (n) {
      for (const key in o) {
        if (!(key in n)) to_null_out[key] = 1;
      }
      for (const key in n) {
        if (!accounted_for[key]) {
          update2[key] = n[key];
          accounted_for[key] = 1;
        }
      }
      levels[i] = n;
    } else {
      for (const key in o) {
        accounted_for[key] = 1;
      }
    }
  }
  for (const key in to_null_out) {
    if (!(key in update2)) update2[key] = void 0;
  }
  return update2;
}
function get_spread_object(spread_props) {
  return typeof spread_props === "object" && spread_props !== null ? spread_props : {};
}
function bind(component, name, callback) {
  const index = component.$$.props[name];
  if (index !== void 0) {
    component.$$.bound[index] = callback;
    callback(component.$$.ctx[index]);
  }
}
function create_component(block2) {
  block2 && block2.c();
}
function mount_component(component, target, anchor) {
  const { fragment, after_update } = component.$$;
  fragment && fragment.m(target, anchor);
  add_render_callback(() => {
    const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
    if (component.$$.on_destroy) {
      component.$$.on_destroy.push(...new_on_destroy);
    } else {
      run_all(new_on_destroy);
    }
    component.$$.on_mount = [];
  });
  after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
  const $$ = component.$$;
  if ($$.fragment !== null) {
    flush_render_callbacks($$.after_update);
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}
function make_dirty(component, i) {
  if (component.$$.dirty[0] === -1) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}
function init(component, options, instance2, create_fragment2, not_equal, props, append_styles = null, dirty = [-1]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    // state
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    // lifecycle
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
    // everything else
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options.target || parent_component.$$.root
  };
  append_styles && append_styles($$.root);
  let ready = false;
  $$.ctx = instance2 ? instance2(component, options.props || {}, (i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i]) $$.bound[i](value);
      if (ready) make_dirty(component, i);
    }
    return ret;
  }) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment2 ? create_fragment2($$.ctx) : false;
  if (options.target) {
    if (options.hydrate) {
      const nodes = children(options.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else {
      $$.fragment && $$.fragment.c();
    }
    if (options.intro) transition_in(component.$$.fragment);
    mount_component(component, options.target, options.anchor);
    flush();
  }
  set_current_component(parent_component);
}
class SvelteComponent {
  constructor() {
    /**
     * ### PRIVATE API
     *
     * Do not use, may change at any time
     *
     * @type {any}
     */
    __publicField(this, "$$");
    /**
     * ### PRIVATE API
     *
     * Do not use, may change at any time
     *
     * @type {any}
     */
    __publicField(this, "$$set");
  }
  /** @returns {void} */
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  /**
   * @template {Extract<keyof Events, string>} K
   * @param {K} type
   * @param {((e: Events[K]) => void) | null | undefined} callback
   * @returns {() => void}
   */
  $on(type, callback) {
    if (!is_function(callback)) {
      return noop;
    }
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index = callbacks.indexOf(callback);
      if (index !== -1) callbacks.splice(index, 1);
    };
  }
  /**
   * @param {Partial<Props>} props
   * @returns {void}
   */
  $set(props) {
    if (this.$$set && !is_empty(props)) {
      this.$$.skip_bound = true;
      this.$$set(props);
      this.$$.skip_bound = false;
    }
  }
}
const PUBLIC_VERSION = "4";
if (typeof window !== "undefined")
  (window.__svelte || (window.__svelte = { v: /* @__PURE__ */ new Set() })).v.add(PUBLIC_VERSION);
function create_if_block_1$f(ctx) {
  let svg;
  let line0;
  let line1;
  let mounted;
  let dispose;
  return {
    c() {
      svg = svg_element("svg");
      line0 = svg_element("line");
      line1 = svg_element("line");
      attr(line0, "x1", "1");
      attr(line0, "y1", "9");
      attr(line0, "x2", "9");
      attr(line0, "y2", "1");
      attr(line0, "stroke", "gray");
      attr(line0, "stroke-width", "0.5");
      attr(line1, "x1", "5");
      attr(line1, "y1", "9");
      attr(line1, "x2", "9");
      attr(line1, "y2", "5");
      attr(line1, "stroke", "gray");
      attr(line1, "stroke-width", "0.5");
      attr(svg, "class", "resize-handle svelte-239wnu");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 10 10");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, line0);
      append(svg, line1);
      if (!mounted) {
        dispose = listen(
          svg,
          "mousedown",
          /*resize*/
          ctx[27]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_dynamic_element(ctx) {
  var _a;
  let svelte_element;
  let t;
  let svelte_element_class_value;
  let svelte_element_dir_value;
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[31].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[30],
    null
  );
  let if_block = (
    /*resizable*/
    ctx[19] && create_if_block_1$f(ctx)
  );
  let svelte_element_levels = [
    { "data-testid": (
      /*test_id*/
      ctx[11]
    ) },
    { id: (
      /*elem_id*/
      ctx[6]
    ) },
    {
      class: svelte_element_class_value = "block " + /*elem_classes*/
      (((_a = ctx[7]) == null ? void 0 : _a.join(" ")) || "") + " svelte-239wnu"
    },
    {
      dir: svelte_element_dir_value = /*rtl*/
      ctx[20] ? "rtl" : "ltr"
    }
  ];
  let svelte_element_data = {};
  for (let i = 0; i < svelte_element_levels.length; i += 1) {
    svelte_element_data = assign(svelte_element_data, svelte_element_levels[i]);
  }
  return {
    c() {
      svelte_element = element(
        /*tag*/
        ctx[25]
      );
      if (default_slot) default_slot.c();
      t = space();
      if (if_block) if_block.c();
      set_dynamic_element_data(
        /*tag*/
        ctx[25]
      )(svelte_element, svelte_element_data);
      toggle_class(
        svelte_element,
        "hidden",
        /*visible*/
        ctx[14] === false || /*visible*/
        ctx[14] === "hidden"
      );
      toggle_class(
        svelte_element,
        "padded",
        /*padding*/
        ctx[10]
      );
      toggle_class(
        svelte_element,
        "flex",
        /*flex*/
        ctx[1]
      );
      toggle_class(
        svelte_element,
        "border_focus",
        /*border_mode*/
        ctx[9] === "focus"
      );
      toggle_class(
        svelte_element,
        "border_contrast",
        /*border_mode*/
        ctx[9] === "contrast"
      );
      toggle_class(svelte_element, "hide-container", !/*explicit_call*/
      ctx[12] && !/*container*/
      ctx[13]);
      toggle_class(
        svelte_element,
        "fullscreen",
        /*fullscreen*/
        ctx[0]
      );
      toggle_class(
        svelte_element,
        "animating",
        /*fullscreen*/
        ctx[0] && /*preexpansionBoundingRect*/
        ctx[24] !== null
      );
      toggle_class(
        svelte_element,
        "auto-margin",
        /*scale*/
        ctx[17] === null
      );
      set_style(
        svelte_element,
        "height",
        /*fullscreen*/
        ctx[0] ? void 0 : (
          /*get_dimension*/
          ctx[26](
            /*height*/
            ctx[2]
          )
        )
      );
      set_style(
        svelte_element,
        "min-height",
        /*fullscreen*/
        ctx[0] ? void 0 : (
          /*get_dimension*/
          ctx[26](
            /*min_height*/
            ctx[3]
          )
        )
      );
      set_style(
        svelte_element,
        "max-height",
        /*fullscreen*/
        ctx[0] ? void 0 : (
          /*get_dimension*/
          ctx[26](
            /*max_height*/
            ctx[4]
          )
        )
      );
      set_style(
        svelte_element,
        "--start-top",
        /*preexpansionBoundingRect*/
        ctx[24] ? `${/*preexpansionBoundingRect*/
        ctx[24].top}px` : "0px"
      );
      set_style(
        svelte_element,
        "--start-left",
        /*preexpansionBoundingRect*/
        ctx[24] ? `${/*preexpansionBoundingRect*/
        ctx[24].left}px` : "0px"
      );
      set_style(
        svelte_element,
        "--start-width",
        /*preexpansionBoundingRect*/
        ctx[24] ? `${/*preexpansionBoundingRect*/
        ctx[24].width}px` : "0px"
      );
      set_style(
        svelte_element,
        "--start-height",
        /*preexpansionBoundingRect*/
        ctx[24] ? `${/*preexpansionBoundingRect*/
        ctx[24].height}px` : "0px"
      );
      set_style(
        svelte_element,
        "width",
        /*fullscreen*/
        ctx[0] ? void 0 : typeof /*width*/
        ctx[5] === "number" ? `calc(min(${/*width*/
        ctx[5]}px, 100%))` : (
          /*get_dimension*/
          ctx[26](
            /*width*/
            ctx[5]
          )
        )
      );
      set_style(
        svelte_element,
        "border-style",
        /*variant*/
        ctx[8]
      );
      set_style(
        svelte_element,
        "overflow",
        /*allow_overflow*/
        ctx[15] ? (
          /*overflow_behavior*/
          ctx[16]
        ) : "hidden"
      );
      set_style(
        svelte_element,
        "flex-grow",
        /*scale*/
        ctx[17]
      );
      set_style(svelte_element, "min-width", `calc(min(${/*min_width*/
      ctx[18]}px, 100%))`);
      set_style(svelte_element, "border-width", `var(--block-border-width)`);
    },
    m(target, anchor) {
      insert(target, svelte_element, anchor);
      if (default_slot) {
        default_slot.m(svelte_element, null);
      }
      append(svelte_element, t);
      if (if_block) if_block.m(svelte_element, null);
      ctx[32](svelte_element);
      current = true;
    },
    p(ctx2, dirty) {
      var _a2;
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope*/
        1073741824)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[30],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[30]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[30],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (
        /*resizable*/
        ctx2[19]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_1$f(ctx2);
          if_block.c();
          if_block.m(svelte_element, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      set_dynamic_element_data(
        /*tag*/
        ctx2[25]
      )(svelte_element, svelte_element_data = get_spread_update(svelte_element_levels, [
        (!current || dirty[0] & /*test_id*/
        2048) && { "data-testid": (
          /*test_id*/
          ctx2[11]
        ) },
        (!current || dirty[0] & /*elem_id*/
        64) && { id: (
          /*elem_id*/
          ctx2[6]
        ) },
        (!current || dirty[0] & /*elem_classes*/
        128 && svelte_element_class_value !== (svelte_element_class_value = "block " + /*elem_classes*/
        (((_a2 = ctx2[7]) == null ? void 0 : _a2.join(" ")) || "") + " svelte-239wnu")) && { class: svelte_element_class_value },
        (!current || dirty[0] & /*rtl*/
        1048576 && svelte_element_dir_value !== (svelte_element_dir_value = /*rtl*/
        ctx2[20] ? "rtl" : "ltr")) && { dir: svelte_element_dir_value }
      ]));
      toggle_class(
        svelte_element,
        "hidden",
        /*visible*/
        ctx2[14] === false || /*visible*/
        ctx2[14] === "hidden"
      );
      toggle_class(
        svelte_element,
        "padded",
        /*padding*/
        ctx2[10]
      );
      toggle_class(
        svelte_element,
        "flex",
        /*flex*/
        ctx2[1]
      );
      toggle_class(
        svelte_element,
        "border_focus",
        /*border_mode*/
        ctx2[9] === "focus"
      );
      toggle_class(
        svelte_element,
        "border_contrast",
        /*border_mode*/
        ctx2[9] === "contrast"
      );
      toggle_class(svelte_element, "hide-container", !/*explicit_call*/
      ctx2[12] && !/*container*/
      ctx2[13]);
      toggle_class(
        svelte_element,
        "fullscreen",
        /*fullscreen*/
        ctx2[0]
      );
      toggle_class(
        svelte_element,
        "animating",
        /*fullscreen*/
        ctx2[0] && /*preexpansionBoundingRect*/
        ctx2[24] !== null
      );
      toggle_class(
        svelte_element,
        "auto-margin",
        /*scale*/
        ctx2[17] === null
      );
      if (dirty[0] & /*fullscreen, height*/
      5) {
        set_style(
          svelte_element,
          "height",
          /*fullscreen*/
          ctx2[0] ? void 0 : (
            /*get_dimension*/
            ctx2[26](
              /*height*/
              ctx2[2]
            )
          )
        );
      }
      if (dirty[0] & /*fullscreen, min_height*/
      9) {
        set_style(
          svelte_element,
          "min-height",
          /*fullscreen*/
          ctx2[0] ? void 0 : (
            /*get_dimension*/
            ctx2[26](
              /*min_height*/
              ctx2[3]
            )
          )
        );
      }
      if (dirty[0] & /*fullscreen, max_height*/
      17) {
        set_style(
          svelte_element,
          "max-height",
          /*fullscreen*/
          ctx2[0] ? void 0 : (
            /*get_dimension*/
            ctx2[26](
              /*max_height*/
              ctx2[4]
            )
          )
        );
      }
      if (dirty[0] & /*preexpansionBoundingRect*/
      16777216) {
        set_style(
          svelte_element,
          "--start-top",
          /*preexpansionBoundingRect*/
          ctx2[24] ? `${/*preexpansionBoundingRect*/
          ctx2[24].top}px` : "0px"
        );
      }
      if (dirty[0] & /*preexpansionBoundingRect*/
      16777216) {
        set_style(
          svelte_element,
          "--start-left",
          /*preexpansionBoundingRect*/
          ctx2[24] ? `${/*preexpansionBoundingRect*/
          ctx2[24].left}px` : "0px"
        );
      }
      if (dirty[0] & /*preexpansionBoundingRect*/
      16777216) {
        set_style(
          svelte_element,
          "--start-width",
          /*preexpansionBoundingRect*/
          ctx2[24] ? `${/*preexpansionBoundingRect*/
          ctx2[24].width}px` : "0px"
        );
      }
      if (dirty[0] & /*preexpansionBoundingRect*/
      16777216) {
        set_style(
          svelte_element,
          "--start-height",
          /*preexpansionBoundingRect*/
          ctx2[24] ? `${/*preexpansionBoundingRect*/
          ctx2[24].height}px` : "0px"
        );
      }
      if (dirty[0] & /*fullscreen, width*/
      33) {
        set_style(
          svelte_element,
          "width",
          /*fullscreen*/
          ctx2[0] ? void 0 : typeof /*width*/
          ctx2[5] === "number" ? `calc(min(${/*width*/
          ctx2[5]}px, 100%))` : (
            /*get_dimension*/
            ctx2[26](
              /*width*/
              ctx2[5]
            )
          )
        );
      }
      if (dirty[0] & /*variant*/
      256) {
        set_style(
          svelte_element,
          "border-style",
          /*variant*/
          ctx2[8]
        );
      }
      if (dirty[0] & /*allow_overflow, overflow_behavior*/
      98304) {
        set_style(
          svelte_element,
          "overflow",
          /*allow_overflow*/
          ctx2[15] ? (
            /*overflow_behavior*/
            ctx2[16]
          ) : "hidden"
        );
      }
      if (dirty[0] & /*scale*/
      131072) {
        set_style(
          svelte_element,
          "flex-grow",
          /*scale*/
          ctx2[17]
        );
      }
      if (dirty[0] & /*min_width*/
      262144) {
        set_style(svelte_element, "min-width", `calc(min(${/*min_width*/
        ctx2[18]}px, 100%))`);
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(svelte_element);
      }
      if (default_slot) default_slot.d(detaching);
      if (if_block) if_block.d();
      ctx[32](null);
    }
  };
}
function create_if_block$m(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "placeholder svelte-239wnu");
      set_style(
        div,
        "height",
        /*placeholder_height*/
        ctx[22] + "px"
      );
      set_style(
        div,
        "width",
        /*placeholder_width*/
        ctx[23] + "px"
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*placeholder_height*/
      4194304) {
        set_style(
          div,
          "height",
          /*placeholder_height*/
          ctx2[22] + "px"
        );
      }
      if (dirty[0] & /*placeholder_width*/
      8388608) {
        set_style(
          div,
          "width",
          /*placeholder_width*/
          ctx2[23] + "px"
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_fragment$W(ctx) {
  let t;
  let if_block_anchor;
  let current;
  let svelte_element = (
    /*tag*/
    ctx[25] && create_dynamic_element(ctx)
  );
  let if_block = (
    /*fullscreen*/
    ctx[0] && create_if_block$m(ctx)
  );
  return {
    c() {
      if (svelte_element) svelte_element.c();
      t = space();
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (svelte_element) svelte_element.m(target, anchor);
      insert(target, t, anchor);
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*tag*/
        ctx2[25]
      ) {
        svelte_element.p(ctx2, dirty);
      }
      if (
        /*fullscreen*/
        ctx2[0]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$m(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i(local) {
      if (current) return;
      transition_in(svelte_element, local);
      current = true;
    },
    o(local) {
      transition_out(svelte_element, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
        detach(if_block_anchor);
      }
      if (svelte_element) svelte_element.d(detaching);
      if (if_block) if_block.d(detaching);
    }
  };
}
function instance$F($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { height: height2 = void 0 } = $$props;
  let { min_height = void 0 } = $$props;
  let { max_height = void 0 } = $$props;
  let { width = void 0 } = $$props;
  let { elem_id = "" } = $$props;
  let { elem_classes = [] } = $$props;
  let { variant = "solid" } = $$props;
  let { border_mode = "base" } = $$props;
  let { padding = true } = $$props;
  let { type = "normal" } = $$props;
  let { test_id = void 0 } = $$props;
  let { explicit_call = false } = $$props;
  let { container = true } = $$props;
  let { visible = true } = $$props;
  let { allow_overflow = true } = $$props;
  let { overflow_behavior = "auto" } = $$props;
  let { scale = null } = $$props;
  let { min_width = 0 } = $$props;
  let { flex = false } = $$props;
  let { resizable = false } = $$props;
  let { rtl = false } = $$props;
  let { fullscreen = false } = $$props;
  let old_fullscreen = fullscreen;
  let element2;
  let tag2 = type === "fieldset" ? "fieldset" : "div";
  let placeholder_height = 0;
  let placeholder_width = 0;
  let preexpansionBoundingRect = null;
  function handleKeydown(event) {
    if (fullscreen && event.key === "Escape") {
      $$invalidate(0, fullscreen = false);
    }
  }
  const get_dimension = (dimension_value) => {
    if (dimension_value === void 0) {
      return void 0;
    }
    if (typeof dimension_value === "number") {
      return dimension_value + "px";
    } else if (typeof dimension_value === "string") {
      return dimension_value;
    }
  };
  const resize = (e) => {
    let prevY = e.clientY;
    const onMouseMove = (e2) => {
      const dy = e2.clientY - prevY;
      prevY = e2.clientY;
      $$invalidate(21, element2.style.height = `${element2.offsetHeight + dy}px`, element2);
    };
    const onMouseUp = () => {
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", onMouseUp);
    };
    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("mouseup", onMouseUp);
  };
  function svelte_element_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      element2 = $$value;
      $$invalidate(21, element2);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("height" in $$props2) $$invalidate(2, height2 = $$props2.height);
    if ("min_height" in $$props2) $$invalidate(3, min_height = $$props2.min_height);
    if ("max_height" in $$props2) $$invalidate(4, max_height = $$props2.max_height);
    if ("width" in $$props2) $$invalidate(5, width = $$props2.width);
    if ("elem_id" in $$props2) $$invalidate(6, elem_id = $$props2.elem_id);
    if ("elem_classes" in $$props2) $$invalidate(7, elem_classes = $$props2.elem_classes);
    if ("variant" in $$props2) $$invalidate(8, variant = $$props2.variant);
    if ("border_mode" in $$props2) $$invalidate(9, border_mode = $$props2.border_mode);
    if ("padding" in $$props2) $$invalidate(10, padding = $$props2.padding);
    if ("type" in $$props2) $$invalidate(28, type = $$props2.type);
    if ("test_id" in $$props2) $$invalidate(11, test_id = $$props2.test_id);
    if ("explicit_call" in $$props2) $$invalidate(12, explicit_call = $$props2.explicit_call);
    if ("container" in $$props2) $$invalidate(13, container = $$props2.container);
    if ("visible" in $$props2) $$invalidate(14, visible = $$props2.visible);
    if ("allow_overflow" in $$props2) $$invalidate(15, allow_overflow = $$props2.allow_overflow);
    if ("overflow_behavior" in $$props2) $$invalidate(16, overflow_behavior = $$props2.overflow_behavior);
    if ("scale" in $$props2) $$invalidate(17, scale = $$props2.scale);
    if ("min_width" in $$props2) $$invalidate(18, min_width = $$props2.min_width);
    if ("flex" in $$props2) $$invalidate(1, flex = $$props2.flex);
    if ("resizable" in $$props2) $$invalidate(19, resizable = $$props2.resizable);
    if ("rtl" in $$props2) $$invalidate(20, rtl = $$props2.rtl);
    if ("fullscreen" in $$props2) $$invalidate(0, fullscreen = $$props2.fullscreen);
    if ("$$scope" in $$props2) $$invalidate(30, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*fullscreen, old_fullscreen, element*/
    538968065) {
      if (fullscreen !== old_fullscreen) {
        $$invalidate(29, old_fullscreen = fullscreen);
        if (fullscreen) {
          $$invalidate(24, preexpansionBoundingRect = element2.getBoundingClientRect());
          $$invalidate(22, placeholder_height = element2.offsetHeight);
          $$invalidate(23, placeholder_width = element2.offsetWidth);
          window.addEventListener("keydown", handleKeydown);
        } else {
          $$invalidate(24, preexpansionBoundingRect = null);
          window.removeEventListener("keydown", handleKeydown);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*visible*/
    16384) {
      if (!visible) {
        $$invalidate(1, flex = false);
      }
    }
  };
  return [
    fullscreen,
    flex,
    height2,
    min_height,
    max_height,
    width,
    elem_id,
    elem_classes,
    variant,
    border_mode,
    padding,
    test_id,
    explicit_call,
    container,
    visible,
    allow_overflow,
    overflow_behavior,
    scale,
    min_width,
    resizable,
    rtl,
    element2,
    placeholder_height,
    placeholder_width,
    preexpansionBoundingRect,
    tag2,
    get_dimension,
    resize,
    type,
    old_fullscreen,
    $$scope,
    slots,
    svelte_element_binding
  ];
}
class Block extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$F,
      create_fragment$W,
      safe_not_equal,
      {
        height: 2,
        min_height: 3,
        max_height: 4,
        width: 5,
        elem_id: 6,
        elem_classes: 7,
        variant: 8,
        border_mode: 9,
        padding: 10,
        type: 28,
        test_id: 11,
        explicit_call: 12,
        container: 13,
        visible: 14,
        allow_overflow: 15,
        overflow_behavior: 16,
        scale: 17,
        min_width: 18,
        flex: 1,
        resizable: 19,
        rtl: 20,
        fullscreen: 0
      },
      null,
      [-1, -1]
    );
  }
}
function _getDefaults() {
  return {
    async: false,
    breaks: false,
    extensions: null,
    gfm: true,
    hooks: null,
    pedantic: false,
    renderer: null,
    silent: false,
    tokenizer: null,
    walkTokens: null
  };
}
let _defaults = _getDefaults();
function changeDefaults(newDefaults) {
  _defaults = newDefaults;
}
const escapeTest$1 = /[&<>"']/;
const escapeReplace$1 = new RegExp(escapeTest$1.source, "g");
const escapeTestNoEncode$1 = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escapeReplaceNoEncode$1 = new RegExp(escapeTestNoEncode$1.source, "g");
const escapeReplacements$1 = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
const getEscapeReplacement$1 = (ch) => escapeReplacements$1[ch];
function escape$1$1(html2, encode) {
  if (encode) {
    if (escapeTest$1.test(html2)) {
      return html2.replace(escapeReplace$1, getEscapeReplacement$1);
    }
  } else {
    if (escapeTestNoEncode$1.test(html2)) {
      return html2.replace(escapeReplaceNoEncode$1, getEscapeReplacement$1);
    }
  }
  return html2;
}
const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
function unescape(html2) {
  return html2.replace(unescapeTest, (_, n) => {
    n = n.toLowerCase();
    if (n === "colon")
      return ":";
    if (n.charAt(0) === "#") {
      return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1));
    }
    return "";
  });
}
const caret = /(^|[^\[])\^/g;
function edit(regex2, opt) {
  let source = typeof regex2 === "string" ? regex2 : regex2.source;
  opt = opt || "";
  const obj = {
    replace: (name, val) => {
      let valSource = typeof val === "string" ? val : val.source;
      valSource = valSource.replace(caret, "$1");
      source = source.replace(name, valSource);
      return obj;
    },
    getRegex: () => {
      return new RegExp(source, opt);
    }
  };
  return obj;
}
function cleanUrl(href) {
  try {
    href = encodeURI(href).replace(/%25/g, "%");
  } catch (e) {
    return null;
  }
  return href;
}
const noopTest = { exec: () => null };
function splitCells(tableRow, count) {
  const row = tableRow.replace(/\|/g, (match, offset, str) => {
    let escaped = false;
    let curr = offset;
    while (--curr >= 0 && str[curr] === "\\")
      escaped = !escaped;
    if (escaped) {
      return "|";
    } else {
      return " |";
    }
  }), cells = row.split(/ \|/);
  let i = 0;
  if (!cells[0].trim()) {
    cells.shift();
  }
  if (cells.length > 0 && !cells[cells.length - 1].trim()) {
    cells.pop();
  }
  if (count) {
    if (cells.length > count) {
      cells.splice(count);
    } else {
      while (cells.length < count)
        cells.push("");
    }
  }
  for (; i < cells.length; i++) {
    cells[i] = cells[i].trim().replace(/\\\|/g, "|");
  }
  return cells;
}
function rtrim(str, c, invert) {
  const l = str.length;
  if (l === 0) {
    return "";
  }
  let suffLen = 0;
  while (suffLen < l) {
    const currChar = str.charAt(l - suffLen - 1);
    if (currChar === c && true) {
      suffLen++;
    } else {
      break;
    }
  }
  return str.slice(0, l - suffLen);
}
function findClosingBracket(str, b) {
  if (str.indexOf(b[1]) === -1) {
    return -1;
  }
  let level = 0;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "\\") {
      i++;
    } else if (str[i] === b[0]) {
      level++;
    } else if (str[i] === b[1]) {
      level--;
      if (level < 0) {
        return i;
      }
    }
  }
  return -1;
}
function outputLink(cap, link2, raw, lexer) {
  const href = link2.href;
  const title = link2.title ? escape$1$1(link2.title) : null;
  const text2 = cap[1].replace(/\\([\[\]])/g, "$1");
  if (cap[0].charAt(0) !== "!") {
    lexer.state.inLink = true;
    const token = {
      type: "link",
      raw,
      href,
      title,
      text: text2,
      tokens: lexer.inlineTokens(text2)
    };
    lexer.state.inLink = false;
    return token;
  }
  return {
    type: "image",
    raw,
    href,
    title,
    text: escape$1$1(text2)
  };
}
function indentCodeCompensation(raw, text2) {
  const matchIndentToCode = raw.match(/^(\s+)(?:```)/);
  if (matchIndentToCode === null) {
    return text2;
  }
  const indentToCode = matchIndentToCode[1];
  return text2.split("\n").map((node) => {
    const matchIndentInNode = node.match(/^\s+/);
    if (matchIndentInNode === null) {
      return node;
    }
    const [indentInNode] = matchIndentInNode;
    if (indentInNode.length >= indentToCode.length) {
      return node.slice(indentToCode.length);
    }
    return node;
  }).join("\n");
}
class _Tokenizer {
  // set by the lexer
  constructor(options) {
    __publicField(this, "options");
    __publicField(this, "rules");
    // set by the lexer
    __publicField(this, "lexer");
    this.options = options || _defaults;
  }
  space(src) {
    const cap = this.rules.block.newline.exec(src);
    if (cap && cap[0].length > 0) {
      return {
        type: "space",
        raw: cap[0]
      };
    }
  }
  code(src) {
    const cap = this.rules.block.code.exec(src);
    if (cap) {
      const text2 = cap[0].replace(/^ {1,4}/gm, "");
      return {
        type: "code",
        raw: cap[0],
        codeBlockStyle: "indented",
        text: !this.options.pedantic ? rtrim(text2, "\n") : text2
      };
    }
  }
  fences(src) {
    const cap = this.rules.block.fences.exec(src);
    if (cap) {
      const raw = cap[0];
      const text2 = indentCodeCompensation(raw, cap[3] || "");
      return {
        type: "code",
        raw,
        lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : cap[2],
        text: text2
      };
    }
  }
  heading(src) {
    const cap = this.rules.block.heading.exec(src);
    if (cap) {
      let text2 = cap[2].trim();
      if (/#$/.test(text2)) {
        const trimmed = rtrim(text2, "#");
        if (this.options.pedantic) {
          text2 = trimmed.trim();
        } else if (!trimmed || / $/.test(trimmed)) {
          text2 = trimmed.trim();
        }
      }
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[1].length,
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  hr(src) {
    const cap = this.rules.block.hr.exec(src);
    if (cap) {
      return {
        type: "hr",
        raw: cap[0]
      };
    }
  }
  blockquote(src) {
    const cap = this.rules.block.blockquote.exec(src);
    if (cap) {
      let text2 = cap[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g, "\n    $1");
      text2 = rtrim(text2.replace(/^ *>[ \t]?/gm, ""), "\n");
      const top = this.lexer.state.top;
      this.lexer.state.top = true;
      const tokens = this.lexer.blockTokens(text2);
      this.lexer.state.top = top;
      return {
        type: "blockquote",
        raw: cap[0],
        tokens,
        text: text2
      };
    }
  }
  list(src) {
    let cap = this.rules.block.list.exec(src);
    if (cap) {
      let bull = cap[1].trim();
      const isordered = bull.length > 1;
      const list2 = {
        type: "list",
        raw: "",
        ordered: isordered,
        start: isordered ? +bull.slice(0, -1) : "",
        loose: false,
        items: []
      };
      bull = isordered ? `\\d{1,9}\\${bull.slice(-1)}` : `\\${bull}`;
      if (this.options.pedantic) {
        bull = isordered ? bull : "[*+-]";
      }
      const itemRegex = new RegExp(`^( {0,3}${bull})((?:[	 ][^\\n]*)?(?:\\n|$))`);
      let raw = "";
      let itemContents = "";
      let endsWithBlankLine = false;
      while (src) {
        let endEarly = false;
        if (!(cap = itemRegex.exec(src))) {
          break;
        }
        if (this.rules.block.hr.test(src)) {
          break;
        }
        raw = cap[0];
        src = src.substring(raw.length);
        let line = cap[2].split("\n", 1)[0].replace(/^\t+/, (t) => " ".repeat(3 * t.length));
        let nextLine = src.split("\n", 1)[0];
        let indent = 0;
        if (this.options.pedantic) {
          indent = 2;
          itemContents = line.trimStart();
        } else {
          indent = cap[2].search(/[^ ]/);
          indent = indent > 4 ? 1 : indent;
          itemContents = line.slice(indent);
          indent += cap[1].length;
        }
        let blankLine = false;
        if (!line && /^ *$/.test(nextLine)) {
          raw += nextLine + "\n";
          src = src.substring(nextLine.length + 1);
          endEarly = true;
        }
        if (!endEarly) {
          const nextBulletRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`);
          const hrRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`);
          const fencesBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\`\`\`|~~~)`);
          const headingBeginRegex = new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`);
          while (src) {
            const rawLine = src.split("\n", 1)[0];
            nextLine = rawLine;
            if (this.options.pedantic) {
              nextLine = nextLine.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
            }
            if (fencesBeginRegex.test(nextLine)) {
              break;
            }
            if (headingBeginRegex.test(nextLine)) {
              break;
            }
            if (nextBulletRegex.test(nextLine)) {
              break;
            }
            if (hrRegex.test(src)) {
              break;
            }
            if (nextLine.search(/[^ ]/) >= indent || !nextLine.trim()) {
              itemContents += "\n" + nextLine.slice(indent);
            } else {
              if (blankLine) {
                break;
              }
              if (line.search(/[^ ]/) >= 4) {
                break;
              }
              if (fencesBeginRegex.test(line)) {
                break;
              }
              if (headingBeginRegex.test(line)) {
                break;
              }
              if (hrRegex.test(line)) {
                break;
              }
              itemContents += "\n" + nextLine;
            }
            if (!blankLine && !nextLine.trim()) {
              blankLine = true;
            }
            raw += rawLine + "\n";
            src = src.substring(rawLine.length + 1);
            line = nextLine.slice(indent);
          }
        }
        if (!list2.loose) {
          if (endsWithBlankLine) {
            list2.loose = true;
          } else if (/\n *\n *$/.test(raw)) {
            endsWithBlankLine = true;
          }
        }
        let istask = null;
        let ischecked;
        if (this.options.gfm) {
          istask = /^\[[ xX]\] /.exec(itemContents);
          if (istask) {
            ischecked = istask[0] !== "[ ] ";
            itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
          }
        }
        list2.items.push({
          type: "list_item",
          raw,
          task: !!istask,
          checked: ischecked,
          loose: false,
          text: itemContents,
          tokens: []
        });
        list2.raw += raw;
      }
      list2.items[list2.items.length - 1].raw = raw.trimEnd();
      list2.items[list2.items.length - 1].text = itemContents.trimEnd();
      list2.raw = list2.raw.trimEnd();
      for (let i = 0; i < list2.items.length; i++) {
        this.lexer.state.top = false;
        list2.items[i].tokens = this.lexer.blockTokens(list2.items[i].text, []);
        if (!list2.loose) {
          const spacers = list2.items[i].tokens.filter((t) => t.type === "space");
          const hasMultipleLineBreaks = spacers.length > 0 && spacers.some((t) => /\n.*\n/.test(t.raw));
          list2.loose = hasMultipleLineBreaks;
        }
      }
      if (list2.loose) {
        for (let i = 0; i < list2.items.length; i++) {
          list2.items[i].loose = true;
        }
      }
      return list2;
    }
  }
  html(src) {
    const cap = this.rules.block.html.exec(src);
    if (cap) {
      const token = {
        type: "html",
        block: true,
        raw: cap[0],
        pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
        text: cap[0]
      };
      return token;
    }
  }
  def(src) {
    const cap = this.rules.block.def.exec(src);
    if (cap) {
      const tag2 = cap[1].toLowerCase().replace(/\s+/g, " ");
      const href = cap[2] ? cap[2].replace(/^<(.*)>$/, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "";
      const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : cap[3];
      return {
        type: "def",
        tag: tag2,
        raw: cap[0],
        href,
        title
      };
    }
  }
  table(src) {
    const cap = this.rules.block.table.exec(src);
    if (!cap) {
      return;
    }
    if (!/[:|]/.test(cap[2])) {
      return;
    }
    const headers = splitCells(cap[1]);
    const aligns = cap[2].replace(/^\||\| *$/g, "").split("|");
    const rows = cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : [];
    const item = {
      type: "table",
      raw: cap[0],
      header: [],
      align: [],
      rows: []
    };
    if (headers.length !== aligns.length) {
      return;
    }
    for (const align of aligns) {
      if (/^ *-+: *$/.test(align)) {
        item.align.push("right");
      } else if (/^ *:-+: *$/.test(align)) {
        item.align.push("center");
      } else if (/^ *:-+ *$/.test(align)) {
        item.align.push("left");
      } else {
        item.align.push(null);
      }
    }
    for (const header of headers) {
      item.header.push({
        text: header,
        tokens: this.lexer.inline(header)
      });
    }
    for (const row of rows) {
      item.rows.push(splitCells(row, item.header.length).map((cell) => {
        return {
          text: cell,
          tokens: this.lexer.inline(cell)
        };
      }));
    }
    return item;
  }
  lheading(src) {
    const cap = this.rules.block.lheading.exec(src);
    if (cap) {
      return {
        type: "heading",
        raw: cap[0],
        depth: cap[2].charAt(0) === "=" ? 1 : 2,
        text: cap[1],
        tokens: this.lexer.inline(cap[1])
      };
    }
  }
  paragraph(src) {
    const cap = this.rules.block.paragraph.exec(src);
    if (cap) {
      const text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
      return {
        type: "paragraph",
        raw: cap[0],
        text: text2,
        tokens: this.lexer.inline(text2)
      };
    }
  }
  text(src) {
    const cap = this.rules.block.text.exec(src);
    if (cap) {
      return {
        type: "text",
        raw: cap[0],
        text: cap[0],
        tokens: this.lexer.inline(cap[0])
      };
    }
  }
  escape(src) {
    const cap = this.rules.inline.escape.exec(src);
    if (cap) {
      return {
        type: "escape",
        raw: cap[0],
        text: escape$1$1(cap[1])
      };
    }
  }
  tag(src) {
    const cap = this.rules.inline.tag.exec(src);
    if (cap) {
      if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
        this.lexer.state.inLink = true;
      } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
        this.lexer.state.inLink = false;
      }
      if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = true;
      } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
        this.lexer.state.inRawBlock = false;
      }
      return {
        type: "html",
        raw: cap[0],
        inLink: this.lexer.state.inLink,
        inRawBlock: this.lexer.state.inRawBlock,
        block: false,
        text: cap[0]
      };
    }
  }
  link(src) {
    const cap = this.rules.inline.link.exec(src);
    if (cap) {
      const trimmedUrl = cap[2].trim();
      if (!this.options.pedantic && /^</.test(trimmedUrl)) {
        if (!/>$/.test(trimmedUrl)) {
          return;
        }
        const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), "\\");
        if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
          return;
        }
      } else {
        const lastParenIndex = findClosingBracket(cap[2], "()");
        if (lastParenIndex > -1) {
          const start = cap[0].indexOf("!") === 0 ? 5 : 4;
          const linkLen = start + cap[1].length + lastParenIndex;
          cap[2] = cap[2].substring(0, lastParenIndex);
          cap[0] = cap[0].substring(0, linkLen).trim();
          cap[3] = "";
        }
      }
      let href = cap[2];
      let title = "";
      if (this.options.pedantic) {
        const link2 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
        if (link2) {
          href = link2[1];
          title = link2[3];
        }
      } else {
        title = cap[3] ? cap[3].slice(1, -1) : "";
      }
      href = href.trim();
      if (/^</.test(href)) {
        if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
          href = href.slice(1);
        } else {
          href = href.slice(1, -1);
        }
      }
      return outputLink(cap, {
        href: href ? href.replace(this.rules.inline.anyPunctuation, "$1") : href,
        title: title ? title.replace(this.rules.inline.anyPunctuation, "$1") : title
      }, cap[0], this.lexer);
    }
  }
  reflink(src, links) {
    let cap;
    if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
      const linkString = (cap[2] || cap[1]).replace(/\s+/g, " ");
      const link2 = links[linkString.toLowerCase()];
      if (!link2) {
        const text2 = cap[0].charAt(0);
        return {
          type: "text",
          raw: text2,
          text: text2
        };
      }
      return outputLink(cap, link2, cap[0], this.lexer);
    }
  }
  emStrong(src, maskedSrc, prevChar = "") {
    let match = this.rules.inline.emStrongLDelim.exec(src);
    if (!match)
      return;
    if (match[3] && prevChar.match(/[\p{L}\p{N}]/u))
      return;
    const nextChar = match[1] || match[2] || "";
    if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {
      const lLength = [...match[0]].length - 1;
      let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
      const endReg = match[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      endReg.lastIndex = 0;
      maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
      while ((match = endReg.exec(maskedSrc)) != null) {
        rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];
        if (!rDelim)
          continue;
        rLength = [...rDelim].length;
        if (match[3] || match[4]) {
          delimTotal += rLength;
          continue;
        } else if (match[5] || match[6]) {
          if (lLength % 3 && !((lLength + rLength) % 3)) {
            midDelimTotal += rLength;
            continue;
          }
        }
        delimTotal -= rLength;
        if (delimTotal > 0)
          continue;
        rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
        const lastCharLength = [...match[0]][0].length;
        const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);
        if (Math.min(lLength, rLength) % 2) {
          const text3 = raw.slice(1, -1);
          return {
            type: "em",
            raw,
            text: text3,
            tokens: this.lexer.inlineTokens(text3)
          };
        }
        const text2 = raw.slice(2, -2);
        return {
          type: "strong",
          raw,
          text: text2,
          tokens: this.lexer.inlineTokens(text2)
        };
      }
    }
  }
  codespan(src) {
    const cap = this.rules.inline.code.exec(src);
    if (cap) {
      let text2 = cap[2].replace(/\n/g, " ");
      const hasNonSpaceChars = /[^ ]/.test(text2);
      const hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2);
      if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
        text2 = text2.substring(1, text2.length - 1);
      }
      text2 = escape$1$1(text2, true);
      return {
        type: "codespan",
        raw: cap[0],
        text: text2
      };
    }
  }
  br(src) {
    const cap = this.rules.inline.br.exec(src);
    if (cap) {
      return {
        type: "br",
        raw: cap[0]
      };
    }
  }
  del(src) {
    const cap = this.rules.inline.del.exec(src);
    if (cap) {
      return {
        type: "del",
        raw: cap[0],
        text: cap[2],
        tokens: this.lexer.inlineTokens(cap[2])
      };
    }
  }
  autolink(src) {
    const cap = this.rules.inline.autolink.exec(src);
    if (cap) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape$1$1(cap[1]);
        href = "mailto:" + text2;
      } else {
        text2 = escape$1$1(cap[1]);
        href = text2;
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  url(src) {
    var _a;
    let cap;
    if (cap = this.rules.inline.url.exec(src)) {
      let text2, href;
      if (cap[2] === "@") {
        text2 = escape$1$1(cap[0]);
        href = "mailto:" + text2;
      } else {
        let prevCapZero;
        do {
          prevCapZero = cap[0];
          cap[0] = ((_a = this.rules.inline._backpedal.exec(cap[0])) == null ? void 0 : _a[0]) ?? "";
        } while (prevCapZero !== cap[0]);
        text2 = escape$1$1(cap[0]);
        if (cap[1] === "www.") {
          href = "http://" + cap[0];
        } else {
          href = cap[0];
        }
      }
      return {
        type: "link",
        raw: cap[0],
        text: text2,
        href,
        tokens: [
          {
            type: "text",
            raw: text2,
            text: text2
          }
        ]
      };
    }
  }
  inlineText(src) {
    const cap = this.rules.inline.text.exec(src);
    if (cap) {
      let text2;
      if (this.lexer.state.inRawBlock) {
        text2 = cap[0];
      } else {
        text2 = escape$1$1(cap[0]);
      }
      return {
        type: "text",
        raw: cap[0],
        text: text2
      };
    }
  }
}
const newline = /^(?: *(?:\n|$))+/;
const blockCode = /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/;
const fences = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/;
const hr = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/;
const heading = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/;
const bullet = /(?:[*+-]|\d{1,9}[.)])/;
const lheading = edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g, bullet).replace(/blockCode/g, / {4}/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).getRegex();
const _paragraph = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/;
const blockText = /^[^\n]+/;
const _blockLabel = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
const def = edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label", _blockLabel).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex();
const list = edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, bullet).getRegex();
const _tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
const _comment = /<!--(?:-?>|[\s\S]*?(?:-->|$))/;
const html = edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))", "i").replace("comment", _comment).replace("tag", _tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
const paragraph = edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
const blockquote = edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", paragraph).getRegex();
const blockNormal = {
  blockquote,
  code: blockCode,
  def,
  fences,
  heading,
  hr,
  html,
  lheading,
  list,
  newline,
  paragraph,
  table: noopTest,
  text: blockText
};
const gfmTable = edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex();
const blockGfm = {
  ...blockNormal,
  table: gfmTable,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", gfmTable).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", _tag).getRegex()
};
const blockPedantic = {
  ...blockNormal,
  html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", _comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
  heading: /^(#{1,6})(.*)(?:\n+|$)/,
  fences: noopTest,
  // fences not supported
  lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
  paragraph: edit(_paragraph).replace("hr", hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", lheading).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex()
};
const escape$2 = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/;
const inlineCode = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
const br = /^( {2,}|\\)\n(?!\s*$)/;
const inlineText = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/;
const _punctuation = "\\p{P}\\p{S}";
const punctuation = edit(/^((?![*_])[\spunctuation])/, "u").replace(/punctuation/g, _punctuation).getRegex();
const blockSkip = /\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g;
const emStrongLDelim = edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/, "u").replace(/punct/g, _punctuation).getRegex();
const emStrongRDelimAst = edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])", "gu").replace(/punct/g, _punctuation).getRegex();
const emStrongRDelimUnd = edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])", "gu").replace(/punct/g, _punctuation).getRegex();
const anyPunctuation = edit(/\\([punct])/, "gu").replace(/punct/g, _punctuation).getRegex();
const autolink = edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();
const _inlineComment = edit(_comment).replace("(?:-->|$)", "-->").getRegex();
const tag = edit("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", _inlineComment).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex();
const _inlineLabel = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
const link = edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label", _inlineLabel).replace("href", /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex();
const reflink = edit(/^!?\[(label)\]\[(ref)\]/).replace("label", _inlineLabel).replace("ref", _blockLabel).getRegex();
const nolink = edit(/^!?\[(ref)\](?:\[\])?/).replace("ref", _blockLabel).getRegex();
const reflinkSearch = edit("reflink|nolink(?!\\()", "g").replace("reflink", reflink).replace("nolink", nolink).getRegex();
const inlineNormal = {
  _backpedal: noopTest,
  // only used for GFM url
  anyPunctuation,
  autolink,
  blockSkip,
  br,
  code: inlineCode,
  del: noopTest,
  emStrongLDelim,
  emStrongRDelimAst,
  emStrongRDelimUnd,
  escape: escape$2,
  link,
  nolink,
  punctuation,
  reflink,
  reflinkSearch,
  tag,
  text: inlineText,
  url: noopTest
};
const inlinePedantic = {
  ...inlineNormal,
  link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", _inlineLabel).getRegex(),
  reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", _inlineLabel).getRegex()
};
const inlineGfm = {
  ...inlineNormal,
  escape: edit(escape$2).replace("])", "~|])").getRegex(),
  url: edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/, "i").replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),
  _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,
  del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
  text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
};
const inlineBreaks = {
  ...inlineGfm,
  br: edit(br).replace("{2,}", "*").getRegex(),
  text: edit(inlineGfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
};
const block = {
  normal: blockNormal,
  gfm: blockGfm,
  pedantic: blockPedantic
};
const inline = {
  normal: inlineNormal,
  gfm: inlineGfm,
  breaks: inlineBreaks,
  pedantic: inlinePedantic
};
class _Lexer {
  constructor(options) {
    __publicField(this, "tokens");
    __publicField(this, "options");
    __publicField(this, "state");
    __publicField(this, "tokenizer");
    __publicField(this, "inlineQueue");
    this.tokens = [];
    this.tokens.links = /* @__PURE__ */ Object.create(null);
    this.options = options || _defaults;
    this.options.tokenizer = this.options.tokenizer || new _Tokenizer();
    this.tokenizer = this.options.tokenizer;
    this.tokenizer.options = this.options;
    this.tokenizer.lexer = this;
    this.inlineQueue = [];
    this.state = {
      inLink: false,
      inRawBlock: false,
      top: true
    };
    const rules = {
      block: block.normal,
      inline: inline.normal
    };
    if (this.options.pedantic) {
      rules.block = block.pedantic;
      rules.inline = inline.pedantic;
    } else if (this.options.gfm) {
      rules.block = block.gfm;
      if (this.options.breaks) {
        rules.inline = inline.breaks;
      } else {
        rules.inline = inline.gfm;
      }
    }
    this.tokenizer.rules = rules;
  }
  /**
   * Expose Rules
   */
  static get rules() {
    return {
      block,
      inline
    };
  }
  /**
   * Static Lex Method
   */
  static lex(src, options) {
    const lexer = new _Lexer(options);
    return lexer.lex(src);
  }
  /**
   * Static Lex Inline Method
   */
  static lexInline(src, options) {
    const lexer = new _Lexer(options);
    return lexer.inlineTokens(src);
  }
  /**
   * Preprocessing
   */
  lex(src) {
    src = src.replace(/\r\n|\r/g, "\n");
    this.blockTokens(src, this.tokens);
    for (let i = 0; i < this.inlineQueue.length; i++) {
      const next = this.inlineQueue[i];
      this.inlineTokens(next.src, next.tokens);
    }
    this.inlineQueue = [];
    return this.tokens;
  }
  blockTokens(src, tokens = []) {
    if (this.options.pedantic) {
      src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
    } else {
      src = src.replace(/^( *)(\t+)/gm, (_, leading, tabs) => {
        return leading + "    ".repeat(tabs.length);
      });
    }
    let token;
    let lastToken;
    let cutSrc;
    let lastParagraphClipped;
    while (src) {
      if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.space(src)) {
        src = src.substring(token.raw.length);
        if (token.raw.length === 1 && tokens.length > 0) {
          tokens[tokens.length - 1].raw += "\n";
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.code(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.fences(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.heading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.hr(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.blockquote(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.list(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.html(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.def(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.raw;
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else if (!this.tokens.links[token.tag]) {
          this.tokens.links[token.tag] = {
            href: token.href,
            title: token.title
          };
        }
        continue;
      }
      if (token = this.tokenizer.table(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.lheading(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startBlock) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startBlock.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
        lastToken = tokens[tokens.length - 1];
        if (lastParagraphClipped && lastToken.type === "paragraph") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        lastParagraphClipped = cutSrc.length !== src.length;
        src = src.substring(token.raw.length);
        continue;
      }
      if (token = this.tokenizer.text(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += "\n" + token.raw;
          lastToken.text += "\n" + token.text;
          this.inlineQueue.pop();
          this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    this.state.top = true;
    return tokens;
  }
  inline(src, tokens = []) {
    this.inlineQueue.push({ src, tokens });
    return tokens;
  }
  /**
   * Lexing/Compiling
   */
  inlineTokens(src, tokens = []) {
    let token, lastToken, cutSrc;
    let maskedSrc = src;
    let match;
    let keepPrevChar, prevChar;
    if (this.tokens.links) {
      const links = Object.keys(this.tokens.links);
      if (links.length > 0) {
        while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
          if (links.includes(match[0].slice(match[0].lastIndexOf("[") + 1, -1))) {
            maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
          }
        }
      }
    }
    while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "[" + "a".repeat(match[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    }
    while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {
      maskedSrc = maskedSrc.slice(0, match.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    }
    while (src) {
      if (!keepPrevChar) {
        prevChar = "";
      }
      keepPrevChar = false;
      if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some((extTokenizer) => {
        if (token = extTokenizer.call({ lexer: this }, src, tokens)) {
          src = src.substring(token.raw.length);
          tokens.push(token);
          return true;
        }
        return false;
      })) {
        continue;
      }
      if (token = this.tokenizer.escape(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.tag(src)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.link(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.reflink(src, this.tokens.links)) {
        src = src.substring(token.raw.length);
        lastToken = tokens[tokens.length - 1];
        if (lastToken && token.type === "text" && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.codespan(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.br(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.del(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (token = this.tokenizer.autolink(src)) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      if (!this.state.inLink && (token = this.tokenizer.url(src))) {
        src = src.substring(token.raw.length);
        tokens.push(token);
        continue;
      }
      cutSrc = src;
      if (this.options.extensions && this.options.extensions.startInline) {
        let startIndex = Infinity;
        const tempSrc = src.slice(1);
        let tempStart;
        this.options.extensions.startInline.forEach((getStartIndex) => {
          tempStart = getStartIndex.call({ lexer: this }, tempSrc);
          if (typeof tempStart === "number" && tempStart >= 0) {
            startIndex = Math.min(startIndex, tempStart);
          }
        });
        if (startIndex < Infinity && startIndex >= 0) {
          cutSrc = src.substring(0, startIndex + 1);
        }
      }
      if (token = this.tokenizer.inlineText(cutSrc)) {
        src = src.substring(token.raw.length);
        if (token.raw.slice(-1) !== "_") {
          prevChar = token.raw.slice(-1);
        }
        keepPrevChar = true;
        lastToken = tokens[tokens.length - 1];
        if (lastToken && lastToken.type === "text") {
          lastToken.raw += token.raw;
          lastToken.text += token.text;
        } else {
          tokens.push(token);
        }
        continue;
      }
      if (src) {
        const errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
        if (this.options.silent) {
          console.error(errMsg);
          break;
        } else {
          throw new Error(errMsg);
        }
      }
    }
    return tokens;
  }
}
class _Renderer {
  constructor(options) {
    __publicField(this, "options");
    this.options = options || _defaults;
  }
  code(code, infostring, escaped) {
    var _a;
    const lang = (_a = (infostring || "").match(/^\S*/)) == null ? void 0 : _a[0];
    code = code.replace(/\n$/, "") + "\n";
    if (!lang) {
      return "<pre><code>" + (escaped ? code : escape$1$1(code, true)) + "</code></pre>\n";
    }
    return '<pre><code class="language-' + escape$1$1(lang) + '">' + (escaped ? code : escape$1$1(code, true)) + "</code></pre>\n";
  }
  blockquote(quote) {
    return `<blockquote>
${quote}</blockquote>
`;
  }
  html(html2, block2) {
    return html2;
  }
  heading(text2, level, raw) {
    return `<h${level}>${text2}</h${level}>
`;
  }
  hr() {
    return "<hr>\n";
  }
  list(body, ordered, start) {
    const type = ordered ? "ol" : "ul";
    const startatt = ordered && start !== 1 ? ' start="' + start + '"' : "";
    return "<" + type + startatt + ">\n" + body + "</" + type + ">\n";
  }
  listitem(text2, task, checked) {
    return `<li>${text2}</li>
`;
  }
  checkbox(checked) {
    return "<input " + (checked ? 'checked="" ' : "") + 'disabled="" type="checkbox">';
  }
  paragraph(text2) {
    return `<p>${text2}</p>
`;
  }
  table(header, body) {
    if (body)
      body = `<tbody>${body}</tbody>`;
    return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
  }
  tablerow(content) {
    return `<tr>
${content}</tr>
`;
  }
  tablecell(content, flags) {
    const type = flags.header ? "th" : "td";
    const tag2 = flags.align ? `<${type} align="${flags.align}">` : `<${type}>`;
    return tag2 + content + `</${type}>
`;
  }
  /**
   * span level renderer
   */
  strong(text2) {
    return `<strong>${text2}</strong>`;
  }
  em(text2) {
    return `<em>${text2}</em>`;
  }
  codespan(text2) {
    return `<code>${text2}</code>`;
  }
  br() {
    return "<br>";
  }
  del(text2) {
    return `<del>${text2}</del>`;
  }
  link(href, title, text2) {
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text2;
    }
    href = cleanHref;
    let out = '<a href="' + href + '"';
    if (title) {
      out += ' title="' + title + '"';
    }
    out += ">" + text2 + "</a>";
    return out;
  }
  image(href, title, text2) {
    const cleanHref = cleanUrl(href);
    if (cleanHref === null) {
      return text2;
    }
    href = cleanHref;
    let out = `<img src="${href}" alt="${text2}"`;
    if (title) {
      out += ` title="${title}"`;
    }
    out += ">";
    return out;
  }
  text(text2) {
    return text2;
  }
}
class _TextRenderer {
  // no need for block level renderers
  strong(text2) {
    return text2;
  }
  em(text2) {
    return text2;
  }
  codespan(text2) {
    return text2;
  }
  del(text2) {
    return text2;
  }
  html(text2) {
    return text2;
  }
  text(text2) {
    return text2;
  }
  link(href, title, text2) {
    return "" + text2;
  }
  image(href, title, text2) {
    return "" + text2;
  }
  br() {
    return "";
  }
}
class _Parser {
  constructor(options) {
    __publicField(this, "options");
    __publicField(this, "renderer");
    __publicField(this, "textRenderer");
    this.options = options || _defaults;
    this.options.renderer = this.options.renderer || new _Renderer();
    this.renderer = this.options.renderer;
    this.renderer.options = this.options;
    this.textRenderer = new _TextRenderer();
  }
  /**
   * Static Parse Method
   */
  static parse(tokens, options) {
    const parser = new _Parser(options);
    return parser.parse(tokens);
  }
  /**
   * Static Parse Inline Method
   */
  static parseInline(tokens, options) {
    const parser = new _Parser(options);
    return parser.parseInline(tokens);
  }
  /**
   * Parse Loop
   */
  parse(tokens, top = true) {
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const token = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        const genericToken = token;
        const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);
        if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(genericToken.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "space": {
          continue;
        }
        case "hr": {
          out += this.renderer.hr();
          continue;
        }
        case "heading": {
          const headingToken = token;
          out += this.renderer.heading(this.parseInline(headingToken.tokens), headingToken.depth, unescape(this.parseInline(headingToken.tokens, this.textRenderer)));
          continue;
        }
        case "code": {
          const codeToken = token;
          out += this.renderer.code(codeToken.text, codeToken.lang, !!codeToken.escaped);
          continue;
        }
        case "table": {
          const tableToken = token;
          let header = "";
          let cell = "";
          for (let j = 0; j < tableToken.header.length; j++) {
            cell += this.renderer.tablecell(this.parseInline(tableToken.header[j].tokens), { header: true, align: tableToken.align[j] });
          }
          header += this.renderer.tablerow(cell);
          let body = "";
          for (let j = 0; j < tableToken.rows.length; j++) {
            const row = tableToken.rows[j];
            cell = "";
            for (let k = 0; k < row.length; k++) {
              cell += this.renderer.tablecell(this.parseInline(row[k].tokens), { header: false, align: tableToken.align[k] });
            }
            body += this.renderer.tablerow(cell);
          }
          out += this.renderer.table(header, body);
          continue;
        }
        case "blockquote": {
          const blockquoteToken = token;
          const body = this.parse(blockquoteToken.tokens);
          out += this.renderer.blockquote(body);
          continue;
        }
        case "list": {
          const listToken = token;
          const ordered = listToken.ordered;
          const start = listToken.start;
          const loose = listToken.loose;
          let body = "";
          for (let j = 0; j < listToken.items.length; j++) {
            const item = listToken.items[j];
            const checked = item.checked;
            const task = item.task;
            let itemBody = "";
            if (item.task) {
              const checkbox = this.renderer.checkbox(!!checked);
              if (loose) {
                if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") {
                  item.tokens[0].text = checkbox + " " + item.tokens[0].text;
                  if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
                    item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text;
                  }
                } else {
                  item.tokens.unshift({
                    type: "text",
                    text: checkbox + " "
                  });
                }
              } else {
                itemBody += checkbox + " ";
              }
            }
            itemBody += this.parse(item.tokens, loose);
            body += this.renderer.listitem(itemBody, task, !!checked);
          }
          out += this.renderer.list(body, ordered, start);
          continue;
        }
        case "html": {
          const htmlToken = token;
          out += this.renderer.html(htmlToken.text, htmlToken.block);
          continue;
        }
        case "paragraph": {
          const paragraphToken = token;
          out += this.renderer.paragraph(this.parseInline(paragraphToken.tokens));
          continue;
        }
        case "text": {
          let textToken = token;
          let body = textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text;
          while (i + 1 < tokens.length && tokens[i + 1].type === "text") {
            textToken = tokens[++i];
            body += "\n" + (textToken.tokens ? this.parseInline(textToken.tokens) : textToken.text);
          }
          out += top ? this.renderer.paragraph(body) : body;
          continue;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
  /**
   * Parse Inline Tokens
   */
  parseInline(tokens, renderer2) {
    renderer2 = renderer2 || this.renderer;
    let out = "";
    for (let i = 0; i < tokens.length; i++) {
      const token = tokens[i];
      if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
        const ret = this.options.extensions.renderers[token.type].call({ parser: this }, token);
        if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) {
          out += ret || "";
          continue;
        }
      }
      switch (token.type) {
        case "escape": {
          const escapeToken = token;
          out += renderer2.text(escapeToken.text);
          break;
        }
        case "html": {
          const tagToken = token;
          out += renderer2.html(tagToken.text);
          break;
        }
        case "link": {
          const linkToken = token;
          out += renderer2.link(linkToken.href, linkToken.title, this.parseInline(linkToken.tokens, renderer2));
          break;
        }
        case "image": {
          const imageToken = token;
          out += renderer2.image(imageToken.href, imageToken.title, imageToken.text);
          break;
        }
        case "strong": {
          const strongToken = token;
          out += renderer2.strong(this.parseInline(strongToken.tokens, renderer2));
          break;
        }
        case "em": {
          const emToken = token;
          out += renderer2.em(this.parseInline(emToken.tokens, renderer2));
          break;
        }
        case "codespan": {
          const codespanToken = token;
          out += renderer2.codespan(codespanToken.text);
          break;
        }
        case "br": {
          out += renderer2.br();
          break;
        }
        case "del": {
          const delToken = token;
          out += renderer2.del(this.parseInline(delToken.tokens, renderer2));
          break;
        }
        case "text": {
          const textToken = token;
          out += renderer2.text(textToken.text);
          break;
        }
        default: {
          const errMsg = 'Token with "' + token.type + '" type was not found.';
          if (this.options.silent) {
            console.error(errMsg);
            return "";
          } else {
            throw new Error(errMsg);
          }
        }
      }
    }
    return out;
  }
}
class _Hooks {
  constructor(options) {
    __publicField(this, "options");
    this.options = options || _defaults;
  }
  /**
   * Process markdown before marked
   */
  preprocess(markdown) {
    return markdown;
  }
  /**
   * Process HTML after marked is finished
   */
  postprocess(html2) {
    return html2;
  }
  /**
   * Process all tokens before walk tokens
   */
  processAllTokens(tokens) {
    return tokens;
  }
}
__publicField(_Hooks, "passThroughHooks", /* @__PURE__ */ new Set([
  "preprocess",
  "postprocess",
  "processAllTokens"
]));
class Marked {
  constructor(...args) {
    __privateAdd(this, _Marked_instances);
    __publicField(this, "defaults", _getDefaults());
    __publicField(this, "options", this.setOptions);
    __publicField(this, "parse", __privateMethod(this, _Marked_instances, parseMarkdown_fn).call(this, _Lexer.lex, _Parser.parse));
    __publicField(this, "parseInline", __privateMethod(this, _Marked_instances, parseMarkdown_fn).call(this, _Lexer.lexInline, _Parser.parseInline));
    __publicField(this, "Parser", _Parser);
    __publicField(this, "Renderer", _Renderer);
    __publicField(this, "TextRenderer", _TextRenderer);
    __publicField(this, "Lexer", _Lexer);
    __publicField(this, "Tokenizer", _Tokenizer);
    __publicField(this, "Hooks", _Hooks);
    this.use(...args);
  }
  /**
   * Run callback for every token
   */
  walkTokens(tokens, callback) {
    var _a, _b;
    let values = [];
    for (const token of tokens) {
      values = values.concat(callback.call(this, token));
      switch (token.type) {
        case "table": {
          const tableToken = token;
          for (const cell of tableToken.header) {
            values = values.concat(this.walkTokens(cell.tokens, callback));
          }
          for (const row of tableToken.rows) {
            for (const cell of row) {
              values = values.concat(this.walkTokens(cell.tokens, callback));
            }
          }
          break;
        }
        case "list": {
          const listToken = token;
          values = values.concat(this.walkTokens(listToken.items, callback));
          break;
        }
        default: {
          const genericToken = token;
          if ((_b = (_a = this.defaults.extensions) == null ? void 0 : _a.childTokens) == null ? void 0 : _b[genericToken.type]) {
            this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {
              const tokens2 = genericToken[childTokens].flat(Infinity);
              values = values.concat(this.walkTokens(tokens2, callback));
            });
          } else if (genericToken.tokens) {
            values = values.concat(this.walkTokens(genericToken.tokens, callback));
          }
        }
      }
    }
    return values;
  }
  use(...args) {
    const extensions = this.defaults.extensions || { renderers: {}, childTokens: {} };
    args.forEach((pack) => {
      const opts = { ...pack };
      opts.async = this.defaults.async || opts.async || false;
      if (pack.extensions) {
        pack.extensions.forEach((ext) => {
          if (!ext.name) {
            throw new Error("extension name required");
          }
          if ("renderer" in ext) {
            const prevRenderer = extensions.renderers[ext.name];
            if (prevRenderer) {
              extensions.renderers[ext.name] = function(...args2) {
                let ret = ext.renderer.apply(this, args2);
                if (ret === false) {
                  ret = prevRenderer.apply(this, args2);
                }
                return ret;
              };
            } else {
              extensions.renderers[ext.name] = ext.renderer;
            }
          }
          if ("tokenizer" in ext) {
            if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
              throw new Error("extension level must be 'block' or 'inline'");
            }
            const extLevel = extensions[ext.level];
            if (extLevel) {
              extLevel.unshift(ext.tokenizer);
            } else {
              extensions[ext.level] = [ext.tokenizer];
            }
            if (ext.start) {
              if (ext.level === "block") {
                if (extensions.startBlock) {
                  extensions.startBlock.push(ext.start);
                } else {
                  extensions.startBlock = [ext.start];
                }
              } else if (ext.level === "inline") {
                if (extensions.startInline) {
                  extensions.startInline.push(ext.start);
                } else {
                  extensions.startInline = [ext.start];
                }
              }
            }
          }
          if ("childTokens" in ext && ext.childTokens) {
            extensions.childTokens[ext.name] = ext.childTokens;
          }
        });
        opts.extensions = extensions;
      }
      if (pack.renderer) {
        const renderer2 = this.defaults.renderer || new _Renderer(this.defaults);
        for (const prop in pack.renderer) {
          if (!(prop in renderer2)) {
            throw new Error(`renderer '${prop}' does not exist`);
          }
          if (prop === "options") {
            continue;
          }
          const rendererProp = prop;
          const rendererFunc = pack.renderer[rendererProp];
          const prevRenderer = renderer2[rendererProp];
          renderer2[rendererProp] = (...args2) => {
            let ret = rendererFunc.apply(renderer2, args2);
            if (ret === false) {
              ret = prevRenderer.apply(renderer2, args2);
            }
            return ret || "";
          };
        }
        opts.renderer = renderer2;
      }
      if (pack.tokenizer) {
        const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);
        for (const prop in pack.tokenizer) {
          if (!(prop in tokenizer)) {
            throw new Error(`tokenizer '${prop}' does not exist`);
          }
          if (["options", "rules", "lexer"].includes(prop)) {
            continue;
          }
          const tokenizerProp = prop;
          const tokenizerFunc = pack.tokenizer[tokenizerProp];
          const prevTokenizer = tokenizer[tokenizerProp];
          tokenizer[tokenizerProp] = (...args2) => {
            let ret = tokenizerFunc.apply(tokenizer, args2);
            if (ret === false) {
              ret = prevTokenizer.apply(tokenizer, args2);
            }
            return ret;
          };
        }
        opts.tokenizer = tokenizer;
      }
      if (pack.hooks) {
        const hooks = this.defaults.hooks || new _Hooks();
        for (const prop in pack.hooks) {
          if (!(prop in hooks)) {
            throw new Error(`hook '${prop}' does not exist`);
          }
          if (prop === "options") {
            continue;
          }
          const hooksProp = prop;
          const hooksFunc = pack.hooks[hooksProp];
          const prevHook = hooks[hooksProp];
          if (_Hooks.passThroughHooks.has(prop)) {
            hooks[hooksProp] = (arg) => {
              if (this.defaults.async) {
                return Promise.resolve(hooksFunc.call(hooks, arg)).then((ret2) => {
                  return prevHook.call(hooks, ret2);
                });
              }
              const ret = hooksFunc.call(hooks, arg);
              return prevHook.call(hooks, ret);
            };
          } else {
            hooks[hooksProp] = (...args2) => {
              let ret = hooksFunc.apply(hooks, args2);
              if (ret === false) {
                ret = prevHook.apply(hooks, args2);
              }
              return ret;
            };
          }
        }
        opts.hooks = hooks;
      }
      if (pack.walkTokens) {
        const walkTokens = this.defaults.walkTokens;
        const packWalktokens = pack.walkTokens;
        opts.walkTokens = function(token) {
          let values = [];
          values.push(packWalktokens.call(this, token));
          if (walkTokens) {
            values = values.concat(walkTokens.call(this, token));
          }
          return values;
        };
      }
      this.defaults = { ...this.defaults, ...opts };
    });
    return this;
  }
  setOptions(opt) {
    this.defaults = { ...this.defaults, ...opt };
    return this;
  }
  lexer(src, options) {
    return _Lexer.lex(src, options ?? this.defaults);
  }
  parser(tokens, options) {
    return _Parser.parse(tokens, options ?? this.defaults);
  }
}
_Marked_instances = new WeakSet();
parseMarkdown_fn = function(lexer, parser) {
  return (src, options) => {
    const origOpt = { ...options };
    const opt = { ...this.defaults, ...origOpt };
    if (this.defaults.async === true && origOpt.async === false) {
      if (!opt.silent) {
        console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored.");
      }
      opt.async = true;
    }
    const throwError = __privateMethod(this, _Marked_instances, onError_fn).call(this, !!opt.silent, !!opt.async);
    if (typeof src === "undefined" || src === null) {
      return throwError(new Error("marked(): input parameter is undefined or null"));
    }
    if (typeof src !== "string") {
      return throwError(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected"));
    }
    if (opt.hooks) {
      opt.hooks.options = opt;
    }
    if (opt.async) {
      return Promise.resolve(opt.hooks ? opt.hooks.preprocess(src) : src).then((src2) => lexer(src2, opt)).then((tokens) => opt.hooks ? opt.hooks.processAllTokens(tokens) : tokens).then((tokens) => opt.walkTokens ? Promise.all(this.walkTokens(tokens, opt.walkTokens)).then(() => tokens) : tokens).then((tokens) => parser(tokens, opt)).then((html2) => opt.hooks ? opt.hooks.postprocess(html2) : html2).catch(throwError);
    }
    try {
      if (opt.hooks) {
        src = opt.hooks.preprocess(src);
      }
      let tokens = lexer(src, opt);
      if (opt.hooks) {
        tokens = opt.hooks.processAllTokens(tokens);
      }
      if (opt.walkTokens) {
        this.walkTokens(tokens, opt.walkTokens);
      }
      let html2 = parser(tokens, opt);
      if (opt.hooks) {
        html2 = opt.hooks.postprocess(html2);
      }
      return html2;
    } catch (e) {
      return throwError(e);
    }
  };
};
onError_fn = function(silent, async) {
  return (e) => {
    e.message += "\nPlease report this to https://github.com/markedjs/marked.";
    if (silent) {
      const msg = "<p>An error occurred:</p><pre>" + escape$1$1(e.message + "", true) + "</pre>";
      if (async) {
        return Promise.resolve(msg);
      }
      return msg;
    }
    if (async) {
      return Promise.reject(e);
    }
    throw e;
  };
};
const markedInstance = new Marked();
function marked(src, opt) {
  return markedInstance.parse(src, opt);
}
marked.options = marked.setOptions = function(options) {
  markedInstance.setOptions(options);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.getDefaults = _getDefaults;
marked.defaults = _defaults;
marked.use = function(...args) {
  markedInstance.use(...args);
  marked.defaults = markedInstance.defaults;
  changeDefaults(marked.defaults);
  return marked;
};
marked.walkTokens = function(tokens, callback) {
  return markedInstance.walkTokens(tokens, callback);
};
marked.parseInline = markedInstance.parseInline;
marked.Parser = _Parser;
marked.parser = _Parser.parse;
marked.Renderer = _Renderer;
marked.TextRenderer = _TextRenderer;
marked.Lexer = _Lexer;
marked.lexer = _Lexer.lex;
marked.Tokenizer = _Tokenizer;
marked.Hooks = _Hooks;
marked.parse = marked;
marked.options;
marked.setOptions;
marked.use;
marked.walkTokens;
marked.parseInline;
_Parser.parse;
_Lexer.lex;
function markedHighlight(options) {
  if (typeof options === "function") {
    options = {
      highlight: options
    };
  }
  if (!options || typeof options.highlight !== "function") {
    throw new Error("Must provide highlight function");
  }
  if (typeof options.langPrefix !== "string") {
    options.langPrefix = "language-";
  }
  if (typeof options.emptyLangClass !== "string") {
    options.emptyLangClass = "";
  }
  return {
    async: !!options.async,
    walkTokens(token) {
      if (token.type !== "code") {
        return;
      }
      const lang = getLang(token.lang);
      if (options.async) {
        return Promise.resolve(options.highlight(token.text, lang, token.lang || "")).then(updateToken(token));
      }
      const code = options.highlight(token.text, lang, token.lang || "");
      if (code instanceof Promise) {
        throw new Error("markedHighlight is not set to async but the highlight function is async. Set the async option to true on markedHighlight to await the async highlight function.");
      }
      updateToken(token)(code);
    },
    useNewRenderer: true,
    renderer: {
      code(code, infoString, escaped) {
        if (typeof code === "object") {
          escaped = code.escaped;
          infoString = code.lang;
          code = code.text;
        }
        const lang = getLang(infoString);
        const classValue = lang ? options.langPrefix + escape$1(lang) : options.emptyLangClass;
        const classAttr = classValue ? ` class="${classValue}"` : "";
        code = code.replace(/\n$/, "");
        return `<pre><code${classAttr}>${escaped ? code : escape$1(code, true)}
</code></pre>`;
      }
    }
  };
}
function getLang(lang) {
  return (lang || "").match(/\S*/)[0];
}
function updateToken(token) {
  return (code) => {
    if (typeof code === "string" && code !== token.text) {
      token.escaped = true;
      token.text = code;
    }
  };
}
const escapeTest = /[&<>"']/;
const escapeReplace = new RegExp(escapeTest.source, "g");
const escapeTestNoEncode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escapeReplaceNoEncode = new RegExp(escapeTestNoEncode.source, "g");
const escapeReplacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
const getEscapeReplacement = (ch) => escapeReplacements[ch];
function escape$1(html2, encode) {
  if (encode) {
    if (escapeTest.test(html2)) {
      return html2.replace(escapeReplace, getEscapeReplacement);
    }
  } else {
    if (escapeTestNoEncode.test(html2)) {
      return html2.replace(escapeReplaceNoEncode, getEscapeReplacement);
    }
  }
  return html2;
}
const regex = /[\0-\x1F!-,\.\/:-@\[-\^`\{-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0378\u0379\u037E\u0380-\u0385\u0387\u038B\u038D\u03A2\u03F6\u0482\u0530\u0557\u0558\u055A-\u055F\u0589-\u0590\u05BE\u05C0\u05C3\u05C6\u05C8-\u05CF\u05EB-\u05EE\u05F3-\u060F\u061B-\u061F\u066A-\u066D\u06D4\u06DD\u06DE\u06E9\u06FD\u06FE\u0700-\u070F\u074B\u074C\u07B2-\u07BF\u07F6-\u07F9\u07FB\u07FC\u07FE\u07FF\u082E-\u083F\u085C-\u085F\u086B-\u089F\u08B5\u08C8-\u08D2\u08E2\u0964\u0965\u0970\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09F2-\u09FB\u09FD\u09FF\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF0-\u0AF8\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B54\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B70\u0B72-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BF0-\u0BFF\u0C0D\u0C11\u0C29\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5B-\u0C5F\u0C64\u0C65\u0C70-\u0C7F\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0CFF\u0D0D\u0D11\u0D45\u0D49\u0D4F-\u0D53\u0D58-\u0D5E\u0D64\u0D65\u0D70-\u0D79\u0D80\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DE5\u0DF0\u0DF1\u0DF4-\u0E00\u0E3B-\u0E3F\u0E4F\u0E5A-\u0E80\u0E83\u0E85\u0E8B\u0EA4\u0EA6\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F01-\u0F17\u0F1A-\u0F1F\u0F2A-\u0F34\u0F36\u0F38\u0F3A-\u0F3D\u0F48\u0F6D-\u0F70\u0F85\u0F98\u0FBD-\u0FC5\u0FC7-\u0FFF\u104A-\u104F\u109E\u109F\u10C6\u10C8-\u10CC\u10CE\u10CF\u10FB\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u1360-\u137F\u1390-\u139F\u13F6\u13F7\u13FE-\u1400\u166D\u166E\u1680\u169B-\u169F\u16EB-\u16ED\u16F9-\u16FF\u170D\u1715-\u171F\u1735-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17D4-\u17D6\u17D8-\u17DB\u17DE\u17DF\u17EA-\u180A\u180E\u180F\u181A-\u181F\u1879-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191F\u192C-\u192F\u193C-\u1945\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DA-\u19FF\u1A1C-\u1A1F\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1AA6\u1AA8-\u1AAF\u1AC1-\u1AFF\u1B4C-\u1B4F\u1B5A-\u1B6A\u1B74-\u1B7F\u1BF4-\u1BFF\u1C38-\u1C3F\u1C4A-\u1C4C\u1C7E\u1C7F\u1C89-\u1C8F\u1CBB\u1CBC\u1CC0-\u1CCF\u1CD3\u1CFB-\u1CFF\u1DFA\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FBD\u1FBF-\u1FC1\u1FC5\u1FCD-\u1FCF\u1FD4\u1FD5\u1FDC-\u1FDF\u1FED-\u1FF1\u1FF5\u1FFD-\u203E\u2041-\u2053\u2055-\u2070\u2072-\u207E\u2080-\u208F\u209D-\u20CF\u20F1-\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F-\u215F\u2189-\u24B5\u24EA-\u2BFF\u2C2F\u2C5F\u2CE5-\u2CEA\u2CF4-\u2CFF\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D70-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E00-\u2E2E\u2E30-\u3004\u3008-\u3020\u3030\u3036\u3037\u303D-\u3040\u3097\u3098\u309B\u309C\u30A0\u30FB\u3100-\u3104\u3130\u318F-\u319F\u31C0-\u31EF\u3200-\u33FF\u4DC0-\u4DFF\u9FFD-\u9FFF\uA48D-\uA4CF\uA4FE\uA4FF\uA60D-\uA60F\uA62C-\uA63F\uA673\uA67E\uA6F2-\uA716\uA720\uA721\uA789\uA78A\uA7C0\uA7C1\uA7CB-\uA7F4\uA828-\uA82B\uA82D-\uA83F\uA874-\uA87F\uA8C6-\uA8CF\uA8DA-\uA8DF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA954-\uA95F\uA97D-\uA97F\uA9C1-\uA9CE\uA9DA-\uA9DF\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A-\uAA5F\uAA77-\uAA79\uAAC3-\uAADA\uAADE\uAADF\uAAF0\uAAF1\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F\uAB5B\uAB6A-\uAB6F\uABEB\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uD7FF\uE000-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB29\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBB2-\uFBD2\uFD3E-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFC-\uFDFF\uFE10-\uFE1F\uFE30-\uFE32\uFE35-\uFE4C\uFE50-\uFE6F\uFE75\uFEFD-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF3E\uFF40\uFF5B-\uFF65\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFFF]|\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDD3F\uDD75-\uDDFC\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEE1-\uDEFF\uDF20-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDF9F\uDFC4-\uDFC7\uDFD0\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56-\uDC5F\uDC77-\uDC7F\uDC9F-\uDCDF\uDCF3\uDCF6-\uDCFF\uDD16-\uDD1F\uDD3A-\uDD7F\uDDB8-\uDDBD\uDDC0-\uDDFF\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE40-\uDE5F\uDE7D-\uDE7F\uDE9D-\uDEBF\uDEC8\uDEE7-\uDEFF\uDF36-\uDF3F\uDF56-\uDF5F\uDF73-\uDF7F\uDF92-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCFF\uDD28-\uDD2F\uDD3A-\uDE7F\uDEAA\uDEAD-\uDEAF\uDEB2-\uDEFF\uDF1D-\uDF26\uDF28-\uDF2F\uDF51-\uDFAF\uDFC5-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC47-\uDC65\uDC70-\uDC7E\uDCBB-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD40-\uDD43\uDD48-\uDD4F\uDD74\uDD75\uDD77-\uDD7F\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDFF\uDE12\uDE38-\uDE3D\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEA9-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC4B-\uDC4F\uDC5A-\uDC5D\uDC62-\uDC7F\uDCC6\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDC1-\uDDD7\uDDDE-\uDDFF\uDE41-\uDE43\uDE45-\uDE4F\uDE5A-\uDE7F\uDEB9-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF3A-\uDFFF]|\uD806[\uDC3B-\uDC9F\uDCEA-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD44-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE2\uDDE5-\uDDFF\uDE3F-\uDE46\uDE48-\uDE4F\uDE9A-\uDE9C\uDE9E-\uDEBF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC41-\uDC4F\uDC5A-\uDC71\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF7-\uDFAF\uDFB1-\uDFFF]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80B\uD80E-\uD810\uD812-\uD819\uD824-\uD82B\uD82D\uD82E\uD830-\uD833\uD837\uD839\uD83D\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDECF\uDEEE\uDEEF\uDEF5-\uDEFF\uDF37-\uDF3F\uDF44-\uDF4F\uDF5A-\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE80-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE2\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82C[\uDD1F-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A-\uDC9C\uDC9F-\uDFFF]|\uD834[\uDC00-\uDD64\uDD6A-\uDD6C\uDD73-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDE41\uDE45-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3\uDFCC\uDFCD]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD4F-\uDEBF\uDEFA-\uDFFF]|\uD83A[\uDCC5-\uDCCF\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDFFF]|\uD83B[\uDC00-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDFFF]|\uD83C[\uDC00-\uDD2F\uDD4A-\uDD4F\uDD6A-\uDD6F\uDD8A-\uDFFF]|\uD83E[\uDC00-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEDE-\uDEFF]|\uD86D[\uDF35-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]/g;
const own = Object.hasOwnProperty;
class BananaSlug {
  /**
   * Create a new slug class.
   */
  constructor() {
    this.occurrences;
    this.reset();
  }
  /**
   * Generate a unique slug.
  *
  * Tracks previously generated slugs: repeated calls with the same value
  * will result in different slugs.
  * Use the `slug` function to get same slugs.
   *
   * @param  {string} value
   *   String of text to slugify
   * @param  {boolean} [maintainCase=false]
   *   Keep the current case, otherwise make all lowercase
   * @return {string}
   *   A unique slug string
   */
  slug(value, maintainCase) {
    const self2 = this;
    let result = slug(value, maintainCase === true);
    const originalSlug = result;
    while (own.call(self2.occurrences, result)) {
      self2.occurrences[originalSlug]++;
      result = originalSlug + "-" + self2.occurrences[originalSlug];
    }
    self2.occurrences[result] = 0;
    return result;
  }
  /**
   * Reset - Forget all previous slugs
   *
   * @return void
   */
  reset() {
    this.occurrences = /* @__PURE__ */ Object.create(null);
  }
}
function slug(value, maintainCase) {
  if (typeof value !== "string") return "";
  if (!maintainCase) value = value.toLowerCase();
  return value.replace(regex, "").replace(/ /g, "-");
}
let slugger$1 = new BananaSlug();
let headings = [];
function gfmHeadingId({ prefix = "", globalSlugs = false } = {}) {
  return {
    headerIds: false,
    // prevent deprecation warning; remove this once headerIds option is removed
    hooks: {
      preprocess(src) {
        if (!globalSlugs) {
          resetHeadings();
        }
        return src;
      }
    },
    renderer: {
      heading(text2, level, raw) {
        raw = raw.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi, "");
        const id = `${prefix}${slugger$1.slug(raw)}`;
        const heading2 = { level, text: text2, id };
        headings.push(heading2);
        return `<h${level} id="${id}">${text2}</h${level}>
`;
      }
    }
  };
}
function resetHeadings() {
  headings = [];
  slugger$1 = new BananaSlug();
}
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var prism = { exports: {} };
(function(module) {
  var _self = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope ? self : {};
  /**
   * Prism: Lightweight, robust, elegant syntax highlighting
   *
   * @license MIT <https://opensource.org/licenses/MIT>
   * @author Lea Verou <https://lea.verou.me>
   * @namespace
   * @public
   */
  var Prism2 = function(_self2) {
    var lang = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i;
    var uniqueId = 0;
    var plainTextGrammar = {};
    var _ = {
      /**
       * By default, Prism will attempt to highlight all code elements (by calling {@link Prism.highlightAll}) on the
       * current page after the page finished loading. This might be a problem if e.g. you wanted to asynchronously load
       * additional languages or plugins yourself.
       *
       * By setting this value to `true`, Prism will not automatically highlight all code elements on the page.
       *
       * You obviously have to change this value before the automatic highlighting started. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.manual = true;
       * // add a new <script> to load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      manual: _self2.Prism && _self2.Prism.manual,
      /**
       * By default, if Prism is in a web worker, it assumes that it is in a worker it created itself, so it uses
       * `addEventListener` to communicate with its parent instance. However, if you're using Prism manually in your
       * own worker, you don't want it to do this.
       *
       * By setting this value to `true`, Prism will not add its own listeners to the worker.
       *
       * You obviously have to change this value before Prism executes. To do this, you can add an
       * empty Prism object into the global scope before loading the Prism script like this:
       *
       * ```js
       * window.Prism = window.Prism || {};
       * Prism.disableWorkerMessageHandler = true;
       * // Load Prism's script
       * ```
       *
       * @default false
       * @type {boolean}
       * @memberof Prism
       * @public
       */
      disableWorkerMessageHandler: _self2.Prism && _self2.Prism.disableWorkerMessageHandler,
      /**
       * A namespace for utility methods.
       *
       * All function in this namespace that are not explicitly marked as _public_ are for __internal use only__ and may
       * change or disappear at any time.
       *
       * @namespace
       * @memberof Prism
       */
      util: {
        encode: function encode(tokens) {
          if (tokens instanceof Token) {
            return new Token(tokens.type, encode(tokens.content), tokens.alias);
          } else if (Array.isArray(tokens)) {
            return tokens.map(encode);
          } else {
            return tokens.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\u00a0/g, " ");
          }
        },
        /**
         * Returns the name of the type of the given value.
         *
         * @param {any} o
         * @returns {string}
         * @example
         * type(null)      === 'Null'
         * type(undefined) === 'Undefined'
         * type(123)       === 'Number'
         * type('foo')     === 'String'
         * type(true)      === 'Boolean'
         * type([1, 2])    === 'Array'
         * type({})        === 'Object'
         * type(String)    === 'Function'
         * type(/abc+/)    === 'RegExp'
         */
        type: function(o) {
          return Object.prototype.toString.call(o).slice(8, -1);
        },
        /**
         * Returns a unique number for the given object. Later calls will still return the same number.
         *
         * @param {Object} obj
         * @returns {number}
         */
        objId: function(obj) {
          if (!obj["__id"]) {
            Object.defineProperty(obj, "__id", { value: ++uniqueId });
          }
          return obj["__id"];
        },
        /**
         * Creates a deep clone of the given object.
         *
         * The main intended use of this function is to clone language definitions.
         *
         * @param {T} o
         * @param {Record<number, any>} [visited]
         * @returns {T}
         * @template T
         */
        clone: function deepClone(o, visited) {
          visited = visited || {};
          var clone;
          var id;
          switch (_.util.type(o)) {
            case "Object":
              id = _.util.objId(o);
              if (visited[id]) {
                return visited[id];
              }
              clone = /** @type {Record<string, any>} */
              {};
              visited[id] = clone;
              for (var key in o) {
                if (o.hasOwnProperty(key)) {
                  clone[key] = deepClone(o[key], visited);
                }
              }
              return (
                /** @type {any} */
                clone
              );
            case "Array":
              id = _.util.objId(o);
              if (visited[id]) {
                return visited[id];
              }
              clone = [];
              visited[id] = clone;
              /** @type {Array} */
              /** @type {any} */
              o.forEach(function(v, i) {
                clone[i] = deepClone(v, visited);
              });
              return (
                /** @type {any} */
                clone
              );
            default:
              return o;
          }
        },
        /**
         * Returns the Prism language of the given element set by a `language-xxxx` or `lang-xxxx` class.
         *
         * If no language is set for the element or the element is `null` or `undefined`, `none` will be returned.
         *
         * @param {Element} element
         * @returns {string}
         */
        getLanguage: function(element2) {
          while (element2) {
            var m = lang.exec(element2.className);
            if (m) {
              return m[1].toLowerCase();
            }
            element2 = element2.parentElement;
          }
          return "none";
        },
        /**
         * Sets the Prism `language-xxxx` class of the given element.
         *
         * @param {Element} element
         * @param {string} language
         * @returns {void}
         */
        setLanguage: function(element2, language) {
          element2.className = element2.className.replace(RegExp(lang, "gi"), "");
          element2.classList.add("language-" + language);
        },
        /**
         * Returns the script element that is currently executing.
         *
         * This does __not__ work for line script element.
         *
         * @returns {HTMLScriptElement | null}
         */
        currentScript: function() {
          if (typeof document === "undefined") {
            return null;
          }
          if (document.currentScript && document.currentScript.tagName === "SCRIPT" && 1 < 2) {
            return (
              /** @type {any} */
              document.currentScript
            );
          }
          try {
            throw new Error();
          } catch (err) {
            var src = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(err.stack) || [])[1];
            if (src) {
              var scripts = document.getElementsByTagName("script");
              for (var i in scripts) {
                if (scripts[i].src == src) {
                  return scripts[i];
                }
              }
            }
            return null;
          }
        },
        /**
         * Returns whether a given class is active for `element`.
         *
         * The class can be activated if `element` or one of its ancestors has the given class and it can be deactivated
         * if `element` or one of its ancestors has the negated version of the given class. The _negated version_ of the
         * given class is just the given class with a `no-` prefix.
         *
         * Whether the class is active is determined by the closest ancestor of `element` (where `element` itself is
         * closest ancestor) that has the given class or the negated version of it. If neither `element` nor any of its
         * ancestors have the given class or the negated version of it, then the default activation will be returned.
         *
         * In the paradoxical situation where the closest ancestor contains __both__ the given class and the negated
         * version of it, the class is considered active.
         *
         * @param {Element} element
         * @param {string} className
         * @param {boolean} [defaultActivation=false]
         * @returns {boolean}
         */
        isActive: function(element2, className, defaultActivation) {
          var no = "no-" + className;
          while (element2) {
            var classList = element2.classList;
            if (classList.contains(className)) {
              return true;
            }
            if (classList.contains(no)) {
              return false;
            }
            element2 = element2.parentElement;
          }
          return !!defaultActivation;
        }
      },
      /**
       * This namespace contains all currently loaded languages and the some helper functions to create and modify languages.
       *
       * @namespace
       * @memberof Prism
       * @public
       */
      languages: {
        /**
         * The grammar for plain, unformatted text.
         */
        plain: plainTextGrammar,
        plaintext: plainTextGrammar,
        text: plainTextGrammar,
        txt: plainTextGrammar,
        /**
         * Creates a deep copy of the language with the given id and appends the given tokens.
         *
         * If a token in `redef` also appears in the copied language, then the existing token in the copied language
         * will be overwritten at its original position.
         *
         * ## Best practices
         *
         * Since the position of overwriting tokens (token in `redef` that overwrite tokens in the copied language)
         * doesn't matter, they can technically be in any order. However, this can be confusing to others that trying to
         * understand the language definition because, normally, the order of tokens matters in Prism grammars.
         *
         * Therefore, it is encouraged to order overwriting tokens according to the positions of the overwritten tokens.
         * Furthermore, all non-overwriting tokens should be placed after the overwriting ones.
         *
         * @param {string} id The id of the language to extend. This has to be a key in `Prism.languages`.
         * @param {Grammar} redef The new tokens to append.
         * @returns {Grammar} The new language created.
         * @public
         * @example
         * Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
         *     // Prism.languages.css already has a 'comment' token, so this token will overwrite CSS' 'comment' token
         *     // at its original position
         *     'comment': { ... },
         *     // CSS doesn't have a 'color' token, so this token will be appended
         *     'color': /\b(?:red|green|blue)\b/
         * });
         */
        extend: function(id, redef) {
          var lang2 = _.util.clone(_.languages[id]);
          for (var key in redef) {
            lang2[key] = redef[key];
          }
          return lang2;
        },
        /**
         * Inserts tokens _before_ another token in a language definition or any other grammar.
         *
         * ## Usage
         *
         * This helper method makes it easy to modify existing languages. For example, the CSS language definition
         * not only defines CSS highlighting for CSS documents, but also needs to define highlighting for CSS embedded
         * in HTML through `<style>` elements. To do this, it needs to modify `Prism.languages.markup` and add the
         * appropriate tokens. However, `Prism.languages.markup` is a regular JavaScript object literal, so if you do
         * this:
         *
         * ```js
         * Prism.languages.markup.style = {
         *     // token
         * };
         * ```
         *
         * then the `style` token will be added (and processed) at the end. `insertBefore` allows you to insert tokens
         * before existing tokens. For the CSS example above, you would use it like this:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'cdata', {
         *     'style': {
         *         // token
         *     }
         * });
         * ```
         *
         * ## Special cases
         *
         * If the grammars of `inside` and `insert` have tokens with the same name, the tokens in `inside`'s grammar
         * will be ignored.
         *
         * This behavior can be used to insert tokens after `before`:
         *
         * ```js
         * Prism.languages.insertBefore('markup', 'comment', {
         *     'comment': Prism.languages.markup.comment,
         *     // tokens after 'comment'
         * });
         * ```
         *
         * ## Limitations
         *
         * The main problem `insertBefore` has to solve is iteration order. Since ES2015, the iteration order for object
         * properties is guaranteed to be the insertion order (except for integer keys) but some browsers behave
         * differently when keys are deleted and re-inserted. So `insertBefore` can't be implemented by temporarily
         * deleting properties which is necessary to insert at arbitrary positions.
         *
         * To solve this problem, `insertBefore` doesn't actually insert the given tokens into the target object.
         * Instead, it will create a new object and replace all references to the target object with the new one. This
         * can be done without temporarily deleting properties, so the iteration order is well-defined.
         *
         * However, only references that can be reached from `Prism.languages` or `insert` will be replaced. I.e. if
         * you hold the target object in a variable, then the value of the variable will not change.
         *
         * ```js
         * var oldMarkup = Prism.languages.markup;
         * var newMarkup = Prism.languages.insertBefore('markup', 'comment', { ... });
         *
         * assert(oldMarkup !== Prism.languages.markup);
         * assert(newMarkup === Prism.languages.markup);
         * ```
         *
         * @param {string} inside The property of `root` (e.g. a language id in `Prism.languages`) that contains the
         * object to be modified.
         * @param {string} before The key to insert before.
         * @param {Grammar} insert An object containing the key-value pairs to be inserted.
         * @param {Object<string, any>} [root] The object containing `inside`, i.e. the object that contains the
         * object to be modified.
         *
         * Defaults to `Prism.languages`.
         * @returns {Grammar} The new grammar object.
         * @public
         */
        insertBefore: function(inside, before, insert2, root) {
          root = root || /** @type {any} */
          _.languages;
          var grammar = root[inside];
          var ret = {};
          for (var token in grammar) {
            if (grammar.hasOwnProperty(token)) {
              if (token == before) {
                for (var newToken in insert2) {
                  if (insert2.hasOwnProperty(newToken)) {
                    ret[newToken] = insert2[newToken];
                  }
                }
              }
              if (!insert2.hasOwnProperty(token)) {
                ret[token] = grammar[token];
              }
            }
          }
          var old = root[inside];
          root[inside] = ret;
          _.languages.DFS(_.languages, function(key, value) {
            if (value === old && key != inside) {
              this[key] = ret;
            }
          });
          return ret;
        },
        // Traverse a language definition with Depth First Search
        DFS: function DFS(o, callback, type, visited) {
          visited = visited || {};
          var objId = _.util.objId;
          for (var i in o) {
            if (o.hasOwnProperty(i)) {
              callback.call(o, i, o[i], type || i);
              var property = o[i];
              var propertyType = _.util.type(property);
              if (propertyType === "Object" && !visited[objId(property)]) {
                visited[objId(property)] = true;
                DFS(property, callback, null, visited);
              } else if (propertyType === "Array" && !visited[objId(property)]) {
                visited[objId(property)] = true;
                DFS(property, callback, i, visited);
              }
            }
          }
        }
      },
      plugins: {},
      /**
       * This is the most high-level function in Prism’s API.
       * It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
       * each one of them.
       *
       * This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
       *
       * @param {boolean} [async=false] Same as in {@link Prism.highlightAllUnder}.
       * @param {HighlightCallback} [callback] Same as in {@link Prism.highlightAllUnder}.
       * @memberof Prism
       * @public
       */
      highlightAll: function(async, callback) {
        _.highlightAllUnder(document, async, callback);
      },
      /**
       * Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
       * {@link Prism.highlightElement} on each one of them.
       *
       * The following hooks will be run:
       * 1. `before-highlightall`
       * 2. `before-all-elements-highlight`
       * 3. All hooks of {@link Prism.highlightElement} for each element.
       *
       * @param {ParentNode} container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
       * @param {boolean} [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
       * @param {HighlightCallback} [callback] An optional callback to be invoked on each element after its highlighting is done.
       * @memberof Prism
       * @public
       */
      highlightAllUnder: function(container, async, callback) {
        var env = {
          callback,
          container,
          selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'
        };
        _.hooks.run("before-highlightall", env);
        env.elements = Array.prototype.slice.apply(env.container.querySelectorAll(env.selector));
        _.hooks.run("before-all-elements-highlight", env);
        for (var i = 0, element2; element2 = env.elements[i++]; ) {
          _.highlightElement(element2, async === true, env.callback);
        }
      },
      /**
       * Highlights the code inside a single element.
       *
       * The following hooks will be run:
       * 1. `before-sanity-check`
       * 2. `before-highlight`
       * 3. All hooks of {@link Prism.highlight}. These hooks will be run by an asynchronous worker if `async` is `true`.
       * 4. `before-insert`
       * 5. `after-highlight`
       * 6. `complete`
       *
       * Some the above hooks will be skipped if the element doesn't contain any text or there is no grammar loaded for
       * the element's language.
       *
       * @param {Element} element The element containing the code.
       * It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
       * @param {boolean} [async=false] Whether the element is to be highlighted asynchronously using Web Workers
       * to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
       * [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
       *
       * Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
       * asynchronous highlighting to work. You can build your own bundle on the
       * [Download page](https://prismjs.com/download.html).
       * @param {HighlightCallback} [callback] An optional callback to be invoked after the highlighting is done.
       * Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
       * @memberof Prism
       * @public
       */
      highlightElement: function(element2, async, callback) {
        var language = _.util.getLanguage(element2);
        var grammar = _.languages[language];
        _.util.setLanguage(element2, language);
        var parent = element2.parentElement;
        if (parent && parent.nodeName.toLowerCase() === "pre") {
          _.util.setLanguage(parent, language);
        }
        var code = element2.textContent;
        var env = {
          element: element2,
          language,
          grammar,
          code
        };
        function insertHighlightedCode(highlightedCode) {
          env.highlightedCode = highlightedCode;
          _.hooks.run("before-insert", env);
          env.element.innerHTML = env.highlightedCode;
          _.hooks.run("after-highlight", env);
          _.hooks.run("complete", env);
          callback && callback.call(env.element);
        }
        _.hooks.run("before-sanity-check", env);
        parent = env.element.parentElement;
        if (parent && parent.nodeName.toLowerCase() === "pre" && !parent.hasAttribute("tabindex")) {
          parent.setAttribute("tabindex", "0");
        }
        if (!env.code) {
          _.hooks.run("complete", env);
          callback && callback.call(env.element);
          return;
        }
        _.hooks.run("before-highlight", env);
        if (!env.grammar) {
          insertHighlightedCode(_.util.encode(env.code));
          return;
        }
        if (async && _self2.Worker) {
          var worker = new Worker(_.filename);
          worker.onmessage = function(evt) {
            insertHighlightedCode(evt.data);
          };
          worker.postMessage(JSON.stringify({
            language: env.language,
            code: env.code,
            immediateClose: true
          }));
        } else {
          insertHighlightedCode(_.highlight(env.code, env.grammar, env.language));
        }
      },
      /**
       * Low-level function, only use if you know what you’re doing. It accepts a string of text as input
       * and the language definitions to use, and returns a string with the HTML produced.
       *
       * The following hooks will be run:
       * 1. `before-tokenize`
       * 2. `after-tokenize`
       * 3. `wrap`: On each {@link Token}.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @param {string} language The name of the language definition passed to `grammar`.
       * @returns {string} The highlighted HTML.
       * @memberof Prism
       * @public
       * @example
       * Prism.highlight('var foo = true;', Prism.languages.javascript, 'javascript');
       */
      highlight: function(text2, grammar, language) {
        var env = {
          code: text2,
          grammar,
          language
        };
        _.hooks.run("before-tokenize", env);
        if (!env.grammar) {
          throw new Error('The language "' + env.language + '" has no grammar.');
        }
        env.tokens = _.tokenize(env.code, env.grammar);
        _.hooks.run("after-tokenize", env);
        return Token.stringify(_.util.encode(env.tokens), env.language);
      },
      /**
       * This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
       * and the language definitions to use, and returns an array with the tokenized code.
       *
       * When the language definition includes nested tokens, the function is called recursively on each of these tokens.
       *
       * This method could be useful in other contexts as well, as a very crude parser.
       *
       * @param {string} text A string with the code to be highlighted.
       * @param {Grammar} grammar An object containing the tokens to use.
       *
       * Usually a language definition like `Prism.languages.markup`.
       * @returns {TokenStream} An array of strings and tokens, a token stream.
       * @memberof Prism
       * @public
       * @example
       * let code = `var foo = 0;`;
       * let tokens = Prism.tokenize(code, Prism.languages.javascript);
       * tokens.forEach(token => {
       *     if (token instanceof Prism.Token && token.type === 'number') {
       *         console.log(`Found numeric literal: ${token.content}`);
       *     }
       * });
       */
      tokenize: function(text2, grammar) {
        var rest = grammar.rest;
        if (rest) {
          for (var token in rest) {
            grammar[token] = rest[token];
          }
          delete grammar.rest;
        }
        var tokenList = new LinkedList();
        addAfter(tokenList, tokenList.head, text2);
        matchGrammar(text2, tokenList, grammar, tokenList.head, 0);
        return toArray(tokenList);
      },
      /**
       * @namespace
       * @memberof Prism
       * @public
       */
      hooks: {
        all: {},
        /**
         * Adds the given callback to the list of callbacks for the given hook.
         *
         * The callback will be invoked when the hook it is registered for is run.
         * Hooks are usually directly run by a highlight function but you can also run hooks yourself.
         *
         * One callback function can be registered to multiple hooks and the same hook multiple times.
         *
         * @param {string} name The name of the hook.
         * @param {HookCallback} callback The callback function which is given environment variables.
         * @public
         */
        add: function(name, callback) {
          var hooks = _.hooks.all;
          hooks[name] = hooks[name] || [];
          hooks[name].push(callback);
        },
        /**
         * Runs a hook invoking all registered callbacks with the given environment variables.
         *
         * Callbacks will be invoked synchronously and in the order in which they were registered.
         *
         * @param {string} name The name of the hook.
         * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
         * @public
         */
        run: function(name, env) {
          var callbacks = _.hooks.all[name];
          if (!callbacks || !callbacks.length) {
            return;
          }
          for (var i = 0, callback; callback = callbacks[i++]; ) {
            callback(env);
          }
        }
      },
      Token
    };
    _self2.Prism = _;
    function Token(type, content, alias, matchedStr) {
      this.type = type;
      this.content = content;
      this.alias = alias;
      this.length = (matchedStr || "").length | 0;
    }
    Token.stringify = function stringify(o, language) {
      if (typeof o == "string") {
        return o;
      }
      if (Array.isArray(o)) {
        var s = "";
        o.forEach(function(e) {
          s += stringify(e, language);
        });
        return s;
      }
      var env = {
        type: o.type,
        content: stringify(o.content, language),
        tag: "span",
        classes: ["token", o.type],
        attributes: {},
        language
      };
      var aliases = o.alias;
      if (aliases) {
        if (Array.isArray(aliases)) {
          Array.prototype.push.apply(env.classes, aliases);
        } else {
          env.classes.push(aliases);
        }
      }
      _.hooks.run("wrap", env);
      var attributes = "";
      for (var name in env.attributes) {
        attributes += " " + name + '="' + (env.attributes[name] || "").replace(/"/g, "&quot;") + '"';
      }
      return "<" + env.tag + ' class="' + env.classes.join(" ") + '"' + attributes + ">" + env.content + "</" + env.tag + ">";
    };
    function matchPattern(pattern, pos, text2, lookbehind) {
      pattern.lastIndex = pos;
      var match = pattern.exec(text2);
      if (match && lookbehind && match[1]) {
        var lookbehindLength = match[1].length;
        match.index += lookbehindLength;
        match[0] = match[0].slice(lookbehindLength);
      }
      return match;
    }
    function matchGrammar(text2, tokenList, grammar, startNode, startPos, rematch) {
      for (var token in grammar) {
        if (!grammar.hasOwnProperty(token) || !grammar[token]) {
          continue;
        }
        var patterns = grammar[token];
        patterns = Array.isArray(patterns) ? patterns : [patterns];
        for (var j = 0; j < patterns.length; ++j) {
          if (rematch && rematch.cause == token + "," + j) {
            return;
          }
          var patternObj = patterns[j];
          var inside = patternObj.inside;
          var lookbehind = !!patternObj.lookbehind;
          var greedy = !!patternObj.greedy;
          var alias = patternObj.alias;
          if (greedy && !patternObj.pattern.global) {
            var flags = patternObj.pattern.toString().match(/[imsuy]*$/)[0];
            patternObj.pattern = RegExp(patternObj.pattern.source, flags + "g");
          }
          var pattern = patternObj.pattern || patternObj;
          for (var currentNode = startNode.next, pos = startPos; currentNode !== tokenList.tail; pos += currentNode.value.length, currentNode = currentNode.next) {
            if (rematch && pos >= rematch.reach) {
              break;
            }
            var str = currentNode.value;
            if (tokenList.length > text2.length) {
              return;
            }
            if (str instanceof Token) {
              continue;
            }
            var removeCount = 1;
            var match;
            if (greedy) {
              match = matchPattern(pattern, pos, text2, lookbehind);
              if (!match || match.index >= text2.length) {
                break;
              }
              var from = match.index;
              var to = match.index + match[0].length;
              var p = pos;
              p += currentNode.value.length;
              while (from >= p) {
                currentNode = currentNode.next;
                p += currentNode.value.length;
              }
              p -= currentNode.value.length;
              pos = p;
              if (currentNode.value instanceof Token) {
                continue;
              }
              for (var k = currentNode; k !== tokenList.tail && (p < to || typeof k.value === "string"); k = k.next) {
                removeCount++;
                p += k.value.length;
              }
              removeCount--;
              str = text2.slice(pos, p);
              match.index -= pos;
            } else {
              match = matchPattern(pattern, 0, str, lookbehind);
              if (!match) {
                continue;
              }
            }
            var from = match.index;
            var matchStr = match[0];
            var before = str.slice(0, from);
            var after = str.slice(from + matchStr.length);
            var reach = pos + str.length;
            if (rematch && reach > rematch.reach) {
              rematch.reach = reach;
            }
            var removeFrom = currentNode.prev;
            if (before) {
              removeFrom = addAfter(tokenList, removeFrom, before);
              pos += before.length;
            }
            removeRange(tokenList, removeFrom, removeCount);
            var wrapped = new Token(token, inside ? _.tokenize(matchStr, inside) : matchStr, alias, matchStr);
            currentNode = addAfter(tokenList, removeFrom, wrapped);
            if (after) {
              addAfter(tokenList, currentNode, after);
            }
            if (removeCount > 1) {
              var nestedRematch = {
                cause: token + "," + j,
                reach
              };
              matchGrammar(text2, tokenList, grammar, currentNode.prev, pos, nestedRematch);
              if (rematch && nestedRematch.reach > rematch.reach) {
                rematch.reach = nestedRematch.reach;
              }
            }
          }
        }
      }
    }
    function LinkedList() {
      var head = { value: null, prev: null, next: null };
      var tail = { value: null, prev: head, next: null };
      head.next = tail;
      this.head = head;
      this.tail = tail;
      this.length = 0;
    }
    function addAfter(list2, node, value) {
      var next = node.next;
      var newNode = { value, prev: node, next };
      node.next = newNode;
      next.prev = newNode;
      list2.length++;
      return newNode;
    }
    function removeRange(list2, node, count) {
      var next = node.next;
      for (var i = 0; i < count && next !== list2.tail; i++) {
        next = next.next;
      }
      node.next = next;
      next.prev = node;
      list2.length -= i;
    }
    function toArray(list2) {
      var array = [];
      var node = list2.head.next;
      while (node !== list2.tail) {
        array.push(node.value);
        node = node.next;
      }
      return array;
    }
    if (!_self2.document) {
      if (!_self2.addEventListener) {
        return _;
      }
      if (!_.disableWorkerMessageHandler) {
        _self2.addEventListener("message", function(evt) {
          var message = JSON.parse(evt.data);
          var lang2 = message.language;
          var code = message.code;
          var immediateClose = message.immediateClose;
          _self2.postMessage(_.highlight(code, _.languages[lang2], lang2));
          if (immediateClose) {
            _self2.close();
          }
        }, false);
      }
      return _;
    }
    var script = _.util.currentScript();
    if (script) {
      _.filename = script.src;
      if (script.hasAttribute("data-manual")) {
        _.manual = true;
      }
    }
    function highlightAutomaticallyCallback() {
      if (!_.manual) {
        _.highlightAll();
      }
    }
    if (!_.manual) {
      var readyState = document.readyState;
      if (readyState === "loading" || readyState === "interactive" && script && script.defer) {
        document.addEventListener("DOMContentLoaded", highlightAutomaticallyCallback);
      } else {
        if (window.requestAnimationFrame) {
          window.requestAnimationFrame(highlightAutomaticallyCallback);
        } else {
          window.setTimeout(highlightAutomaticallyCallback, 16);
        }
      }
    }
    return _;
  }(_self);
  if (module.exports) {
    module.exports = Prism2;
  }
  if (typeof commonjsGlobal !== "undefined") {
    commonjsGlobal.Prism = Prism2;
  }
  Prism2.languages.markup = {
    "comment": {
      pattern: /<!--(?:(?!<!--)[\s\S])*?-->/,
      greedy: true
    },
    "prolog": {
      pattern: /<\?[\s\S]+?\?>/,
      greedy: true
    },
    "doctype": {
      // https://www.w3.org/TR/xml/#NT-doctypedecl
      pattern: /<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
      greedy: true,
      inside: {
        "internal-subset": {
          pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
          lookbehind: true,
          greedy: true,
          inside: null
          // see below
        },
        "string": {
          pattern: /"[^"]*"|'[^']*'/,
          greedy: true
        },
        "punctuation": /^<!|>$|[[\]]/,
        "doctype-tag": /^DOCTYPE/i,
        "name": /[^\s<>'"]+/
      }
    },
    "cdata": {
      pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
      greedy: true
    },
    "tag": {
      pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
      greedy: true,
      inside: {
        "tag": {
          pattern: /^<\/?[^\s>\/]+/,
          inside: {
            "punctuation": /^<\/?/,
            "namespace": /^[^\s>\/:]+:/
          }
        },
        "special-attr": [],
        "attr-value": {
          pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
          inside: {
            "punctuation": [
              {
                pattern: /^=/,
                alias: "attr-equals"
              },
              {
                pattern: /^(\s*)["']|["']$/,
                lookbehind: true
              }
            ]
          }
        },
        "punctuation": /\/?>/,
        "attr-name": {
          pattern: /[^\s>\/]+/,
          inside: {
            "namespace": /^[^\s>\/:]+:/
          }
        }
      }
    },
    "entity": [
      {
        pattern: /&[\da-z]{1,8};/i,
        alias: "named-entity"
      },
      /&#x?[\da-f]{1,8};/i
    ]
  };
  Prism2.languages.markup["tag"].inside["attr-value"].inside["entity"] = Prism2.languages.markup["entity"];
  Prism2.languages.markup["doctype"].inside["internal-subset"].inside = Prism2.languages.markup;
  Prism2.hooks.add("wrap", function(env) {
    if (env.type === "entity") {
      env.attributes["title"] = env.content.replace(/&amp;/, "&");
    }
  });
  Object.defineProperty(Prism2.languages.markup.tag, "addInlined", {
    /**
     * Adds an inlined language to markup.
     *
     * An example of an inlined language is CSS with `<style>` tags.
     *
     * @param {string} tagName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addInlined('style', 'css');
     */
    value: function addInlined(tagName, lang) {
      var includedCdataInside = {};
      includedCdataInside["language-" + lang] = {
        pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
        lookbehind: true,
        inside: Prism2.languages[lang]
      };
      includedCdataInside["cdata"] = /^<!\[CDATA\[|\]\]>$/i;
      var inside = {
        "included-cdata": {
          pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i,
          inside: includedCdataInside
        }
      };
      inside["language-" + lang] = {
        pattern: /[\s\S]+/,
        inside: Prism2.languages[lang]
      };
      var def2 = {};
      def2[tagName] = {
        pattern: RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g, function() {
          return tagName;
        }), "i"),
        lookbehind: true,
        greedy: true,
        inside
      };
      Prism2.languages.insertBefore("markup", "cdata", def2);
    }
  });
  Object.defineProperty(Prism2.languages.markup.tag, "addAttribute", {
    /**
     * Adds an pattern to highlight languages embedded in HTML attributes.
     *
     * An example of an inlined language is CSS with `style` attributes.
     *
     * @param {string} attrName The name of the tag that contains the inlined language. This name will be treated as
     * case insensitive.
     * @param {string} lang The language key.
     * @example
     * addAttribute('style', 'css');
     */
    value: function(attrName, lang) {
      Prism2.languages.markup.tag.inside["special-attr"].push({
        pattern: RegExp(
          /(^|["'\s])/.source + "(?:" + attrName + ")" + /\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,
          "i"
        ),
        lookbehind: true,
        inside: {
          "attr-name": /^[^\s=]+/,
          "attr-value": {
            pattern: /=[\s\S]+/,
            inside: {
              "value": {
                pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
                lookbehind: true,
                alias: [lang, "language-" + lang],
                inside: Prism2.languages[lang]
              },
              "punctuation": [
                {
                  pattern: /^=/,
                  alias: "attr-equals"
                },
                /"|'/
              ]
            }
          }
        }
      });
    }
  });
  Prism2.languages.html = Prism2.languages.markup;
  Prism2.languages.mathml = Prism2.languages.markup;
  Prism2.languages.svg = Prism2.languages.markup;
  Prism2.languages.xml = Prism2.languages.extend("markup", {});
  Prism2.languages.ssml = Prism2.languages.xml;
  Prism2.languages.atom = Prism2.languages.xml;
  Prism2.languages.rss = Prism2.languages.xml;
  (function(Prism3) {
    var string = /(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
    Prism3.languages.css = {
      "comment": /\/\*[\s\S]*?\*\//,
      "atrule": {
        pattern: RegExp("@[\\w-](?:" + /[^;{\s"']|\s+(?!\s)/.source + "|" + string.source + ")*?" + /(?:;|(?=\s*\{))/.source),
        inside: {
          "rule": /^@[\w-]+/,
          "selector-function-argument": {
            pattern: /(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
            lookbehind: true,
            alias: "selector"
          },
          "keyword": {
            pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
            lookbehind: true
          }
          // See rest below
        }
      },
      "url": {
        // https://drafts.csswg.org/css-values-3/#urls
        pattern: RegExp("\\burl\\((?:" + string.source + "|" + /(?:[^\\\r\n()"']|\\[\s\S])*/.source + ")\\)", "i"),
        greedy: true,
        inside: {
          "function": /^url/i,
          "punctuation": /^\(|\)$/,
          "string": {
            pattern: RegExp("^" + string.source + "$"),
            alias: "url"
          }
        }
      },
      "selector": {
        pattern: RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|` + string.source + ")*(?=\\s*\\{)"),
        lookbehind: true
      },
      "string": {
        pattern: string,
        greedy: true
      },
      "property": {
        pattern: /(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
        lookbehind: true
      },
      "important": /!important\b/i,
      "function": {
        pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,
        lookbehind: true
      },
      "punctuation": /[(){};:,]/
    };
    Prism3.languages.css["atrule"].inside.rest = Prism3.languages.css;
    var markup = Prism3.languages.markup;
    if (markup) {
      markup.tag.addInlined("style", "css");
      markup.tag.addAttribute("style", "css");
    }
  })(Prism2);
  Prism2.languages.clike = {
    "comment": [
      {
        pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,
        lookbehind: true,
        greedy: true
      },
      {
        pattern: /(^|[^\\:])\/\/.*/,
        lookbehind: true,
        greedy: true
      }
    ],
    "string": {
      pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
      greedy: true
    },
    "class-name": {
      pattern: /(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
      lookbehind: true,
      inside: {
        "punctuation": /[.\\]/
      }
    },
    "keyword": /\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
    "boolean": /\b(?:false|true)\b/,
    "function": /\b\w+(?=\()/,
    "number": /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
    "operator": /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
    "punctuation": /[{}[\];(),.:]/
  };
  Prism2.languages.javascript = Prism2.languages.extend("clike", {
    "class-name": [
      Prism2.languages.clike["class-name"],
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
        lookbehind: true
      }
    ],
    "keyword": [
      {
        pattern: /((?:^|\})\s*)catch\b/,
        lookbehind: true
      },
      {
        pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
        lookbehind: true
      }
    ],
    // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
    "function": /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
    "number": {
      pattern: RegExp(
        /(^|[^\w$])/.source + "(?:" + // constant
        (/NaN|Infinity/.source + "|" + // binary integer
        /0[bB][01]+(?:_[01]+)*n?/.source + "|" + // octal integer
        /0[oO][0-7]+(?:_[0-7]+)*n?/.source + "|" + // hexadecimal integer
        /0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source + "|" + // decimal bigint
        /\d+(?:_\d+)*n/.source + "|" + // decimal number (integer or float) but no bigint
        /(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source) + ")" + /(?![\w$])/.source
      ),
      lookbehind: true
    },
    "operator": /--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/
  });
  Prism2.languages.javascript["class-name"][0].pattern = /(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;
  Prism2.languages.insertBefore("javascript", "keyword", {
    "regex": {
      pattern: RegExp(
        // lookbehind
        // eslint-disable-next-line regexp/no-dupe-characters-character-class
        /((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source + // Regex pattern:
        // There are 2 regex patterns here. The RegExp set notation proposal added support for nested character
        // classes if the `v` flag is present. Unfortunately, nested CCs are both context-free and incompatible
        // with the only syntax, so we have to define 2 different regex patterns.
        /\//.source + "(?:" + /(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source + "|" + // `v` flag syntax. This supports 3 levels of nested character classes.
        /(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source + ")" + // lookahead
        /(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source
      ),
      lookbehind: true,
      greedy: true,
      inside: {
        "regex-source": {
          pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
          lookbehind: true,
          alias: "language-regex",
          inside: Prism2.languages.regex
        },
        "regex-delimiter": /^\/|\/$/,
        "regex-flags": /^[a-z]+$/
      }
    },
    // This must be declared before keyword because we use "function" inside the look-forward
    "function-variable": {
      pattern: /#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
      alias: "function"
    },
    "parameter": [
      {
        pattern: /(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      },
      {
        pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
        lookbehind: true,
        inside: Prism2.languages.javascript
      }
    ],
    "constant": /\b[A-Z](?:[A-Z_]|\dx?)*\b/
  });
  Prism2.languages.insertBefore("javascript", "string", {
    "hashbang": {
      pattern: /^#!.*/,
      greedy: true,
      alias: "comment"
    },
    "template-string": {
      pattern: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
      greedy: true,
      inside: {
        "template-punctuation": {
          pattern: /^`|`$/,
          alias: "string"
        },
        "interpolation": {
          pattern: /((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
          lookbehind: true,
          inside: {
            "interpolation-punctuation": {
              pattern: /^\$\{|\}$/,
              alias: "punctuation"
            },
            rest: Prism2.languages.javascript
          }
        },
        "string": /[\s\S]+/
      }
    },
    "string-property": {
      pattern: /((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
      lookbehind: true,
      greedy: true,
      alias: "property"
    }
  });
  Prism2.languages.insertBefore("javascript", "operator", {
    "literal-property": {
      pattern: /((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
      lookbehind: true,
      alias: "property"
    }
  });
  if (Prism2.languages.markup) {
    Prism2.languages.markup.tag.addInlined("script", "javascript");
    Prism2.languages.markup.tag.addAttribute(
      /on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,
      "javascript"
    );
  }
  Prism2.languages.js = Prism2.languages.javascript;
  (function() {
    if (typeof Prism2 === "undefined" || typeof document === "undefined") {
      return;
    }
    if (!Element.prototype.matches) {
      Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
    }
    var LOADING_MESSAGE = "Loading…";
    var FAILURE_MESSAGE = function(status, message) {
      return "✖ Error " + status + " while fetching file: " + message;
    };
    var FAILURE_EMPTY_MESSAGE = "✖ Error: File does not exist or is empty";
    var EXTENSIONS = {
      "js": "javascript",
      "py": "python",
      "rb": "ruby",
      "ps1": "powershell",
      "psm1": "powershell",
      "sh": "bash",
      "bat": "batch",
      "h": "c",
      "tex": "latex"
    };
    var STATUS_ATTR = "data-src-status";
    var STATUS_LOADING = "loading";
    var STATUS_LOADED = "loaded";
    var STATUS_FAILED = "failed";
    var SELECTOR = "pre[data-src]:not([" + STATUS_ATTR + '="' + STATUS_LOADED + '"]):not([' + STATUS_ATTR + '="' + STATUS_LOADING + '"])';
    function loadFile(src, success, error) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", src, true);
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
          if (xhr.status < 400 && xhr.responseText) {
            success(xhr.responseText);
          } else {
            if (xhr.status >= 400) {
              error(FAILURE_MESSAGE(xhr.status, xhr.statusText));
            } else {
              error(FAILURE_EMPTY_MESSAGE);
            }
          }
        }
      };
      xhr.send(null);
    }
    function parseRange(range) {
      var m = /^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(range || "");
      if (m) {
        var start = Number(m[1]);
        var comma = m[2];
        var end = m[3];
        if (!comma) {
          return [start, start];
        }
        if (!end) {
          return [start, void 0];
        }
        return [start, Number(end)];
      }
      return void 0;
    }
    Prism2.hooks.add("before-highlightall", function(env) {
      env.selector += ", " + SELECTOR;
    });
    Prism2.hooks.add("before-sanity-check", function(env) {
      var pre = (
        /** @type {HTMLPreElement} */
        env.element
      );
      if (pre.matches(SELECTOR)) {
        env.code = "";
        pre.setAttribute(STATUS_ATTR, STATUS_LOADING);
        var code = pre.appendChild(document.createElement("CODE"));
        code.textContent = LOADING_MESSAGE;
        var src = pre.getAttribute("data-src");
        var language = env.language;
        if (language === "none") {
          var extension = (/\.(\w+)$/.exec(src) || [, "none"])[1];
          language = EXTENSIONS[extension] || extension;
        }
        Prism2.util.setLanguage(code, language);
        Prism2.util.setLanguage(pre, language);
        var autoloader = Prism2.plugins.autoloader;
        if (autoloader) {
          autoloader.loadLanguages(language);
        }
        loadFile(
          src,
          function(text2) {
            pre.setAttribute(STATUS_ATTR, STATUS_LOADED);
            var range = parseRange(pre.getAttribute("data-range"));
            if (range) {
              var lines = text2.split(/\r\n?|\n/g);
              var start = range[0];
              var end = range[1] == null ? lines.length : range[1];
              if (start < 0) {
                start += lines.length;
              }
              start = Math.max(0, Math.min(start - 1, lines.length));
              if (end < 0) {
                end += lines.length;
              }
              end = Math.max(0, Math.min(end, lines.length));
              text2 = lines.slice(start, end).join("\n");
              if (!pre.hasAttribute("data-start")) {
                pre.setAttribute("data-start", String(start + 1));
              }
            }
            code.textContent = text2;
            Prism2.highlightElement(code);
          },
          function(error) {
            pre.setAttribute(STATUS_ATTR, STATUS_FAILED);
            code.textContent = error;
          }
        );
      }
    });
    Prism2.plugins.fileHighlight = {
      /**
       * Executes the File Highlight plugin for all matching `pre` elements under the given container.
       *
       * Note: Elements which are already loaded or currently loading will not be touched by this method.
       *
       * @param {ParentNode} [container=document]
       */
      highlight: function highlight(container) {
        var elements = (container || document).querySelectorAll(SELECTOR);
        for (var i = 0, element2; element2 = elements[i++]; ) {
          Prism2.highlightElement(element2);
        }
      }
    };
    var logged = false;
    Prism2.fileHighlight = function() {
      if (!logged) {
        console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead.");
        logged = true;
      }
      Prism2.plugins.fileHighlight.highlight.apply(this, arguments);
    };
  })();
})(prism);
var prismExports = prism.exports;
Prism.languages.python = {
  "comment": {
    pattern: /(^|[^\\])#.*/,
    lookbehind: true,
    greedy: true
  },
  "string-interpolation": {
    pattern: /(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,
    greedy: true,
    inside: {
      "interpolation": {
        // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" format specifier> "}"
        pattern: /((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,
        lookbehind: true,
        inside: {
          "format-spec": {
            pattern: /(:)[^:(){}]+(?=\}$)/,
            lookbehind: true
          },
          "conversion-option": {
            pattern: /![sra](?=[:}]$)/,
            alias: "punctuation"
          },
          rest: null
        }
      },
      "string": /[\s\S]+/
    }
  },
  "triple-quoted-string": {
    pattern: /(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,
    greedy: true,
    alias: "string"
  },
  "string": {
    pattern: /(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
    greedy: true
  },
  "function": {
    pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,
    lookbehind: true
  },
  "class-name": {
    pattern: /(\bclass\s+)\w+/i,
    lookbehind: true
  },
  "decorator": {
    pattern: /(^[\t ]*)@\w+(?:\.\w+)*/m,
    lookbehind: true,
    alias: ["annotation", "punctuation"],
    inside: {
      "punctuation": /\./
    }
  },
  "keyword": /\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,
  "builtin": /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,
  "boolean": /\b(?:False|None|True)\b/,
  "number": /\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,
  "operator": /[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,
  "punctuation": /[{}[\];(),.:]/
};
Prism.languages.python["string-interpolation"].inside["interpolation"].inside.rest = Prism.languages.python;
Prism.languages.py = Prism.languages.python;
(function(Prism2) {
  var funcPattern = /\\(?:[^a-z()[\]]|[a-z*]+)/i;
  var insideEqu = {
    "equation-command": {
      pattern: funcPattern,
      alias: "regex"
    }
  };
  Prism2.languages.latex = {
    "comment": /%.*/,
    // the verbatim environment prints whitespace to the document
    "cdata": {
      pattern: /(\\begin\{((?:lstlisting|verbatim)\*?)\})[\s\S]*?(?=\\end\{\2\})/,
      lookbehind: true
    },
    /*
     * equations can be between $$ $$ or $ $ or \( \) or \[ \]
     * (all are multiline)
     */
    "equation": [
      {
        pattern: /\$\$(?:\\[\s\S]|[^\\$])+\$\$|\$(?:\\[\s\S]|[^\\$])+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]/,
        inside: insideEqu,
        alias: "string"
      },
      {
        pattern: /(\\begin\{((?:align|eqnarray|equation|gather|math|multline)\*?)\})[\s\S]*?(?=\\end\{\2\})/,
        lookbehind: true,
        inside: insideEqu,
        alias: "string"
      }
    ],
    /*
     * arguments which are keywords or references are highlighted
     * as keywords
     */
    "keyword": {
      pattern: /(\\(?:begin|cite|documentclass|end|label|ref|usepackage)(?:\[[^\]]+\])?\{)[^}]+(?=\})/,
      lookbehind: true
    },
    "url": {
      pattern: /(\\url\{)[^}]+(?=\})/,
      lookbehind: true
    },
    /*
     * section or chapter headlines are highlighted as bold so that
     * they stand out more
     */
    "headline": {
      pattern: /(\\(?:chapter|frametitle|paragraph|part|section|subparagraph|subsection|subsubparagraph|subsubsection|subsubsubparagraph)\*?(?:\[[^\]]+\])?\{)[^}]+(?=\})/,
      lookbehind: true,
      alias: "class-name"
    },
    "function": {
      pattern: funcPattern,
      alias: "selector"
    },
    "punctuation": /[[\]{}&]/
  };
  Prism2.languages.tex = Prism2.languages.latex;
  Prism2.languages.context = Prism2.languages.latex;
})(Prism);
(function(Prism2) {
  var envVars = "\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b";
  var commandAfterHeredoc = {
    pattern: /(^(["']?)\w+\2)[ \t]+\S.*/,
    lookbehind: true,
    alias: "punctuation",
    // this looks reasonably well in all themes
    inside: null
    // see below
  };
  var insideString = {
    "bash": commandAfterHeredoc,
    "environment": {
      pattern: RegExp("\\$" + envVars),
      alias: "constant"
    },
    "variable": [
      // [0]: Arithmetic Environment
      {
        pattern: /\$?\(\([\s\S]+?\)\)/,
        greedy: true,
        inside: {
          // If there is a $ sign at the beginning highlight $(( and )) as variable
          "variable": [
            {
              pattern: /(^\$\(\([\s\S]+)\)\)/,
              lookbehind: true
            },
            /^\$\(\(/
          ],
          "number": /\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,
          // Operators according to https://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic
          "operator": /--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,
          // If there is no $ sign at the beginning highlight (( and )) as punctuation
          "punctuation": /\(\(?|\)\)?|,|;/
        }
      },
      // [1]: Command Substitution
      {
        pattern: /\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,
        greedy: true,
        inside: {
          "variable": /^\$\(|^`|\)$|`$/
        }
      },
      // [2]: Brace expansion
      {
        pattern: /\$\{[^}]+\}/,
        greedy: true,
        inside: {
          "operator": /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
          "punctuation": /[\[\]]/,
          "environment": {
            pattern: RegExp("(\\{)" + envVars),
            lookbehind: true,
            alias: "constant"
          }
        }
      },
      /\$(?:\w+|[#?*!@$])/
    ],
    // Escape sequences from echo and printf's manuals, and escaped quotes.
    "entity": /\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/
  };
  Prism2.languages.bash = {
    "shebang": {
      pattern: /^#!\s*\/.*/,
      alias: "important"
    },
    "comment": {
      pattern: /(^|[^"{\\$])#.*/,
      lookbehind: true
    },
    "function-name": [
      // a) function foo {
      // b) foo() {
      // c) function foo() {
      // but not “foo {”
      {
        // a) and c)
        pattern: /(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,
        lookbehind: true,
        alias: "function"
      },
      {
        // b)
        pattern: /\b[\w-]+(?=\s*\(\s*\)\s*\{)/,
        alias: "function"
      }
    ],
    // Highlight variable names as variables in for and select beginnings.
    "for-or-select": {
      pattern: /(\b(?:for|select)\s+)\w+(?=\s+in\s)/,
      alias: "variable",
      lookbehind: true
    },
    // Highlight variable names as variables in the left-hand part
    // of assignments (“=” and “+=”).
    "assign-left": {
      pattern: /(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,
      inside: {
        "environment": {
          pattern: RegExp("(^|[\\s;|&]|[<>]\\()" + envVars),
          lookbehind: true,
          alias: "constant"
        }
      },
      alias: "variable",
      lookbehind: true
    },
    // Highlight parameter names as variables
    "parameter": {
      pattern: /(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,
      alias: "variable",
      lookbehind: true
    },
    "string": [
      // Support for Here-documents https://en.wikipedia.org/wiki/Here_document
      {
        pattern: /((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,
        lookbehind: true,
        greedy: true,
        inside: insideString
      },
      // Here-document with quotes around the tag
      // → No expansion (so no “inside”).
      {
        pattern: /((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,
        lookbehind: true,
        greedy: true,
        inside: {
          "bash": commandAfterHeredoc
        }
      },
      // “Normal” string
      {
        // https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
        pattern: /(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,
        lookbehind: true,
        greedy: true,
        inside: insideString
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html
        pattern: /(^|[^$\\])'[^']*'/,
        lookbehind: true,
        greedy: true
      },
      {
        // https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
        pattern: /\$'(?:[^'\\]|\\[\s\S])*'/,
        greedy: true,
        inside: {
          "entity": insideString.entity
        }
      }
    ],
    "environment": {
      pattern: RegExp("\\$?" + envVars),
      alias: "constant"
    },
    "variable": insideString.variable,
    "function": {
      pattern: /(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    "keyword": {
      pattern: /(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    // https://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
    "builtin": {
      pattern: /(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,
      lookbehind: true,
      // Alias added to make those easier to distinguish from strings.
      alias: "class-name"
    },
    "boolean": {
      pattern: /(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,
      lookbehind: true
    },
    "file-descriptor": {
      pattern: /\B&\d\b/,
      alias: "important"
    },
    "operator": {
      // Lots of redirections here, but not just that.
      pattern: /\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,
      inside: {
        "file-descriptor": {
          pattern: /^\d/,
          alias: "important"
        }
      }
    },
    "punctuation": /\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,
    "number": {
      pattern: /(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,
      lookbehind: true
    }
  };
  commandAfterHeredoc.inside = Prism2.languages.bash;
  var toBeCopied = [
    "comment",
    "function-name",
    "for-or-select",
    "assign-left",
    "parameter",
    "string",
    "environment",
    "function",
    "keyword",
    "builtin",
    "boolean",
    "file-descriptor",
    "operator",
    "punctuation",
    "number"
  ];
  var inside = insideString.variable[1].inside;
  for (var i = 0; i < toBeCopied.length; i++) {
    inside[toBeCopied[i]] = Prism2.languages.bash[toBeCopied[i]];
  }
  Prism2.languages.sh = Prism2.languages.bash;
  Prism2.languages.shell = Prism2.languages.bash;
})(Prism);
Prism.languages.c = Prism.languages.extend("clike", {
  "comment": {
    pattern: /\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,
    greedy: true
  },
  "string": {
    // https://en.cppreference.com/w/c/language/string_literal
    pattern: /"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,
    greedy: true
  },
  "class-name": {
    pattern: /(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,
    lookbehind: true
  },
  "keyword": /\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,
  "function": /\b[a-z_]\w*(?=\s*\()/i,
  "number": /(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,
  "operator": />>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/
});
Prism.languages.insertBefore("c", "string", {
  "char": {
    // https://en.cppreference.com/w/c/language/character_constant
    pattern: /'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,
    greedy: true
  }
});
Prism.languages.insertBefore("c", "string", {
  "macro": {
    // allow for multiline macro definitions
    // spaces after the # character compile fine with gcc
    pattern: /(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,
    lookbehind: true,
    greedy: true,
    alias: "property",
    inside: {
      "string": [
        {
          // highlight the path of the include statement as a string
          pattern: /^(#\s*include\s*)<[^>]+>/,
          lookbehind: true
        },
        Prism.languages.c["string"]
      ],
      "char": Prism.languages.c["char"],
      "comment": Prism.languages.c["comment"],
      "macro-name": [
        {
          pattern: /(^#\s*define\s+)\w+\b(?!\()/i,
          lookbehind: true
        },
        {
          pattern: /(^#\s*define\s+)\w+\b(?=\()/i,
          lookbehind: true,
          alias: "function"
        }
      ],
      // highlight macro directives as keywords
      "directive": {
        pattern: /^(#\s*)[a-z]+/,
        lookbehind: true,
        alias: "keyword"
      },
      "directive-hash": /^#/,
      "punctuation": /##|\\(?=[\r\n])/,
      "expression": {
        pattern: /\S[\s\S]*/,
        inside: Prism.languages.c
      }
    }
  }
});
Prism.languages.insertBefore("c", "function", {
  // highlight predefined macros as constants
  "constant": /\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/
});
delete Prism.languages.c["boolean"];
(function(Prism2) {
  var keyword = /\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/;
  var modName = /\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g, function() {
    return keyword.source;
  });
  Prism2.languages.cpp = Prism2.languages.extend("c", {
    "class-name": [
      {
        pattern: RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g, function() {
          return keyword.source;
        })),
        lookbehind: true
      },
      // This is intended to capture the class name of method implementations like:
      //   void foo::bar() const {}
      // However! The `foo` in the above example could also be a namespace, so we only capture the class name if
      // it starts with an uppercase letter. This approximation should give decent results.
      /\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,
      // This will capture the class name before destructors like:
      //   Foo::~Foo() {}
      /\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,
      // This also intends to capture the class name of method implementations but here the class has template
      // parameters, so it can't be a namespace (until C++ adds generic namespaces).
      /\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/
    ],
    "keyword": keyword,
    "number": {
      pattern: /(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,
      greedy: true
    },
    "operator": />>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,
    "boolean": /\b(?:false|true)\b/
  });
  Prism2.languages.insertBefore("cpp", "string", {
    "module": {
      // https://en.cppreference.com/w/cpp/language/modules
      pattern: RegExp(
        /(\b(?:import|module)\s+)/.source + "(?:" + // header-name
        /"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source + "|" + // module name or partition or both
        /<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g, function() {
          return modName;
        }) + ")"
      ),
      lookbehind: true,
      greedy: true,
      inside: {
        "string": /^[<"][\s\S]+/,
        "operator": /:/,
        "punctuation": /\./
      }
    },
    "raw-string": {
      pattern: /R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,
      alias: "string",
      greedy: true
    }
  });
  Prism2.languages.insertBefore("cpp", "keyword", {
    "generic-function": {
      pattern: /\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,
      inside: {
        "function": /^\w+/,
        "generic": {
          pattern: /<[\s\S]+/,
          alias: "class-name",
          inside: Prism2.languages.cpp
        }
      }
    }
  });
  Prism2.languages.insertBefore("cpp", "operator", {
    "double-colon": {
      pattern: /::/,
      alias: "punctuation"
    }
  });
  Prism2.languages.insertBefore("cpp", "class-name", {
    // the base clause is an optional list of parent classes
    // https://en.cppreference.com/w/cpp/language/class
    "base-clause": {
      pattern: /(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,
      lookbehind: true,
      greedy: true,
      inside: Prism2.languages.extend("cpp", {})
    }
  });
  Prism2.languages.insertBefore("inside", "double-colon", {
    // All untokenized words that are not namespaces should be class names
    "class-name": /\b[a-z_]\w*\b(?!\s*::)/i
  }, Prism2.languages.cpp["base-clause"]);
})(Prism);
Prism.languages.json = {
  "property": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "string": {
    pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
    lookbehind: true,
    greedy: true
  },
  "comment": {
    pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
    greedy: true
  },
  "number": /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
  "punctuation": /[{}[\],]/,
  "operator": /:/,
  "boolean": /\b(?:false|true)\b/,
  "null": {
    pattern: /\bnull\b/,
    alias: "keyword"
  }
};
Prism.languages.webmanifest = Prism.languages.json;
Prism.languages.sql = {
  "comment": {
    pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,
    lookbehind: true
  },
  "variable": [
    {
      pattern: /@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,
      greedy: true
    },
    /@[\w.$]+/
  ],
  "string": {
    pattern: /(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,
    greedy: true,
    lookbehind: true
  },
  "identifier": {
    pattern: /(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,
    greedy: true,
    lookbehind: true,
    inside: {
      "punctuation": /^`|`$/
    }
  },
  "function": /\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,
  // Should we highlight user defined functions too?
  "keyword": /\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,
  "boolean": /\b(?:FALSE|NULL|TRUE)\b/i,
  "number": /\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,
  "operator": /[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,
  "punctuation": /[;[\]()`,.]/
};
(function(Prism2) {
  var keywords = /\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/;
  var classNamePrefix = /(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source;
  var className = {
    pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),
    lookbehind: true,
    inside: {
      "namespace": {
        pattern: /^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,
        inside: {
          "punctuation": /\./
        }
      },
      "punctuation": /\./
    }
  };
  Prism2.languages.java = Prism2.languages.extend("clike", {
    "string": {
      pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,
      lookbehind: true,
      greedy: true
    },
    "class-name": [
      className,
      {
        // variables, parameters, and constructor references
        // this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
        pattern: RegExp(/(^|[^\w.])/.source + classNamePrefix + /[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),
        lookbehind: true,
        inside: className.inside
      },
      {
        // class names based on keyword
        // this to support class names (or generic parameters) which do not contain a lower case letter (also works for methods)
        pattern: RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source + classNamePrefix + /[A-Z]\w*\b/.source),
        lookbehind: true,
        inside: className.inside
      }
    ],
    "keyword": keywords,
    "function": [
      Prism2.languages.clike.function,
      {
        pattern: /(::\s*)[a-z_]\w*/,
        lookbehind: true
      }
    ],
    "number": /\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,
    "operator": {
      pattern: /(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,
      lookbehind: true
    },
    "constant": /\b[A-Z][A-Z_\d]+\b/
  });
  Prism2.languages.insertBefore("java", "string", {
    "triple-quoted-string": {
      // http://openjdk.java.net/jeps/355#Description
      pattern: /"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,
      greedy: true,
      alias: "string"
    },
    "char": {
      pattern: /'(?:\\.|[^'\\\r\n]){1,6}'/,
      greedy: true
    }
  });
  Prism2.languages.insertBefore("java", "class-name", {
    "annotation": {
      pattern: /(^|[^.])@\w+(?:\s*\.\s*\w+)*/,
      lookbehind: true,
      alias: "punctuation"
    },
    "generics": {
      pattern: /<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,
      inside: {
        "class-name": className,
        "keyword": keywords,
        "punctuation": /[<>(),.:]/,
        "operator": /[?&|]/
      }
    },
    "import": [
      {
        pattern: RegExp(/(\bimport\s+)/.source + classNamePrefix + /(?:[A-Z]\w*|\*)(?=\s*;)/.source),
        lookbehind: true,
        inside: {
          "namespace": className.inside.namespace,
          "punctuation": /\./,
          "operator": /\*/,
          "class-name": /\w+/
        }
      },
      {
        pattern: RegExp(/(\bimport\s+static\s+)/.source + classNamePrefix + /(?:\w+|\*)(?=\s*;)/.source),
        lookbehind: true,
        alias: "static",
        inside: {
          "namespace": className.inside.namespace,
          "static": /\b\w+$/,
          "punctuation": /\./,
          "operator": /\*/,
          "class-name": /\w+/
        }
      }
    ],
    "namespace": {
      pattern: RegExp(
        /(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/.source.replace(/<keyword>/g, function() {
          return keywords.source;
        })
      ),
      lookbehind: true,
      inside: {
        "punctuation": /\./
      }
    }
  });
})(Prism);
Prism.languages.go = Prism.languages.extend("clike", {
  "string": {
    pattern: /(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,
    lookbehind: true,
    greedy: true
  },
  "keyword": /\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,
  "boolean": /\b(?:_|false|iota|nil|true)\b/,
  "number": [
    // binary and octal integers
    /\b0(?:b[01_]+|o[0-7_]+)i?\b/i,
    // hexadecimal integers and floats
    /\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,
    // decimal integers and floats
    /(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i
  ],
  "operator": /[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,
  "builtin": /\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/
});
Prism.languages.insertBefore("go", "string", {
  "char": {
    pattern: /'(?:\\.|[^'\\\r\n]){0,10}'/,
    greedy: true
  }
});
delete Prism.languages.go["class-name"];
(function(Prism2) {
  var multilineComment = /\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source;
  for (var i = 0; i < 2; i++) {
    multilineComment = multilineComment.replace(/<self>/g, function() {
      return multilineComment;
    });
  }
  multilineComment = multilineComment.replace(/<self>/g, function() {
    return /[^\s\S]/.source;
  });
  Prism2.languages.rust = {
    "comment": [
      {
        pattern: RegExp(/(^|[^\\])/.source + multilineComment),
        lookbehind: true,
        greedy: true
      },
      {
        pattern: /(^|[^\\:])\/\/.*/,
        lookbehind: true,
        greedy: true
      }
    ],
    "string": {
      pattern: /b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,
      greedy: true
    },
    "char": {
      pattern: /b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,
      greedy: true
    },
    "attribute": {
      pattern: /#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,
      greedy: true,
      alias: "attr-name",
      inside: {
        "string": null
        // see below
      }
    },
    // Closure params should not be confused with bitwise OR |
    "closure-params": {
      pattern: /([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,
      lookbehind: true,
      greedy: true,
      inside: {
        "closure-punctuation": {
          pattern: /^\||\|$/,
          alias: "punctuation"
        },
        rest: null
        // see below
      }
    },
    "lifetime-annotation": {
      pattern: /'\w+/,
      alias: "symbol"
    },
    "fragment-specifier": {
      pattern: /(\$\w+:)[a-z]+/,
      lookbehind: true,
      alias: "punctuation"
    },
    "variable": /\$\w+/,
    "function-definition": {
      pattern: /(\bfn\s+)\w+/,
      lookbehind: true,
      alias: "function"
    },
    "type-definition": {
      pattern: /(\b(?:enum|struct|trait|type|union)\s+)\w+/,
      lookbehind: true,
      alias: "class-name"
    },
    "module-declaration": [
      {
        pattern: /(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,
        lookbehind: true,
        alias: "namespace"
      },
      {
        pattern: /(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,
        lookbehind: true,
        alias: "namespace",
        inside: {
          "punctuation": /::/
        }
      }
    ],
    "keyword": [
      // https://github.com/rust-lang/reference/blob/master/src/keywords.md
      /\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,
      // primitives and str
      // https://doc.rust-lang.org/stable/rust-by-example/primitives.html
      /\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/
    ],
    // functions can technically start with an upper-case letter, but this will introduce a lot of false positives
    // and Rust's naming conventions recommend snake_case anyway.
    // https://doc.rust-lang.org/1.0.0/style/style/naming/README.html
    "function": /\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,
    "macro": {
      pattern: /\b\w+!/,
      alias: "property"
    },
    "constant": /\b[A-Z_][A-Z_\d]+\b/,
    "class-name": /\b[A-Z]\w*\b/,
    "namespace": {
      pattern: /(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,
      inside: {
        "punctuation": /::/
      }
    },
    // Hex, oct, bin, dec numbers with visual separators and type suffix
    "number": /\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,
    "boolean": /\b(?:false|true)\b/,
    "punctuation": /->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,
    "operator": /[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/
  };
  Prism2.languages.rust["closure-params"].inside.rest = Prism2.languages.rust;
  Prism2.languages.rust["attribute"].inside["string"] = Prism2.languages.rust["string"];
})(Prism);
(function(Prism2) {
  var comment = /\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/;
  var constant = [
    {
      pattern: /\b(?:false|true)\b/i,
      alias: "boolean"
    },
    {
      pattern: /(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,
      greedy: true,
      lookbehind: true
    },
    {
      pattern: /(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,
      greedy: true,
      lookbehind: true
    },
    /\b(?:null)\b/i,
    /\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/
  ];
  var number = /\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i;
  var operator = /<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/;
  var punctuation2 = /[{}\[\](),:;]/;
  Prism2.languages.php = {
    "delimiter": {
      pattern: /\?>$|^<\?(?:php(?=\s)|=)?/i,
      alias: "important"
    },
    "comment": comment,
    "variable": /\$+(?:\w+\b|(?=\{))/,
    "package": {
      pattern: /(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
      lookbehind: true,
      inside: {
        "punctuation": /\\/
      }
    },
    "class-name-definition": {
      pattern: /(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,
      lookbehind: true,
      alias: "class-name"
    },
    "function-definition": {
      pattern: /(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,
      lookbehind: true,
      alias: "function"
    },
    "keyword": [
      {
        pattern: /(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,
        alias: "type-casting",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,
        alias: "type-hint",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,
        alias: "return-type",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,
        alias: "type-declaration",
        greedy: true
      },
      {
        pattern: /(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,
        alias: "type-declaration",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /\b(?:parent|self|static)(?=\s*::)/i,
        alias: "static-context",
        greedy: true
      },
      {
        // yield from
        pattern: /(\byield\s+)from\b/i,
        lookbehind: true
      },
      // `class` is always a keyword unlike other keywords
      /\bclass\b/i,
      {
        // https://www.php.net/manual/en/reserved.keywords.php
        //
        // keywords cannot be preceded by "->"
        // the complex lookbehind means `(?<!(?:->|::)\s*)`
        pattern: /((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,
        lookbehind: true
      }
    ],
    "argument-name": {
      pattern: /([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,
      lookbehind: true
    },
    "class-name": [
      {
        pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /(\|\s*)\b[a-z_]\w*(?!\\)\b/i,
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,
        greedy: true
      },
      {
        pattern: /(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,
        alias: "class-name-fully-qualified",
        greedy: true,
        lookbehind: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,
        alias: "class-name-fully-qualified",
        greedy: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
        alias: "class-name-fully-qualified",
        greedy: true,
        lookbehind: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /\b[a-z_]\w*(?=\s*\$)/i,
        alias: "type-declaration",
        greedy: true
      },
      {
        pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
        alias: ["class-name-fully-qualified", "type-declaration"],
        greedy: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /\b[a-z_]\w*(?=\s*::)/i,
        alias: "static-context",
        greedy: true
      },
      {
        pattern: /(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,
        alias: ["class-name-fully-qualified", "static-context"],
        greedy: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,
        alias: "type-hint",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,
        alias: ["class-name-fully-qualified", "type-hint"],
        greedy: true,
        lookbehind: true,
        inside: {
          "punctuation": /\\/
        }
      },
      {
        pattern: /(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,
        alias: "return-type",
        greedy: true,
        lookbehind: true
      },
      {
        pattern: /(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,
        alias: ["class-name-fully-qualified", "return-type"],
        greedy: true,
        lookbehind: true,
        inside: {
          "punctuation": /\\/
        }
      }
    ],
    "constant": constant,
    "function": {
      pattern: /(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,
      lookbehind: true,
      inside: {
        "punctuation": /\\/
      }
    },
    "property": {
      pattern: /(->\s*)\w+/,
      lookbehind: true
    },
    "number": number,
    "operator": operator,
    "punctuation": punctuation2
  };
  var string_interpolation = {
    pattern: /\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,
    lookbehind: true,
    inside: Prism2.languages.php
  };
  var string = [
    {
      pattern: /<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,
      alias: "nowdoc-string",
      greedy: true,
      inside: {
        "delimiter": {
          pattern: /^<<<'[^']+'|[a-z_]\w*;$/i,
          alias: "symbol",
          inside: {
            "punctuation": /^<<<'?|[';]$/
          }
        }
      }
    },
    {
      pattern: /<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,
      alias: "heredoc-string",
      greedy: true,
      inside: {
        "delimiter": {
          pattern: /^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,
          alias: "symbol",
          inside: {
            "punctuation": /^<<<"?|[";]$/
          }
        },
        "interpolation": string_interpolation
      }
    },
    {
      pattern: /`(?:\\[\s\S]|[^\\`])*`/,
      alias: "backtick-quoted-string",
      greedy: true
    },
    {
      pattern: /'(?:\\[\s\S]|[^\\'])*'/,
      alias: "single-quoted-string",
      greedy: true
    },
    {
      pattern: /"(?:\\[\s\S]|[^\\"])*"/,
      alias: "double-quoted-string",
      greedy: true,
      inside: {
        "interpolation": string_interpolation
      }
    }
  ];
  Prism2.languages.insertBefore("php", "variable", {
    "string": string,
    "attribute": {
      pattern: /#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,
      greedy: true,
      inside: {
        "attribute-content": {
          pattern: /^(#\[)[\s\S]+(?=\]$)/,
          lookbehind: true,
          // inside can appear subset of php
          inside: {
            "comment": comment,
            "string": string,
            "attribute-class-name": [
              {
                pattern: /([^:]|^)\b[a-z_]\w*(?!\\)\b/i,
                alias: "class-name",
                greedy: true,
                lookbehind: true
              },
              {
                pattern: /([^:]|^)(?:\\?\b[a-z_]\w*)+/i,
                alias: [
                  "class-name",
                  "class-name-fully-qualified"
                ],
                greedy: true,
                lookbehind: true,
                inside: {
                  "punctuation": /\\/
                }
              }
            ],
            "constant": constant,
            "number": number,
            "operator": operator,
            "punctuation": punctuation2
          }
        },
        "delimiter": {
          pattern: /^#\[|\]$/,
          alias: "punctuation"
        }
      }
    }
  });
  Prism2.hooks.add("before-tokenize", function(env) {
    if (!/<\?/.test(env.code)) {
      return;
    }
    var phpPattern = /<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;
    Prism2.languages["markup-templating"].buildPlaceholders(env, "php", phpPattern);
  });
  Prism2.hooks.add("after-tokenize", function(env) {
    Prism2.languages["markup-templating"].tokenizePlaceholders(env, "php");
  });
})(Prism);
(function(Prism2) {
  var anchorOrAlias = /[*&][^\s[\]{},]+/;
  var tag2 = /!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/;
  var properties = "(?:" + tag2.source + "(?:[ 	]+" + anchorOrAlias.source + ")?|" + anchorOrAlias.source + "(?:[ 	]+" + tag2.source + ")?)";
  var plainKey = /(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g, function() {
    return /[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source;
  });
  var string = /"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;
  function createValuePattern(value, flags) {
    flags = (flags || "").replace(/m/g, "") + "m";
    var pattern = /([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g, function() {
      return properties;
    }).replace(/<<value>>/g, function() {
      return value;
    });
    return RegExp(pattern, flags);
  }
  Prism2.languages.yaml = {
    "scalar": {
      pattern: RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g, function() {
        return properties;
      })),
      lookbehind: true,
      alias: "string"
    },
    "comment": /#.*/,
    "key": {
      pattern: RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g, function() {
        return properties;
      }).replace(/<<key>>/g, function() {
        return "(?:" + plainKey + "|" + string + ")";
      })),
      lookbehind: true,
      greedy: true,
      alias: "atrule"
    },
    "directive": {
      pattern: /(^[ \t]*)%.+/m,
      lookbehind: true,
      alias: "important"
    },
    "datetime": {
      pattern: createValuePattern(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),
      lookbehind: true,
      alias: "number"
    },
    "boolean": {
      pattern: createValuePattern(/false|true/.source, "i"),
      lookbehind: true,
      alias: "important"
    },
    "null": {
      pattern: createValuePattern(/null|~/.source, "i"),
      lookbehind: true,
      alias: "important"
    },
    "string": {
      pattern: createValuePattern(string),
      lookbehind: true,
      greedy: true
    },
    "number": {
      pattern: createValuePattern(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source, "i"),
      lookbehind: true
    },
    "tag": tag2,
    "important": anchorOrAlias,
    "punctuation": /---|[:[\]{}\-,|>?]|\.\.\./
  };
  Prism2.languages.yml = Prism2.languages.yaml;
})(Prism);
(function(Prism2) {
  function getPlaceholder(language, index) {
    return "___" + language.toUpperCase() + index + "___";
  }
  Object.defineProperties(Prism2.languages["markup-templating"] = {}, {
    buildPlaceholders: {
      /**
       * Tokenize all inline templating expressions matching `placeholderPattern`.
       *
       * If `replaceFilter` is provided, only matches of `placeholderPattern` for which `replaceFilter` returns
       * `true` will be replaced.
       *
       * @param {object} env The environment of the `before-tokenize` hook.
       * @param {string} language The language id.
       * @param {RegExp} placeholderPattern The matches of this pattern will be replaced by placeholders.
       * @param {(match: string) => boolean} [replaceFilter]
       */
      value: function(env, language, placeholderPattern, replaceFilter) {
        if (env.language !== language) {
          return;
        }
        var tokenStack = env.tokenStack = [];
        env.code = env.code.replace(placeholderPattern, function(match) {
          if (typeof replaceFilter === "function" && !replaceFilter(match)) {
            return match;
          }
          var i = tokenStack.length;
          var placeholder;
          while (env.code.indexOf(placeholder = getPlaceholder(language, i)) !== -1) {
            ++i;
          }
          tokenStack[i] = match;
          return placeholder;
        });
        env.grammar = Prism2.languages.markup;
      }
    },
    tokenizePlaceholders: {
      /**
       * Replace placeholders with proper tokens after tokenizing.
       *
       * @param {object} env The environment of the `after-tokenize` hook.
       * @param {string} language The language id.
       */
      value: function(env, language) {
        if (env.language !== language || !env.tokenStack) {
          return;
        }
        env.grammar = Prism2.languages[language];
        var j = 0;
        var keys = Object.keys(env.tokenStack);
        function walkTokens(tokens) {
          for (var i = 0; i < tokens.length; i++) {
            if (j >= keys.length) {
              break;
            }
            var token = tokens[i];
            if (typeof token === "string" || token.content && typeof token.content === "string") {
              var k = keys[j];
              var t = env.tokenStack[k];
              var s = typeof token === "string" ? token : token.content;
              var placeholder = getPlaceholder(language, k);
              var index = s.indexOf(placeholder);
              if (index > -1) {
                ++j;
                var before = s.substring(0, index);
                var middle = new Prism2.Token(language, Prism2.tokenize(t, env.grammar), "language-" + language, t);
                var after = s.substring(index + placeholder.length);
                var replacement = [];
                if (before) {
                  replacement.push.apply(replacement, walkTokens([before]));
                }
                replacement.push(middle);
                if (after) {
                  replacement.push.apply(replacement, walkTokens([after]));
                }
                if (typeof token === "string") {
                  tokens.splice.apply(tokens, [i, 1].concat(replacement));
                } else {
                  token.content = replacement;
                }
              }
            } else if (token.content) {
              walkTokens(token.content);
            }
          }
          return tokens;
        }
        walkTokens(env.tokens);
      }
    }
  });
})(Prism);
const LINK_ICON_CODE = `<svg class="md-link-icon" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true" fill="currentColor"><path d="m7.775 3.275 1.25-1.25a3.5 3.5 0 1 1 4.95 4.95l-2.5 2.5a3.5 3.5 0 0 1-4.95 0 .751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018 1.998 1.998 0 0 0 2.83 0l2.5-2.5a2.002 2.002 0 0 0-2.83-2.83l-1.25 1.25a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042Zm-4.69 9.64a1.998 1.998 0 0 0 2.83 0l1.25-1.25a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042l-1.25 1.25a3.5 3.5 0 1 1-4.95-4.95l2.5-2.5a3.5 3.5 0 0 1 4.95 0 .751.751 0 0 1-.018 1.042.751.751 0 0 1-1.042.018 1.998 1.998 0 0 0-2.83 0l-2.5 2.5a1.998 1.998 0 0 0 0 2.83Z"></path></svg>`;
const COPY_ICON_CODE = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" color="currentColor" aria-hidden="true" aria-label="Copy" stroke-width="1.3" width="15" height="15">
  <path fill="currentColor" d="M12.728 4.545v8.182H4.545V4.545zm0 -0.909H4.545a0.909 0.909 0 0 0 -0.909 0.909v8.182a0.909 0.909 0 0 0 0.909 0.909h8.182a0.909 0.909 0 0 0 0.909 -0.909V4.545a0.909 0.909 0 0 0 -0.909 -0.909"/>
  <path fill="currentColor" d="M1.818 8.182H0.909V1.818a0.909 0.909 0 0 1 0.909 -0.909h6.364v0.909H1.818Z"/>
</svg>

`;
const CHECK_ICON_CODE = `<svg xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 17 17" aria-hidden="true" aria-label="Copied" fill="none" stroke="currentColor" stroke-width="1.3">
  <path d="m13.813 4.781 -7.438 7.438 -3.188 -3.188"/>
</svg>
`;
const COPY_BUTTON_CODE = `<button title="copy" class="copy_code_button">
  <span class="copy-text">${COPY_ICON_CODE}</span>
  <span class="check">${CHECK_ICON_CODE}</span>
</button>`;
const escape_test = /[&<>"']/;
const escape_replace = new RegExp(escape_test.source, "g");
const escape_test_no_encode = /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/;
const escape_replace_no_encode = new RegExp(escape_test_no_encode.source, "g");
const escape_replacements = {
  "&": "&amp;",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;"
};
const get_escape_replacement = (ch) => escape_replacements[ch] || "";
function escape(html2, encode) {
  if (encode) {
    if (escape_test.test(html2)) {
      return html2.replace(escape_replace, get_escape_replacement);
    }
  } else {
    if (escape_test_no_encode.test(html2)) {
      return html2.replace(escape_replace_no_encode, get_escape_replacement);
    }
  }
  return html2;
}
function createLatexTokenizer(delimiters) {
  const delimiterPatterns = delimiters.map((delimiter) => ({
    start: new RegExp(delimiter.left.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&")),
    end: new RegExp(delimiter.right.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"))
  }));
  return {
    name: "latex",
    level: "block",
    start(src) {
      for (const pattern of delimiterPatterns) {
        const match = src.match(pattern.start);
        if (match) {
          return match.index;
        }
      }
      return -1;
    },
    tokenizer(src, tokens) {
      for (const pattern of delimiterPatterns) {
        const match = new RegExp(
          `${pattern.start.source}([\\s\\S]+?)${pattern.end.source}`
        ).exec(src);
        if (match) {
          return {
            type: "latex",
            raw: match[0],
            text: match[1].trim()
          };
        }
      }
    },
    renderer(token) {
      return `<div class="latex-block">${token.text}</div>`;
    }
  };
}
function createMermaidTokenizer() {
  return {
    name: "mermaid",
    level: "block",
    start(src) {
      var _a;
      return (_a = src.match(/^```mermaid\s*\n/)) == null ? void 0 : _a.index;
    },
    tokenizer(src) {
      const match = /^```mermaid\s*\n([\s\S]*?)```\s*(?:\n|$)/.exec(src);
      if (match) {
        return {
          type: "mermaid",
          raw: match[0],
          text: match[1].trim()
        };
      }
      return void 0;
    },
    renderer(token) {
      return `<div class="mermaid">${token.text}</div>
`;
    }
  };
}
const renderer = {
  code(code, infostring, escaped) {
    var _a;
    const lang = ((_a = (infostring ?? "").match(/\S*/)) == null ? void 0 : _a[0]) ?? "";
    code = code.replace(/\n$/, "") + "\n";
    if (!lang || lang === "mermaid") {
      return '<div class="code_wrap">' + COPY_BUTTON_CODE + "<pre><code>" + (escaped ? code : escape(code, true)) + "</code></pre></div>\n";
    }
    return '<div class="code_wrap">' + COPY_BUTTON_CODE + '<pre><code class="language-' + escape(lang) + '">' + (escaped ? code : escape(code, true)) + "</code></pre></div>\n";
  }
};
const slugger = new BananaSlug();
function create_marked({
  header_links,
  line_breaks,
  latex_delimiters
}) {
  const marked2 = new Marked();
  marked2.use(
    {
      gfm: true,
      pedantic: false,
      breaks: line_breaks
    },
    markedHighlight({
      highlight: (code, lang) => {
        var _a;
        if ((_a = prismExports.languages) == null ? void 0 : _a[lang]) {
          return prismExports.highlight(code, prismExports.languages[lang], lang);
        }
        return code;
      }
    }),
    { renderer }
  );
  if (header_links) {
    marked2.use(gfmHeadingId());
    marked2.use({
      extensions: [
        {
          name: "heading",
          level: "block",
          renderer(token) {
            const raw = token.raw.toLowerCase().trim().replace(/<[!\/a-z].*?>/gi, "");
            const id = "h" + slugger.slug(raw);
            const level = token.depth;
            const text2 = this.parser.parseInline(token.tokens);
            return `<h${level} id="${id}"><a class="md-header-anchor" href="#${id}">${LINK_ICON_CODE}</a>${text2}</h${level}>
`;
          }
        }
      ]
    });
  }
  const mermaidTokenizer = createMermaidTokenizer();
  const latexTokenizer = createLatexTokenizer(latex_delimiters);
  marked2.use({
    extensions: [mermaidTokenizer, latexTokenizer]
  });
  return marked2;
}
const cloneDeep = (value) => {
  return JSON.parse(JSON.stringify(value));
};
const isElement = (value) => {
  return value.nodeType === 1;
};
const isElementFunky = (value) => {
  return FUNKY_TAG_NAMES.has(value.tagName);
};
const isElementAction = (value) => {
  return "action" in value;
};
const isElementIframe = (value) => {
  return value.tagName === "IFRAME";
};
const isElementFormAction = (value) => {
  return "formAction" in value;
};
const isElementHyperlink = (value) => {
  return "protocol" in value;
};
const isScriptOrDataUrl = /* @__PURE__ */ (() => {
  const re = /^(?:\w+script|data):/i;
  return (url) => {
    return re.test(url);
  };
})();
const isScriptOrDataUrlLoose = /* @__PURE__ */ (() => {
  const re = /(?:script|data):/i;
  return (url) => {
    return re.test(url);
  };
})();
const mergeMaps = (maps) => {
  const merged = {};
  for (let i = 0, l = maps.length; i < l; i++) {
    const map = maps[i];
    for (const key in map) {
      if (!merged[key]) {
        merged[key] = map[key];
      } else {
        merged[key] = merged[key].concat(map[key]);
      }
    }
  }
  return merged;
};
const traverseElementsBasic = (parent, callback) => {
  let current = parent.firstChild;
  while (current) {
    const next = current.nextSibling;
    if (isElement(current)) {
      callback(current, parent);
      if (current.parentNode) {
        traverseElementsBasic(current, callback);
      }
    }
    current = next;
  }
};
const traverseElementsIterator = (parent, callback) => {
  const iterator = document.createNodeIterator(parent, NodeFilter.SHOW_ELEMENT);
  let current;
  while (current = iterator.nextNode()) {
    const parent2 = current.parentNode;
    if (!parent2)
      continue;
    callback(current, parent2);
  }
};
const traverseElements = (parent, callback) => {
  const hasIterator = !!globalThis.document && !!globalThis.document.createNodeIterator;
  if (hasIterator) {
    return traverseElementsIterator(parent, callback);
  } else {
    return traverseElementsBasic(parent, callback);
  }
};
const HTML_ELEMENTS_ALLOW = [
  "a",
  "abbr",
  "acronym",
  "address",
  "area",
  "article",
  "aside",
  "audio",
  "b",
  "bdi",
  "bdo",
  "bgsound",
  "big",
  "blockquote",
  "body",
  "br",
  "button",
  "canvas",
  "caption",
  "center",
  "cite",
  "code",
  "col",
  "colgroup",
  "datalist",
  "dd",
  "del",
  "details",
  "dfn",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "em",
  "fieldset",
  "figcaption",
  "figure",
  "font",
  "footer",
  "form",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hgroup",
  "hr",
  "html",
  "i",
  "img",
  "input",
  "ins",
  "kbd",
  "keygen",
  "label",
  "layer",
  "legend",
  "li",
  "link",
  "listing",
  "main",
  "map",
  "mark",
  "marquee",
  "menu",
  "meta",
  "meter",
  "nav",
  "nobr",
  "ol",
  "optgroup",
  "option",
  "output",
  "p",
  "picture",
  "popup",
  "pre",
  "progress",
  "q",
  "rb",
  "rp",
  "rt",
  "rtc",
  "ruby",
  "s",
  "samp",
  "section",
  "select",
  "selectmenu",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "style",
  "sub",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "track",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
];
const HTML_ELEMENTS_DISALLOW = [
  "basefont",
  "command",
  "data",
  "iframe",
  "image",
  "plaintext",
  "portal",
  "slot",
  // 'template', //TODO: Not exactly correct to never allow this, too strict
  "textarea",
  "title",
  "xmp"
];
const HTML_ELEMENTS = /* @__PURE__ */ new Set([
  ...HTML_ELEMENTS_ALLOW,
  ...HTML_ELEMENTS_DISALLOW
]);
const SVG_ELEMENTS_ALLOW = [
  "svg",
  "a",
  "altglyph",
  "altglyphdef",
  "altglyphitem",
  "animatecolor",
  "animatemotion",
  "animatetransform",
  "circle",
  "clippath",
  "defs",
  "desc",
  "ellipse",
  "filter",
  "font",
  "g",
  "glyph",
  "glyphref",
  "hkern",
  "image",
  "line",
  "lineargradient",
  "marker",
  "mask",
  "metadata",
  "mpath",
  "path",
  "pattern",
  "polygon",
  "polyline",
  "radialgradient",
  "rect",
  "stop",
  "style",
  "switch",
  "symbol",
  "text",
  "textpath",
  "title",
  "tref",
  "tspan",
  "view",
  "vkern",
  /* FILTERS */
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feDistantLight",
  "feFlood",
  "feFuncA",
  "feFuncB",
  "feFuncG",
  "feFuncR",
  "feGaussianBlur",
  "feImage",
  "feMerge",
  "feMergeNode",
  "feMorphology",
  "feOffset",
  "fePointLight",
  "feSpecularLighting",
  "feSpotLight",
  "feTile",
  "feTurbulence"
];
const SVG_ELEMENTS_DISALLOW = [
  "animate",
  "color-profile",
  "cursor",
  "discard",
  "fedropshadow",
  "font-face",
  "font-face-format",
  "font-face-name",
  "font-face-src",
  "font-face-uri",
  "foreignobject",
  "hatch",
  "hatchpath",
  "mesh",
  "meshgradient",
  "meshpatch",
  "meshrow",
  "missing-glyph",
  "script",
  "set",
  "solidcolor",
  "unknown",
  "use"
];
const SVG_ELEMENTS = /* @__PURE__ */ new Set([
  ...SVG_ELEMENTS_ALLOW,
  ...SVG_ELEMENTS_DISALLOW
]);
const MATH_ELEMENTS_ALLOW = [
  "math",
  "menclose",
  "merror",
  "mfenced",
  "mfrac",
  "mglyph",
  "mi",
  "mlabeledtr",
  "mmultiscripts",
  "mn",
  "mo",
  "mover",
  "mpadded",
  "mphantom",
  "mroot",
  "mrow",
  "ms",
  "mspace",
  "msqrt",
  "mstyle",
  "msub",
  "msup",
  "msubsup",
  "mtable",
  "mtd",
  "mtext",
  "mtr",
  "munder",
  "munderover"
];
const MATH_ELEMENTS_DISALLOW = [
  "maction",
  "maligngroup",
  "malignmark",
  "mlongdiv",
  "mscarries",
  "mscarry",
  "msgroup",
  "mstack",
  "msline",
  "msrow",
  "semantics",
  "annotation",
  "annotation-xml",
  "mprescripts",
  "none"
];
const MATH_ELEMENTS = /* @__PURE__ */ new Set([
  ...MATH_ELEMENTS_ALLOW,
  ...MATH_ELEMENTS_DISALLOW
]);
const HTML_ATTRIBUTES_ALLOW = [
  "abbr",
  "accept",
  "accept-charset",
  "accesskey",
  "action",
  "align",
  "alink",
  "allow",
  "allowfullscreen",
  "alt",
  "anchor",
  "archive",
  "as",
  "async",
  "autocapitalize",
  "autocomplete",
  "autocorrect",
  "autofocus",
  "autopictureinpicture",
  "autoplay",
  "axis",
  "background",
  "behavior",
  "bgcolor",
  "border",
  "bordercolor",
  "capture",
  "cellpadding",
  "cellspacing",
  "challenge",
  "char",
  "charoff",
  "charset",
  "checked",
  "cite",
  "class",
  "classid",
  "clear",
  "code",
  "codebase",
  "codetype",
  "color",
  "cols",
  "colspan",
  "compact",
  "content",
  "contenteditable",
  "controls",
  "controlslist",
  "conversiondestination",
  "coords",
  "crossorigin",
  "csp",
  "data",
  "datetime",
  "declare",
  "decoding",
  "default",
  "defer",
  "dir",
  "direction",
  "dirname",
  "disabled",
  "disablepictureinpicture",
  "disableremoteplayback",
  "disallowdocumentaccess",
  "download",
  "draggable",
  "elementtiming",
  "enctype",
  "end",
  "enterkeyhint",
  "event",
  "exportparts",
  "face",
  "for",
  "form",
  "formaction",
  "formenctype",
  "formmethod",
  "formnovalidate",
  "formtarget",
  "frame",
  "frameborder",
  "headers",
  "height",
  "hidden",
  "high",
  "href",
  "hreflang",
  "hreftranslate",
  "hspace",
  "http-equiv",
  "id",
  "imagesizes",
  "imagesrcset",
  "importance",
  "impressiondata",
  "impressionexpiry",
  "incremental",
  "inert",
  "inputmode",
  "integrity",
  "invisible",
  "ismap",
  "keytype",
  "kind",
  "label",
  "lang",
  "language",
  "latencyhint",
  "leftmargin",
  "link",
  "list",
  "loading",
  "longdesc",
  "loop",
  "low",
  "lowsrc",
  "manifest",
  "marginheight",
  "marginwidth",
  "max",
  "maxlength",
  "mayscript",
  "media",
  "method",
  "min",
  "minlength",
  "multiple",
  "muted",
  "name",
  "nohref",
  "nomodule",
  "nonce",
  "noresize",
  "noshade",
  "novalidate",
  "nowrap",
  "object",
  "open",
  "optimum",
  "part",
  "pattern",
  "ping",
  "placeholder",
  "playsinline",
  "policy",
  "poster",
  "preload",
  "pseudo",
  "readonly",
  "referrerpolicy",
  "rel",
  "reportingorigin",
  "required",
  "resources",
  "rev",
  "reversed",
  "role",
  "rows",
  "rowspan",
  "rules",
  "sandbox",
  "scheme",
  "scope",
  "scopes",
  "scrollamount",
  "scrolldelay",
  "scrolling",
  "select",
  "selected",
  "shadowroot",
  "shadowrootdelegatesfocus",
  "shape",
  "size",
  "sizes",
  "slot",
  "span",
  "spellcheck",
  "src",
  "srclang",
  "srcset",
  "standby",
  "start",
  "step",
  "style",
  "summary",
  "tabindex",
  "target",
  "text",
  "title",
  "topmargin",
  "translate",
  "truespeed",
  "trusttoken",
  "type",
  "usemap",
  "valign",
  "value",
  "valuetype",
  "version",
  "virtualkeyboardpolicy",
  "vlink",
  "vspace",
  "webkitdirectory",
  "width",
  "wrap"
];
const SVG_ATTRIBUTES_ALLOW = [
  "accent-height",
  "accumulate",
  "additive",
  "alignment-baseline",
  "ascent",
  "attributename",
  "attributetype",
  "azimuth",
  "basefrequency",
  "baseline-shift",
  "begin",
  "bias",
  "by",
  "class",
  "clip",
  "clippathunits",
  "clip-path",
  "clip-rule",
  "color",
  "color-interpolation",
  "color-interpolation-filters",
  "color-profile",
  "color-rendering",
  "cx",
  "cy",
  "d",
  "dx",
  "dy",
  "diffuseconstant",
  "direction",
  "display",
  "divisor",
  "dominant-baseline",
  "dur",
  "edgemode",
  "elevation",
  "end",
  "fill",
  "fill-opacity",
  "fill-rule",
  "filter",
  "filterunits",
  "flood-color",
  "flood-opacity",
  "font-family",
  "font-size",
  "font-size-adjust",
  "font-stretch",
  "font-style",
  "font-variant",
  "font-weight",
  "fx",
  "fy",
  "g1",
  "g2",
  "glyph-name",
  "glyphref",
  "gradientunits",
  "gradienttransform",
  "height",
  "href",
  "id",
  "image-rendering",
  "in",
  "in2",
  "k",
  "k1",
  "k2",
  "k3",
  "k4",
  "kerning",
  "keypoints",
  "keysplines",
  "keytimes",
  "lang",
  "lengthadjust",
  "letter-spacing",
  "kernelmatrix",
  "kernelunitlength",
  "lighting-color",
  "local",
  "marker-end",
  "marker-mid",
  "marker-start",
  "markerheight",
  "markerunits",
  "markerwidth",
  "maskcontentunits",
  "maskunits",
  "max",
  "mask",
  "media",
  "method",
  "mode",
  "min",
  "name",
  "numoctaves",
  "offset",
  "operator",
  "opacity",
  "order",
  "orient",
  "orientation",
  "origin",
  "overflow",
  "paint-order",
  "path",
  "pathlength",
  "patterncontentunits",
  "patterntransform",
  "patternunits",
  "points",
  "preservealpha",
  "preserveaspectratio",
  "primitiveunits",
  "r",
  "rx",
  "ry",
  "radius",
  "refx",
  "refy",
  "repeatcount",
  "repeatdur",
  "restart",
  "result",
  "rotate",
  "scale",
  "seed",
  "shape-rendering",
  "specularconstant",
  "specularexponent",
  "spreadmethod",
  "startoffset",
  "stddeviation",
  "stitchtiles",
  "stop-color",
  "stop-opacity",
  "stroke-dasharray",
  "stroke-dashoffset",
  "stroke-linecap",
  "stroke-linejoin",
  "stroke-miterlimit",
  "stroke-opacity",
  "stroke",
  "stroke-width",
  "style",
  "surfacescale",
  "systemlanguage",
  "tabindex",
  "targetx",
  "targety",
  "transform",
  "transform-origin",
  "text-anchor",
  "text-decoration",
  "text-rendering",
  "textlength",
  "type",
  "u1",
  "u2",
  "unicode",
  "values",
  "viewbox",
  "visibility",
  "version",
  "vert-adv-y",
  "vert-origin-x",
  "vert-origin-y",
  "width",
  "word-spacing",
  "wrap",
  "writing-mode",
  "xchannelselector",
  "ychannelselector",
  "x",
  "x1",
  "x2",
  "xmlns",
  "y",
  "y1",
  "y2",
  "z",
  "zoomandpan"
];
const MATH_ATTRIBUTES_ALLOW = [
  "accent",
  "accentunder",
  "align",
  "bevelled",
  "close",
  "columnsalign",
  "columnlines",
  "columnspan",
  "denomalign",
  "depth",
  "dir",
  "display",
  "displaystyle",
  "encoding",
  "fence",
  "frame",
  "height",
  "href",
  "id",
  "largeop",
  "length",
  "linethickness",
  "lspace",
  "lquote",
  "mathbackground",
  "mathcolor",
  "mathsize",
  "mathvariant",
  "maxsize",
  "minsize",
  "movablelimits",
  "notation",
  "numalign",
  "open",
  "rowalign",
  "rowlines",
  "rowspacing",
  "rowspan",
  "rspace",
  "rquote",
  "scriptlevel",
  "scriptminsize",
  "scriptsizemultiplier",
  "selection",
  "separator",
  "separators",
  "stretchy",
  "subscriptshift",
  "supscriptshift",
  "symmetric",
  "voffset",
  "width",
  "xmlns"
];
const NAMESPACES = {
  HTML: "http://www.w3.org/1999/xhtml",
  SVG: "http://www.w3.org/2000/svg",
  MATH: "http://www.w3.org/1998/Math/MathML"
};
const NAMESPACES_ELEMENTS = {
  [NAMESPACES.HTML]: HTML_ELEMENTS,
  [NAMESPACES.SVG]: SVG_ELEMENTS,
  [NAMESPACES.MATH]: MATH_ELEMENTS
};
const NAMESPACES_ROOTS = {
  [NAMESPACES.HTML]: "html",
  [NAMESPACES.SVG]: "svg",
  [NAMESPACES.MATH]: "math"
};
const NAMESPACES_PREFIXES = {
  [NAMESPACES.HTML]: "",
  [NAMESPACES.SVG]: "svg:",
  [NAMESPACES.MATH]: "math:"
};
const FUNKY_TAG_NAMES = /* @__PURE__ */ new Set([
  "A",
  "AREA",
  "BUTTON",
  "FORM",
  "IFRAME",
  "INPUT"
]);
const DEFAULTS = {
  allowComments: true,
  allowCustomElements: false,
  allowUnknownMarkup: false,
  allowElements: [
    ...HTML_ELEMENTS_ALLOW,
    ...SVG_ELEMENTS_ALLOW.map((name) => `svg:${name}`),
    ...MATH_ELEMENTS_ALLOW.map((name) => `math:${name}`)
  ],
  allowAttributes: mergeMaps([
    Object.fromEntries(HTML_ATTRIBUTES_ALLOW.map((name) => [name, ["*"]])),
    Object.fromEntries(SVG_ATTRIBUTES_ALLOW.map((name) => [name, ["svg:*"]])),
    Object.fromEntries(MATH_ATTRIBUTES_ALLOW.map((name) => [name, ["math:*"]]))
  ])
};
var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
  if (typeof state === "function" ? receiver !== state || true : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return state.set(receiver, value), value;
};
var __classPrivateFieldGet = function(receiver, state, kind, f) {
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : state.get(receiver);
};
var _Amuchina_configuration, _Amuchina_allowElements, _Amuchina_allowAttributes;
class Amuchina {
  /* CONSTRUCTOR */
  constructor(configuration = {}) {
    _Amuchina_configuration.set(this, void 0);
    _Amuchina_allowElements.set(this, void 0);
    _Amuchina_allowAttributes.set(this, void 0);
    this.getConfiguration = () => {
      return cloneDeep(__classPrivateFieldGet(this, _Amuchina_configuration, "f"));
    };
    this.sanitize = (input) => {
      const allowElements2 = __classPrivateFieldGet(this, _Amuchina_allowElements, "f");
      const allowAttributes2 = __classPrivateFieldGet(this, _Amuchina_allowAttributes, "f");
      traverseElements(input, (node, parent) => {
        const namespace = node.namespaceURI || NAMESPACES.HTML;
        const namespaceParent = parent["namespaceURI"] || NAMESPACES.HTML;
        const elements = NAMESPACES_ELEMENTS[namespace];
        const root = NAMESPACES_ROOTS[namespace];
        const prefix = NAMESPACES_PREFIXES[namespace];
        const tag2 = node.tagName.toLowerCase();
        const tagPrefixed = `${prefix}${tag2}`;
        const all = "*";
        const allPrefixed = `${prefix}${all}`;
        if (!elements.has(tag2) || !allowElements2.has(tagPrefixed) || namespace !== namespaceParent && tag2 !== root) {
          parent.removeChild(node);
        } else {
          const attributes = node.getAttributeNames();
          const attributesLength = attributes.length;
          if (attributesLength) {
            for (let i = 0; i < attributesLength; i++) {
              const attribute = attributes[i];
              const allowedValues = allowAttributes2[attribute];
              if (!allowedValues || !allowedValues.has(allPrefixed) && !allowedValues.has(tagPrefixed)) {
                node.removeAttribute(attribute);
              }
            }
            if (isElementFunky(node)) {
              if (isElementHyperlink(node)) {
                const href = node.getAttribute("href");
                if (href && isScriptOrDataUrlLoose(href) && isScriptOrDataUrl(node.protocol)) {
                  node.removeAttribute("href");
                }
              } else if (isElementAction(node)) {
                if (isScriptOrDataUrl(node.action)) {
                  node.removeAttribute("action");
                }
              } else if (isElementFormAction(node)) {
                if (isScriptOrDataUrl(node.formAction)) {
                  node.removeAttribute("formaction");
                }
              } else if (isElementIframe(node)) {
                if (isScriptOrDataUrl(node.src)) {
                  node.removeAttribute("formaction");
                }
                node.setAttribute("sandbox", "allow-scripts");
              }
            }
          }
        }
      });
      return input;
    };
    this.sanitizeFor = (element2, input) => {
      throw new Error('"sanitizeFor" is not implemented yet');
    };
    const { allowComments, allowCustomElements, allowUnknownMarkup, blockElements, dropElements, dropAttributes } = configuration;
    if (allowComments === false)
      throw new Error('A false "allowComments" is not supported yet');
    if (allowCustomElements)
      throw new Error('A true "allowCustomElements" is not supported yet');
    if (allowUnknownMarkup)
      throw new Error('A true "allowUnknownMarkup" is not supported yet');
    if (blockElements)
      throw new Error('"blockElements" is not supported yet, use "allowElements" instead');
    if (dropElements)
      throw new Error('"dropElements" is not supported yet, use "allowElements" instead');
    if (dropAttributes)
      throw new Error('"dropAttributes" is not supported yet, use "allowAttributes" instead');
    __classPrivateFieldSet(this, _Amuchina_configuration, cloneDeep(DEFAULTS));
    const { allowElements, allowAttributes } = configuration;
    if (allowElements)
      __classPrivateFieldGet(this, _Amuchina_configuration, "f").allowElements = configuration.allowElements;
    if (allowAttributes)
      __classPrivateFieldGet(this, _Amuchina_configuration, "f").allowAttributes = configuration.allowAttributes;
    __classPrivateFieldSet(this, _Amuchina_allowElements, new Set(__classPrivateFieldGet(this, _Amuchina_configuration, "f").allowElements));
    __classPrivateFieldSet(this, _Amuchina_allowAttributes, Object.fromEntries(Object.entries(__classPrivateFieldGet(this, _Amuchina_configuration, "f").allowAttributes || {}).map(([element2, attributes]) => [element2, new Set(attributes)])));
  }
}
_Amuchina_configuration = /* @__PURE__ */ new WeakMap(), _Amuchina_allowElements = /* @__PURE__ */ new WeakMap(), _Amuchina_allowAttributes = /* @__PURE__ */ new WeakMap();
Amuchina.getDefaultConfiguration = () => {
  return cloneDeep(DEFAULTS);
};
const is_external_url = (link2, root = location.href) => {
  try {
    return !!link2 && new URL(link2).origin !== new URL(root).origin;
  } catch (e) {
    return false;
  }
};
function sanitize(source) {
  const amuchina = new Amuchina();
  const node = new DOMParser().parseFromString(source, "text/html");
  walk_nodes(node.body, "A", (node2) => {
    if (node2 instanceof HTMLElement && "target" in node2) {
      if (is_external_url(node2.getAttribute("href"), location.href)) {
        node2.setAttribute("target", "_blank");
        node2.setAttribute("rel", "noopener noreferrer");
      }
    }
  });
  return amuchina.sanitize(node).body.innerHTML;
}
function walk_nodes(node, test, callback) {
  if (node && (node.nodeName === test || typeof test === "function")) {
    callback(node);
  }
  const children2 = (node == null ? void 0 : node.childNodes) || [];
  for (let i = 0; i < children2.length; i++) {
    walk_nodes(children2[i], test, callback);
  }
}
const standardHtmlTags = [
  "!--",
  "!doctype",
  "a",
  "abbr",
  "acronym",
  "address",
  "applet",
  "area",
  "article",
  "aside",
  "audio",
  "b",
  "base",
  "basefont",
  "bdi",
  "bdo",
  "big",
  "blockquote",
  "body",
  "br",
  "button",
  "canvas",
  "caption",
  "center",
  "cite",
  "code",
  "col",
  "colgroup",
  "data",
  "datalist",
  "dd",
  "del",
  "details",
  "dfn",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "em",
  "embed",
  "fieldset",
  "figcaption",
  "figure",
  "font",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hgroup",
  "hr",
  "html",
  "i",
  "iframe",
  "img",
  "input",
  "ins",
  "kbd",
  "label",
  "legend",
  "li",
  "link",
  "main",
  "map",
  "mark",
  "menu",
  "meta",
  "meter",
  "nav",
  "noframes",
  "noscript",
  "object",
  "ol",
  "optgroup",
  "option",
  "output",
  "p",
  "param",
  "picture",
  "pre",
  "progress",
  "q",
  "rp",
  "rt",
  "ruby",
  "s",
  "samp",
  "script",
  "search",
  "section",
  "select",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "style",
  "sub",
  "summary",
  "sup",
  "svg",
  "table",
  "tbody",
  "td",
  "template",
  "textarea",
  "tfoot",
  "th",
  "thead",
  "time",
  "title",
  "tr",
  "track",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
];
const svgTags = [
  // Base structural elements
  "g",
  "defs",
  "use",
  "symbol",
  // Shape elements
  "rect",
  "circle",
  "ellipse",
  "line",
  "polyline",
  "polygon",
  "path",
  "image",
  // Text elements
  "text",
  "tspan",
  "textPath",
  // Gradient and effects
  "linearGradient",
  "radialGradient",
  "stop",
  "pattern",
  "clipPath",
  "mask",
  "filter",
  // Filter effects
  "feBlend",
  "feColorMatrix",
  "feComponentTransfer",
  "feComposite",
  "feConvolveMatrix",
  "feDiffuseLighting",
  "feDisplacementMap",
  "feGaussianBlur",
  "feMerge",
  "feMorphology",
  "feOffset",
  "feSpecularLighting",
  "feTurbulence",
  "feMergeNode",
  "feFuncR",
  "feFuncG",
  "feFuncB",
  "feFuncA",
  "feDistantLight",
  "fePointLight",
  "feSpotLight",
  "feFlood",
  "feTile",
  // Animation elements
  "animate",
  "animateTransform",
  "animateMotion",
  "mpath",
  "set",
  // Interactive and other elements
  "view",
  "cursor",
  "foreignObject",
  "desc",
  "title",
  "metadata",
  "switch"
];
const standardHtmlAndSvgTags = [
  ...standardHtmlTags,
  ...svgTags.filter((tag2) => !standardHtmlTags.includes(tag2))
];
function create_fragment$V(ctx) {
  let span;
  return {
    c() {
      span = element("span");
      attr(span, "class", "md svelte-1m32c2s");
      toggle_class(
        span,
        "chatbot",
        /*chatbot*/
        ctx[0]
      );
      toggle_class(
        span,
        "prose",
        /*render_markdown*/
        ctx[1]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      span.innerHTML = /*html*/
      ctx[3];
      ctx[11](span);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*html*/
      8) span.innerHTML = /*html*/
      ctx2[3];
      if (dirty & /*chatbot*/
      1) {
        toggle_class(
          span,
          "chatbot",
          /*chatbot*/
          ctx2[0]
        );
      }
      if (dirty & /*render_markdown*/
      2) {
        toggle_class(
          span,
          "prose",
          /*render_markdown*/
          ctx2[1]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      ctx[11](null);
    }
  };
}
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function instance$E($$self, $$props, $$invalidate) {
  let { chatbot = true } = $$props;
  let { message } = $$props;
  let { sanitize_html = true } = $$props;
  let { latex_delimiters = [] } = $$props;
  let { render_markdown = true } = $$props;
  let { line_breaks = true } = $$props;
  let { header_links = false } = $$props;
  let { allow_tags = false } = $$props;
  let { theme_mode = "system" } = $$props;
  let el;
  let html2;
  let katex_loaded = false;
  const marked2 = create_marked({
    header_links,
    line_breaks,
    latex_delimiters: latex_delimiters || []
  });
  function has_math_syntax(text2) {
    if (!latex_delimiters || latex_delimiters.length === 0) {
      return false;
    }
    return latex_delimiters.some((delimiter) => text2.includes(delimiter.left) && text2.includes(delimiter.right));
  }
  function escapeTags(content, tagsToEscape) {
    if (tagsToEscape === true) {
      const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9-]*)([\s>])/g;
      return content.replace(tagRegex, (match, tagName, endChar) => {
        if (!standardHtmlAndSvgTags.includes(tagName.toLowerCase())) {
          return match.replace(/</g, "&lt;").replace(/>/g, "&gt;");
        }
        return match;
      });
    }
    if (Array.isArray(tagsToEscape)) {
      const tagPattern = tagsToEscape.map((tag2) => ({
        open: new RegExp(`<(${tag2})(\\s+[^>]*)?>`, "gi"),
        close: new RegExp(`</(${tag2})>`, "gi")
      }));
      let result = content;
      tagPattern.forEach((pattern) => {
        result = result.replace(pattern.open, (match) => match.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
        result = result.replace(pattern.close, (match) => match.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
      });
      return result;
    }
    return content;
  }
  function process_message(value) {
    let parsedValue = value;
    if (render_markdown) {
      const latexBlocks = [];
      latex_delimiters.forEach((delimiter, index) => {
        const leftDelimiter = escapeRegExp(delimiter.left);
        const rightDelimiter = escapeRegExp(delimiter.right);
        const regex2 = new RegExp(`${leftDelimiter}([\\s\\S]+?)${rightDelimiter}`, "g");
        parsedValue = parsedValue.replace(regex2, (match, p1) => {
          latexBlocks.push(match);
          return `%%%LATEX_BLOCK_${latexBlocks.length - 1}%%%`;
        });
      });
      parsedValue = marked2.parse(parsedValue);
      parsedValue = parsedValue.replace(/%%%LATEX_BLOCK_(\d+)%%%/g, (match, p1) => latexBlocks[parseInt(p1, 10)]);
    }
    if (allow_tags) {
      parsedValue = escapeTags(parsedValue, allow_tags);
    }
    if (sanitize_html && sanitize) {
      parsedValue = sanitize(parsedValue);
    }
    return parsedValue;
  }
  async function render_html(value) {
    if (latex_delimiters.length > 0 && value && has_math_syntax(value)) {
      if (!katex_loaded) {
        await Promise.all([Promise.resolve({              }), __vitePreload(() => import('./auto-render-DTMSUk0Z-BeunX3LV.js'),true              ?__vite__mapDeps([0,1]):void 0,import.meta.url)]).then(([, { default: render_math_in_element }]) => {
          katex_loaded = true;
          render_math_in_element(el, {
            delimiters: latex_delimiters,
            throwOnError: false
          });
        });
      } else {
        const { default: render_math_in_element } = await __vitePreload(async () => { const { default: render_math_in_element } = await import('./auto-render-DTMSUk0Z-BeunX3LV.js');return { default: render_math_in_element }},true              ?__vite__mapDeps([0,1]):void 0,import.meta.url);
        render_math_in_element(el, {
          delimiters: latex_delimiters,
          throwOnError: false
        });
      }
    }
    if (el) {
      const mermaidDivs = el.querySelectorAll(".mermaid");
      if (mermaidDivs.length > 0) {
        await tick();
        const { default: mermaid } = await __vitePreload(() => import('./mermaid.core-vMMZVCDT-alxhRXoZ.js'),true              ?__vite__mapDeps([2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37]):void 0,import.meta.url).then((n) => n.bA);
        mermaid.initialize({
          startOnLoad: false,
          theme: theme_mode === "dark" ? "dark" : "default",
          securityLevel: "antiscript"
        });
        await mermaid.run({
          nodes: Array.from(mermaidDivs).map((node) => node)
        });
      }
    }
  }
  afterUpdate(async () => {
    if (el && document.body.contains(el)) {
      await render_html(message);
    } else {
      console.error("Element is not in the DOM");
    }
  });
  function span_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      el = $$value;
      $$invalidate(2, el);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("chatbot" in $$props2) $$invalidate(0, chatbot = $$props2.chatbot);
    if ("message" in $$props2) $$invalidate(4, message = $$props2.message);
    if ("sanitize_html" in $$props2) $$invalidate(5, sanitize_html = $$props2.sanitize_html);
    if ("latex_delimiters" in $$props2) $$invalidate(6, latex_delimiters = $$props2.latex_delimiters);
    if ("render_markdown" in $$props2) $$invalidate(1, render_markdown = $$props2.render_markdown);
    if ("line_breaks" in $$props2) $$invalidate(7, line_breaks = $$props2.line_breaks);
    if ("header_links" in $$props2) $$invalidate(8, header_links = $$props2.header_links);
    if ("allow_tags" in $$props2) $$invalidate(9, allow_tags = $$props2.allow_tags);
    if ("theme_mode" in $$props2) $$invalidate(10, theme_mode = $$props2.theme_mode);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*message*/
    16) {
      if (message && message.trim()) {
        $$invalidate(3, html2 = process_message(message));
      } else {
        $$invalidate(3, html2 = "");
      }
    }
  };
  return [
    chatbot,
    render_markdown,
    el,
    html2,
    message,
    sanitize_html,
    latex_delimiters,
    line_breaks,
    header_links,
    allow_tags,
    theme_mode,
    span_binding
  ];
}
class MarkdownCode extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$E, create_fragment$V, safe_not_equal, {
      chatbot: 0,
      message: 4,
      sanitize_html: 5,
      latex_delimiters: 6,
      render_markdown: 1,
      line_breaks: 7,
      header_links: 8,
      allow_tags: 9,
      theme_mode: 10
    });
  }
}
function create_fragment$U(ctx) {
  let label_1;
  let span;
  let icon;
  let t0;
  let t1;
  let label_1_dir_value;
  let current;
  icon = new /*Icon*/
  ctx[1]({});
  return {
    c() {
      label_1 = element("label");
      span = element("span");
      create_component(icon.$$.fragment);
      t0 = space();
      t1 = text(
        /*label*/
        ctx[0]
      );
      attr(span, "class", "svelte-igqdol");
      attr(label_1, "for", "");
      attr(label_1, "data-testid", "block-label");
      attr(label_1, "dir", label_1_dir_value = /*rtl*/
      ctx[5] ? "rtl" : "ltr");
      attr(label_1, "class", "svelte-igqdol");
      toggle_class(label_1, "hide", !/*show_label*/
      ctx[2]);
      toggle_class(label_1, "sr-only", !/*show_label*/
      ctx[2]);
      toggle_class(
        label_1,
        "float",
        /*float*/
        ctx[4]
      );
      toggle_class(
        label_1,
        "hide-label",
        /*disable*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, label_1, anchor);
      append(label_1, span);
      mount_component(icon, span, null);
      append(label_1, t0);
      append(label_1, t1);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (!current || dirty & /*label*/
      1) set_data(
        t1,
        /*label*/
        ctx2[0]
      );
      if (!current || dirty & /*rtl*/
      32 && label_1_dir_value !== (label_1_dir_value = /*rtl*/
      ctx2[5] ? "rtl" : "ltr")) {
        attr(label_1, "dir", label_1_dir_value);
      }
      if (!current || dirty & /*show_label*/
      4) {
        toggle_class(label_1, "hide", !/*show_label*/
        ctx2[2]);
      }
      if (!current || dirty & /*show_label*/
      4) {
        toggle_class(label_1, "sr-only", !/*show_label*/
        ctx2[2]);
      }
      if (!current || dirty & /*float*/
      16) {
        toggle_class(
          label_1,
          "float",
          /*float*/
          ctx2[4]
        );
      }
      if (!current || dirty & /*disable*/
      8) {
        toggle_class(
          label_1,
          "hide-label",
          /*disable*/
          ctx2[3]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(icon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(icon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(label_1);
      }
      destroy_component(icon);
    }
  };
}
function instance$D($$self, $$props, $$invalidate) {
  let { label = null } = $$props;
  let { Icon } = $$props;
  let { show_label = true } = $$props;
  let { disable = false } = $$props;
  let { float = true } = $$props;
  let { rtl = false } = $$props;
  $$self.$$set = ($$props2) => {
    if ("label" in $$props2) $$invalidate(0, label = $$props2.label);
    if ("Icon" in $$props2) $$invalidate(1, Icon = $$props2.Icon);
    if ("show_label" in $$props2) $$invalidate(2, show_label = $$props2.show_label);
    if ("disable" in $$props2) $$invalidate(3, disable = $$props2.disable);
    if ("float" in $$props2) $$invalidate(4, float = $$props2.float);
    if ("rtl" in $$props2) $$invalidate(5, rtl = $$props2.rtl);
  };
  return [label, Icon, show_label, disable, float, rtl];
}
class BlockLabel extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$D, create_fragment$U, safe_not_equal, {
      label: 0,
      Icon: 1,
      show_label: 2,
      disable: 3,
      float: 4,
      rtl: 5
    });
  }
}
function create_fragment$T(ctx) {
  let a;
  let a_target_value;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[5].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[4],
    null
  );
  let a_levels = [
    { class: "download-link" },
    { href: (
      /*href*/
      ctx[0]
    ) },
    {
      target: a_target_value = typeof window !== "undefined" && window.__is_colab__ ? "_blank" : null
    },
    { rel: "noopener noreferrer" },
    { download: (
      /*download*/
      ctx[1]
    ) },
    /*$$restProps*/
    ctx[3]
  ];
  let a_data = {};
  for (let i = 0; i < a_levels.length; i += 1) {
    a_data = assign(a_data, a_levels[i]);
  }
  return {
    c() {
      a = element("a");
      if (default_slot) default_slot.c();
      set_attributes(a, a_data);
      set_style(a, "position", `relative`);
      toggle_class(a, "svelte-151nsdd", true);
    },
    m(target, anchor) {
      insert(target, a, anchor);
      if (default_slot) {
        default_slot.m(a, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(
          a,
          "click",
          /*dispatch*/
          ctx[2].bind(null, "click")
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[4],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[4]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[4],
              dirty,
              null
            ),
            null
          );
        }
      }
      set_attributes(a, a_data = get_spread_update(a_levels, [
        { class: "download-link" },
        (!current || dirty & /*href*/
        1) && { href: (
          /*href*/
          ctx2[0]
        ) },
        { target: a_target_value },
        { rel: "noopener noreferrer" },
        (!current || dirty & /*download*/
        2) && { download: (
          /*download*/
          ctx2[1]
        ) },
        dirty & /*$$restProps*/
        8 && /*$$restProps*/
        ctx2[3]
      ]));
      set_style(a, "position", `relative`);
      toggle_class(a, "svelte-151nsdd", true);
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(a);
      }
      if (default_slot) default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance$C($$self, $$props, $$invalidate) {
  const omit_props_names = ["href", "download"];
  let $$restProps = compute_rest_props($$props, omit_props_names);
  let { $$slots: slots = {}, $$scope } = $$props;
  let { href = void 0 } = $$props;
  let { download } = $$props;
  const dispatch2 = createEventDispatcher();
  $$self.$$set = ($$new_props) => {
    $$props = assign(assign({}, $$props), exclude_internal_props($$new_props));
    $$invalidate(3, $$restProps = compute_rest_props($$props, omit_props_names));
    if ("href" in $$new_props) $$invalidate(0, href = $$new_props.href);
    if ("download" in $$new_props) $$invalidate(1, download = $$new_props.download);
    if ("$$scope" in $$new_props) $$invalidate(4, $$scope = $$new_props.$$scope);
  };
  return [href, download, dispatch2, $$restProps, $$scope, slots];
}
class DownloadLink extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$C, create_fragment$T, safe_not_equal, { href: 0, download: 1 });
  }
}
function create_if_block$l(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*label*/
        ctx[1]
      );
      attr(span, "class", "svelte-y0enk4");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*label*/
      2) set_data(
        t,
        /*label*/
        ctx2[1]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_fragment$S(ctx) {
  let button;
  let t0;
  let div;
  let switch_instance;
  let t1;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*show_label*/
    ctx[2] && create_if_block$l(ctx)
  );
  var switch_value = (
    /*Icon*/
    ctx[0]
  );
  function switch_props(ctx2, dirty) {
    return {};
  }
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props());
  }
  const default_slot_template = (
    /*#slots*/
    ctx[15].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[14],
    null
  );
  return {
    c() {
      button = element("button");
      if (if_block) if_block.c();
      t0 = space();
      div = element("div");
      if (switch_instance) create_component(switch_instance.$$.fragment);
      t1 = space();
      if (default_slot) default_slot.c();
      attr(div, "class", "svelte-y0enk4");
      toggle_class(
        div,
        "x-small",
        /*size*/
        ctx[4] === "x-small"
      );
      toggle_class(
        div,
        "small",
        /*size*/
        ctx[4] === "small"
      );
      toggle_class(
        div,
        "large",
        /*size*/
        ctx[4] === "large"
      );
      toggle_class(
        div,
        "medium",
        /*size*/
        ctx[4] === "medium"
      );
      attr(button, "class", "icon-button svelte-y0enk4");
      button.disabled = /*disabled*/
      ctx[7];
      attr(
        button,
        "aria-label",
        /*label*/
        ctx[1]
      );
      attr(
        button,
        "aria-haspopup",
        /*hasPopup*/
        ctx[8]
      );
      attr(
        button,
        "title",
        /*label*/
        ctx[1]
      );
      toggle_class(
        button,
        "pending",
        /*pending*/
        ctx[3]
      );
      toggle_class(
        button,
        "padded",
        /*padded*/
        ctx[5]
      );
      toggle_class(
        button,
        "highlight",
        /*highlight*/
        ctx[6]
      );
      toggle_class(
        button,
        "transparent",
        /*transparent*/
        ctx[9]
      );
      set_style(
        button,
        "--border-color",
        /*border*/
        ctx[11]
      );
      set_style(button, "color", !/*disabled*/
      ctx[7] && /*_color*/
      ctx[12] ? (
        /*_color*/
        ctx[12]
      ) : "var(--block-label-text-color)");
      set_style(button, "--bg-color", !/*disabled*/
      ctx[7] ? (
        /*background*/
        ctx[10]
      ) : "auto");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (if_block) if_block.m(button, null);
      append(button, t0);
      append(button, div);
      if (switch_instance) mount_component(switch_instance, div, null);
      append(div, t1);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[16]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (
        /*show_label*/
        ctx2[2]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$l(ctx2);
          if_block.c();
          if_block.m(button, t0);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*Icon*/
      1 && switch_value !== (switch_value = /*Icon*/
      ctx2[0])) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props());
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, div, t1);
        } else {
          switch_instance = null;
        }
      }
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        16384)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[14],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[14]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[14],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*size*/
      16) {
        toggle_class(
          div,
          "x-small",
          /*size*/
          ctx2[4] === "x-small"
        );
      }
      if (!current || dirty & /*size*/
      16) {
        toggle_class(
          div,
          "small",
          /*size*/
          ctx2[4] === "small"
        );
      }
      if (!current || dirty & /*size*/
      16) {
        toggle_class(
          div,
          "large",
          /*size*/
          ctx2[4] === "large"
        );
      }
      if (!current || dirty & /*size*/
      16) {
        toggle_class(
          div,
          "medium",
          /*size*/
          ctx2[4] === "medium"
        );
      }
      if (!current || dirty & /*disabled*/
      128) {
        button.disabled = /*disabled*/
        ctx2[7];
      }
      if (!current || dirty & /*label*/
      2) {
        attr(
          button,
          "aria-label",
          /*label*/
          ctx2[1]
        );
      }
      if (!current || dirty & /*hasPopup*/
      256) {
        attr(
          button,
          "aria-haspopup",
          /*hasPopup*/
          ctx2[8]
        );
      }
      if (!current || dirty & /*label*/
      2) {
        attr(
          button,
          "title",
          /*label*/
          ctx2[1]
        );
      }
      if (!current || dirty & /*pending*/
      8) {
        toggle_class(
          button,
          "pending",
          /*pending*/
          ctx2[3]
        );
      }
      if (!current || dirty & /*padded*/
      32) {
        toggle_class(
          button,
          "padded",
          /*padded*/
          ctx2[5]
        );
      }
      if (!current || dirty & /*highlight*/
      64) {
        toggle_class(
          button,
          "highlight",
          /*highlight*/
          ctx2[6]
        );
      }
      if (!current || dirty & /*transparent*/
      512) {
        toggle_class(
          button,
          "transparent",
          /*transparent*/
          ctx2[9]
        );
      }
      if (dirty & /*border*/
      2048) {
        set_style(
          button,
          "--border-color",
          /*border*/
          ctx2[11]
        );
      }
      if (dirty & /*disabled, _color*/
      4224) {
        set_style(button, "color", !/*disabled*/
        ctx2[7] && /*_color*/
        ctx2[12] ? (
          /*_color*/
          ctx2[12]
        ) : "var(--block-label-text-color)");
      }
      if (dirty & /*disabled, background*/
      1152) {
        set_style(button, "--bg-color", !/*disabled*/
        ctx2[7] ? (
          /*background*/
          ctx2[10]
        ) : "auto");
      }
    },
    i(local) {
      if (current) return;
      if (switch_instance) transition_in(switch_instance.$$.fragment, local);
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      if (switch_instance) transition_out(switch_instance.$$.fragment, local);
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      if (if_block) if_block.d();
      if (switch_instance) destroy_component(switch_instance);
      if (default_slot) default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function instance$B($$self, $$props, $$invalidate) {
  let _color;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { Icon } = $$props;
  let { label = "" } = $$props;
  let { show_label = false } = $$props;
  let { pending = false } = $$props;
  let { size = "small" } = $$props;
  let { padded = true } = $$props;
  let { highlight = false } = $$props;
  let { disabled = false } = $$props;
  let { hasPopup = false } = $$props;
  let { color = "var(--block-label-text-color)" } = $$props;
  let { transparent = false } = $$props;
  let { background = "var(--block-background-fill)" } = $$props;
  let { border = "transparent" } = $$props;
  function click_handler(event) {
    bubble.call(this, $$self, event);
  }
  $$self.$$set = ($$props2) => {
    if ("Icon" in $$props2) $$invalidate(0, Icon = $$props2.Icon);
    if ("label" in $$props2) $$invalidate(1, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(2, show_label = $$props2.show_label);
    if ("pending" in $$props2) $$invalidate(3, pending = $$props2.pending);
    if ("size" in $$props2) $$invalidate(4, size = $$props2.size);
    if ("padded" in $$props2) $$invalidate(5, padded = $$props2.padded);
    if ("highlight" in $$props2) $$invalidate(6, highlight = $$props2.highlight);
    if ("disabled" in $$props2) $$invalidate(7, disabled = $$props2.disabled);
    if ("hasPopup" in $$props2) $$invalidate(8, hasPopup = $$props2.hasPopup);
    if ("color" in $$props2) $$invalidate(13, color = $$props2.color);
    if ("transparent" in $$props2) $$invalidate(9, transparent = $$props2.transparent);
    if ("background" in $$props2) $$invalidate(10, background = $$props2.background);
    if ("border" in $$props2) $$invalidate(11, border = $$props2.border);
    if ("$$scope" in $$props2) $$invalidate(14, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*highlight, color*/
    8256) {
      $$invalidate(12, _color = highlight ? "var(--color-accent)" : color);
    }
  };
  return [
    Icon,
    label,
    show_label,
    pending,
    size,
    padded,
    highlight,
    disabled,
    hasPopup,
    transparent,
    background,
    border,
    _color,
    color,
    $$scope,
    slots,
    click_handler
  ];
}
class IconButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$B, create_fragment$S, safe_not_equal, {
      Icon: 0,
      label: 1,
      show_label: 2,
      pending: 3,
      size: 4,
      padded: 5,
      highlight: 6,
      disabled: 7,
      hasPopup: 8,
      color: 13,
      transparent: 9,
      background: 10,
      border: 11
    });
  }
}
function create_fragment$R(ctx) {
  let div1;
  let div0;
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[5].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[4],
    null
  );
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (default_slot) default_slot.c();
      attr(div0, "class", "icon svelte-3w3rth");
      attr(div1, "class", "empty svelte-3w3rth");
      attr(div1, "aria-label", "Empty value");
      toggle_class(
        div1,
        "small",
        /*size*/
        ctx[0] === "small"
      );
      toggle_class(
        div1,
        "large",
        /*size*/
        ctx[0] === "large"
      );
      toggle_class(
        div1,
        "unpadded_box",
        /*unpadded_box*/
        ctx[1]
      );
      toggle_class(
        div1,
        "small_parent",
        /*parent_height*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (default_slot) {
        default_slot.m(div0, null);
      }
      ctx[6](div1);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        16)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[4],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[4]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[4],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*size*/
      1) {
        toggle_class(
          div1,
          "small",
          /*size*/
          ctx2[0] === "small"
        );
      }
      if (!current || dirty & /*size*/
      1) {
        toggle_class(
          div1,
          "large",
          /*size*/
          ctx2[0] === "large"
        );
      }
      if (!current || dirty & /*unpadded_box*/
      2) {
        toggle_class(
          div1,
          "unpadded_box",
          /*unpadded_box*/
          ctx2[1]
        );
      }
      if (!current || dirty & /*parent_height*/
      8) {
        toggle_class(
          div1,
          "small_parent",
          /*parent_height*/
          ctx2[3]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      if (default_slot) default_slot.d(detaching);
      ctx[6](null);
    }
  };
}
function compare_el_to_parent(el2) {
  var _a;
  if (!el2) return false;
  const { height: el_height } = el2.getBoundingClientRect();
  const { height: parent_height2 } = ((_a = el2.parentElement) == null ? void 0 : _a.getBoundingClientRect()) || { height: el_height };
  return el_height > parent_height2 + 2;
}
function instance$A($$self, $$props, $$invalidate) {
  let parent_height;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { size = "small" } = $$props;
  let { unpadded_box = false } = $$props;
  let el;
  function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      el = $$value;
      $$invalidate(2, el);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("size" in $$props2) $$invalidate(0, size = $$props2.size);
    if ("unpadded_box" in $$props2) $$invalidate(1, unpadded_box = $$props2.unpadded_box);
    if ("$$scope" in $$props2) $$invalidate(4, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*el*/
    4) {
      $$invalidate(3, parent_height = compare_el_to_parent(el));
    }
  };
  return [size, unpadded_box, el, parent_height, $$scope, slots, div1_binding];
}
class Empty extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$A, create_fragment$R, safe_not_equal, { size: 0, unpadded_box: 1 });
  }
}
function create_fragment$Q(ctx) {
  let svg;
  let path;
  let circle;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      circle = svg_element("circle");
      attr(path, "d", "M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z");
      attr(circle, "cx", "12");
      attr(circle, "cy", "13");
      attr(circle, "r", "4");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "1.5");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-camera");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
      append(svg, circle);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Camera extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$Q, safe_not_equal, {});
  }
}
function create_fragment$P(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "M5 13L9 17L19 7");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "1.5");
      attr(path, "stroke-linecap", "round");
      attr(path, "stroke-linejoin", "round");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "stroke-width", "1.5");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "color", "currentColor");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Check extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$P, safe_not_equal, {});
  }
}
function create_fragment$O(ctx) {
  let svg;
  let circle;
  return {
    c() {
      svg = svg_element("svg");
      circle = svg_element("circle");
      attr(circle, "cx", "12");
      attr(circle, "cy", "12");
      attr(circle, "r", "10");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "stroke-width", "1.5");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-circle");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, circle);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Circle extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$O, safe_not_equal, {});
  }
}
function create_fragment$N(ctx) {
  let svg;
  let g;
  let path0;
  let path1;
  return {
    c() {
      svg = svg_element("svg");
      g = svg_element("g");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "d", "M18,6L6.087,17.913");
      set_style(path0, "fill", "none");
      set_style(path0, "fill-rule", "nonzero");
      set_style(path0, "stroke-width", "2px");
      attr(g, "transform", "matrix(1.14096,-0.140958,-0.140958,1.14096,-0.0559523,0.0559523)");
      attr(path1, "d", "M4.364,4.364L19.636,19.636");
      set_style(path1, "fill", "none");
      set_style(path1, "fill-rule", "nonzero");
      set_style(path1, "stroke-width", "2px");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "version", "1.1");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "xmlns:xlink", "http://www.w3.org/1999/xlink");
      attr(svg, "xml:space", "preserve");
      attr(svg, "stroke", "currentColor");
      set_style(svg, "fill-rule", "evenodd");
      set_style(svg, "clip-rule", "evenodd");
      set_style(svg, "stroke-linecap", "round");
      set_style(svg, "stroke-linejoin", "round");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, g);
      append(g, path0);
      append(svg, path1);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Clear extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$N, safe_not_equal, {});
  }
}
function create_fragment$M(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "M23,20a5,5,0,0,0-3.89,1.89L11.8,17.32a4.46,4.46,0,0,0,0-2.64l7.31-4.57A5,5,0,1,0,18,7a4.79,4.79,0,0,0,.2,1.32l-7.31,4.57a5,5,0,1,0,0,6.22l7.31,4.57A4.79,4.79,0,0,0,18,25a5,5,0,1,0,5-5ZM23,4a3,3,0,1,1-3,3A3,3,0,0,1,23,4ZM7,19a3,3,0,1,1,3-3A3,3,0,0,1,7,19Zm16,9a3,3,0,1,1,3-3A3,3,0,0,1,23,28Z");
      attr(path, "fill", "currentColor");
      attr(svg, "id", "icon");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 32 32");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Community extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$M, safe_not_equal, {});
  }
}
function create_fragment$L(ctx) {
  let svg;
  let path0;
  let path1;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "fill", "currentColor");
      attr(path0, "d", "M28 10v18H10V10h18m0-2H10a2 2 0 0 0-2 2v18a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2V10a2 2 0 0 0-2-2Z");
      attr(path1, "fill", "currentColor");
      attr(path1, "d", "M4 18H2V4a2 2 0 0 1 2-2h14v2H4Z");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 33 33");
      attr(svg, "color", "currentColor");
      attr(svg, "aria-hidden", "true");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Copy extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$L, safe_not_equal, {});
  }
}
function create_fragment$K(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "fill", "currentColor");
      attr(path, "d", "M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4zm0-10l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10l10-10z");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 32 32");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Download extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$K, safe_not_equal, {});
  }
}
function create_fragment$J(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "M5 8l4 4 4-4z");
      attr(svg, "class", "dropdown-arrow svelte-145leq6");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 18 18");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class DropdownArrow extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$J, safe_not_equal, {});
  }
}
function create_fragment$I(ctx) {
  let svg;
  let rect;
  let circle;
  let polyline;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      circle = svg_element("circle");
      polyline = svg_element("polyline");
      attr(rect, "x", "3");
      attr(rect, "y", "3");
      attr(rect, "width", "18");
      attr(rect, "height", "18");
      attr(rect, "rx", "2");
      attr(rect, "ry", "2");
      attr(circle, "cx", "8.5");
      attr(circle, "cy", "8.5");
      attr(circle, "r", "1.5");
      attr(polyline, "points", "21 15 16 10 5 21");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "1.5");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-image");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, circle);
      append(svg, polyline);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
let Image$1 = class Image extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$I, safe_not_equal, {});
  }
};
function create_fragment$H(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "fill", "currentColor");
      attr(path, "d", "M200 32h-36.26a47.92 47.92 0 0 0-71.48 0H56a16 16 0 0 0-16 16v168a16 16 0 0 0 16 16h144a16 16 0 0 0 16-16V48a16 16 0 0 0-16-16m-72 0a32 32 0 0 1 32 32H96a32 32 0 0 1 32-32m72 184H56V48h26.75A47.9 47.9 0 0 0 80 64v8a8 8 0 0 0 8 8h80a8 8 0 0 0 8-8v-8a47.9 47.9 0 0 0-2.75-16H200Z");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 256 256");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class ImagePaste extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$H, safe_not_equal, {});
  }
}
function create_fragment$G(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "2");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-maximize");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Maximize extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$G, safe_not_equal, {});
  }
}
function create_fragment$F(ctx) {
  let svg;
  let path0;
  let path1;
  let line0;
  let line1;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      line0 = svg_element("line");
      line1 = svg_element("line");
      attr(path0, "d", "M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z");
      attr(path1, "d", "M19 10v2a7 7 0 0 1-14 0v-2");
      attr(line0, "x1", "12");
      attr(line0, "y1", "19");
      attr(line0, "x2", "12");
      attr(line0, "y2", "23");
      attr(line1, "x1", "8");
      attr(line1, "y1", "23");
      attr(line1, "x2", "16");
      attr(line1, "y2", "23");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "2");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-mic");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, line0);
      append(svg, line1);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Microphone extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$F, safe_not_equal, {});
  }
}
function create_fragment$E(ctx) {
  let svg;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "2");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-minimize");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Minimize extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$E, safe_not_equal, {});
  }
}
function create_fragment$D(ctx) {
  let svg;
  let rect;
  let svg_stroke_width_value;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      attr(rect, "x", "3");
      attr(rect, "y", "3");
      attr(rect, "width", "18");
      attr(rect, "height", "18");
      attr(rect, "rx", "2");
      attr(rect, "ry", "2");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(
        svg,
        "fill",
        /*fill*/
        ctx[0]
      );
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", svg_stroke_width_value = `${/*stroke_width*/
      ctx[1]}`);
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-square");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*fill*/
      1) {
        attr(
          svg,
          "fill",
          /*fill*/
          ctx2[0]
        );
      }
      if (dirty & /*stroke_width*/
      2 && svg_stroke_width_value !== (svg_stroke_width_value = `${/*stroke_width*/
      ctx2[1]}`)) {
        attr(svg, "stroke-width", svg_stroke_width_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function instance$z($$self, $$props, $$invalidate) {
  let { fill = "currentColor" } = $$props;
  let { stroke_width = 1.5 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("fill" in $$props2) $$invalidate(0, fill = $$props2.fill);
    if ("stroke_width" in $$props2) $$invalidate(1, stroke_width = $$props2.stroke_width);
  };
  return [fill, stroke_width];
}
class Square extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$z, create_fragment$D, safe_not_equal, { fill: 0, stroke_width: 1 });
  }
}
function create_fragment$C(ctx) {
  let svg;
  let path;
  let polyline;
  let line;
  return {
    c() {
      svg = svg_element("svg");
      path = svg_element("path");
      polyline = svg_element("polyline");
      line = svg_element("line");
      attr(path, "d", "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4");
      attr(polyline, "points", "17 8 12 3 7 8");
      attr(line, "x1", "12");
      attr(line, "y1", "3");
      attr(line, "x2", "12");
      attr(line, "y2", "15");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "90%");
      attr(svg, "height", "90%");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "fill", "none");
      attr(svg, "stroke", "currentColor");
      attr(svg, "stroke-width", "2");
      attr(svg, "stroke-linecap", "round");
      attr(svg, "stroke-linejoin", "round");
      attr(svg, "class", "feather feather-upload");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path);
      append(svg, polyline);
      append(svg, line);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
let Upload$1 = class Upload extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$C, safe_not_equal, {});
  }
};
function create_fragment$B(ctx) {
  let svg;
  let path0;
  let path1;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "fill", "currentColor");
      attr(path0, "d", "M12 2c-4.963 0-9 4.038-9 9c0 3.328 1.82 6.232 4.513 7.79l-2.067 1.378A1 1 0 0 0 6 22h12a1 1 0 0 0 .555-1.832l-2.067-1.378C19.18 17.232 21 14.328 21 11c0-4.962-4.037-9-9-9zm0 16c-3.859 0-7-3.141-7-7c0-3.86 3.141-7 7-7s7 3.14 7 7c0 3.859-3.141 7-7 7z");
      attr(path1, "fill", "currentColor");
      attr(path1, "d", "M12 6c-2.757 0-5 2.243-5 5s2.243 5 5 5s5-2.243 5-5s-2.243-5-5-5zm0 8c-1.654 0-3-1.346-3-3s1.346-3 3-3s3 1.346 3 3s-1.346 3-3 3z");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 24 24");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
let Webcam$1 = class Webcam extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$B, safe_not_equal, {});
  }
};
function create_fragment$A(ctx) {
  let svg;
  let circle;
  let animateTransform;
  return {
    c() {
      svg = svg_element("svg");
      circle = svg_element("circle");
      animateTransform = svg_element("animateTransform");
      attr(animateTransform, "attributeName", "transform");
      attr(animateTransform, "type", "rotate");
      attr(animateTransform, "from", "0 25 25");
      attr(animateTransform, "to", "360 25 25");
      attr(animateTransform, "repeatCount", "indefinite");
      attr(circle, "cx", "25");
      attr(circle, "cy", "25");
      attr(circle, "r", "20");
      attr(circle, "fill", "none");
      attr(circle, "stroke-width", "3.0");
      attr(circle, "stroke-linecap", "round");
      attr(circle, "stroke-dasharray", "94.2477796076938 94.2477796076938");
      attr(circle, "stroke-dashoffset", "0");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "width", "100%");
      attr(svg, "height", "100%");
      attr(svg, "viewBox", "0 0 50 50");
      attr(svg, "class", "svelte-pb9pol");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, circle);
      append(circle, animateTransform);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
class Spinner extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$A, safe_not_equal, {});
  }
}
const color_values = [
  { color: "red", primary: 600, secondary: 100 },
  { color: "green", primary: 600, secondary: 100 },
  { color: "blue", primary: 600, secondary: 100 },
  { color: "yellow", primary: 500, secondary: 100 },
  { color: "purple", primary: 600, secondary: 100 },
  { color: "teal", primary: 600, secondary: 100 },
  { color: "orange", primary: 600, secondary: 100 },
  { color: "cyan", primary: 600, secondary: 100 },
  { color: "lime", primary: 500, secondary: 100 },
  { color: "pink", primary: 600, secondary: 100 }
];
const tw_colors = {
  inherit: "inherit",
  current: "currentColor",
  transparent: "transparent",
  black: "#000",
  white: "#fff",
  slate: {
    50: "#f8fafc",
    100: "#f1f5f9",
    200: "#e2e8f0",
    300: "#cbd5e1",
    400: "#94a3b8",
    500: "#64748b",
    600: "#475569",
    700: "#334155",
    800: "#1e293b",
    900: "#0f172a",
    950: "#020617"
  },
  gray: {
    50: "#f9fafb",
    100: "#f3f4f6",
    200: "#e5e7eb",
    300: "#d1d5db",
    400: "#9ca3af",
    500: "#6b7280",
    600: "#4b5563",
    700: "#374151",
    800: "#1f2937",
    900: "#111827",
    950: "#030712"
  },
  zinc: {
    50: "#fafafa",
    100: "#f4f4f5",
    200: "#e4e4e7",
    300: "#d4d4d8",
    400: "#a1a1aa",
    500: "#71717a",
    600: "#52525b",
    700: "#3f3f46",
    800: "#27272a",
    900: "#18181b",
    950: "#09090b"
  },
  neutral: {
    50: "#fafafa",
    100: "#f5f5f5",
    200: "#e5e5e5",
    300: "#d4d4d4",
    400: "#a3a3a3",
    500: "#737373",
    600: "#525252",
    700: "#404040",
    800: "#262626",
    900: "#171717",
    950: "#0a0a0a"
  },
  stone: {
    50: "#fafaf9",
    100: "#f5f5f4",
    200: "#e7e5e4",
    300: "#d6d3d1",
    400: "#a8a29e",
    500: "#78716c",
    600: "#57534e",
    700: "#44403c",
    800: "#292524",
    900: "#1c1917",
    950: "#0c0a09"
  },
  red: {
    50: "#fef2f2",
    100: "#fee2e2",
    200: "#fecaca",
    300: "#fca5a5",
    400: "#f87171",
    500: "#ef4444",
    600: "#dc2626",
    700: "#b91c1c",
    800: "#991b1b",
    900: "#7f1d1d",
    950: "#450a0a"
  },
  orange: {
    50: "#fff7ed",
    100: "#ffedd5",
    200: "#fed7aa",
    300: "#fdba74",
    400: "#fb923c",
    500: "#f97316",
    600: "#ea580c",
    700: "#c2410c",
    800: "#9a3412",
    900: "#7c2d12",
    950: "#431407"
  },
  amber: {
    50: "#fffbeb",
    100: "#fef3c7",
    200: "#fde68a",
    300: "#fcd34d",
    400: "#fbbf24",
    500: "#f59e0b",
    600: "#d97706",
    700: "#b45309",
    800: "#92400e",
    900: "#78350f",
    950: "#451a03"
  },
  yellow: {
    50: "#fefce8",
    100: "#fef9c3",
    200: "#fef08a",
    300: "#fde047",
    400: "#facc15",
    500: "#eab308",
    600: "#ca8a04",
    700: "#a16207",
    800: "#854d0e",
    900: "#713f12",
    950: "#422006"
  },
  lime: {
    50: "#f7fee7",
    100: "#ecfccb",
    200: "#d9f99d",
    300: "#bef264",
    400: "#a3e635",
    500: "#84cc16",
    600: "#65a30d",
    700: "#4d7c0f",
    800: "#3f6212",
    900: "#365314",
    950: "#1a2e05"
  },
  green: {
    50: "#f0fdf4",
    100: "#dcfce7",
    200: "#bbf7d0",
    300: "#86efac",
    400: "#4ade80",
    500: "#22c55e",
    600: "#16a34a",
    700: "#15803d",
    800: "#166534",
    900: "#14532d",
    950: "#052e16"
  },
  emerald: {
    50: "#ecfdf5",
    100: "#d1fae5",
    200: "#a7f3d0",
    300: "#6ee7b7",
    400: "#34d399",
    500: "#10b981",
    600: "#059669",
    700: "#047857",
    800: "#065f46",
    900: "#064e3b",
    950: "#022c22"
  },
  teal: {
    50: "#f0fdfa",
    100: "#ccfbf1",
    200: "#99f6e4",
    300: "#5eead4",
    400: "#2dd4bf",
    500: "#14b8a6",
    600: "#0d9488",
    700: "#0f766e",
    800: "#115e59",
    900: "#134e4a",
    950: "#042f2e"
  },
  cyan: {
    50: "#ecfeff",
    100: "#cffafe",
    200: "#a5f3fc",
    300: "#67e8f9",
    400: "#22d3ee",
    500: "#06b6d4",
    600: "#0891b2",
    700: "#0e7490",
    800: "#155e75",
    900: "#164e63",
    950: "#083344"
  },
  sky: {
    50: "#f0f9ff",
    100: "#e0f2fe",
    200: "#bae6fd",
    300: "#7dd3fc",
    400: "#38bdf8",
    500: "#0ea5e9",
    600: "#0284c7",
    700: "#0369a1",
    800: "#075985",
    900: "#0c4a6e",
    950: "#082f49"
  },
  blue: {
    50: "#eff6ff",
    100: "#dbeafe",
    200: "#bfdbfe",
    300: "#93c5fd",
    400: "#60a5fa",
    500: "#3b82f6",
    600: "#2563eb",
    700: "#1d4ed8",
    800: "#1e40af",
    900: "#1e3a8a",
    950: "#172554"
  },
  indigo: {
    50: "#eef2ff",
    100: "#e0e7ff",
    200: "#c7d2fe",
    300: "#a5b4fc",
    400: "#818cf8",
    500: "#6366f1",
    600: "#4f46e5",
    700: "#4338ca",
    800: "#3730a3",
    900: "#312e81",
    950: "#1e1b4b"
  },
  violet: {
    50: "#f5f3ff",
    100: "#ede9fe",
    200: "#ddd6fe",
    300: "#c4b5fd",
    400: "#a78bfa",
    500: "#8b5cf6",
    600: "#7c3aed",
    700: "#6d28d9",
    800: "#5b21b6",
    900: "#4c1d95",
    950: "#2e1065"
  },
  purple: {
    50: "#faf5ff",
    100: "#f3e8ff",
    200: "#e9d5ff",
    300: "#d8b4fe",
    400: "#c084fc",
    500: "#a855f7",
    600: "#9333ea",
    700: "#7e22ce",
    800: "#6b21a8",
    900: "#581c87",
    950: "#3b0764"
  },
  fuchsia: {
    50: "#fdf4ff",
    100: "#fae8ff",
    200: "#f5d0fe",
    300: "#f0abfc",
    400: "#e879f9",
    500: "#d946ef",
    600: "#c026d3",
    700: "#a21caf",
    800: "#86198f",
    900: "#701a75",
    950: "#4a044e"
  },
  pink: {
    50: "#fdf2f8",
    100: "#fce7f3",
    200: "#fbcfe8",
    300: "#f9a8d4",
    400: "#f472b6",
    500: "#ec4899",
    600: "#db2777",
    700: "#be185d",
    800: "#9d174d",
    900: "#831843",
    950: "#500724"
  },
  rose: {
    50: "#fff1f2",
    100: "#ffe4e6",
    200: "#fecdd3",
    300: "#fda4af",
    400: "#fb7185",
    500: "#f43f5e",
    600: "#e11d48",
    700: "#be123c",
    800: "#9f1239",
    900: "#881337",
    950: "#4c0519"
  }
};
color_values.reduce(
  (acc, { color, primary, secondary }) => ({
    ...acc,
    [color]: {
      primary: tw_colors[color][primary],
      secondary: tw_colors[color][secondary]
    }
  }),
  {}
);
class ShareError extends Error {
  constructor(message) {
    super(message);
    this.name = "ShareError";
  }
}
async function uploadToHuggingFace(data, type) {
  var _a;
  if (window.__gradio_space__ == null) {
    throw new ShareError("Must be on Spaces to share.");
  }
  let blob;
  let contentType;
  let filename;
  {
    let url;
    if (typeof data === "object" && data.url) {
      url = data.url;
    } else if (typeof data === "string") {
      url = data;
    } else {
      throw new Error("Invalid data format for URL type");
    }
    const response = await fetch(url);
    blob = await response.blob();
    contentType = response.headers.get("content-type") || "";
    filename = response.headers.get("content-disposition") || "";
  }
  const file = new File([blob], filename, { type: contentType });
  const uploadResponse = await fetch("https://huggingface.co/uploads", {
    method: "POST",
    body: file,
    headers: {
      "Content-Type": file.type,
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  if (!uploadResponse.ok) {
    if ((_a = uploadResponse.headers.get("content-type")) == null ? void 0 : _a.includes("application/json")) {
      const error = await uploadResponse.json();
      throw new ShareError(`Upload failed: ${error.error}`);
    }
    throw new ShareError(`Upload failed.`);
  }
  const result = await uploadResponse.text();
  return result;
}
function create_fragment$z(ctx) {
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: Community,
      label: (
        /*i18n*/
        ctx[2]("common.share")
      ),
      pending: (
        /*pending*/
        ctx[3]
      )
    }
  });
  iconbutton.$on(
    "click",
    /*click_handler*/
    ctx[5]
  );
  return {
    c() {
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const iconbutton_changes = {};
      if (dirty & /*i18n*/
      4) iconbutton_changes.label = /*i18n*/
      ctx2[2]("common.share");
      if (dirty & /*pending*/
      8) iconbutton_changes.pending = /*pending*/
      ctx2[3];
      iconbutton.$set(iconbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(iconbutton, detaching);
    }
  };
}
function instance$y($$self, $$props, $$invalidate) {
  const dispatch2 = createEventDispatcher();
  let { formatter } = $$props;
  let { value } = $$props;
  let { i18n } = $$props;
  let pending = false;
  const click_handler = async () => {
    try {
      $$invalidate(3, pending = true);
      const formatted = await formatter(value);
      dispatch2("share", { description: formatted });
    } catch (e) {
      console.error(e);
      let message = e instanceof ShareError ? e.message : "Share failed.";
      dispatch2("error", message);
    } finally {
      $$invalidate(3, pending = false);
    }
  };
  $$self.$$set = ($$props2) => {
    if ("formatter" in $$props2) $$invalidate(0, formatter = $$props2.formatter);
    if ("value" in $$props2) $$invalidate(1, value = $$props2.value);
    if ("i18n" in $$props2) $$invalidate(2, i18n = $$props2.i18n);
  };
  return [formatter, value, i18n, pending, dispatch2, click_handler];
}
class ShareButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$y, create_fragment$z, safe_not_equal, { formatter: 0, value: 1, i18n: 2 });
  }
}
const RE_HEADING = /^(#\s*)(.+)$/m;
function inject(text2) {
  const trimmed_text = text2.trim();
  const heading_match = trimmed_text.match(RE_HEADING);
  if (!heading_match) {
    return [false, trimmed_text || false];
  }
  const [full_match, , heading_content] = heading_match;
  const _heading = heading_content.trim();
  if (trimmed_text === full_match) {
    return [_heading, false];
  }
  const heading_end_index = heading_match.index !== void 0 ? heading_match.index + full_match.length : 0;
  const remaining_text = trimmed_text.substring(heading_end_index).trim();
  const _paragraph2 = remaining_text || false;
  return [_heading, _paragraph2];
}
function create_else_block_1$3(ctx) {
  let uploadicon;
  let current;
  uploadicon = new Upload$1({});
  return {
    c() {
      create_component(uploadicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(uploadicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(uploadicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(uploadicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(uploadicon, detaching);
    }
  };
}
function create_if_block_4$9(ctx) {
  let imagepaste;
  let current;
  imagepaste = new ImagePaste({});
  return {
    c() {
      create_component(imagepaste.$$.fragment);
    },
    m(target, anchor) {
      mount_component(imagepaste, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(imagepaste.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(imagepaste.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(imagepaste, detaching);
    }
  };
}
function create_else_block$9(ctx) {
  let t0_value = (
    /*i18n*/
    ctx[1](
      /*defs*/
      ctx[7][
        /*type*/
        ctx[0]
      ] || /*defs*/
      ctx[7].file
    ) + ""
  );
  let t0;
  let t1;
  let if_block_anchor;
  let if_block = (
    /*mode*/
    ctx[3] !== "short" && create_if_block_3$b(ctx)
  );
  return {
    c() {
      t0 = text(t0_value);
      t1 = space();
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*i18n, type*/
      3 && t0_value !== (t0_value = /*i18n*/
      ctx2[1](
        /*defs*/
        ctx2[7][
          /*type*/
          ctx2[0]
        ] || /*defs*/
        ctx2[7].file
      ) + "")) set_data(t0, t0_value);
      if (
        /*mode*/
        ctx2[3] !== "short"
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3$b(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block$k(ctx) {
  let t;
  let if_block1_anchor;
  let if_block0 = (
    /*heading*/
    ctx[6] && create_if_block_2$d(ctx)
  );
  let if_block1 = (
    /*paragraph*/
    ctx[5] && create_if_block_1$e(ctx)
  );
  return {
    c() {
      if (if_block0) if_block0.c();
      t = space();
      if (if_block1) if_block1.c();
      if_block1_anchor = empty();
    },
    m(target, anchor) {
      if (if_block0) if_block0.m(target, anchor);
      insert(target, t, anchor);
      if (if_block1) if_block1.m(target, anchor);
      insert(target, if_block1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*heading*/
        ctx2[6]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_2$d(ctx2);
          if_block0.c();
          if_block0.m(t.parentNode, t);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (
        /*paragraph*/
        ctx2[5]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_1$e(ctx2);
          if_block1.c();
          if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(t);
        detach(if_block1_anchor);
      }
      if (if_block0) if_block0.d(detaching);
      if (if_block1) if_block1.d(detaching);
    }
  };
}
function create_if_block_3$b(ctx) {
  let span;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[1]("common.or") + ""
  );
  let t1;
  let t2;
  let t3;
  let t4_value = (
    /*message*/
    (ctx[2] || /*i18n*/
    ctx[1]("upload_text.click_to_upload")) + ""
  );
  let t4;
  return {
    c() {
      span = element("span");
      t0 = text("- ");
      t1 = text(t1_value);
      t2 = text(" -");
      t3 = space();
      t4 = text(t4_value);
      attr(span, "class", "or svelte-1xg7h5n");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t0);
      append(span, t1);
      append(span, t2);
      insert(target, t3, anchor);
      insert(target, t4, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*i18n*/
      2 && t1_value !== (t1_value = /*i18n*/
      ctx2[1]("common.or") + "")) set_data(t1, t1_value);
      if (dirty & /*message, i18n*/
      6 && t4_value !== (t4_value = /*message*/
      (ctx2[2] || /*i18n*/
      ctx2[1]("upload_text.click_to_upload")) + "")) set_data(t4, t4_value);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
        detach(t3);
        detach(t4);
      }
    }
  };
}
function create_if_block_2$d(ctx) {
  let h2;
  let t;
  return {
    c() {
      h2 = element("h2");
      t = text(
        /*heading*/
        ctx[6]
      );
      attr(h2, "class", "svelte-1xg7h5n");
    },
    m(target, anchor) {
      insert(target, h2, anchor);
      append(h2, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*heading*/
      64) set_data(
        t,
        /*heading*/
        ctx2[6]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(h2);
      }
    }
  };
}
function create_if_block_1$e(ctx) {
  let p;
  let t;
  return {
    c() {
      p = element("p");
      t = text(
        /*paragraph*/
        ctx[5]
      );
      attr(p, "class", "svelte-1xg7h5n");
    },
    m(target, anchor) {
      insert(target, p, anchor);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*paragraph*/
      32) set_data(
        t,
        /*paragraph*/
        ctx2[5]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(p);
      }
    }
  };
}
function create_fragment$y(ctx) {
  let div;
  let span;
  let current_block_type_index;
  let if_block0;
  let t;
  let current;
  const if_block_creators = [create_if_block_4$9, create_else_block_1$3];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*type*/
      ctx2[0] === "clipboard"
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  function select_block_type_1(ctx2, dirty) {
    if (
      /*heading*/
      ctx2[6] || /*paragraph*/
      ctx2[5]
    ) return create_if_block$k;
    return create_else_block$9;
  }
  let current_block_type = select_block_type_1(ctx);
  let if_block1 = current_block_type(ctx);
  return {
    c() {
      div = element("div");
      span = element("span");
      if_block0.c();
      t = space();
      if_block1.c();
      attr(span, "class", "icon-wrap svelte-1xg7h5n");
      toggle_class(
        span,
        "hovered",
        /*hovered*/
        ctx[4]
      );
      attr(div, "class", "wrap svelte-1xg7h5n");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      if_blocks[current_block_type_index].m(span, null);
      append(div, t);
      if_block1.m(div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index !== previous_block_index) {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        }
        transition_in(if_block0, 1);
        if_block0.m(span, null);
      }
      if (!current || dirty & /*hovered*/
      16) {
        toggle_class(
          span,
          "hovered",
          /*hovered*/
          ctx2[4]
        );
      }
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if_block1.d(1);
        if_block1 = current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div, null);
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if_blocks[current_block_type_index].d();
      if_block1.d();
    }
  };
}
function instance$x($$self, $$props, $$invalidate) {
  let heading2;
  let paragraph2;
  let { type = "file" } = $$props;
  let { i18n } = $$props;
  let { message = void 0 } = $$props;
  let { mode = "full" } = $$props;
  let { hovered = false } = $$props;
  let { placeholder = void 0 } = $$props;
  const defs = {
    image: "upload_text.drop_image",
    video: "upload_text.drop_video",
    audio: "upload_text.drop_audio",
    file: "upload_text.drop_file",
    csv: "upload_text.drop_csv",
    gallery: "upload_text.drop_gallery",
    clipboard: "upload_text.paste_clipboard"
  };
  $$self.$$set = ($$props2) => {
    if ("type" in $$props2) $$invalidate(0, type = $$props2.type);
    if ("i18n" in $$props2) $$invalidate(1, i18n = $$props2.i18n);
    if ("message" in $$props2) $$invalidate(2, message = $$props2.message);
    if ("mode" in $$props2) $$invalidate(3, mode = $$props2.mode);
    if ("hovered" in $$props2) $$invalidate(4, hovered = $$props2.hovered);
    if ("placeholder" in $$props2) $$invalidate(8, placeholder = $$props2.placeholder);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*placeholder*/
    256) {
      $$invalidate(6, [heading2, paragraph2] = placeholder ? inject(placeholder) : [false, false], heading2, ($$invalidate(5, paragraph2), $$invalidate(8, placeholder)));
    }
  };
  return [type, i18n, message, mode, hovered, paragraph2, heading2, defs, placeholder];
}
class UploadText extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$x, create_fragment$y, safe_not_equal, {
      type: 0,
      i18n: 1,
      message: 2,
      mode: 3,
      hovered: 4,
      placeholder: 8
    });
  }
}
function create_if_block$j(ctx) {
  let span;
  let show_if_3 = (
    /*sources*/
    ctx[1].includes("upload")
  );
  let t0;
  let show_if_2 = (
    /*sources*/
    ctx[1].includes("microphone")
  );
  let t1;
  let show_if_1 = (
    /*sources*/
    ctx[1].includes("webcam")
  );
  let t2;
  let show_if = (
    /*sources*/
    ctx[1].includes("clipboard")
  );
  let current;
  let if_block0 = show_if_3 && create_if_block_4$8(ctx);
  let if_block1 = show_if_2 && create_if_block_3$a(ctx);
  let if_block2 = show_if_1 && create_if_block_2$c(ctx);
  let if_block3 = show_if && create_if_block_1$d(ctx);
  return {
    c() {
      span = element("span");
      if (if_block0) if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      t2 = space();
      if (if_block3) if_block3.c();
      attr(span, "class", "source-selection svelte-15ls1gu");
      attr(span, "data-testid", "source-select");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if (if_block0) if_block0.m(span, null);
      append(span, t0);
      if (if_block1) if_block1.m(span, null);
      append(span, t1);
      if (if_block2) if_block2.m(span, null);
      append(span, t2);
      if (if_block3) if_block3.m(span, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty & /*sources*/
      2) show_if_3 = /*sources*/
      ctx2[1].includes("upload");
      if (show_if_3) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*sources*/
          2) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_4$8(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(span, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (dirty & /*sources*/
      2) show_if_2 = /*sources*/
      ctx2[1].includes("microphone");
      if (show_if_2) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*sources*/
          2) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_3$a(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(span, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (dirty & /*sources*/
      2) show_if_1 = /*sources*/
      ctx2[1].includes("webcam");
      if (show_if_1) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty & /*sources*/
          2) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_2$c(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(span, t2);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (dirty & /*sources*/
      2) show_if = /*sources*/
      ctx2[1].includes("clipboard");
      if (show_if) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
          if (dirty & /*sources*/
          2) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block_1$d(ctx2);
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(span, null);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      transition_in(if_block3);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      transition_out(if_block3);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
      if (if_block3) if_block3.d();
    }
  };
}
function create_if_block_4$8(ctx) {
  let button;
  let upload;
  let current;
  let mounted;
  let dispose;
  upload = new Upload$1({});
  return {
    c() {
      button = element("button");
      create_component(upload.$$.fragment);
      attr(button, "class", "icon svelte-15ls1gu");
      attr(button, "aria-label", "Upload file");
      toggle_class(
        button,
        "selected",
        /*active_source*/
        ctx[0] === "upload" || !/*active_source*/
        ctx[0]
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(upload, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[6]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*active_source*/
      1) {
        toggle_class(
          button,
          "selected",
          /*active_source*/
          ctx2[0] === "upload" || !/*active_source*/
          ctx2[0]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(upload.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(upload.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(upload);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_3$a(ctx) {
  let button;
  let microphone;
  let current;
  let mounted;
  let dispose;
  microphone = new Microphone({});
  return {
    c() {
      button = element("button");
      create_component(microphone.$$.fragment);
      attr(button, "class", "icon svelte-15ls1gu");
      attr(button, "aria-label", "Record audio");
      toggle_class(
        button,
        "selected",
        /*active_source*/
        ctx[0] === "microphone"
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(microphone, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*active_source*/
      1) {
        toggle_class(
          button,
          "selected",
          /*active_source*/
          ctx2[0] === "microphone"
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(microphone.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(microphone.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(microphone);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_2$c(ctx) {
  let button;
  let webcam;
  let current;
  let mounted;
  let dispose;
  webcam = new Webcam$1({});
  return {
    c() {
      button = element("button");
      create_component(webcam.$$.fragment);
      attr(button, "class", "icon svelte-15ls1gu");
      attr(button, "aria-label", "Capture from camera");
      toggle_class(
        button,
        "selected",
        /*active_source*/
        ctx[0] === "webcam"
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(webcam, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[8]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*active_source*/
      1) {
        toggle_class(
          button,
          "selected",
          /*active_source*/
          ctx2[0] === "webcam"
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(webcam.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(webcam.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(webcam);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$d(ctx) {
  let button;
  let imagepaste;
  let current;
  let mounted;
  let dispose;
  imagepaste = new ImagePaste({});
  return {
    c() {
      button = element("button");
      create_component(imagepaste.$$.fragment);
      attr(button, "class", "icon svelte-15ls1gu");
      attr(button, "aria-label", "Paste from clipboard");
      toggle_class(
        button,
        "selected",
        /*active_source*/
        ctx[0] === "clipboard"
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(imagepaste, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_3*/
          ctx[9]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*active_source*/
      1) {
        toggle_class(
          button,
          "selected",
          /*active_source*/
          ctx2[0] === "clipboard"
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(imagepaste.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(imagepaste.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(imagepaste);
      mounted = false;
      dispose();
    }
  };
}
function create_fragment$x(ctx) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*unique_sources*/
    ctx[2].length > 1 && create_if_block$j(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (
        /*unique_sources*/
        ctx2[2].length > 1
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*unique_sources*/
          4) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$j(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function instance$w($$self, $$props, $$invalidate) {
  let unique_sources;
  let { sources } = $$props;
  let { active_source } = $$props;
  let { handle_clear = () => {
  } } = $$props;
  let { handle_select = () => {
  } } = $$props;
  async function handle_select_source(source) {
    handle_clear();
    $$invalidate(0, active_source = source);
    handle_select(source);
  }
  const click_handler = () => handle_select_source("upload");
  const click_handler_1 = () => handle_select_source("microphone");
  const click_handler_2 = () => handle_select_source("webcam");
  const click_handler_3 = () => handle_select_source("clipboard");
  $$self.$$set = ($$props2) => {
    if ("sources" in $$props2) $$invalidate(1, sources = $$props2.sources);
    if ("active_source" in $$props2) $$invalidate(0, active_source = $$props2.active_source);
    if ("handle_clear" in $$props2) $$invalidate(4, handle_clear = $$props2.handle_clear);
    if ("handle_select" in $$props2) $$invalidate(5, handle_select = $$props2.handle_select);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*sources*/
    2) {
      $$invalidate(2, unique_sources = [...new Set(sources)]);
    }
  };
  return [
    active_source,
    sources,
    unique_sources,
    handle_select_source,
    handle_clear,
    handle_select,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_3
  ];
}
class SelectSource extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$w, create_fragment$x, safe_not_equal, {
      sources: 1,
      active_source: 0,
      handle_clear: 4,
      handle_select: 5
    });
  }
}
function create_fragment$w(ctx) {
  let div;
  let div_class_value;
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[3].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[2],
    null
  );
  return {
    c() {
      div = element("div");
      if (default_slot) default_slot.c();
      attr(div, "class", div_class_value = null_to_empty(`icon-button-wrapper ${/*top_panel*/
      ctx[0] ? "top-panel" : ""} ${/*display_top_corner*/
      ctx[1] ? "display-top-corner" : "hide-top-corner"}`) + " svelte-1h0hs6p");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) {
        default_slot.m(div, null);
      }
      current = true;
    },
    p(ctx2, [dirty]) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty & /*$$scope*/
        4)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[2],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[2]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[2],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty & /*top_panel, display_top_corner*/
      3 && div_class_value !== (div_class_value = null_to_empty(`icon-button-wrapper ${/*top_panel*/
      ctx2[0] ? "top-panel" : ""} ${/*display_top_corner*/
      ctx2[1] ? "display-top-corner" : "hide-top-corner"}`) + " svelte-1h0hs6p")) {
        attr(div, "class", div_class_value);
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (default_slot) default_slot.d(detaching);
    }
  };
}
function instance$v($$self, $$props, $$invalidate) {
  let { $$slots: slots = {}, $$scope } = $$props;
  let { top_panel = true } = $$props;
  let { display_top_corner = false } = $$props;
  $$self.$$set = ($$props2) => {
    if ("top_panel" in $$props2) $$invalidate(0, top_panel = $$props2.top_panel);
    if ("display_top_corner" in $$props2) $$invalidate(1, display_top_corner = $$props2.display_top_corner);
    if ("$$scope" in $$props2) $$invalidate(2, $$scope = $$props2.$$scope);
  };
  return [top_panel, display_top_corner, $$scope, slots];
}
class IconButtonWrapper extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$v, create_fragment$w, safe_not_equal, { top_panel: 0, display_top_corner: 1 });
  }
}
function create_else_block$8(ctx) {
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: { Icon: Maximize, label: "Fullscreen" }
  });
  iconbutton.$on(
    "click",
    /*click_handler_1*/
    ctx[3]
  );
  return {
    c() {
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(iconbutton, detaching);
    }
  };
}
function create_if_block$i(ctx) {
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: Minimize,
      label: "Exit fullscreen mode"
    }
  });
  iconbutton.$on(
    "click",
    /*click_handler*/
    ctx[2]
  );
  return {
    c() {
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(iconbutton, detaching);
    }
  };
}
function create_fragment$v(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$i, create_else_block$8];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*fullscreen*/
      ctx2[0]
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance$u($$self, $$props, $$invalidate) {
  const dispatch2 = createEventDispatcher();
  let { fullscreen } = $$props;
  const click_handler = () => dispatch2("fullscreen", false);
  const click_handler_1 = () => dispatch2("fullscreen", true);
  $$self.$$set = ($$props2) => {
    if ("fullscreen" in $$props2) $$invalidate(0, fullscreen = $$props2.fullscreen);
  };
  return [fullscreen, dispatch2, click_handler, click_handler_1];
}
class FullscreenButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$u, create_fragment$v, safe_not_equal, { fullscreen: 0 });
  }
}
var has$1 = Object.prototype.hasOwnProperty;
function find(iter, tar, key) {
  for (key of iter.keys()) {
    if (dequal$1(key, tar)) return key;
  }
}
function dequal$1(foo, bar) {
  var ctor, len, tmp;
  if (foo === bar) return true;
  if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
    if (ctor === Date) return foo.getTime() === bar.getTime();
    if (ctor === RegExp) return foo.toString() === bar.toString();
    if (ctor === Array) {
      if ((len = foo.length) === bar.length) {
        while (len-- && dequal$1(foo[len], bar[len])) ;
      }
      return len === -1;
    }
    if (ctor === Set) {
      if (foo.size !== bar.size) {
        return false;
      }
      for (len of foo) {
        tmp = len;
        if (tmp && typeof tmp === "object") {
          tmp = find(bar, tmp);
          if (!tmp) return false;
        }
        if (!bar.has(tmp)) return false;
      }
      return true;
    }
    if (ctor === Map) {
      if (foo.size !== bar.size) {
        return false;
      }
      for (len of foo) {
        tmp = len[0];
        if (tmp && typeof tmp === "object") {
          tmp = find(bar, tmp);
          if (!tmp) return false;
        }
        if (!dequal$1(len[1], bar.get(tmp))) {
          return false;
        }
      }
      return true;
    }
    if (ctor === ArrayBuffer) {
      foo = new Uint8Array(foo);
      bar = new Uint8Array(bar);
    } else if (ctor === DataView) {
      if ((len = foo.byteLength) === bar.byteLength) {
        while (len-- && foo.getInt8(len) === bar.getInt8(len)) ;
      }
      return len === -1;
    }
    if (ArrayBuffer.isView(foo)) {
      if ((len = foo.byteLength) === bar.byteLength) {
        while (len-- && foo[len] === bar[len]) ;
      }
      return len === -1;
    }
    if (!ctor || typeof foo === "object") {
      len = 0;
      for (ctor in foo) {
        if (has$1.call(foo, ctor) && ++len && !has$1.call(bar, ctor)) return false;
        if (!(ctor in bar) || !dequal$1(foo[ctor], bar[ctor])) return false;
      }
      return Object.keys(bar).length === len;
    }
  }
  return foo !== foo && bar !== bar;
}
const subscriber_queue = [];
function writable(value, start = noop) {
  let stop;
  const subscribers = /* @__PURE__ */ new Set();
  function set(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) {
            subscriber_queue[i][0](subscriber_queue[i + 1]);
          }
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update2(fn) {
    set(fn(value));
  }
  function subscribe2(run2, invalidate = noop) {
    const subscriber = [run2, invalidate];
    subscribers.add(subscriber);
    if (subscribers.size === 1) {
      stop = start(set, update2) || noop;
    }
    run2(value);
    return () => {
      subscribers.delete(subscriber);
      if (subscribers.size === 0 && stop) {
        stop();
        stop = null;
      }
    };
  }
  return { set, update: update2, subscribe: subscribe2 };
}
function get_sort_status$1(name, sort_columns, headers) {
  if (!sort_columns.length) return "none";
  const sort_item = sort_columns.find((item) => {
    const col = item.col;
    if (col < 0 || col >= headers.length) return false;
    return headers[col] === name;
  });
  if (!sort_item) return "none";
  return sort_item.direction;
}
function sort_data$1(data, sort_columns) {
  if (!data || !data.length || !data[0]) {
    return [];
  }
  if (sort_columns.length > 0) {
    const row_indices = [...Array(data.length)].map((_, i) => i);
    row_indices.sort((row_a_idx, row_b_idx) => {
      const row_a = data[row_a_idx];
      const row_b = data[row_b_idx];
      for (const { col: sort_by, direction } of sort_columns) {
        if (!row_a || !row_b || sort_by < 0 || sort_by >= row_a.length || sort_by >= row_b.length || !row_a[sort_by] || !row_b[sort_by]) {
          continue;
        }
        const val_a = row_a[sort_by].value;
        const val_b = row_b[sort_by].value;
        const comparison = val_a < val_b ? -1 : val_a > val_b ? 1 : 0;
        if (comparison !== 0) {
          return direction === "asc" ? comparison : -comparison;
        }
      }
      return 0;
    });
    return row_indices;
  }
  return [...Array(data.length)].map((_, i) => i);
}
function sort_data_and_preserve_selection$1(data, display_value, styling, sort_columns, selected, get_current_indices2) {
  let id = null;
  if (selected && selected[0] in data && selected[1] in data[selected[0]]) {
    id = data[selected[0]][selected[1]].id;
  }
  sort_table_data$1(data, display_value, styling, sort_columns);
  let new_selected = selected;
  if (id) {
    const [i, j] = get_current_indices2(id, data);
    new_selected = [i, j];
  }
  return { data, selected: new_selected };
}
function filter_data$1(data, filter_columns) {
  if (!data || !data.length || !data[0]) {
    return [];
  }
  let row_indices = [...Array(data.length)].map((_, i) => i);
  if (filter_columns.length > 0) {
    filter_columns.forEach((column) => {
      if (column.datatype === "string") {
        switch (column.filter) {
          case "Contains":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return (_a = data[i][column.col]) == null ? void 0 : _a.value.toString().includes(column.value);
              }
            );
            break;
          case "Does not contain":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return !((_a = data[i][column.col]) == null ? void 0 : _a.value.toString().includes(column.value));
              }
            );
            break;
          case "Starts with":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return (_a = data[i][column.col]) == null ? void 0 : _a.value.toString().startsWith(column.value);
              }
            );
            break;
          case "Ends with":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return (_a = data[i][column.col]) == null ? void 0 : _a.value.toString().endsWith(column.value);
              }
            );
            break;
          case "Is":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return ((_a = data[i][column.col]) == null ? void 0 : _a.value.toString()) === column.value;
              }
            );
            break;
          case "Is not":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return !(((_a = data[i][column.col]) == null ? void 0 : _a.value.toString()) === column.value);
              }
            );
            break;
          case "Is empty":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return ((_a = data[i][column.col]) == null ? void 0 : _a.value.toString()) === "";
              }
            );
            break;
          case "Is not empty":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return !(((_a = data[i][column.col]) == null ? void 0 : _a.value.toString()) === "");
              }
            );
            break;
        }
      } else if (column.datatype === "number") {
        switch (column.filter) {
          case "=":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return Number((_b = data[i][column.col]) == null ? void 0 : _b.value) === Number(column.value);
              }
              return false;
            });
            break;
          case "≠":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return !(Number((_b = data[i][column.col]) == null ? void 0 : _b.value) === Number(column.value));
              }
              return false;
            });
            break;
          case ">":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return Number((_b = data[i][column.col]) == null ? void 0 : _b.value) > Number(column.value);
              }
              return false;
            });
            break;
          case "<":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return Number((_b = data[i][column.col]) == null ? void 0 : _b.value) < Number(column.value);
              }
              return false;
            });
            break;
          case "≥":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return Number((_b = data[i][column.col]) == null ? void 0 : _b.value) >= Number(column.value);
              }
              return false;
            });
            break;
          case "≤":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value)) && !isNaN(Number(column.value))) {
                return Number((_b = data[i][column.col]) == null ? void 0 : _b.value) <= Number(column.value);
              }
              return false;
            });
            break;
          case "Is empty":
            row_indices = row_indices.filter(
              (i) => {
                var _a;
                return ((_a = data[i][column.col]) == null ? void 0 : _a.value.toString()) === "";
              }
            );
            break;
          case "Is not empty":
            row_indices = row_indices.filter((i) => {
              var _a, _b;
              if (!isNaN(Number((_a = data[i][column.col]) == null ? void 0 : _a.value))) {
                return !(((_b = data[i][column.col]) == null ? void 0 : _b.value.toString()) === "");
              }
              return false;
            });
            break;
        }
      }
    });
    return row_indices;
  }
  return [...Array(data.length)].map((_, i) => i);
}
function filter_data_and_preserve_selection$1(data, display_value, styling, filter_columns, selected, get_current_indices2, original_data, original_display_value, original_styling) {
  let id = null;
  if (selected && selected[0] in data && selected[1] in data[selected[0]]) {
    id = data[selected[0]][selected[1]].id;
  }
  filter_table_data$1(
    data,
    display_value,
    styling,
    filter_columns,
    original_data,
    original_display_value,
    original_styling
  );
  let new_selected = selected;
  if (id) {
    const [i, j] = get_current_indices2(id, data);
    new_selected = [i, j];
  }
  return { data, selected: new_selected };
}
var EOL = {}, EOF = {}, QUOTE = 34, NEWLINE = 10, RETURN = 13;
function objectConverter(columns) {
  return new Function("d", "return {" + columns.map(function(name, i) {
    return JSON.stringify(name) + ": d[" + i + '] || ""';
  }).join(",") + "}");
}
function customConverter(columns, f) {
  var object = objectConverter(columns);
  return function(row, i) {
    return f(object(row), i, columns);
  };
}
function inferColumns(rows) {
  var columnSet = /* @__PURE__ */ Object.create(null), columns = [];
  rows.forEach(function(row) {
    for (var column in row) {
      if (!(column in columnSet)) {
        columns.push(columnSet[column] = column);
      }
    }
  });
  return columns;
}
function pad(value, width) {
  var s = value + "", length = s.length;
  return length < width ? new Array(width - length + 1).join(0) + s : s;
}
function formatYear(year) {
  return year < 0 ? "-" + pad(-year, 6) : year > 9999 ? "+" + pad(year, 6) : pad(year, 4);
}
function formatDate(date) {
  var hours = date.getUTCHours(), minutes = date.getUTCMinutes(), seconds = date.getUTCSeconds(), milliseconds = date.getUTCMilliseconds();
  return isNaN(date) ? "Invalid Date" : formatYear(date.getUTCFullYear()) + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2) + (milliseconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "." + pad(milliseconds, 3) + "Z" : seconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "Z" : minutes || hours ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + "Z" : "");
}
function dsvFormat(delimiter) {
  var reFormat = new RegExp('["' + delimiter + "\n\r]"), DELIMITER = delimiter.charCodeAt(0);
  function parse(text2, f) {
    var convert, columns, rows = parseRows(text2, function(row, i) {
      if (convert) return convert(row, i - 1);
      columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
    });
    rows.columns = columns || [];
    return rows;
  }
  function parseRows(text2, f) {
    var rows = [], N = text2.length, I = 0, n = 0, t, eof = N <= 0, eol = false;
    if (text2.charCodeAt(N - 1) === NEWLINE) --N;
    if (text2.charCodeAt(N - 1) === RETURN) --N;
    function token() {
      if (eof) return EOF;
      if (eol) return eol = false, EOL;
      var i, j = I, c;
      if (text2.charCodeAt(j) === QUOTE) {
        while (I++ < N && text2.charCodeAt(I) !== QUOTE || text2.charCodeAt(++I) === QUOTE) ;
        if ((i = I) >= N) eof = true;
        else if ((c = text2.charCodeAt(I++)) === NEWLINE) eol = true;
        else if (c === RETURN) {
          eol = true;
          if (text2.charCodeAt(I) === NEWLINE) ++I;
        }
        return text2.slice(j + 1, i - 1).replace(/""/g, '"');
      }
      while (I < N) {
        if ((c = text2.charCodeAt(i = I++)) === NEWLINE) eol = true;
        else if (c === RETURN) {
          eol = true;
          if (text2.charCodeAt(I) === NEWLINE) ++I;
        } else if (c !== DELIMITER) continue;
        return text2.slice(j, i);
      }
      return eof = true, text2.slice(j, N);
    }
    while ((t = token()) !== EOF) {
      var row = [];
      while (t !== EOL && t !== EOF) row.push(t), t = token();
      if (f && (row = f(row, n++)) == null) continue;
      rows.push(row);
    }
    return rows;
  }
  function preformatBody(rows, columns) {
    return rows.map(function(row) {
      return columns.map(function(column) {
        return formatValue(row[column]);
      }).join(delimiter);
    });
  }
  function format(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join("\n");
  }
  function formatBody(rows, columns) {
    if (columns == null) columns = inferColumns(rows);
    return preformatBody(rows, columns).join("\n");
  }
  function formatRows(rows) {
    return rows.map(formatRow).join("\n");
  }
  function formatRow(row) {
    return row.map(formatValue).join(delimiter);
  }
  function formatValue(value) {
    return value == null ? "" : value instanceof Date ? formatDate(value) : reFormat.test(value += "") ? '"' + value.replace(/"/g, '""') + '"' : value;
  }
  return {
    parse,
    parseRows,
    format,
    formatBody,
    formatRows,
    formatRow,
    formatValue
  };
}
function get_max$1(data) {
  if (!data || !data.length) return [];
  let max = data[0].slice();
  for (let i = 0; i < data.length; i++) {
    for (let j = 0; j < data[i].length; j++) {
      if (`${max[j].value}`.length < `${data[i][j].value}`.length) {
        max[j] = data[i][j];
      }
    }
  }
  return max;
}
function sort_table_data$1(data, display_value, styling, sort_columns) {
  if (!sort_columns.length) return;
  if (!data || !data.length) return;
  const indices = sort_data$1(data, sort_columns);
  const new_data = indices.map((i) => data[i]);
  data.splice(0, data.length, ...new_data);
  if (display_value) {
    const new_display = indices.map((i) => display_value[i]);
    display_value.splice(0, display_value.length, ...new_display);
  }
  if (styling) {
    const new_styling = indices.map((i) => styling[i]);
    styling.splice(0, styling.length, ...new_styling);
  }
}
function filter_table_data$1(data, display_value, styling, filter_columns, original_data, original_display_value, original_styling) {
  const base_data = original_data ?? data;
  const base_display_value = original_display_value ?? display_value;
  const base_styling = original_styling ?? styling;
  if (!filter_columns.length) {
    data.splice(0, data.length, ...base_data.map((row) => [...row]));
    if (display_value && base_display_value) {
      display_value.splice(
        0,
        display_value.length,
        ...base_display_value.map((row) => [...row])
      );
    }
    if (styling && base_styling) {
      styling.splice(0, styling.length, ...base_styling.map((row) => [...row]));
    }
    return;
  }
  if (!data || !data.length) return;
  const indices = filter_data$1(base_data, filter_columns);
  const new_data = indices.map((i) => base_data[i]);
  data.splice(0, data.length, ...new_data);
  if (display_value && base_display_value) {
    const new_display = indices.map((i) => base_display_value[i]);
    display_value.splice(0, display_value.length, ...new_display);
  }
  if (styling && base_styling) {
    const new_styling = indices.map((i) => base_styling[i]);
    styling.splice(0, styling.length, ...new_styling);
  }
}
async function copy_table_data$1(data, selected_cells) {
  if (!data || !data.length) return;
  const cells_to_copy = selected_cells || data.flatMap((row, r) => row.map((_, c) => [r, c]));
  const csv = cells_to_copy.reduce(
    (acc, [row, col]) => {
      acc[row] = acc[row] || {};
      const value = String(data[row][col].value);
      acc[row][col] = value.includes(",") || value.includes('"') || value.includes("\n") ? `"${value.replace(/"/g, '""')}"` : value;
      return acc;
    },
    {}
  );
  const rows = Object.keys(csv).sort((a, b) => +a - +b);
  if (!rows.length) return;
  const cols = Object.keys(csv[rows[0]]).sort((a, b) => +a - +b);
  const text2 = rows.map((r) => cols.map((c) => csv[r][c] || "").join(",")).join("\n");
  try {
    await navigator.clipboard.writeText(text2);
  } catch (err) {
    throw new Error("Failed to copy to clipboard: " + err.message);
  }
}
function guess_delimiter$1(text2, possibleDelimiters) {
  return possibleDelimiters.filter(weedOut);
  function weedOut(delimiter) {
    var cache = -1;
    return text2.split("\n").every(checkLength);
    function checkLength(line) {
      if (!line) return true;
      var length = line.split(delimiter).length;
      if (cache < 0) cache = length;
      return cache === length && length > 1;
    }
  }
}
function data_uri_to_blob$1(data_uri) {
  const byte_str = atob(data_uri.split(",")[1]);
  const mime_str = data_uri.split(",")[0].split(":")[1].split(";")[0];
  const ab = new ArrayBuffer(byte_str.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byte_str.length; i++) {
    ia[i] = byte_str.charCodeAt(i);
  }
  return new Blob([ab], { type: mime_str });
}
function handle_file_upload$1(data_uri, update_headers, update_values) {
  const blob = data_uri_to_blob$1(data_uri);
  const reader = new FileReader();
  reader.addEventListener("loadend", (e) => {
    var _a;
    if (!((_a = e == null ? void 0 : e.target) == null ? void 0 : _a.result) || typeof e.target.result !== "string") return;
    const [delimiter] = guess_delimiter$1(e.target.result, [",", "	"]);
    const [head, ...rest] = dsvFormat(delimiter).parseRows(e.target.result);
    update_headers(head);
    update_values(rest);
  });
  reader.readAsText(blob);
}
function is_cell_in_selection$1(coords, selected_cells) {
  const [row, col] = coords;
  return selected_cells.some(([r, c]) => r === row && c === col);
}
function is_cell_selected$1(cell, selected_cells) {
  const [row, col] = cell;
  if (!selected_cells.some(([r, c]) => r === row && c === col)) return "";
  const up = selected_cells.some(([r, c]) => r === row - 1 && c === col);
  const down = selected_cells.some(([r, c]) => r === row + 1 && c === col);
  const left = selected_cells.some(([r, c]) => r === row && c === col - 1);
  const right = selected_cells.some(([r, c]) => r === row && c === col + 1);
  return `cell-selected${up ? " no-top" : ""}${down ? " no-bottom" : ""}${left ? " no-left" : ""}${right ? " no-right" : ""}`;
}
function get_range_selection$1(start, end) {
  const [start_row, start_col] = start;
  const [end_row, end_col] = end;
  const min_row = Math.min(start_row, end_row);
  const max_row = Math.max(start_row, end_row);
  const min_col = Math.min(start_col, end_col);
  const max_col = Math.max(start_col, end_col);
  const cells = [];
  cells.push(start);
  for (let i = min_row; i <= max_row; i++) {
    for (let j = min_col; j <= max_col; j++) {
      if (i === start_row && j === start_col) continue;
      cells.push([i, j]);
    }
  }
  return cells;
}
function handle_selection$1(current, selected_cells, event) {
  if (event.shiftKey && selected_cells.length > 0) {
    return get_range_selection$1(
      selected_cells[selected_cells.length - 1],
      current
    );
  }
  if (event.metaKey || event.ctrlKey) {
    const is_cell_match = ([r, c]) => r === current[0] && c === current[1];
    const index = selected_cells.findIndex(is_cell_match);
    return index === -1 ? [...selected_cells, current] : selected_cells.filter((_, i) => i !== index);
  }
  return [current];
}
function handle_delete_key$1(data, selected_cells) {
  const new_data = data.map((row) => [...row]);
  selected_cells.forEach(([row, col]) => {
    if (new_data[row] && new_data[row][col]) {
      new_data[row][col] = { ...new_data[row][col], value: "" };
    }
  });
  return new_data;
}
function should_show_cell_menu$1(cell, selected_cells, editable) {
  const [row, col] = cell;
  return editable && selected_cells.length === 1 && selected_cells[0][0] === row && selected_cells[0][1] === col;
}
function get_next_cell_coordinates$1(current, data, shift_key) {
  var _a, _b, _c;
  const [row, col] = current;
  const direction = shift_key ? -1 : 1;
  if ((_a = data[row]) == null ? void 0 : _a[col + direction]) {
    return [row, col + direction];
  }
  const next_row = row + (direction > 0 ? 1 : 0);
  const prev_row = row + (direction < 0 ? -1 : 0);
  if (direction > 0 && ((_b = data[next_row]) == null ? void 0 : _b[0])) {
    return [next_row, 0];
  }
  if (direction < 0 && ((_c = data[prev_row]) == null ? void 0 : _c[data[0].length - 1])) {
    return [prev_row, data[0].length - 1];
  }
  return false;
}
function move_cursor$1(event, current_coords, data) {
  var _a;
  const key = event.key;
  const dir = {
    ArrowRight: [0, 1],
    ArrowLeft: [0, -1],
    ArrowDown: [1, 0],
    ArrowUp: [-1, 0]
  }[key];
  let i, j;
  if (event.metaKey || event.ctrlKey) {
    if (key === "ArrowRight") {
      i = current_coords[0];
      j = data[0].length - 1;
    } else if (key === "ArrowLeft") {
      i = current_coords[0];
      j = 0;
    } else if (key === "ArrowDown") {
      i = data.length - 1;
      j = current_coords[1];
    } else if (key === "ArrowUp") {
      i = 0;
      j = current_coords[1];
    } else {
      return false;
    }
  } else {
    i = current_coords[0] + dir[0];
    j = current_coords[1] + dir[1];
  }
  if (i < 0 && j <= 0) {
    return false;
  }
  const is_data = (_a = data[i]) == null ? void 0 : _a[j];
  if (is_data) {
    return [i, j];
  }
  return false;
}
function get_current_indices$1(id, data) {
  return data.reduce(
    (acc, arr, i) => {
      const j = arr.reduce(
        (_acc, _data, k) => id === _data.id ? k : _acc,
        -1
      );
      return j === -1 ? acc : [i, j];
    },
    [-1, -1]
  );
}
function handle_click_outside$1(event, parent) {
  const [trigger] = event.composedPath();
  return !parent.contains(trigger);
}
function calculate_selection_positions$1(selected, data, els, parent, table) {
  var _a, _b;
  const [row, col] = selected;
  if (!((_a = data[row]) == null ? void 0 : _a[col])) {
    return { col_pos: "0px", row_pos: void 0 };
  }
  const cell_id = data[row][col].id;
  const cell_el = (_b = els[cell_id]) == null ? void 0 : _b.cell;
  if (!cell_el) {
    return { col_pos: "0px", row_pos: void 0 };
  }
  const cell_rect = cell_el.getBoundingClientRect();
  const table_rect = table.getBoundingClientRect();
  const col_pos = `${cell_rect.left - table_rect.left + cell_rect.width / 2}px`;
  const row_pos = `${cell_rect.top - table_rect.top + cell_rect.height / 2}px`;
  return { col_pos, row_pos };
}
const DATAFRAME_KEY$1 = Symbol("dataframe");
function create_actions$1(state, context) {
  const update_state = (updater) => state.update((s) => ({ ...s, ...updater(s) }));
  const add_row = (data, make_id2, index) => {
    var _a;
    const new_row = ((_a = data[0]) == null ? void 0 : _a.length) ? Array(data[0].length).fill(null).map(() => ({ value: "", id: make_id2() })) : [{ value: "", id: make_id2() }];
    const new_data = [...data];
    index !== void 0 ? new_data.splice(index, 0, new_row) : new_data.push(new_row);
    return new_data;
  };
  const add_col = (data, headers, make_id2, index) => {
    const new_headers = [...headers, `Header ${headers.length + 1}`];
    const new_data = data.map((row) => [...row, { value: "", id: make_id2() }]);
    if (index !== void 0) {
      new_headers.splice(index, 0, new_headers.pop());
      new_data.forEach((row) => row.splice(index, 0, row.pop()));
    }
    return { data: new_data, headers: new_headers };
  };
  const update_array = (source, target) => {
    if (source && target) {
      target.splice(0, target.length, ...JSON.parse(JSON.stringify(source)));
    }
  };
  return {
    handle_search: (query) => update_state((s) => ({ current_search_query: query })),
    handle_sort: (col, direction) => update_state((s) => {
      const sort_cols = s.sort_state.sort_columns.filter(
        (c) => c.col !== col
      );
      if (!s.sort_state.sort_columns.some(
        (c) => c.col === col && c.direction === direction
      )) {
        sort_cols.push({ col, direction });
      }
      const initial_data = s.sort_state.initial_data || (context.data && sort_cols.length > 0 ? {
        data: JSON.parse(JSON.stringify(context.data)),
        display_value: context.display_value ? JSON.parse(JSON.stringify(context.display_value)) : null,
        styling: context.styling ? JSON.parse(JSON.stringify(context.styling)) : null
      } : null);
      return {
        sort_state: {
          ...s.sort_state,
          sort_columns: sort_cols.slice(-3),
          initial_data
        }
      };
    }),
    handle_filter: (col, datatype, filter, value) => update_state((s) => {
      const filter_cols = s.filter_state.filter_columns.some(
        (c) => c.col === col
      ) ? s.filter_state.filter_columns.filter((c) => c.col !== col) : [
        ...s.filter_state.filter_columns,
        { col, datatype, filter, value }
      ];
      const initial_data = s.filter_state.initial_data || (context.data && filter_cols.length > 0 ? {
        data: JSON.parse(JSON.stringify(context.data)),
        display_value: context.display_value ? JSON.parse(JSON.stringify(context.display_value)) : null,
        styling: context.styling ? JSON.parse(JSON.stringify(context.styling)) : null
      } : null);
      return {
        filter_state: {
          ...s.filter_state,
          filter_columns: filter_cols,
          initial_data
        }
      };
    }),
    get_sort_status: (name, headers) => {
      const s = get_store_value(state);
      const sort_item = s.sort_state.sort_columns.find(
        (item) => headers[item.col] === name
      );
      return sort_item ? sort_item.direction : "none";
    },
    sort_data: (data, display_value, styling) => {
      const {
        sort_state: { sort_columns }
      } = get_store_value(state);
      if (sort_columns.length)
        sort_table_data$1(data, display_value, styling, sort_columns);
    },
    update_row_order: (data) => update_state((s) => ({
      sort_state: {
        ...s.sort_state,
        row_order: s.sort_state.sort_columns.length && data[0] ? [...Array(data.length)].map((_, i) => i).sort((a, b) => {
          var _a, _b, _c, _d;
          for (const { col, direction } of s.sort_state.sort_columns) {
            const comp = (((_b = (_a = data[a]) == null ? void 0 : _a[col]) == null ? void 0 : _b.value) ?? "") < (((_d = (_c = data[b]) == null ? void 0 : _c[col]) == null ? void 0 : _d.value) ?? "") ? -1 : 1;
            return direction === "asc" ? comp : -comp;
          }
          return 0;
        }) : [...Array(data.length)].map((_, i) => i)
      }
    })),
    filter_data: (data) => {
      var _a;
      const query = (_a = get_store_value(state).current_search_query) == null ? void 0 : _a.toLowerCase();
      return query ? data.filter(
        (row) => row.some(
          (cell) => String(cell == null ? void 0 : cell.value).toLowerCase().includes(query)
        )
      ) : data;
    },
    add_row,
    add_col,
    add_row_at: (data, index, position, make_id2) => add_row(data, make_id2, position === "above" ? index : index + 1),
    add_col_at: (data, headers, index, position, make_id2) => add_col(data, headers, make_id2, position === "left" ? index : index + 1),
    delete_row: (data, index) => data.length > 1 ? data.filter((_, i) => i !== index) : data,
    delete_col: (data, headers, index) => headers.length > 1 ? {
      data: data.map((row) => row.filter((_, i) => i !== index)),
      headers: headers.filter((_, i) => i !== index)
    } : { data, headers },
    delete_row_at: (data, index) => data.length > 1 ? [...data.slice(0, index), ...data.slice(index + 1)] : data,
    delete_col_at: (data, headers, index) => headers.length > 1 ? {
      data: data.map((row) => [
        ...row.slice(0, index),
        ...row.slice(index + 1)
      ]),
      headers: [...headers.slice(0, index), ...headers.slice(index + 1)]
    } : { data, headers },
    trigger_change: async (data, headers, previous_data, previous_headers, value_is_output, dispatch2) => {
      const s = get_store_value(state);
      if (s.current_search_query) return;
      const current_headers = headers.map((h) => h.value);
      const current_data = data.map((row) => row.map((cell) => cell.value));
      if (!dequal$1(current_data, previous_data) || !dequal$1(current_headers, previous_headers)) {
        if (!dequal$1(current_headers, previous_headers)) {
          update_state((s2) => ({
            sort_state: { sort_columns: [], row_order: [], initial_data: null },
            filter_state: { filter_columns: [], initial_data: null }
          }));
        }
        dispatch2("change", {
          data: data.map((row) => row.map((cell) => cell.value)),
          headers: current_headers,
          metadata: null
        });
        const index = s.ui_state.selected;
        if (index) {
          dispatch2("edit", {
            index,
            value: data[index[0]][index[1]].value,
            previous_value: previous_data[index[0]][index[1]]
          });
        }
        if (!value_is_output) dispatch2("input");
      }
    },
    reset_sort_state: () => update_state((s) => {
      if (s.sort_state.initial_data && context.data) {
        const original = s.sort_state.initial_data;
        update_array(original.data, context.data);
        update_array(original.display_value, context.display_value);
        update_array(original.styling, context.styling);
      }
      return {
        sort_state: { sort_columns: [], row_order: [], initial_data: null }
      };
    }),
    reset_filter_state: () => update_state((s) => {
      if (s.filter_state.initial_data && context.data) {
        const original = s.filter_state.initial_data;
        update_array(original.data, context.data);
        update_array(original.display_value, context.display_value);
        update_array(original.styling, context.styling);
      }
      return {
        filter_state: { filter_columns: [], initial_data: null }
      };
    }),
    set_active_cell_menu: (menu) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_cell_menu: menu }
    })),
    set_active_header_menu: (menu) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_header_menu: menu }
    })),
    set_selected_cells: (cells) => update_state((s) => ({
      ui_state: { ...s.ui_state, selected_cells: cells }
    })),
    set_selected: (selected) => update_state((s) => ({ ui_state: { ...s.ui_state, selected } })),
    set_editing: (editing) => update_state((s) => ({ ui_state: { ...s.ui_state, editing } })),
    clear_ui_state: () => update_state((s) => ({
      ui_state: {
        active_cell_menu: null,
        active_header_menu: null,
        selected_cells: [],
        selected: false,
        editing: false,
        header_edit: false,
        selected_header: false,
        active_button: null,
        copy_flash: false
      }
    })),
    set_header_edit: (header_index) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        selected_cells: [],
        selected_header: header_index,
        header_edit: header_index
      }
    })),
    set_selected_header: (header_index) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        selected_header: header_index,
        selected: false,
        selected_cells: []
      }
    })),
    handle_header_click: (col, editable) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        active_cell_menu: null,
        active_header_menu: null,
        selected: false,
        selected_cells: [],
        selected_header: col,
        header_edit: editable ? col : false
      }
    })),
    end_header_edit: (key) => {
      if (["Escape", "Enter", "Tab"].includes(key)) {
        update_state((s) => ({
          ui_state: { ...s.ui_state, selected: false, header_edit: false }
        }));
      }
    },
    get_selected_cells: () => get_store_value(state).ui_state.selected_cells,
    get_active_cell_menu: () => get_store_value(state).ui_state.active_cell_menu,
    get_active_button: () => get_store_value(state).ui_state.active_button,
    set_active_button: (button) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_button: button }
    })),
    set_copy_flash: (value) => update_state((s) => ({ ui_state: { ...s.ui_state, copy_flash: value } })),
    handle_cell_click: (event, row, col) => {
      var _a;
      event.preventDefault();
      event.stopPropagation();
      const s = get_store_value(state);
      if (s.config.show_row_numbers && col === -1) return;
      let actual_row = row;
      if (s.current_search_query && context.data) {
        const filtered_indices = [];
        context.data.forEach((dataRow, idx) => {
          if (dataRow.some(
            (cell) => {
              var _a2;
              return String(cell == null ? void 0 : cell.value).toLowerCase().includes(((_a2 = s.current_search_query) == null ? void 0 : _a2.toLowerCase()) || "");
            }
          )) {
            filtered_indices.push(idx);
          }
        });
        actual_row = filtered_indices[row] ?? row;
      }
      const cells = handle_selection$1(
        [actual_row, col],
        s.ui_state.selected_cells,
        event
      );
      update_state((s2) => ({
        ui_state: {
          ...s2.ui_state,
          active_cell_menu: null,
          active_header_menu: null,
          selected_header: false,
          header_edit: false,
          selected_cells: cells,
          selected: cells[0]
        }
      }));
      if (s.config.editable && cells.length === 1) {
        update_state((s2) => ({
          ui_state: { ...s2.ui_state, editing: [actual_row, col] }
        }));
        tick().then(
          () => {
            var _a2, _b;
            return (_b = (_a2 = context.els[context.data[actual_row][col].id]) == null ? void 0 : _a2.input) == null ? void 0 : _b.focus();
          }
        );
      } else {
        tick().then(() => {
          if (context.parent_element) {
            context.parent_element.focus();
          }
        });
      }
      (_a = context.dispatch) == null ? void 0 : _a.call(context, "select", {
        index: [actual_row, col],
        col_value: context.get_column(col),
        row_value: context.get_row(actual_row),
        value: context.get_data_at(actual_row, col)
      });
    },
    toggle_cell_menu: (event, row, col) => {
      event.stopPropagation();
      const current_menu = get_store_value(state).ui_state.active_cell_menu;
      if ((current_menu == null ? void 0 : current_menu.row) === row && current_menu.col === col) {
        update_state((s) => ({
          ui_state: { ...s.ui_state, active_cell_menu: null }
        }));
      } else {
        const cell = event.target.closest("td");
        if (cell) {
          const rect = cell.getBoundingClientRect();
          update_state((s) => ({
            ui_state: {
              ...s.ui_state,
              active_cell_menu: { row, col, x: rect.right, y: rect.bottom }
            }
          }));
        }
      }
    },
    toggle_cell_button: (row, col) => {
      const current_button = get_store_value(state).ui_state.active_button;
      const new_button = (current_button == null ? void 0 : current_button.type) === "cell" && current_button.row === row && current_button.col === col ? null : { type: "cell", row, col };
      update_state((s) => ({
        ui_state: { ...s.ui_state, active_button: new_button }
      }));
    },
    handle_select_column: (col) => {
      if (!context.data) return;
      const cells = context.data.map((_, row) => [row, col]);
      update_state((s) => ({
        ui_state: {
          ...s.ui_state,
          selected_cells: cells,
          selected: cells[0],
          editing: false
        }
      }));
      setTimeout(() => {
        var _a;
        return (_a = context.parent_element) == null ? void 0 : _a.focus();
      }, 0);
    },
    handle_select_row: (row) => {
      if (!context.data || !context.data[0]) return;
      const cells = context.data[0].map(
        (_, col) => [row, col]
      );
      update_state((s) => ({
        ui_state: {
          ...s.ui_state,
          selected_cells: cells,
          selected: cells[0],
          editing: false
        }
      }));
      setTimeout(() => {
        var _a;
        return (_a = context.parent_element) == null ? void 0 : _a.focus();
      }, 0);
    },
    get_next_cell_coordinates: get_next_cell_coordinates$1,
    get_range_selection: get_range_selection$1,
    move_cursor: move_cursor$1
  };
}
function create_dataframe_context$1(config) {
  const state = writable({
    config,
    current_search_query: null,
    sort_state: { sort_columns: [], row_order: [], initial_data: null },
    filter_state: { filter_columns: [], initial_data: null },
    ui_state: {
      active_cell_menu: null,
      active_header_menu: null,
      selected_cells: [],
      selected: false,
      editing: false,
      header_edit: false,
      selected_header: false,
      active_button: null,
      copy_flash: false
    }
  });
  const context = { state, actions: null };
  context.actions = create_actions$1(state, context);
  const instance_id = Symbol(
    `dataframe_${Math.random().toString(36).substring(2)}`
  );
  setContext(instance_id, context);
  setContext(DATAFRAME_KEY$1, { instance_id, context });
  return context;
}
var has = Object.prototype.hasOwnProperty;
function dequal(foo, bar) {
  var ctor, len;
  if (foo === bar) return true;
  if (foo && bar && (ctor = foo.constructor) === bar.constructor) {
    if (ctor === Date) return foo.getTime() === bar.getTime();
    if (ctor === RegExp) return foo.toString() === bar.toString();
    if (ctor === Array) {
      if ((len = foo.length) === bar.length) {
        while (len-- && dequal(foo[len], bar[len])) ;
      }
      return len === -1;
    }
    if (!ctor || typeof foo === "object") {
      len = 0;
      for (ctor in foo) {
        if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;
        if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false;
      }
      return Object.keys(bar).length === len;
    }
  }
  return foo !== foo && bar !== bar;
}
new Intl.Collator(0, { numeric: 1 }).compare;
async function prepare_files(files, is_stream) {
  return files.map(
    (f) => new FileData({
      path: f.name,
      orig_name: f.name,
      blob: f,
      size: f.size,
      mime_type: f.type,
      is_stream
    })
  );
}
class FileData {
  constructor({
    path,
    url,
    orig_name,
    size,
    blob,
    is_stream,
    mime_type,
    alt_text,
    b64
  }) {
    this.meta = { _type: "gradio.FileData" };
    this.path = path;
    this.url = url;
    this.orig_name = orig_name;
    this.size = size;
    this.blob = url ? void 0 : blob;
    this.is_stream = is_stream;
    this.mime_type = mime_type;
    this.alt_text = alt_text;
    this.b64 = b64;
  }
}
typeof process !== "undefined" && process.versions && process.versions.node;
class TextLineStream extends TransformStream {
  /** Constructs a new instance. */
  constructor(options = { allowCR: false }) {
    super({
      transform: (chars, controller) => {
        chars = __privateGet(this, _currentLine) + chars;
        while (true) {
          const lfIndex = chars.indexOf("\n");
          const crIndex = options.allowCR ? chars.indexOf("\r") : -1;
          if (crIndex !== -1 && crIndex !== chars.length - 1 && (lfIndex === -1 || lfIndex - 1 > crIndex)) {
            controller.enqueue(chars.slice(0, crIndex));
            chars = chars.slice(crIndex + 1);
            continue;
          }
          if (lfIndex === -1)
            break;
          const endIndex = chars[lfIndex - 1] === "\r" ? lfIndex - 1 : lfIndex;
          controller.enqueue(chars.slice(0, endIndex));
          chars = chars.slice(lfIndex + 1);
        }
        __privateSet(this, _currentLine, chars);
      },
      flush: (controller) => {
        if (__privateGet(this, _currentLine) === "")
          return;
        const currentLine = options.allowCR && __privateGet(this, _currentLine).endsWith("\r") ? __privateGet(this, _currentLine).slice(0, -1) : __privateGet(this, _currentLine);
        controller.enqueue(currentLine);
      }
    });
    __privateAdd(this, _currentLine, "");
  }
}
_currentLine = new WeakMap();
function create_if_block$h(ctx) {
  let div1;
  let span0;
  let div0;
  let progress_1;
  let t0_value = getProgress(
    /*file_to_display*/
    ctx[2]
  ) + "";
  let t0;
  let progress_1_value_value;
  let t1;
  let span1;
  let t2_value = (
    /*file_to_display*/
    ctx[2].orig_name + ""
  );
  let t2;
  return {
    c() {
      div1 = element("div");
      span0 = element("span");
      div0 = element("div");
      progress_1 = element("progress");
      t0 = text(t0_value);
      t1 = space();
      span1 = element("span");
      t2 = text(t2_value);
      set_style(progress_1, "visibility", "hidden");
      set_style(progress_1, "height", "0");
      set_style(progress_1, "width", "0");
      progress_1.value = progress_1_value_value = getProgress(
        /*file_to_display*/
        ctx[2]
      );
      attr(progress_1, "max", "100");
      attr(progress_1, "class", "svelte-cr2edf");
      attr(div0, "class", "progress-bar svelte-cr2edf");
      attr(span1, "class", "file-name svelte-cr2edf");
      attr(div1, "class", "file svelte-cr2edf");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, span0);
      append(span0, div0);
      append(div0, progress_1);
      append(progress_1, t0);
      append(div1, t1);
      append(div1, span1);
      append(span1, t2);
    },
    p(ctx2, dirty) {
      if (dirty & /*file_to_display*/
      4 && t0_value !== (t0_value = getProgress(
        /*file_to_display*/
        ctx2[2]
      ) + "")) set_data(t0, t0_value);
      if (dirty & /*file_to_display*/
      4 && progress_1_value_value !== (progress_1_value_value = getProgress(
        /*file_to_display*/
        ctx2[2]
      ))) {
        progress_1.value = progress_1_value_value;
      }
      if (dirty & /*file_to_display*/
      4 && t2_value !== (t2_value = /*file_to_display*/
      ctx2[2].orig_name + "")) set_data(t2, t2_value);
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
    }
  };
}
function create_fragment$u(ctx) {
  let div;
  let span;
  let t0;
  let t1_value = (
    /*files_with_progress*/
    ctx[0].length + ""
  );
  let t1;
  let t2;
  let t3_value = (
    /*files_with_progress*/
    ctx[0].length > 1 ? "files" : "file"
  );
  let t3;
  let t4;
  let t5;
  let if_block = (
    /*file_to_display*/
    ctx[2] && create_if_block$h(ctx)
  );
  return {
    c() {
      div = element("div");
      span = element("span");
      t0 = text("Uploading ");
      t1 = text(t1_value);
      t2 = space();
      t3 = text(t3_value);
      t4 = text("...");
      t5 = space();
      if (if_block) if_block.c();
      attr(span, "class", "uploading svelte-cr2edf");
      attr(div, "class", "wrap svelte-cr2edf");
      toggle_class(
        div,
        "progress",
        /*progress*/
        ctx[1]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      append(span, t0);
      append(span, t1);
      append(span, t2);
      append(span, t3);
      append(span, t4);
      append(div, t5);
      if (if_block) if_block.m(div, null);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*files_with_progress*/
      1 && t1_value !== (t1_value = /*files_with_progress*/
      ctx2[0].length + "")) set_data(t1, t1_value);
      if (dirty & /*files_with_progress*/
      1 && t3_value !== (t3_value = /*files_with_progress*/
      ctx2[0].length > 1 ? "files" : "file")) set_data(t3, t3_value);
      if (
        /*file_to_display*/
        ctx2[2]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$h(ctx2);
          if_block.c();
          if_block.m(div, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty & /*progress*/
      2) {
        toggle_class(
          div,
          "progress",
          /*progress*/
          ctx2[1]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (if_block) if_block.d();
    }
  };
}
function getProgress(file) {
  return file.progress * 100 / (file.size || 0) || 0;
}
function calculateTotalProgress(files2) {
  let totalProgress = 0;
  files2.forEach((file) => {
    totalProgress += getProgress(file);
  });
  document.documentElement.style.setProperty("--upload-progress-width", (totalProgress / files2.length).toFixed(2) + "%");
  return totalProgress / files2.length;
}
function instance$t($$self, $$props, $$invalidate) {
  let { upload_id } = $$props;
  let { root } = $$props;
  let { files } = $$props;
  let { stream_handler } = $$props;
  let stream;
  let progress = false;
  let current_file_upload;
  let file_to_display;
  let files_with_progress = files.map((file) => {
    return { ...file, progress: 0 };
  });
  const dispatch2 = createEventDispatcher();
  function handleProgress(filename, chunk_size) {
    $$invalidate(0, files_with_progress = files_with_progress.map((file) => {
      if (file.orig_name === filename) {
        file.progress += chunk_size;
      }
      return file;
    }));
  }
  onMount(async () => {
    stream = await stream_handler(new URL(`${root}/gradio_api/upload_progress?upload_id=${upload_id}`));
    if (stream == null) {
      throw new Error("Event source is not defined");
    }
    stream.onmessage = async function(event) {
      const _data = JSON.parse(event.data);
      if (!progress) $$invalidate(1, progress = true);
      if (_data.msg === "done") {
        stream == null ? void 0 : stream.close();
        dispatch2("done");
      } else {
        $$invalidate(7, current_file_upload = _data);
        handleProgress(_data.orig_name, _data.chunk_size);
      }
    };
  });
  onDestroy(() => {
    if (stream != null || stream != void 0) stream.close();
  });
  $$self.$$set = ($$props2) => {
    if ("upload_id" in $$props2) $$invalidate(3, upload_id = $$props2.upload_id);
    if ("root" in $$props2) $$invalidate(4, root = $$props2.root);
    if ("files" in $$props2) $$invalidate(5, files = $$props2.files);
    if ("stream_handler" in $$props2) $$invalidate(6, stream_handler = $$props2.stream_handler);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*files_with_progress*/
    1) {
      calculateTotalProgress(files_with_progress);
    }
    if ($$self.$$.dirty & /*current_file_upload, files_with_progress*/
    129) {
      $$invalidate(2, file_to_display = current_file_upload || files_with_progress[0]);
    }
  };
  return [
    files_with_progress,
    progress,
    file_to_display,
    upload_id,
    root,
    files,
    stream_handler,
    current_file_upload
  ];
}
class UploadProgress extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$t, create_fragment$u, safe_not_equal, {
      upload_id: 3,
      root: 4,
      files: 5,
      stream_handler: 6
    });
  }
}
function create_drag() {
  let hidden_input;
  let _options;
  return {
    drag(node, options = {}) {
      _options = options;
      function setup_hidden_input() {
        hidden_input = document.createElement("input");
        hidden_input.type = "file";
        hidden_input.style.display = "none";
        hidden_input.setAttribute("aria-label", "File upload");
        hidden_input.setAttribute("data-testid", "file-upload");
        const accept_options = Array.isArray(_options.accepted_types) ? _options.accepted_types.join(",") : _options.accepted_types || void 0;
        if (accept_options) {
          hidden_input.accept = accept_options;
        }
        hidden_input.multiple = _options.mode === "multiple" || false;
        if (_options.mode === "directory") {
          hidden_input.webkitdirectory = true;
          hidden_input.setAttribute("directory", "");
          hidden_input.setAttribute("mozdirectory", "");
        }
        node.appendChild(hidden_input);
      }
      setup_hidden_input();
      function handle_drag(e) {
        e.preventDefault();
        e.stopPropagation();
      }
      function handle_drag_enter(e) {
        var _a;
        e.preventDefault();
        e.stopPropagation();
        (_a = _options.on_drag_change) == null ? void 0 : _a.call(_options, true);
      }
      function handle_drag_leave(e) {
        var _a;
        e.preventDefault();
        e.stopPropagation();
        (_a = _options.on_drag_change) == null ? void 0 : _a.call(_options, false);
      }
      function handle_drop(e) {
        var _a, _b, _c;
        e.preventDefault();
        e.stopPropagation();
        (_a = _options.on_drag_change) == null ? void 0 : _a.call(_options, false);
        if (!((_b = e.dataTransfer) == null ? void 0 : _b.files)) return;
        const files = Array.from(e.dataTransfer.files);
        if (files.length > 0) {
          (_c = _options.on_files) == null ? void 0 : _c.call(_options, files);
        }
      }
      function handle_click() {
        if (!_options.disable_click) {
          hidden_input.value = "";
          hidden_input.click();
        }
      }
      function handle_file_input_change() {
        var _a;
        if (hidden_input.files) {
          const files = Array.from(hidden_input.files);
          if (files.length > 0) {
            (_a = _options.on_files) == null ? void 0 : _a.call(_options, files);
          }
        }
      }
      node.addEventListener("drag", handle_drag);
      node.addEventListener("dragstart", handle_drag);
      node.addEventListener("dragend", handle_drag);
      node.addEventListener("dragover", handle_drag);
      node.addEventListener("dragenter", handle_drag_enter);
      node.addEventListener("dragleave", handle_drag_leave);
      node.addEventListener("drop", handle_drop);
      node.addEventListener("click", handle_click);
      hidden_input.addEventListener("change", handle_file_input_change);
      return {
        update(new_options) {
          _options = new_options;
          hidden_input.remove();
          setup_hidden_input();
          hidden_input.addEventListener("change", handle_file_input_change);
        },
        destroy() {
          node.removeEventListener("drag", handle_drag);
          node.removeEventListener("dragstart", handle_drag);
          node.removeEventListener("dragend", handle_drag);
          node.removeEventListener("dragover", handle_drag);
          node.removeEventListener("dragenter", handle_drag_enter);
          node.removeEventListener("dragleave", handle_drag_leave);
          node.removeEventListener("drop", handle_drop);
          node.removeEventListener("click", handle_click);
          hidden_input.removeEventListener("change", handle_file_input_change);
          hidden_input.remove();
        }
      };
    },
    open_file_upload() {
      if (hidden_input) {
        hidden_input.value = "";
        hidden_input.click();
      }
    }
  };
}
function create_else_block$7(ctx) {
  let button;
  let button_tabindex_value;
  let button_aria_label_value;
  let drag_action;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[30].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[29],
    null
  );
  return {
    c() {
      button = element("button");
      if (default_slot) default_slot.c();
      attr(button, "tabindex", button_tabindex_value = /*hidden*/
      ctx[9] ? -1 : 0);
      attr(button, "aria-label", button_aria_label_value = /*aria_label*/
      ctx[14] || "Click to upload or drop files");
      attr(button, "aria-dropeffect", "copy");
      attr(button, "class", "svelte-1o7nwih");
      toggle_class(
        button,
        "hidden",
        /*hidden*/
        ctx[9]
      );
      toggle_class(
        button,
        "center",
        /*center*/
        ctx[4]
      );
      toggle_class(
        button,
        "boundedheight",
        /*boundedheight*/
        ctx[3]
      );
      toggle_class(
        button,
        "flex",
        /*flex*/
        ctx[5]
      );
      toggle_class(
        button,
        "disable_click",
        /*disable_click*/
        ctx[7]
      );
      toggle_class(
        button,
        "icon-mode",
        /*icon_upload*/
        ctx[12]
      );
      set_style(
        button,
        "height",
        /*icon_upload*/
        ctx[12] ? "" : (
          /*height*/
          ctx[13] ? typeof /*height*/
          ctx[13] === "number" ? (
            /*height*/
            ctx[13] + "px"
          ) : (
            /*height*/
            ctx[13]
          ) : "100%"
        )
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (default_slot) {
        default_slot.m(button, null);
      }
      current = true;
      if (!mounted) {
        dispose = action_destroyer(drag_action = /*drag*/
        ctx[18].call(null, button, {
          on_drag_change: drag_function,
          on_files: (
            /*drag_function_1*/
            ctx[31]
          ),
          accepted_types: (
            /*accept_file_types*/
            ctx[17]
          ),
          mode: (
            /*file_count*/
            ctx[6]
          ),
          disable_click: (
            /*disable_click*/
            ctx[7]
          )
        }));
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope*/
        536870912)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[29],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[29]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[29],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty[0] & /*hidden*/
      512 && button_tabindex_value !== (button_tabindex_value = /*hidden*/
      ctx2[9] ? -1 : 0)) {
        attr(button, "tabindex", button_tabindex_value);
      }
      if (!current || dirty[0] & /*aria_label*/
      16384 && button_aria_label_value !== (button_aria_label_value = /*aria_label*/
      ctx2[14] || "Click to upload or drop files")) {
        attr(button, "aria-label", button_aria_label_value);
      }
      if (drag_action && is_function(drag_action.update) && dirty[0] & /*accept_file_types, file_count, disable_click*/
      131264) drag_action.update.call(null, {
        on_drag_change: drag_function,
        on_files: (
          /*drag_function_1*/
          ctx2[31]
        ),
        accepted_types: (
          /*accept_file_types*/
          ctx2[17]
        ),
        mode: (
          /*file_count*/
          ctx2[6]
        ),
        disable_click: (
          /*disable_click*/
          ctx2[7]
        )
      });
      if (!current || dirty[0] & /*hidden*/
      512) {
        toggle_class(
          button,
          "hidden",
          /*hidden*/
          ctx2[9]
        );
      }
      if (!current || dirty[0] & /*center*/
      16) {
        toggle_class(
          button,
          "center",
          /*center*/
          ctx2[4]
        );
      }
      if (!current || dirty[0] & /*boundedheight*/
      8) {
        toggle_class(
          button,
          "boundedheight",
          /*boundedheight*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*flex*/
      32) {
        toggle_class(
          button,
          "flex",
          /*flex*/
          ctx2[5]
        );
      }
      if (!current || dirty[0] & /*disable_click*/
      128) {
        toggle_class(
          button,
          "disable_click",
          /*disable_click*/
          ctx2[7]
        );
      }
      if (!current || dirty[0] & /*icon_upload*/
      4096) {
        toggle_class(
          button,
          "icon-mode",
          /*icon_upload*/
          ctx2[12]
        );
      }
      if (dirty[0] & /*icon_upload, height*/
      12288) {
        set_style(
          button,
          "height",
          /*icon_upload*/
          ctx2[12] ? "" : (
            /*height*/
            ctx2[13] ? typeof /*height*/
            ctx2[13] === "number" ? (
              /*height*/
              ctx2[13] + "px"
            ) : (
              /*height*/
              ctx2[13]
            ) : "100%"
          )
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      if (default_slot) default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$c(ctx) {
  let if_block_anchor;
  let current;
  let if_block = !/*hidden*/
  ctx[9] && create_if_block_2$b(ctx);
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (!/*hidden*/
      ctx2[9]) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*hidden*/
          512) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_2$b(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block$g(ctx) {
  let button;
  let button_tabindex_value;
  let button_aria_label_value;
  let current;
  let mounted;
  let dispose;
  const default_slot_template = (
    /*#slots*/
    ctx[30].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[29],
    null
  );
  return {
    c() {
      button = element("button");
      if (default_slot) default_slot.c();
      attr(button, "tabindex", button_tabindex_value = /*hidden*/
      ctx[9] ? -1 : 0);
      attr(button, "aria-label", button_aria_label_value = /*aria_label*/
      ctx[14] || "Paste from clipboard");
      attr(button, "class", "svelte-1o7nwih");
      toggle_class(
        button,
        "hidden",
        /*hidden*/
        ctx[9]
      );
      toggle_class(
        button,
        "center",
        /*center*/
        ctx[4]
      );
      toggle_class(
        button,
        "boundedheight",
        /*boundedheight*/
        ctx[3]
      );
      toggle_class(
        button,
        "flex",
        /*flex*/
        ctx[5]
      );
      toggle_class(
        button,
        "icon-mode",
        /*icon_upload*/
        ctx[12]
      );
      set_style(
        button,
        "height",
        /*icon_upload*/
        ctx[12] ? "" : (
          /*height*/
          ctx[13] ? typeof /*height*/
          ctx[13] === "number" ? (
            /*height*/
            ctx[13] + "px"
          ) : (
            /*height*/
            ctx[13]
          ) : "100%"
        )
      );
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (default_slot) {
        default_slot.m(button, null);
      }
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*paste_clipboard*/
          ctx[15]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[0] & /*$$scope*/
        536870912)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[29],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[29]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[29],
              dirty,
              null
            ),
            null
          );
        }
      }
      if (!current || dirty[0] & /*hidden*/
      512 && button_tabindex_value !== (button_tabindex_value = /*hidden*/
      ctx2[9] ? -1 : 0)) {
        attr(button, "tabindex", button_tabindex_value);
      }
      if (!current || dirty[0] & /*aria_label*/
      16384 && button_aria_label_value !== (button_aria_label_value = /*aria_label*/
      ctx2[14] || "Paste from clipboard")) {
        attr(button, "aria-label", button_aria_label_value);
      }
      if (!current || dirty[0] & /*hidden*/
      512) {
        toggle_class(
          button,
          "hidden",
          /*hidden*/
          ctx2[9]
        );
      }
      if (!current || dirty[0] & /*center*/
      16) {
        toggle_class(
          button,
          "center",
          /*center*/
          ctx2[4]
        );
      }
      if (!current || dirty[0] & /*boundedheight*/
      8) {
        toggle_class(
          button,
          "boundedheight",
          /*boundedheight*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*flex*/
      32) {
        toggle_class(
          button,
          "flex",
          /*flex*/
          ctx2[5]
        );
      }
      if (!current || dirty[0] & /*icon_upload*/
      4096) {
        toggle_class(
          button,
          "icon-mode",
          /*icon_upload*/
          ctx2[12]
        );
      }
      if (dirty[0] & /*icon_upload, height*/
      12288) {
        set_style(
          button,
          "height",
          /*icon_upload*/
          ctx2[12] ? "" : (
            /*height*/
            ctx2[13] ? typeof /*height*/
            ctx2[13] === "number" ? (
              /*height*/
              ctx2[13] + "px"
            ) : (
              /*height*/
              ctx2[13]
            ) : "100%"
          )
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      if (default_slot) default_slot.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_2$b(ctx) {
  let uploadprogress;
  let current;
  uploadprogress = new UploadProgress({
    props: {
      root: (
        /*root*/
        ctx[8]
      ),
      upload_id: (
        /*upload_id*/
        ctx[19]
      ),
      files: (
        /*file_data*/
        ctx[16]
      ),
      stream_handler: (
        /*stream_handler*/
        ctx[11]
      )
    }
  });
  return {
    c() {
      create_component(uploadprogress.$$.fragment);
    },
    m(target, anchor) {
      mount_component(uploadprogress, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const uploadprogress_changes = {};
      if (dirty[0] & /*root*/
      256) uploadprogress_changes.root = /*root*/
      ctx2[8];
      if (dirty[0] & /*file_data*/
      65536) uploadprogress_changes.files = /*file_data*/
      ctx2[16];
      if (dirty[0] & /*stream_handler*/
      2048) uploadprogress_changes.stream_handler = /*stream_handler*/
      ctx2[11];
      uploadprogress.$set(uploadprogress_changes);
    },
    i(local) {
      if (current) return;
      transition_in(uploadprogress.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(uploadprogress.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(uploadprogress, detaching);
    }
  };
}
function create_fragment$t(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block$g, create_if_block_1$c, create_else_block$7];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*filetype*/
      ctx2[0] === "clipboard"
    ) return 0;
    if (
      /*uploading*/
      ctx2[2] && /*show_progress*/
      ctx2[10]
    ) return 1;
    return 2;
  }
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function is_valid_mimetype(file_accept, uploaded_file_extension, uploaded_file_type) {
  if (!file_accept || file_accept === "*" || file_accept === "file/*" || Array.isArray(file_accept) && file_accept.some((accept) => accept === "*" || accept === "file/*")) {
    return true;
  }
  let acceptArray;
  if (typeof file_accept === "string") {
    acceptArray = file_accept.split(",").map((s) => s.trim());
  } else if (Array.isArray(file_accept)) {
    acceptArray = file_accept;
  } else {
    return false;
  }
  return acceptArray.includes(uploaded_file_extension) || acceptArray.some((type) => {
    const [category] = type.split("/").map((s) => s.trim());
    return type.endsWith("/*") && uploaded_file_type.startsWith(category + "/");
  });
}
const drag_function = (dragging) => dragging = dragging;
function instance$s($$self, $$props, $$invalidate) {
  let ios;
  let { $$slots: slots = {}, $$scope } = $$props;
  const { drag, open_file_upload: _open_file_upload } = create_drag();
  let { filetype = null } = $$props;
  let { dragging = false } = $$props;
  let { boundedheight = true } = $$props;
  let { center = true } = $$props;
  let { flex = true } = $$props;
  let { file_count = "single" } = $$props;
  let { disable_click = false } = $$props;
  let { root } = $$props;
  let { hidden = false } = $$props;
  let { format = "file" } = $$props;
  let { uploading = false } = $$props;
  let { show_progress = true } = $$props;
  let { max_file_size = null } = $$props;
  let { upload } = $$props;
  let { stream_handler } = $$props;
  let { icon_upload = false } = $$props;
  let { height: height2 = void 0 } = $$props;
  let { aria_label = void 0 } = $$props;
  function open_upload() {
    _open_file_upload();
  }
  let upload_id;
  let file_data;
  let accept_file_types;
  let use_post_upload_validation = null;
  const get_ios = () => {
    if (typeof navigator !== "undefined") {
      const userAgent = navigator.userAgent.toLowerCase();
      return userAgent.indexOf("iphone") > -1 || userAgent.indexOf("ipad") > -1;
    }
    return false;
  };
  const dispatch2 = createEventDispatcher();
  const validFileTypes = ["image", "video", "audio", "text", "file"];
  const process_file_type = (type) => {
    if (ios && type.startsWith(".")) {
      use_post_upload_validation = true;
      return type;
    }
    if (ios && type.includes("file/*")) {
      return "*";
    }
    if (type.startsWith(".") || type.endsWith("/*")) {
      return type;
    }
    if (validFileTypes.includes(type)) {
      return type + "/*";
    }
    return "." + type;
  };
  function paste_clipboard() {
    navigator.clipboard.read().then(async (items2) => {
      for (let i = 0; i < items2.length; i++) {
        const type = items2[i].types.find((t) => t.startsWith("image/"));
        if (type) {
          items2[i].getType(type).then(async (blob) => {
            const file = new File([blob], `clipboard.${type.replace("image/", "")}`);
            await load_files([file]);
          });
          break;
        }
      }
    });
  }
  function open_file_upload() {
    _open_file_upload();
  }
  async function handle_upload(file_data2, upload_id2) {
    await tick();
    if (!upload_id2) {
      upload_id2 = Math.random().toString(36).substring(2, 15);
    }
    $$invalidate(2, uploading = true);
    try {
      const _file_data = await upload(file_data2, root, upload_id2, max_file_size ?? Infinity);
      dispatch2("load", file_count === "single" ? _file_data == null ? void 0 : _file_data[0] : _file_data);
      $$invalidate(2, uploading = false);
      return _file_data || [];
    } catch (e) {
      dispatch2("error", e.message);
      $$invalidate(2, uploading = false);
      return [];
    }
  }
  async function load_files(files, upload_id2) {
    if (!files.length) {
      return;
    }
    let _files = files.map((f) => new File([f], f instanceof File ? f.name : "file", { type: f.type }));
    if (ios && use_post_upload_validation) {
      _files = _files.filter((file) => {
        if (is_valid_file(file)) {
          return true;
        }
        dispatch2("error", `Invalid file type: ${file.name}. Only ${filetype} allowed.`);
        return false;
      });
      if (_files.length === 0) {
        return [];
      }
    }
    $$invalidate(16, file_data = await prepare_files(_files));
    return await handle_upload(file_data, upload_id2);
  }
  function is_valid_file(file) {
    if (!filetype) return true;
    const allowed_types = Array.isArray(filetype) ? filetype : [filetype];
    return allowed_types.some((type) => {
      const processed_type = process_file_type(type);
      if (processed_type.startsWith(".")) {
        return file.name.toLowerCase().endsWith(processed_type.toLowerCase());
      }
      if (processed_type === "*") {
        return true;
      }
      if (processed_type.endsWith("/*")) {
        const [category] = processed_type.split("/");
        return file.type.startsWith(category + "/");
      }
      return file.type === processed_type;
    });
  }
  async function load_files_from_upload(files) {
    const files_to_load = files.filter((file) => {
      const file_extension = "." + file.name.toLowerCase().split(".").pop();
      if (file_extension && is_valid_mimetype(accept_file_types, file_extension, file.type)) {
        return true;
      }
      if (file_extension && Array.isArray(filetype) ? filetype.includes(file_extension) : file_extension === filetype) {
        return true;
      }
      dispatch2("error", `Invalid file type only ${filetype} allowed.`);
      return false;
    });
    if (format != "blob") {
      await load_files(files_to_load);
    } else {
      if (file_count === "single") {
        dispatch2("load", files_to_load[0]);
        return;
      }
      dispatch2("load", files_to_load);
    }
  }
  async function load_files_from_drop(e) {
    var _a;
    $$invalidate(1, dragging = false);
    if (!((_a = e.dataTransfer) == null ? void 0 : _a.files)) return;
    const files_to_load = Array.from(e.dataTransfer.files).filter(is_valid_file);
    if (format != "blob") {
      await load_files(files_to_load);
    } else {
      if (file_count === "single") {
        dispatch2("load", files_to_load[0]);
        return;
      }
      dispatch2("load", files_to_load);
    }
  }
  const drag_function_1 = (files) => load_files_from_upload(files);
  $$self.$$set = ($$props2) => {
    if ("filetype" in $$props2) $$invalidate(0, filetype = $$props2.filetype);
    if ("dragging" in $$props2) $$invalidate(1, dragging = $$props2.dragging);
    if ("boundedheight" in $$props2) $$invalidate(3, boundedheight = $$props2.boundedheight);
    if ("center" in $$props2) $$invalidate(4, center = $$props2.center);
    if ("flex" in $$props2) $$invalidate(5, flex = $$props2.flex);
    if ("file_count" in $$props2) $$invalidate(6, file_count = $$props2.file_count);
    if ("disable_click" in $$props2) $$invalidate(7, disable_click = $$props2.disable_click);
    if ("root" in $$props2) $$invalidate(8, root = $$props2.root);
    if ("hidden" in $$props2) $$invalidate(9, hidden = $$props2.hidden);
    if ("format" in $$props2) $$invalidate(21, format = $$props2.format);
    if ("uploading" in $$props2) $$invalidate(2, uploading = $$props2.uploading);
    if ("show_progress" in $$props2) $$invalidate(10, show_progress = $$props2.show_progress);
    if ("max_file_size" in $$props2) $$invalidate(22, max_file_size = $$props2.max_file_size);
    if ("upload" in $$props2) $$invalidate(23, upload = $$props2.upload);
    if ("stream_handler" in $$props2) $$invalidate(11, stream_handler = $$props2.stream_handler);
    if ("icon_upload" in $$props2) $$invalidate(12, icon_upload = $$props2.icon_upload);
    if ("height" in $$props2) $$invalidate(13, height2 = $$props2.height);
    if ("aria_label" in $$props2) $$invalidate(14, aria_label = $$props2.aria_label);
    if ("$$scope" in $$props2) $$invalidate(29, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*filetype, ios*/
    268435457) {
      if (filetype == null) {
        $$invalidate(17, accept_file_types = null);
      } else if (typeof filetype === "string") {
        $$invalidate(17, accept_file_types = process_file_type(filetype));
      } else if (ios && filetype.includes("file/*")) {
        $$invalidate(17, accept_file_types = "*");
      } else {
        $$invalidate(0, filetype = filetype.map(process_file_type));
        $$invalidate(17, accept_file_types = filetype.join(", "));
      }
    }
  };
  $$invalidate(28, ios = get_ios());
  return [
    filetype,
    dragging,
    uploading,
    boundedheight,
    center,
    flex,
    file_count,
    disable_click,
    root,
    hidden,
    show_progress,
    stream_handler,
    icon_upload,
    height2,
    aria_label,
    paste_clipboard,
    file_data,
    accept_file_types,
    drag,
    upload_id,
    load_files_from_upload,
    format,
    max_file_size,
    upload,
    open_upload,
    open_file_upload,
    load_files,
    load_files_from_drop,
    ios,
    $$scope,
    slots,
    drag_function_1
  ];
}
class Upload2 extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$s,
      create_fragment$t,
      safe_not_equal,
      {
        filetype: 0,
        dragging: 1,
        boundedheight: 3,
        center: 4,
        flex: 5,
        file_count: 6,
        disable_click: 7,
        root: 8,
        hidden: 9,
        format: 21,
        uploading: 2,
        show_progress: 10,
        max_file_size: 22,
        upload: 23,
        stream_handler: 11,
        icon_upload: 12,
        height: 13,
        aria_label: 14,
        open_upload: 24,
        paste_clipboard: 15,
        open_file_upload: 25,
        load_files: 26,
        load_files_from_drop: 27
      },
      null,
      [-1, -1]
    );
  }
  get open_upload() {
    return this.$$.ctx[24];
  }
  get paste_clipboard() {
    return this.$$.ctx[15];
  }
  get open_file_upload() {
    return this.$$.ctx[25];
  }
  get load_files() {
    return this.$$.ctx[26];
  }
  get load_files_from_drop() {
    return this.$$.ctx[27];
  }
}
function create_fragment$s(ctx) {
  let button;
  let span;
  let svg;
  let path;
  let span_class_value;
  let button_class_value;
  let button_aria_label_value;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      span = element("span");
      svg = svg_element("svg");
      path = svg_element("path");
      attr(path, "d", "m16.707 13.293-4-4a1 1 0 0 0-1.414 0l-4 4A1 1 0 0 0 8 15h8a1 1 0 0 0 .707-1.707z");
      attr(
        path,
        "data-name",
        /*direction*/
        ctx[3]
      );
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "class", "svelte-liwrp1");
      attr(span, "class", span_class_value = null_to_empty(
        /*direction*/
        ctx[3]
      ) + " svelte-liwrp1");
      attr(button, "class", button_class_value = "selection-button selection-button-" + /*position*/
      ctx[0] + " " + /*is_first_position*/
      (ctx[2] ? `move-${/*direction*/
      ctx[3]}` : "") + " svelte-liwrp1");
      attr(button, "aria-label", button_aria_label_value = `Select ${/*position*/
      ctx[0]}`);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, span);
      append(span, svg);
      append(svg, path);
      if (!mounted) {
        dispose = listen(button, "click", stop_propagation(
          /*click_handler*/
          ctx[5]
        ));
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*direction*/
      8) {
        attr(
          path,
          "data-name",
          /*direction*/
          ctx2[3]
        );
      }
      if (dirty & /*direction*/
      8 && span_class_value !== (span_class_value = null_to_empty(
        /*direction*/
        ctx2[3]
      ) + " svelte-liwrp1")) {
        attr(span, "class", span_class_value);
      }
      if (dirty & /*position, is_first_position, direction*/
      13 && button_class_value !== (button_class_value = "selection-button selection-button-" + /*position*/
      ctx2[0] + " " + /*is_first_position*/
      (ctx2[2] ? `move-${/*direction*/
      ctx2[3]}` : "") + " svelte-liwrp1")) {
        attr(button, "class", button_class_value);
      }
      if (dirty & /*position*/
      1 && button_aria_label_value !== (button_aria_label_value = `Select ${/*position*/
      ctx2[0]}`)) {
        attr(button, "aria-label", button_aria_label_value);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance$r($$self, $$props, $$invalidate) {
  let is_first_position;
  let direction;
  let { position } = $$props;
  let { coords } = $$props;
  let { on_click = null } = $$props;
  const click_handler = () => on_click && on_click();
  $$self.$$set = ($$props2) => {
    if ("position" in $$props2) $$invalidate(0, position = $$props2.position);
    if ("coords" in $$props2) $$invalidate(4, coords = $$props2.coords);
    if ("on_click" in $$props2) $$invalidate(1, on_click = $$props2.on_click);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*position, coords*/
    17) {
      $$invalidate(2, is_first_position = position === "column" ? coords[0] === 0 : coords[1] === 0);
    }
    if ($$self.$$.dirty & /*position, is_first_position*/
    5) {
      $$invalidate(3, direction = position === "column" ? is_first_position ? "down" : "up" : is_first_position ? "right" : "left");
    }
  };
  return [position, on_click, is_first_position, direction, coords, click_handler];
}
let SelectionButtons$1 = class SelectionButtons extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$r, create_fragment$s, safe_not_equal, { position: 0, coords: 4, on_click: 1 });
  }
};
function pretty_si(num) {
  let units = ["", "k", "M", "G", "T", "P", "E", "Z"];
  let i = 0;
  while (num > 1e3 && i < units.length - 1) {
    num /= 1e3;
    i++;
  }
  let unit = units[i];
  return (Number.isInteger(num) ? num : num.toFixed(1)) + unit;
}
function is_date(obj) {
  return Object.prototype.toString.call(obj) === "[object Date]";
}
function tick_spring(ctx, last_value, current_value, target_value) {
  if (typeof current_value === "number" || is_date(current_value)) {
    const delta = target_value - current_value;
    const velocity = (current_value - last_value) / (ctx.dt || 1 / 60);
    const spring2 = ctx.opts.stiffness * delta;
    const damper = ctx.opts.damping * velocity;
    const acceleration = (spring2 - damper) * ctx.inv_mass;
    const d = (velocity + acceleration) * ctx.dt;
    if (Math.abs(d) < ctx.opts.precision && Math.abs(delta) < ctx.opts.precision) {
      return target_value;
    } else {
      ctx.settled = false;
      return is_date(current_value) ? new Date(current_value.getTime() + d) : current_value + d;
    }
  } else if (Array.isArray(current_value)) {
    return current_value.map(
      (_, i) => tick_spring(ctx, last_value[i], current_value[i], target_value[i])
    );
  } else if (typeof current_value === "object") {
    const next_value = {};
    for (const k in current_value) {
      next_value[k] = tick_spring(ctx, last_value[k], current_value[k], target_value[k]);
    }
    return next_value;
  } else {
    throw new Error(`Cannot spring ${typeof current_value} values`);
  }
}
function spring(value, opts = {}) {
  const store = writable(value);
  const { stiffness = 0.15, damping = 0.8, precision = 0.01 } = opts;
  let last_time;
  let task;
  let current_token;
  let last_value = value;
  let target_value = value;
  let inv_mass = 1;
  let inv_mass_recovery_rate = 0;
  let cancel_task = false;
  function set(new_value, opts2 = {}) {
    target_value = new_value;
    const token = current_token = {};
    if (value == null || opts2.hard || spring2.stiffness >= 1 && spring2.damping >= 1) {
      cancel_task = true;
      last_time = now();
      last_value = new_value;
      store.set(value = target_value);
      return Promise.resolve();
    } else if (opts2.soft) {
      const rate = opts2.soft === true ? 0.5 : +opts2.soft;
      inv_mass_recovery_rate = 1 / (rate * 60);
      inv_mass = 0;
    }
    if (!task) {
      last_time = now();
      cancel_task = false;
      task = loop((now2) => {
        if (cancel_task) {
          cancel_task = false;
          task = null;
          return false;
        }
        inv_mass = Math.min(inv_mass + inv_mass_recovery_rate, 1);
        const ctx = {
          inv_mass,
          opts: spring2,
          settled: true,
          dt: (now2 - last_time) * 60 / 1e3
        };
        const next_value = tick_spring(ctx, last_value, value, target_value);
        last_time = now2;
        last_value = value;
        store.set(value = next_value);
        if (ctx.settled) {
          task = null;
        }
        return !ctx.settled;
      });
    }
    return new Promise((fulfil) => {
      task.promise.then(() => {
        if (token === current_token) fulfil();
      });
    });
  }
  const spring2 = {
    set,
    update: (fn, opts2) => set(fn(target_value, value), opts2),
    subscribe: store.subscribe,
    stiffness,
    damping,
    precision
  };
  return spring2;
}
function create_fragment$r(ctx) {
  let div;
  let svg;
  let g0;
  let path0;
  let path1;
  let path2;
  let path3;
  let g1;
  let path4;
  let path5;
  let path6;
  let path7;
  return {
    c() {
      div = element("div");
      svg = svg_element("svg");
      g0 = svg_element("g");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      path3 = svg_element("path");
      g1 = svg_element("g");
      path4 = svg_element("path");
      path5 = svg_element("path");
      path6 = svg_element("path");
      path7 = svg_element("path");
      attr(path0, "d", "M255.926 0.754768L509.702 139.936V221.027L255.926 81.8465V0.754768Z");
      attr(path0, "fill", "#FF7C00");
      attr(path0, "fill-opacity", "0.4");
      attr(path0, "class", "svelte-43sxxs");
      attr(path1, "d", "M509.69 139.936L254.981 279.641V361.255L509.69 221.55V139.936Z");
      attr(path1, "fill", "#FF7C00");
      attr(path1, "class", "svelte-43sxxs");
      attr(path2, "d", "M0.250138 139.937L254.981 279.641V361.255L0.250138 221.55V139.937Z");
      attr(path2, "fill", "#FF7C00");
      attr(path2, "fill-opacity", "0.4");
      attr(path2, "class", "svelte-43sxxs");
      attr(path3, "d", "M255.923 0.232622L0.236328 139.936V221.55L255.923 81.8469V0.232622Z");
      attr(path3, "fill", "#FF7C00");
      attr(path3, "class", "svelte-43sxxs");
      set_style(g0, "transform", "translate(" + /*$top*/
      ctx[1][0] + "px, " + /*$top*/
      ctx[1][1] + "px)");
      attr(path4, "d", "M255.926 141.5L509.702 280.681V361.773L255.926 222.592V141.5Z");
      attr(path4, "fill", "#FF7C00");
      attr(path4, "fill-opacity", "0.4");
      attr(path4, "class", "svelte-43sxxs");
      attr(path5, "d", "M509.69 280.679L254.981 420.384V501.998L509.69 362.293V280.679Z");
      attr(path5, "fill", "#FF7C00");
      attr(path5, "class", "svelte-43sxxs");
      attr(path6, "d", "M0.250138 280.681L254.981 420.386V502L0.250138 362.295V280.681Z");
      attr(path6, "fill", "#FF7C00");
      attr(path6, "fill-opacity", "0.4");
      attr(path6, "class", "svelte-43sxxs");
      attr(path7, "d", "M255.923 140.977L0.236328 280.68V362.294L255.923 222.591V140.977Z");
      attr(path7, "fill", "#FF7C00");
      attr(path7, "class", "svelte-43sxxs");
      set_style(g1, "transform", "translate(" + /*$bottom*/
      ctx[2][0] + "px, " + /*$bottom*/
      ctx[2][1] + "px)");
      attr(svg, "viewBox", "-1200 -1200 3000 3000");
      attr(svg, "fill", "none");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
      attr(svg, "class", "svelte-43sxxs");
      attr(div, "class", "svelte-43sxxs");
      toggle_class(
        div,
        "margin",
        /*margin*/
        ctx[0]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, svg);
      append(svg, g0);
      append(g0, path0);
      append(g0, path1);
      append(g0, path2);
      append(g0, path3);
      append(svg, g1);
      append(g1, path4);
      append(g1, path5);
      append(g1, path6);
      append(g1, path7);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*$top*/
      2) {
        set_style(g0, "transform", "translate(" + /*$top*/
        ctx2[1][0] + "px, " + /*$top*/
        ctx2[1][1] + "px)");
      }
      if (dirty & /*$bottom*/
      4) {
        set_style(g1, "transform", "translate(" + /*$bottom*/
        ctx2[2][0] + "px, " + /*$bottom*/
        ctx2[2][1] + "px)");
      }
      if (dirty & /*margin*/
      1) {
        toggle_class(
          div,
          "margin",
          /*margin*/
          ctx2[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function instance$q($$self, $$props, $$invalidate) {
  let $top;
  let $bottom;
  let { margin = true } = $$props;
  const top = spring([0, 0]);
  component_subscribe($$self, top, (value) => $$invalidate(1, $top = value));
  const bottom = spring([0, 0]);
  component_subscribe($$self, bottom, (value) => $$invalidate(2, $bottom = value));
  let dismounted;
  async function animate() {
    await Promise.all([top.set([125, 140]), bottom.set([-125, -140])]);
    await Promise.all([top.set([-125, 140]), bottom.set([125, -140])]);
    await Promise.all([top.set([-125, 0]), bottom.set([125, -0])]);
    await Promise.all([top.set([125, 0]), bottom.set([-125, 0])]);
  }
  async function run2() {
    await animate();
    if (!dismounted) run2();
  }
  async function loading() {
    await Promise.all([top.set([125, 0]), bottom.set([-125, 0])]);
    run2();
  }
  onMount(() => {
    loading();
    return () => dismounted = true;
  });
  $$self.$$set = ($$props2) => {
    if ("margin" in $$props2) $$invalidate(0, margin = $$props2.margin);
  };
  return [margin, $top, $bottom, top, bottom];
}
class Loader extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$q, create_fragment$r, safe_not_equal, { margin: 0 });
  }
}
const get_error_slot_changes = (dirty) => ({});
const get_error_slot_context = (ctx) => ({});
const get_additional_loading_text_slot_changes = (dirty) => ({});
const get_additional_loading_text_slot_context = (ctx) => ({});
function get_each_context$4(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[43] = list2[i];
  child_ctx[45] = i;
  return child_ctx;
}
function get_each_context_1$1(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[43] = list2[i];
  return child_ctx;
}
function create_if_block_18(ctx) {
  let div;
  let t0;
  let t1;
  let button;
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: Clear,
      label: (
        /*i18n*/
        ctx[2]("common.clear")
      ),
      disabled: false,
      size: "x-small",
      background: "var(--background-fill-primary)",
      color: "var(--error-background-text)",
      border: "var(--border-color-primary)"
    }
  });
  iconbutton.$on(
    "click",
    /*click_handler*/
    ctx[33]
  );
  return {
    c() {
      div = element("div");
      t0 = text(
        /*validation_error*/
        ctx[1]
      );
      t1 = space();
      button = element("button");
      create_component(iconbutton.$$.fragment);
      attr(div, "class", "validation-error svelte-vusapu");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, t0);
      append(div, t1);
      append(div, button);
      mount_component(iconbutton, button, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (!current || dirty[0] & /*validation_error*/
      2) set_data(
        t0,
        /*validation_error*/
        ctx2[1]
      );
      const iconbutton_changes = {};
      if (dirty[0] & /*i18n*/
      4) iconbutton_changes.label = /*i18n*/
      ctx2[2]("common.clear");
      iconbutton.$set(iconbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(iconbutton);
    }
  };
}
function create_if_block_17(ctx) {
  let div;
  let iconbutton;
  let t0;
  let span;
  let t1_value = (
    /*i18n*/
    ctx[2]("common.error") + ""
  );
  let t1;
  let t2;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: Clear,
      label: (
        /*i18n*/
        ctx[2]("common.clear")
      ),
      disabled: false
    }
  });
  iconbutton.$on(
    "click",
    /*click_handler_1*/
    ctx[35]
  );
  const error_slot_template = (
    /*#slots*/
    ctx[32].error
  );
  const error_slot = create_slot(
    error_slot_template,
    ctx,
    /*$$scope*/
    ctx[31],
    get_error_slot_context
  );
  return {
    c() {
      div = element("div");
      create_component(iconbutton.$$.fragment);
      t0 = space();
      span = element("span");
      t1 = text(t1_value);
      t2 = space();
      if (error_slot) error_slot.c();
      attr(div, "class", "clear-status svelte-vusapu");
      attr(span, "class", "error svelte-vusapu");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(iconbutton, div, null);
      insert(target, t0, anchor);
      insert(target, span, anchor);
      append(span, t1);
      insert(target, t2, anchor);
      if (error_slot) {
        error_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      const iconbutton_changes = {};
      if (dirty[0] & /*i18n*/
      4) iconbutton_changes.label = /*i18n*/
      ctx2[2]("common.clear");
      iconbutton.$set(iconbutton_changes);
      if ((!current || dirty[0] & /*i18n*/
      4) && t1_value !== (t1_value = /*i18n*/
      ctx2[2]("common.error") + "")) set_data(t1, t1_value);
      if (error_slot) {
        if (error_slot.p && (!current || dirty[1] & /*$$scope*/
        1)) {
          update_slot_base(
            error_slot,
            error_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[31],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[31]
            ) : get_slot_changes(
              error_slot_template,
              /*$$scope*/
              ctx2[31],
              dirty,
              get_error_slot_changes
            ),
            get_error_slot_context
          );
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      transition_in(error_slot, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      transition_out(error_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
        detach(t0);
        detach(span);
        detach(t2);
      }
      destroy_component(iconbutton);
      if (error_slot) error_slot.d(detaching);
    }
  };
}
function create_if_block$f(ctx) {
  let t0;
  let div;
  let t1;
  let t2;
  let current_block_type_index;
  let if_block3;
  let t3;
  let if_block4_anchor;
  let current;
  let if_block0 = (
    /*variant*/
    ctx[9] === "default" && /*show_eta_bar*/
    ctx[20] && /*show_progress*/
    ctx[7] === "full" && create_if_block_16(ctx)
  );
  function select_block_type_1(ctx2, dirty) {
    if (
      /*progress*/
      ctx2[8]
    ) return create_if_block_11;
    if (
      /*queue_position*/
      ctx2[3] !== null && /*queue_size*/
      ctx2[4] !== void 0 && /*queue_position*/
      ctx2[3] >= 0
    ) return create_if_block_14;
    if (
      /*queue_position*/
      ctx2[3] === 0
    ) return create_if_block_15;
  }
  let current_block_type = select_block_type_1(ctx);
  let if_block1 = current_block_type && current_block_type(ctx);
  let if_block2 = (
    /*timer*/
    ctx[6] && create_if_block_10$1(ctx)
  );
  const if_block_creators = [create_if_block_2$a, create_if_block_9$2];
  const if_blocks = [];
  function select_block_type_3(ctx2, dirty) {
    if (
      /*last_progress_level*/
      ctx2[17] != null
    ) return 0;
    if (
      /*show_progress*/
      ctx2[7] === "full"
    ) return 1;
    return -1;
  }
  if (~(current_block_type_index = select_block_type_3(ctx))) {
    if_block3 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  let if_block4 = !/*timer*/
  ctx[6] && create_if_block_1$b(ctx);
  return {
    c() {
      if (if_block0) if_block0.c();
      t0 = space();
      div = element("div");
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      t2 = space();
      if (if_block3) if_block3.c();
      t3 = space();
      if (if_block4) if_block4.c();
      if_block4_anchor = empty();
      attr(div, "class", "progress-text svelte-vusapu");
      toggle_class(
        div,
        "meta-text-center",
        /*variant*/
        ctx[9] === "center"
      );
      toggle_class(
        div,
        "meta-text",
        /*variant*/
        ctx[9] === "default"
      );
    },
    m(target, anchor) {
      if (if_block0) if_block0.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, div, anchor);
      if (if_block1) if_block1.m(div, null);
      append(div, t1);
      if (if_block2) if_block2.m(div, null);
      insert(target, t2, anchor);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(target, anchor);
      }
      insert(target, t3, anchor);
      if (if_block4) if_block4.m(target, anchor);
      insert(target, if_block4_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*variant*/
        ctx2[9] === "default" && /*show_eta_bar*/
        ctx2[20] && /*show_progress*/
        ctx2[7] === "full"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_16(ctx2);
          if_block0.c();
          if_block0.m(t0.parentNode, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block1) {
        if_block1.p(ctx2, dirty);
      } else {
        if (if_block1) if_block1.d(1);
        if_block1 = current_block_type && current_block_type(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div, t1);
        }
      }
      if (
        /*timer*/
        ctx2[6]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
        } else {
          if_block2 = create_if_block_10$1(ctx2);
          if_block2.c();
          if_block2.m(div, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (!current || dirty[0] & /*variant*/
      512) {
        toggle_class(
          div,
          "meta-text-center",
          /*variant*/
          ctx2[9] === "center"
        );
      }
      if (!current || dirty[0] & /*variant*/
      512) {
        toggle_class(
          div,
          "meta-text",
          /*variant*/
          ctx2[9] === "default"
        );
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_3(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block3) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block3 = if_blocks[current_block_type_index];
          if (!if_block3) {
            if_block3 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block3.c();
          } else {
            if_block3.p(ctx2, dirty);
          }
          transition_in(if_block3, 1);
          if_block3.m(t3.parentNode, t3);
        } else {
          if_block3 = null;
        }
      }
      if (!/*timer*/
      ctx2[6]) {
        if (if_block4) {
          if_block4.p(ctx2, dirty);
          if (dirty[0] & /*timer*/
          64) {
            transition_in(if_block4, 1);
          }
        } else {
          if_block4 = create_if_block_1$b(ctx2);
          if_block4.c();
          transition_in(if_block4, 1);
          if_block4.m(if_block4_anchor.parentNode, if_block4_anchor);
        }
      } else if (if_block4) {
        group_outros();
        transition_out(if_block4, 1, 1, () => {
          if_block4 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block3);
      transition_in(if_block4);
      current = true;
    },
    o(local) {
      transition_out(if_block3);
      transition_out(if_block4);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(div);
        detach(t2);
        detach(t3);
        detach(if_block4_anchor);
      }
      if (if_block0) if_block0.d(detaching);
      if (if_block1) {
        if_block1.d();
      }
      if (if_block2) if_block2.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d(detaching);
      }
      if (if_block4) if_block4.d(detaching);
    }
  };
}
function create_if_block_16(ctx) {
  let div;
  let style_transform = `translateX(${/*eta_level*/
  (ctx[19] || 0) * 100 - 100}%)`;
  return {
    c() {
      div = element("div");
      attr(div, "class", "eta-bar svelte-vusapu");
      set_style(div, "transform", style_transform);
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*eta_level*/
      524288 && style_transform !== (style_transform = `translateX(${/*eta_level*/
      (ctx2[19] || 0) * 100 - 100}%)`)) {
        set_style(div, "transform", style_transform);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_if_block_15(ctx) {
  let t;
  return {
    c() {
      t = text("processing |");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_14(ctx) {
  let t0;
  let t1_value = (
    /*queue_position*/
    ctx[3] + 1 + ""
  );
  let t1;
  let t2;
  let t3;
  let t4;
  return {
    c() {
      t0 = text("queue: ");
      t1 = text(t1_value);
      t2 = text("/");
      t3 = text(
        /*queue_size*/
        ctx[4]
      );
      t4 = text(" |");
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      insert(target, t2, anchor);
      insert(target, t3, anchor);
      insert(target, t4, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*queue_position*/
      8 && t1_value !== (t1_value = /*queue_position*/
      ctx2[3] + 1 + "")) set_data(t1, t1_value);
      if (dirty[0] & /*queue_size*/
      16) set_data(
        t3,
        /*queue_size*/
        ctx2[4]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
        detach(t3);
        detach(t4);
      }
    }
  };
}
function create_if_block_11(ctx) {
  let each_1_anchor;
  let each_value_1 = ensure_array_like(
    /*progress*/
    ctx[8]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) {
    each_blocks[i] = create_each_block_1$1(get_each_context_1$1(ctx, each_value_1, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress*/
      256) {
        each_value_1 = ensure_array_like(
          /*progress*/
          ctx2[8]
        );
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1$1(ctx2, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block_1$1(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value_1.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_if_block_12(ctx) {
  let t0;
  let t1_value = (
    /*p*/
    ctx[43].unit + ""
  );
  let t1;
  let t2;
  let t3_value = " ";
  let t3;
  function select_block_type_2(ctx2, dirty) {
    if (
      /*p*/
      ctx2[43].length != null
    ) return create_if_block_13;
    return create_else_block$6;
  }
  let current_block_type = select_block_type_2(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      t0 = space();
      t1 = text(t1_value);
      t2 = text(" | ");
      t3 = text(t3_value);
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      insert(target, t2, anchor);
      insert(target, t3, anchor);
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_2(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(t0.parentNode, t0);
        }
      }
      if (dirty[0] & /*progress*/
      256 && t1_value !== (t1_value = /*p*/
      ctx2[43].unit + "")) set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
        detach(t3);
      }
      if_block.d(detaching);
    }
  };
}
function create_else_block$6(ctx) {
  let t_value = pretty_si(
    /*p*/
    ctx[43].index || 0
  ) + "";
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress*/
      256 && t_value !== (t_value = pretty_si(
        /*p*/
        ctx2[43].index || 0
      ) + "")) set_data(t, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_13(ctx) {
  let t0_value = pretty_si(
    /*p*/
    ctx[43].index || 0
  ) + "";
  let t0;
  let t1;
  let t2_value = pretty_si(
    /*p*/
    ctx[43].length
  ) + "";
  let t2;
  return {
    c() {
      t0 = text(t0_value);
      t1 = text("/");
      t2 = text(t2_value);
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      insert(target, t2, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress*/
      256 && t0_value !== (t0_value = pretty_si(
        /*p*/
        ctx2[43].index || 0
      ) + "")) set_data(t0, t0_value);
      if (dirty[0] & /*progress*/
      256 && t2_value !== (t2_value = pretty_si(
        /*p*/
        ctx2[43].length
      ) + "")) set_data(t2, t2_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
      }
    }
  };
}
function create_each_block_1$1(ctx) {
  let if_block_anchor;
  let if_block = (
    /*p*/
    ctx[43].index != null && create_if_block_12(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*p*/
        ctx2[43].index != null
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_12(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block_10$1(ctx) {
  let t0;
  let t1_value = (
    /*eta*/
    ctx[0] ? `/${/*formatted_eta*/
    ctx[21]}` : ""
  );
  let t1;
  let t2;
  return {
    c() {
      t0 = text(
        /*formatted_timer*/
        ctx[22]
      );
      t1 = text(t1_value);
      t2 = text("s");
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
      insert(target, t2, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*formatted_timer*/
      4194304) set_data(
        t0,
        /*formatted_timer*/
        ctx2[22]
      );
      if (dirty[0] & /*eta, formatted_eta*/
      2097153 && t1_value !== (t1_value = /*eta*/
      ctx2[0] ? `/${/*formatted_eta*/
      ctx2[21]}` : "")) set_data(t1, t1_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
      }
    }
  };
}
function create_if_block_9$2(ctx) {
  let loader;
  let current;
  loader = new Loader({
    props: { margin: (
      /*variant*/
      ctx[9] === "default"
    ) }
  });
  return {
    c() {
      create_component(loader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(loader, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const loader_changes = {};
      if (dirty[0] & /*variant*/
      512) loader_changes.margin = /*variant*/
      ctx2[9] === "default";
      loader.$set(loader_changes);
    },
    i(local) {
      if (current) return;
      transition_in(loader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(loader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(loader, detaching);
    }
  };
}
function create_if_block_2$a(ctx) {
  let div3;
  let div0;
  let t;
  let div2;
  let div1;
  let style_width = `${/*last_progress_level*/
  ctx[17] * 100}%`;
  let if_block = (
    /*progress*/
    ctx[8] != null && create_if_block_3$9(ctx)
  );
  return {
    c() {
      div3 = element("div");
      div0 = element("div");
      if (if_block) if_block.c();
      t = space();
      div2 = element("div");
      div1 = element("div");
      attr(div0, "class", "progress-level-inner svelte-vusapu");
      attr(div1, "class", "progress-bar svelte-vusapu");
      set_style(div1, "width", style_width);
      attr(div2, "class", "progress-bar-wrap svelte-vusapu");
      attr(div3, "class", "progress-level svelte-vusapu");
    },
    m(target, anchor) {
      insert(target, div3, anchor);
      append(div3, div0);
      if (if_block) if_block.m(div0, null);
      append(div3, t);
      append(div3, div2);
      append(div2, div1);
      ctx[34](div1);
    },
    p(ctx2, dirty) {
      if (
        /*progress*/
        ctx2[8] != null
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_3$9(ctx2);
          if_block.c();
          if_block.m(div0, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (dirty[0] & /*last_progress_level*/
      131072 && style_width !== (style_width = `${/*last_progress_level*/
      ctx2[17] * 100}%`)) {
        set_style(div1, "width", style_width);
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div3);
      }
      if (if_block) if_block.d();
      ctx[34](null);
    }
  };
}
function create_if_block_3$9(ctx) {
  let each_1_anchor;
  let each_value = ensure_array_like(
    /*progress*/
    ctx[8]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress_level, progress*/
      65792) {
        each_value = ensure_array_like(
          /*progress*/
          ctx2[8]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$4(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$4(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_if_block_4$7(ctx) {
  let t0;
  let t1;
  let t2;
  let if_block3_anchor;
  let if_block0 = (
    /*i*/
    ctx[45] !== 0 && create_if_block_8$3()
  );
  let if_block1 = (
    /*p*/
    ctx[43].desc != null && create_if_block_7$3(ctx)
  );
  let if_block2 = (
    /*p*/
    ctx[43].desc != null && /*progress_level*/
    ctx[16] && /*progress_level*/
    ctx[16][
      /*i*/
      ctx[45]
    ] != null && create_if_block_6$6()
  );
  let if_block3 = (
    /*progress_level*/
    ctx[16] != null && create_if_block_5$7(ctx)
  );
  return {
    c() {
      if (if_block0) if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      t2 = space();
      if (if_block3) if_block3.c();
      if_block3_anchor = empty();
    },
    m(target, anchor) {
      if (if_block0) if_block0.m(target, anchor);
      insert(target, t0, anchor);
      if (if_block1) if_block1.m(target, anchor);
      insert(target, t1, anchor);
      if (if_block2) if_block2.m(target, anchor);
      insert(target, t2, anchor);
      if (if_block3) if_block3.m(target, anchor);
      insert(target, if_block3_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*p*/
        ctx2[43].desc != null
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_7$3(ctx2);
          if_block1.c();
          if_block1.m(t1.parentNode, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (
        /*p*/
        ctx2[43].desc != null && /*progress_level*/
        ctx2[16] && /*progress_level*/
        ctx2[16][
          /*i*/
          ctx2[45]
        ] != null
      ) {
        if (if_block2) ;
        else {
          if_block2 = create_if_block_6$6();
          if_block2.c();
          if_block2.m(t2.parentNode, t2);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (
        /*progress_level*/
        ctx2[16] != null
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
        } else {
          if_block3 = create_if_block_5$7(ctx2);
          if_block3.c();
          if_block3.m(if_block3_anchor.parentNode, if_block3_anchor);
        }
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(t2);
        detach(if_block3_anchor);
      }
      if (if_block0) if_block0.d(detaching);
      if (if_block1) if_block1.d(detaching);
      if (if_block2) if_block2.d(detaching);
      if (if_block3) if_block3.d(detaching);
    }
  };
}
function create_if_block_8$3(ctx) {
  let t;
  return {
    c() {
      t = text(" /");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_7$3(ctx) {
  let t_value = (
    /*p*/
    ctx[43].desc + ""
  );
  let t;
  return {
    c() {
      t = text(t_value);
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress*/
      256 && t_value !== (t_value = /*p*/
      ctx2[43].desc + "")) set_data(t, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_6$6(ctx) {
  let t;
  return {
    c() {
      t = text("-");
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_5$7(ctx) {
  let t0_value = (100 * /*progress_level*/
  (ctx[16][
    /*i*/
    ctx[45]
  ] || 0)).toFixed(1) + "";
  let t0;
  let t1;
  return {
    c() {
      t0 = text(t0_value);
      t1 = text("%");
    },
    m(target, anchor) {
      insert(target, t0, anchor);
      insert(target, t1, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*progress_level*/
      65536 && t0_value !== (t0_value = (100 * /*progress_level*/
      (ctx2[16][
        /*i*/
        ctx2[45]
      ] || 0)).toFixed(1) + "")) set_data(t0, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
      }
    }
  };
}
function create_each_block$4(ctx) {
  let if_block_anchor;
  let if_block = (
    /*p*/
    (ctx[43].desc != null || /*progress_level*/
    ctx[16] && /*progress_level*/
    ctx[16][
      /*i*/
      ctx[45]
    ] != null) && create_if_block_4$7(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (
        /*p*/
        ctx2[43].desc != null || /*progress_level*/
        ctx2[16] && /*progress_level*/
        ctx2[16][
          /*i*/
          ctx2[45]
        ] != null
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_4$7(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block_1$b(ctx) {
  let p_1;
  let t0;
  let t1;
  let current;
  const additional_loading_text_slot_template = (
    /*#slots*/
    ctx[32]["additional-loading-text"]
  );
  const additional_loading_text_slot = create_slot(
    additional_loading_text_slot_template,
    ctx,
    /*$$scope*/
    ctx[31],
    get_additional_loading_text_slot_context
  );
  return {
    c() {
      p_1 = element("p");
      t0 = text(
        /*loading_text*/
        ctx[10]
      );
      t1 = space();
      if (additional_loading_text_slot) additional_loading_text_slot.c();
      attr(p_1, "class", "loading svelte-vusapu");
    },
    m(target, anchor) {
      insert(target, p_1, anchor);
      append(p_1, t0);
      insert(target, t1, anchor);
      if (additional_loading_text_slot) {
        additional_loading_text_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (!current || dirty[0] & /*loading_text*/
      1024) set_data(
        t0,
        /*loading_text*/
        ctx2[10]
      );
      if (additional_loading_text_slot) {
        if (additional_loading_text_slot.p && (!current || dirty[1] & /*$$scope*/
        1)) {
          update_slot_base(
            additional_loading_text_slot,
            additional_loading_text_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[31],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[31]
            ) : get_slot_changes(
              additional_loading_text_slot_template,
              /*$$scope*/
              ctx2[31],
              dirty,
              get_additional_loading_text_slot_changes
            ),
            get_additional_loading_text_slot_context
          );
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(additional_loading_text_slot, local);
      current = true;
    },
    o(local) {
      transition_out(additional_loading_text_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(p_1);
        detach(t1);
      }
      if (additional_loading_text_slot) additional_loading_text_slot.d(detaching);
    }
  };
}
function create_fragment$q(ctx) {
  let div;
  let t;
  let current_block_type_index;
  let if_block1;
  let div_class_value;
  let current;
  let if_block0 = (
    /*validation_error*/
    ctx[1] && /*show_validation_error*/
    ctx[14] && create_if_block_18(ctx)
  );
  const if_block_creators = [create_if_block$f, create_if_block_17];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*status*/
      ctx2[5] === "pending"
    ) return 0;
    if (
      /*status*/
      ctx2[5] === "error"
    ) return 1;
    return -1;
  }
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  return {
    c() {
      div = element("div");
      if (if_block0) if_block0.c();
      t = space();
      if (if_block1) if_block1.c();
      attr(div, "class", div_class_value = "wrap " + /*variant*/
      ctx[9] + " " + /*show_progress*/
      ctx[7] + " svelte-vusapu");
      toggle_class(div, "hide", (!/*status*/
      ctx[5] || /*status*/
      ctx[5] === "complete" || /*show_progress*/
      ctx[7] === "hidden" || /*status*/
      ctx[5] == "streaming") && !/*validation_error*/
      ctx[1]);
      toggle_class(
        div,
        "translucent",
        /*variant*/
        ctx[9] === "center" && /*status*/
        (ctx[5] === "pending" || /*status*/
        ctx[5] === "error") || /*translucent*/
        ctx[12] || /*show_progress*/
        ctx[7] === "minimal" || /*validation_error*/
        ctx[1]
      );
      toggle_class(
        div,
        "generating",
        /*status*/
        ctx[5] === "generating" && /*show_progress*/
        ctx[7] === "full"
      );
      toggle_class(
        div,
        "border",
        /*border*/
        ctx[13]
      );
      set_style(
        div,
        "position",
        /*absolute*/
        ctx[11] ? "absolute" : "static"
      );
      set_style(
        div,
        "padding",
        /*absolute*/
        ctx[11] ? "0" : "var(--size-8) 0"
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0) if_block0.m(div, null);
      append(div, t);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div, null);
      }
      ctx[36](div);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*validation_error*/
        ctx2[1] && /*show_validation_error*/
        ctx2[14]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*validation_error, show_validation_error*/
          16386) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_18(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div, t);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block1) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block1 = if_blocks[current_block_type_index];
          if (!if_block1) {
            if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block1.c();
          } else {
            if_block1.p(ctx2, dirty);
          }
          transition_in(if_block1, 1);
          if_block1.m(div, null);
        } else {
          if_block1 = null;
        }
      }
      if (!current || dirty[0] & /*variant, show_progress*/
      640 && div_class_value !== (div_class_value = "wrap " + /*variant*/
      ctx2[9] + " " + /*show_progress*/
      ctx2[7] + " svelte-vusapu")) {
        attr(div, "class", div_class_value);
      }
      if (!current || dirty[0] & /*variant, show_progress, status, show_progress, validation_error*/
      674) {
        toggle_class(div, "hide", (!/*status*/
        ctx2[5] || /*status*/
        ctx2[5] === "complete" || /*show_progress*/
        ctx2[7] === "hidden" || /*status*/
        ctx2[5] == "streaming") && !/*validation_error*/
        ctx2[1]);
      }
      if (!current || dirty[0] & /*variant, show_progress, variant, status, translucent, show_progress, validation_error*/
      4770) {
        toggle_class(
          div,
          "translucent",
          /*variant*/
          ctx2[9] === "center" && /*status*/
          (ctx2[5] === "pending" || /*status*/
          ctx2[5] === "error") || /*translucent*/
          ctx2[12] || /*show_progress*/
          ctx2[7] === "minimal" || /*validation_error*/
          ctx2[1]
        );
      }
      if (!current || dirty[0] & /*variant, show_progress, status, show_progress*/
      672) {
        toggle_class(
          div,
          "generating",
          /*status*/
          ctx2[5] === "generating" && /*show_progress*/
          ctx2[7] === "full"
        );
      }
      if (!current || dirty[0] & /*variant, show_progress, border*/
      8832) {
        toggle_class(
          div,
          "border",
          /*border*/
          ctx2[13]
        );
      }
      if (dirty[0] & /*absolute*/
      2048) {
        set_style(
          div,
          "position",
          /*absolute*/
          ctx2[11] ? "absolute" : "static"
        );
      }
      if (dirty[0] & /*absolute*/
      2048) {
        set_style(
          div,
          "padding",
          /*absolute*/
          ctx2[11] ? "0" : "var(--size-8) 0"
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (if_block0) if_block0.d();
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      ctx[36](null);
    }
  };
}
let items = [];
let called = false;
const is_browser = typeof window !== "undefined";
const raf = is_browser ? window.requestAnimationFrame : (cb) => {
};
async function scroll_into_view(el, enable = true) {
  if (window.__gradio_mode__ === "website" || window.__gradio_mode__ !== "app" && enable !== true) {
    return;
  }
  items.push(el);
  if (!called) called = true;
  else return;
  await tick();
  raf(() => {
    let min = [0, 0];
    for (let i = 0; i < items.length; i++) {
      const element2 = items[i];
      const box = element2.getBoundingClientRect();
      if (i === 0 || box.top + window.scrollY <= min[0]) {
        min[0] = box.top + window.scrollY;
        min[1] = i;
      }
    }
    window.scrollTo({ top: min[0] - 20, behavior: "smooth" });
    called = false;
    items = [];
  });
}
function instance$p($$self, $$props, $$invalidate) {
  let formatted_timer;
  let { $$slots: slots = {}, $$scope } = $$props;
  const dispatch2 = createEventDispatcher();
  let { i18n } = $$props;
  let { eta = null } = $$props;
  let { queue_position } = $$props;
  let { queue_size } = $$props;
  let { status } = $$props;
  let { scroll_to_output = false } = $$props;
  let { timer = true } = $$props;
  let { show_progress = "full" } = $$props;
  let { message = null } = $$props;
  let { progress = null } = $$props;
  let { variant = "default" } = $$props;
  let { loading_text = "Loading..." } = $$props;
  let { absolute = true } = $$props;
  let { translucent = false } = $$props;
  let { border = false } = $$props;
  let { autoscroll } = $$props;
  let { validation_error = null } = $$props;
  let { show_validation_error = true } = $$props;
  let el;
  let _timer = false;
  let timer_start = 0;
  let timer_diff = 0;
  let old_eta = null;
  let eta_from_start = null;
  let eta_level = 0;
  let progress_level = null;
  let last_progress_level = void 0;
  let progress_bar = null;
  let show_eta_bar = true;
  const start_timer = () => {
    $$invalidate(0, eta = $$invalidate(29, old_eta = $$invalidate(21, formatted_eta = null)));
    $$invalidate(27, timer_start = performance.now());
    $$invalidate(28, timer_diff = 0);
    _timer = true;
    run2();
  };
  function run2() {
    raf(() => {
      $$invalidate(28, timer_diff = (performance.now() - timer_start) / 1e3);
      if (_timer) run2();
    });
  }
  function stop_timer() {
    $$invalidate(28, timer_diff = 0);
    $$invalidate(0, eta = $$invalidate(29, old_eta = $$invalidate(21, formatted_eta = null)));
    if (!_timer) return;
    _timer = false;
  }
  onDestroy(() => {
    if (_timer) stop_timer();
  });
  let formatted_eta = null;
  const click_handler = () => $$invalidate(1, validation_error = null);
  function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      progress_bar = $$value;
      $$invalidate(18, progress_bar), $$invalidate(8, progress), $$invalidate(16, progress_level), $$invalidate(17, last_progress_level);
    });
  }
  const click_handler_1 = () => {
    dispatch2("clear_status");
  };
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      el = $$value;
      $$invalidate(15, el);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("i18n" in $$props2) $$invalidate(2, i18n = $$props2.i18n);
    if ("eta" in $$props2) $$invalidate(0, eta = $$props2.eta);
    if ("queue_position" in $$props2) $$invalidate(3, queue_position = $$props2.queue_position);
    if ("queue_size" in $$props2) $$invalidate(4, queue_size = $$props2.queue_size);
    if ("status" in $$props2) $$invalidate(5, status = $$props2.status);
    if ("scroll_to_output" in $$props2) $$invalidate(24, scroll_to_output = $$props2.scroll_to_output);
    if ("timer" in $$props2) $$invalidate(6, timer = $$props2.timer);
    if ("show_progress" in $$props2) $$invalidate(7, show_progress = $$props2.show_progress);
    if ("message" in $$props2) $$invalidate(25, message = $$props2.message);
    if ("progress" in $$props2) $$invalidate(8, progress = $$props2.progress);
    if ("variant" in $$props2) $$invalidate(9, variant = $$props2.variant);
    if ("loading_text" in $$props2) $$invalidate(10, loading_text = $$props2.loading_text);
    if ("absolute" in $$props2) $$invalidate(11, absolute = $$props2.absolute);
    if ("translucent" in $$props2) $$invalidate(12, translucent = $$props2.translucent);
    if ("border" in $$props2) $$invalidate(13, border = $$props2.border);
    if ("autoscroll" in $$props2) $$invalidate(26, autoscroll = $$props2.autoscroll);
    if ("validation_error" in $$props2) $$invalidate(1, validation_error = $$props2.validation_error);
    if ("show_validation_error" in $$props2) $$invalidate(14, show_validation_error = $$props2.show_validation_error);
    if ("$$scope" in $$props2) $$invalidate(31, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*eta, old_eta, timer_start, eta_from_start*/
    1744830465) {
      {
        if (eta === null) {
          $$invalidate(0, eta = old_eta);
        }
        if (eta != null && old_eta !== eta) {
          $$invalidate(30, eta_from_start = (performance.now() - timer_start) / 1e3 + eta);
          $$invalidate(21, formatted_eta = eta_from_start.toFixed(1));
          $$invalidate(29, old_eta = eta);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*eta_from_start, timer_diff*/
    1342177280) {
      $$invalidate(19, eta_level = eta_from_start === null || eta_from_start <= 0 || !timer_diff ? null : Math.min(timer_diff / eta_from_start, 1));
    }
    if ($$self.$$.dirty[0] & /*progress*/
    256) {
      if (progress != null) {
        $$invalidate(20, show_eta_bar = false);
      }
    }
    if ($$self.$$.dirty[0] & /*progress, progress_level, progress_bar, last_progress_level*/
    459008) {
      {
        if (progress != null) {
          $$invalidate(16, progress_level = progress.map((p) => {
            if (p.index != null && p.length != null) {
              return p.index / p.length;
            } else if (p.progress != null) {
              return p.progress;
            }
            return void 0;
          }));
        } else {
          $$invalidate(16, progress_level = null);
        }
        if (progress_level) {
          $$invalidate(17, last_progress_level = progress_level[progress_level.length - 1]);
          if (progress_bar) {
            if (last_progress_level === 0) {
              $$invalidate(18, progress_bar.style.transition = "0", progress_bar);
            } else {
              $$invalidate(18, progress_bar.style.transition = "150ms", progress_bar);
            }
          }
        } else {
          $$invalidate(17, last_progress_level = void 0);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*status*/
    32) {
      {
        if (status === "pending") {
          start_timer();
        } else {
          stop_timer();
        }
      }
    }
    if ($$self.$$.dirty[0] & /*el, scroll_to_output, status, autoscroll*/
    83918880) {
      el && scroll_to_output && (status === "pending" || status === "complete") && scroll_into_view(el, autoscroll);
    }
    if ($$self.$$.dirty[0] & /*status, message*/
    33554464) ;
    if ($$self.$$.dirty[0] & /*timer_diff*/
    268435456) {
      $$invalidate(22, formatted_timer = timer_diff.toFixed(1));
    }
  };
  return [
    eta,
    validation_error,
    i18n,
    queue_position,
    queue_size,
    status,
    timer,
    show_progress,
    progress,
    variant,
    loading_text,
    absolute,
    translucent,
    border,
    show_validation_error,
    el,
    progress_level,
    last_progress_level,
    progress_bar,
    eta_level,
    show_eta_bar,
    formatted_eta,
    formatted_timer,
    dispatch2,
    scroll_to_output,
    message,
    autoscroll,
    timer_start,
    timer_diff,
    old_eta,
    eta_from_start,
    $$scope,
    slots,
    click_handler,
    div1_binding,
    click_handler_1,
    div_binding
  ];
}
class Static extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$p,
      create_fragment$q,
      safe_not_equal,
      {
        i18n: 2,
        eta: 0,
        queue_position: 3,
        queue_size: 4,
        status: 5,
        scroll_to_output: 24,
        timer: 6,
        show_progress: 7,
        message: 25,
        progress: 8,
        variant: 9,
        loading_text: 10,
        absolute: 11,
        translucent: 12,
        border: 13,
        autoscroll: 26,
        validation_error: 1,
        show_validation_error: 14
      },
      null,
      [-1, -1]
    );
  }
}
function fade(node, { delay = 0, duration = 400, easing = identity } = {}) {
  const o = +getComputedStyle(node).opacity;
  return {
    delay,
    duration,
    easing,
    css: (t) => `opacity: ${t * o}`
  };
}
function create_if_block$e(ctx) {
  let div;
  let style_animation_duration = `${/*time_limit*/
  ctx[0]}s`;
  return {
    c() {
      div = element("div");
      attr(div, "class", "streaming-bar svelte-ga0jj6");
      set_style(div, "animation-duration", style_animation_duration);
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p(ctx2, dirty) {
      if (dirty & /*time_limit*/
      1 && style_animation_duration !== (style_animation_duration = `${/*time_limit*/
      ctx2[0]}s`)) {
        set_style(div, "animation-duration", style_animation_duration);
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_fragment$p(ctx) {
  let if_block_anchor;
  let if_block = (
    /*time_limit*/
    ctx[0] && create_if_block$e(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, [dirty]) {
      if (
        /*time_limit*/
        ctx2[0]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$e(ctx2);
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function instance$o($$self, $$props, $$invalidate) {
  let { time_limit } = $$props;
  $$self.$$set = ($$props2) => {
    if ("time_limit" in $$props2) $$invalidate(0, time_limit = $$props2.time_limit);
  };
  return [time_limit];
}
class StreamingBar extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$o, create_fragment$p, safe_not_equal, { time_limit: 0 });
  }
}
function create_fragment$o(ctx) {
  let label_1;
  let input;
  let t0;
  let span;
  let t1;
  let mounted;
  let dispose;
  return {
    c() {
      label_1 = element("label");
      input = element("input");
      t0 = space();
      span = element("span");
      t1 = text(
        /*label*/
        ctx[2]
      );
      input.disabled = /*disabled*/
      ctx[3];
      attr(input, "type", "checkbox");
      attr(input, "name", "test");
      attr(input, "data-testid", "checkbox");
      attr(input, "class", "svelte-1q14yvm");
      if (
        /*value*/
        ctx[0] === void 0 || /*indeterminate*/
        ctx[1] === void 0
      ) add_render_callback(() => (
        /*input_change_handler*/
        ctx[7].call(input)
      ));
      attr(span, "class", "svelte-1q14yvm");
      attr(label_1, "class", "svelte-1q14yvm");
      toggle_class(
        label_1,
        "disabled",
        /*disabled*/
        ctx[3]
      );
    },
    m(target, anchor) {
      insert(target, label_1, anchor);
      append(label_1, input);
      input.checked = /*value*/
      ctx[0];
      input.indeterminate = /*indeterminate*/
      ctx[1];
      append(label_1, t0);
      append(label_1, span);
      append(span, t1);
      if (!mounted) {
        dispose = [
          listen(
            input,
            "change",
            /*input_change_handler*/
            ctx[7]
          ),
          listen(
            input,
            "keydown",
            /*handle_enter*/
            ctx[4]
          ),
          listen(
            input,
            "input",
            /*handle_input*/
            ctx[5]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (dirty & /*disabled*/
      8) {
        input.disabled = /*disabled*/
        ctx2[3];
      }
      if (dirty & /*value*/
      1) {
        input.checked = /*value*/
        ctx2[0];
      }
      if (dirty & /*indeterminate*/
      2) {
        input.indeterminate = /*indeterminate*/
        ctx2[1];
      }
      if (dirty & /*label*/
      4) set_data(
        t1,
        /*label*/
        ctx2[2]
      );
      if (dirty & /*disabled*/
      8) {
        toggle_class(
          label_1,
          "disabled",
          /*disabled*/
          ctx2[3]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(label_1);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance$n($$self, $$props, $$invalidate) {
  let disabled;
  let { value = false } = $$props;
  let { label = "Checkbox" } = $$props;
  let { interactive } = $$props;
  let { indeterminate = false } = $$props;
  const dispatch2 = createEventDispatcher();
  async function handle_enter(event) {
    if (event.key === "Enter") {
      $$invalidate(0, value = !value);
      dispatch2("select", {
        index: 0,
        value: event.currentTarget.checked,
        selected: event.currentTarget.checked
      });
    }
  }
  async function handle_input(event) {
    $$invalidate(0, value = event.currentTarget.checked);
    dispatch2("select", {
      index: 0,
      value: event.currentTarget.checked,
      selected: event.currentTarget.checked
    });
  }
  function input_change_handler() {
    value = this.checked;
    indeterminate = this.indeterminate;
    $$invalidate(0, value);
    $$invalidate(1, indeterminate);
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("label" in $$props2) $$invalidate(2, label = $$props2.label);
    if ("interactive" in $$props2) $$invalidate(6, interactive = $$props2.interactive);
    if ("indeterminate" in $$props2) $$invalidate(1, indeterminate = $$props2.indeterminate);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty & /*value*/
    1) {
      dispatch2("change", value);
    }
    if ($$self.$$.dirty & /*interactive*/
    64) {
      $$invalidate(3, disabled = !interactive);
    }
  };
  return [
    value,
    indeterminate,
    label,
    disabled,
    handle_enter,
    handle_input,
    interactive,
    input_change_handler
  ];
}
class Checkbox extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$n, create_fragment$o, safe_not_equal, {
      value: 0,
      label: 2,
      interactive: 6,
      indeterminate: 1
    });
  }
}
function create_fragment$n(ctx) {
  let div;
  let basecheckbox;
  let updating_value;
  let current;
  function basecheckbox_value_binding(value) {
    ctx[4](value);
  }
  let basecheckbox_props = {
    label: "",
    interactive: (
      /*editable*/
      ctx[1]
    )
  };
  if (
    /*value*/
    ctx[0] !== void 0
  ) {
    basecheckbox_props.value = /*value*/
    ctx[0];
  }
  basecheckbox = new Checkbox({ props: basecheckbox_props });
  binding_callbacks.push(() => bind(basecheckbox, "value", basecheckbox_value_binding));
  basecheckbox.$on(
    "change",
    /*handle_change*/
    ctx[2]
  );
  return {
    c() {
      div = element("div");
      create_component(basecheckbox.$$.fragment);
      attr(div, "class", "bool-cell svelte-1fodq17");
      attr(div, "role", "button");
      attr(div, "tabindex", "-1");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(basecheckbox, div, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      const basecheckbox_changes = {};
      if (dirty & /*editable*/
      2) basecheckbox_changes.interactive = /*editable*/
      ctx2[1];
      if (!updating_value && dirty & /*value*/
      1) {
        updating_value = true;
        basecheckbox_changes.value = /*value*/
        ctx2[0];
        add_flush_callback(() => updating_value = false);
      }
      basecheckbox.$set(basecheckbox_changes);
    },
    i(local) {
      if (current) return;
      transition_in(basecheckbox.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(basecheckbox.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(basecheckbox);
    }
  };
}
function instance$m($$self, $$props, $$invalidate) {
  let { value = false } = $$props;
  let { editable = true } = $$props;
  let { on_change } = $$props;
  function handle_change(event) {
    if (editable) {
      on_change(event.detail);
    }
  }
  function basecheckbox_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("editable" in $$props2) $$invalidate(1, editable = $$props2.editable);
    if ("on_change" in $$props2) $$invalidate(3, on_change = $$props2.on_change);
  };
  return [value, editable, handle_change, on_change, basecheckbox_value_binding];
}
let BooleanCell$1 = class BooleanCell extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$m, create_fragment$n, safe_not_equal, { value: 0, editable: 1, on_change: 3 });
  }
};
function create_if_block_5$6(ctx) {
  let textarea;
  let textarea_aria_label_value;
  let mounted;
  let dispose;
  return {
    c() {
      textarea = element("textarea");
      textarea.readOnly = /*is_static*/
      ctx[9];
      attr(
        textarea,
        "aria-readonly",
        /*is_static*/
        ctx[9]
      );
      attr(textarea, "aria-label", textarea_aria_label_value = /*is_static*/
      ctx[9] ? "Cell is read-only" : "Edit cell");
      attr(textarea, "tabindex", "-1");
      attr(textarea, "class", "svelte-8fgf56");
      toggle_class(
        textarea,
        "header",
        /*header*/
        ctx[4]
      );
    },
    m(target, anchor) {
      insert(target, textarea, anchor);
      ctx[29](textarea);
      set_input_value(
        textarea,
        /*value*/
        ctx[0]
      );
      if (!mounted) {
        dispose = [
          listen(
            textarea,
            "input",
            /*textarea_input_handler*/
            ctx[30]
          ),
          listen(
            textarea,
            "blur",
            /*handle_blur*/
            ctx[20]
          ),
          listen(textarea, "mousedown", stop_propagation(
            /*mousedown_handler*/
            ctx[27]
          )),
          listen(textarea, "click", stop_propagation(
            /*click_handler*/
            ctx[28]
          )),
          action_destroyer(use_focus.call(null, textarea)),
          listen(
            textarea,
            "keydown",
            /*handle_keydown*/
            ctx[21]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*is_static*/
      512) {
        textarea.readOnly = /*is_static*/
        ctx2[9];
      }
      if (dirty[0] & /*is_static*/
      512) {
        attr(
          textarea,
          "aria-readonly",
          /*is_static*/
          ctx2[9]
        );
      }
      if (dirty[0] & /*is_static*/
      512 && textarea_aria_label_value !== (textarea_aria_label_value = /*is_static*/
      ctx2[9] ? "Cell is read-only" : "Edit cell")) {
        attr(textarea, "aria-label", textarea_aria_label_value);
      }
      if (dirty[0] & /*value*/
      1) {
        set_input_value(
          textarea,
          /*value*/
          ctx2[0]
        );
      }
      if (dirty[0] & /*header*/
      16) {
        toggle_class(
          textarea,
          "header",
          /*header*/
          ctx2[4]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(textarea);
      }
      ctx[29](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_else_block$5(ctx) {
  let span;
  let current_block_type_index;
  let if_block;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block_2$9, create_if_block_3$8, create_if_block_4$6, create_else_block_1$2];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*datatype*/
      ctx2[5] === "image" && /*components*/
      ctx2[11].image
    ) return 0;
    if (
      /*datatype*/
      ctx2[5] === "html"
    ) return 1;
    if (
      /*datatype*/
      ctx2[5] === "markdown"
    ) return 2;
    return 3;
  }
  current_block_type_index = select_block_type_1(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      span = element("span");
      if_block.c();
      attr(span, "tabindex", "0");
      attr(span, "role", "button");
      attr(
        span,
        "style",
        /*styling*/
        ctx[3]
      );
      attr(
        span,
        "data-editable",
        /*editable*/
        ctx[8]
      );
      attr(
        span,
        "data-max-chars",
        /*max_chars*/
        ctx[10]
      );
      attr(
        span,
        "data-expanded",
        /*edit*/
        ctx[2]
      );
      attr(span, "placeholder", " ");
      attr(span, "class", "svelte-8fgf56");
      toggle_class(
        span,
        "dragging",
        /*is_dragging*/
        ctx[13]
      );
      toggle_class(
        span,
        "edit",
        /*edit*/
        ctx[2]
      );
      toggle_class(
        span,
        "expanded",
        /*edit*/
        ctx[2]
      );
      toggle_class(
        span,
        "multiline",
        /*header*/
        ctx[4]
      );
      toggle_class(
        span,
        "text",
        /*datatype*/
        ctx[5] === "str"
      );
      toggle_class(
        span,
        "wrap",
        /*wrap_text*/
        ctx[14]
      );
    },
    m(target, anchor) {
      insert(target, span, anchor);
      if_blocks[current_block_type_index].m(span, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            span,
            "keydown",
            /*handle_keydown*/
            ctx[21]
          ),
          listen(span, "focus", prevent_default(
            /*focus_handler*/
            ctx[26]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(span, null);
      }
      if (!current || dirty[0] & /*styling*/
      8) {
        attr(
          span,
          "style",
          /*styling*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*editable*/
      256) {
        attr(
          span,
          "data-editable",
          /*editable*/
          ctx2[8]
        );
      }
      if (!current || dirty[0] & /*max_chars*/
      1024) {
        attr(
          span,
          "data-max-chars",
          /*max_chars*/
          ctx2[10]
        );
      }
      if (!current || dirty[0] & /*edit*/
      4) {
        attr(
          span,
          "data-expanded",
          /*edit*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*is_dragging*/
      8192) {
        toggle_class(
          span,
          "dragging",
          /*is_dragging*/
          ctx2[13]
        );
      }
      if (!current || dirty[0] & /*edit*/
      4) {
        toggle_class(
          span,
          "edit",
          /*edit*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*edit*/
      4) {
        toggle_class(
          span,
          "expanded",
          /*edit*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*header*/
      16) {
        toggle_class(
          span,
          "multiline",
          /*header*/
          ctx2[4]
        );
      }
      if (!current || dirty[0] & /*datatype*/
      32) {
        toggle_class(
          span,
          "text",
          /*datatype*/
          ctx2[5] === "str"
        );
      }
      if (!current || dirty[0] & /*wrap_text*/
      16384) {
        toggle_class(
          span,
          "wrap",
          /*wrap_text*/
          ctx2[14]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
      if_blocks[current_block_type_index].d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_1$a(ctx) {
  let booleancell;
  let updating_value;
  let current;
  function booleancell_value_binding(value) {
    ctx[31](value);
  }
  let booleancell_props = {
    editable: (
      /*editable*/
      ctx[8]
    ),
    on_change: (
      /*commit_change*/
      ctx[22]
    )
  };
  if (
    /*value*/
    ctx[0] !== void 0
  ) {
    booleancell_props.value = /*value*/
    ctx[0];
  }
  booleancell = new BooleanCell$1({ props: booleancell_props });
  binding_callbacks.push(() => bind(booleancell, "value", booleancell_value_binding));
  return {
    c() {
      create_component(booleancell.$$.fragment);
    },
    m(target, anchor) {
      mount_component(booleancell, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const booleancell_changes = {};
      if (dirty[0] & /*editable*/
      256) booleancell_changes.editable = /*editable*/
      ctx2[8];
      if (!updating_value && dirty[0] & /*value*/
      1) {
        updating_value = true;
        booleancell_changes.value = /*value*/
        ctx2[0];
        add_flush_callback(() => updating_value = false);
      }
      booleancell.$set(booleancell_changes);
    },
    i(local) {
      if (current) return;
      transition_in(booleancell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(booleancell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(booleancell, detaching);
    }
  };
}
function create_else_block_1$2(ctx) {
  let t;
  return {
    c() {
      t = text(
        /*display_text*/
        ctx[19]
      );
    },
    m(target, anchor) {
      insert(target, t, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*display_text*/
      524288) set_data(
        t,
        /*display_text*/
        ctx2[19]
      );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(t);
      }
    }
  };
}
function create_if_block_4$6(ctx) {
  let markdowncode;
  let current;
  markdowncode = new MarkdownCode({
    props: {
      message: (
        /*display_text*/
        ctx[19].toLocaleString()
      ),
      latex_delimiters: (
        /*latex_delimiters*/
        ctx[6]
      ),
      line_breaks: (
        /*line_breaks*/
        ctx[7]
      ),
      chatbot: false
    }
  });
  return {
    c() {
      create_component(markdowncode.$$.fragment);
    },
    m(target, anchor) {
      mount_component(markdowncode, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const markdowncode_changes = {};
      if (dirty[0] & /*display_text*/
      524288) markdowncode_changes.message = /*display_text*/
      ctx2[19].toLocaleString();
      if (dirty[0] & /*latex_delimiters*/
      64) markdowncode_changes.latex_delimiters = /*latex_delimiters*/
      ctx2[6];
      if (dirty[0] & /*line_breaks*/
      128) markdowncode_changes.line_breaks = /*line_breaks*/
      ctx2[7];
      markdowncode.$set(markdowncode_changes);
    },
    i(local) {
      if (current) return;
      transition_in(markdowncode.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(markdowncode.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(markdowncode, detaching);
    }
  };
}
function create_if_block_3$8(ctx) {
  let html_tag;
  let html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(
        /*display_text*/
        ctx[19],
        target,
        anchor
      );
      insert(target, html_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*display_text*/
      524288) html_tag.p(
        /*display_text*/
        ctx2[19]
      );
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}
function create_if_block_2$9(ctx) {
  let switch_instance;
  let switch_instance_anchor;
  let current;
  var switch_value = (
    /*components*/
    ctx[11].image
  );
  function switch_props(ctx2, dirty) {
    return {
      props: {
        value: { url: (
          /*display_text*/
          ctx2[19]
        ) },
        show_label: false,
        label: "cell-image",
        show_download_button: false,
        i18n: (
          /*i18n*/
          ctx2[12]
        ),
        gradio: { dispatch: func }
      }
    };
  }
  if (switch_value) {
    switch_instance = construct_svelte_component(switch_value, switch_props(ctx));
  }
  return {
    c() {
      if (switch_instance) create_component(switch_instance.$$.fragment);
      switch_instance_anchor = empty();
    },
    m(target, anchor) {
      if (switch_instance) mount_component(switch_instance, target, anchor);
      insert(target, switch_instance_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*components*/
      2048 && switch_value !== (switch_value = /*components*/
      ctx2[11].image)) {
        if (switch_instance) {
          group_outros();
          const old_component = switch_instance;
          transition_out(old_component.$$.fragment, 1, 0, () => {
            destroy_component(old_component, 1);
          });
          check_outros();
        }
        if (switch_value) {
          switch_instance = construct_svelte_component(switch_value, switch_props(ctx2));
          create_component(switch_instance.$$.fragment);
          transition_in(switch_instance.$$.fragment, 1);
          mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
        } else {
          switch_instance = null;
        }
      } else if (switch_value) {
        const switch_instance_changes = {};
        if (dirty[0] & /*display_text*/
        524288) switch_instance_changes.value = { url: (
          /*display_text*/
          ctx2[19]
        ) };
        if (dirty[0] & /*i18n*/
        4096) switch_instance_changes.i18n = /*i18n*/
        ctx2[12];
        switch_instance.$set(switch_instance_changes);
      }
    },
    i(local) {
      if (current) return;
      if (switch_instance) transition_in(switch_instance.$$.fragment, local);
      current = true;
    },
    o(local) {
      if (switch_instance) transition_out(switch_instance.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(switch_instance_anchor);
      }
      if (switch_instance) destroy_component(switch_instance, detaching);
    }
  };
}
function create_if_block$d(ctx) {
  let selectionbuttons0;
  let t;
  let selectionbuttons1;
  let current;
  selectionbuttons0 = new SelectionButtons$1({
    props: {
      position: "column",
      coords: (
        /*coords*/
        ctx[16]
      ),
      on_click: (
        /*func_1*/
        ctx[32]
      )
    }
  });
  selectionbuttons1 = new SelectionButtons$1({
    props: {
      position: "row",
      coords: (
        /*coords*/
        ctx[16]
      ),
      on_click: (
        /*func_2*/
        ctx[33]
      )
    }
  });
  return {
    c() {
      create_component(selectionbuttons0.$$.fragment);
      t = space();
      create_component(selectionbuttons1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(selectionbuttons0, target, anchor);
      insert(target, t, anchor);
      mount_component(selectionbuttons1, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const selectionbuttons0_changes = {};
      if (dirty[0] & /*coords*/
      65536) selectionbuttons0_changes.coords = /*coords*/
      ctx2[16];
      if (dirty[0] & /*on_select_column, coords*/
      196608) selectionbuttons0_changes.on_click = /*func_1*/
      ctx2[32];
      selectionbuttons0.$set(selectionbuttons0_changes);
      const selectionbuttons1_changes = {};
      if (dirty[0] & /*coords*/
      65536) selectionbuttons1_changes.coords = /*coords*/
      ctx2[16];
      if (dirty[0] & /*on_select_row, coords*/
      327680) selectionbuttons1_changes.on_click = /*func_2*/
      ctx2[33];
      selectionbuttons1.$set(selectionbuttons1_changes);
    },
    i(local) {
      if (current) return;
      transition_in(selectionbuttons0.$$.fragment, local);
      transition_in(selectionbuttons1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(selectionbuttons0.$$.fragment, local);
      transition_out(selectionbuttons1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
      destroy_component(selectionbuttons0, detaching);
      destroy_component(selectionbuttons1, detaching);
    }
  };
}
function create_fragment$m(ctx) {
  let t0;
  let current_block_type_index;
  let if_block1;
  let t1;
  let if_block2_anchor;
  let current;
  let if_block0 = (
    /*edit*/
    ctx[2] && /*datatype*/
    ctx[5] !== "bool" && create_if_block_5$6(ctx)
  );
  const if_block_creators = [create_if_block_1$a, create_else_block$5];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*datatype*/
      ctx2[5] === "bool" && typeof /*value*/
      ctx2[0] === "boolean"
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block2 = (
    /*show_selection_buttons*/
    ctx[15] && /*coords*/
    ctx[16] && /*on_select_column*/
    ctx[17] && /*on_select_row*/
    ctx[18] && create_if_block$d(ctx)
  );
  return {
    c() {
      if (if_block0) if_block0.c();
      t0 = space();
      if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      if_block2_anchor = empty();
    },
    m(target, anchor) {
      if (if_block0) if_block0.m(target, anchor);
      insert(target, t0, anchor);
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, t1, anchor);
      if (if_block2) if_block2.m(target, anchor);
      insert(target, if_block2_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*edit*/
        ctx2[2] && /*datatype*/
        ctx2[5] !== "bool"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_5$6(ctx2);
          if_block0.c();
          if_block0.m(t0.parentNode, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block1 = if_blocks[current_block_type_index];
        if (!if_block1) {
          if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block1.c();
        } else {
          if_block1.p(ctx2, dirty);
        }
        transition_in(if_block1, 1);
        if_block1.m(t1.parentNode, t1);
      }
      if (
        /*show_selection_buttons*/
        ctx2[15] && /*coords*/
        ctx2[16] && /*on_select_column*/
        ctx2[17] && /*on_select_row*/
        ctx2[18]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*show_selection_buttons, coords, on_select_column, on_select_row*/
          491520) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block$d(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(if_block2_anchor);
      }
      if (if_block0) if_block0.d(detaching);
      if_blocks[current_block_type_index].d(detaching);
      if (if_block2) if_block2.d(detaching);
    }
  };
}
function truncate_text(text2, max_length = null, is_image = false) {
  if (is_image) return String(text2);
  const str = String(text2);
  if (!max_length || max_length <= 0) return str;
  if (str.length <= max_length) return str;
  return str.slice(0, max_length) + "...";
}
function use_focus(node) {
  requestAnimationFrame(() => {
    node.focus();
  });
  return {};
}
const func = () => {
};
function instance$l($$self, $$props, $$invalidate) {
  let should_truncate;
  let display_content;
  let display_text;
  let { edit: edit2 } = $$props;
  let { value = "" } = $$props;
  let { display_value = null } = $$props;
  let { styling = "" } = $$props;
  let { header = false } = $$props;
  let { datatype = "str" } = $$props;
  let { latex_delimiters } = $$props;
  let { line_breaks = true } = $$props;
  let { editable = true } = $$props;
  let { is_static = false } = $$props;
  let { max_chars = null } = $$props;
  let { components = {} } = $$props;
  let { i18n } = $$props;
  let { is_dragging = false } = $$props;
  let { wrap_text = false } = $$props;
  let { show_selection_buttons = false } = $$props;
  let { coords } = $$props;
  let { on_select_column = null } = $$props;
  let { on_select_row = null } = $$props;
  let { el } = $$props;
  const dispatch2 = createEventDispatcher();
  function handle_blur(event) {
    dispatch2("blur", { blur_event: event, coords });
  }
  function handle_keydown2(event) {
    dispatch2("keydown", event);
  }
  function commit_change(checked) {
    handle_blur({ target: { value } });
  }
  function focus_handler(event) {
    bubble.call(this, $$self, event);
  }
  function mousedown_handler(event) {
    bubble.call(this, $$self, event);
  }
  function click_handler(event) {
    bubble.call(this, $$self, event);
  }
  function textarea_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      el = $$value;
      $$invalidate(1, el);
    });
  }
  function textarea_input_handler() {
    value = this.value;
    $$invalidate(0, value);
  }
  function booleancell_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  const func_1 = () => on_select_column(coords[1]);
  const func_2 = () => on_select_row(coords[0]);
  $$self.$$set = ($$props2) => {
    if ("edit" in $$props2) $$invalidate(2, edit2 = $$props2.edit);
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("display_value" in $$props2) $$invalidate(23, display_value = $$props2.display_value);
    if ("styling" in $$props2) $$invalidate(3, styling = $$props2.styling);
    if ("header" in $$props2) $$invalidate(4, header = $$props2.header);
    if ("datatype" in $$props2) $$invalidate(5, datatype = $$props2.datatype);
    if ("latex_delimiters" in $$props2) $$invalidate(6, latex_delimiters = $$props2.latex_delimiters);
    if ("line_breaks" in $$props2) $$invalidate(7, line_breaks = $$props2.line_breaks);
    if ("editable" in $$props2) $$invalidate(8, editable = $$props2.editable);
    if ("is_static" in $$props2) $$invalidate(9, is_static = $$props2.is_static);
    if ("max_chars" in $$props2) $$invalidate(10, max_chars = $$props2.max_chars);
    if ("components" in $$props2) $$invalidate(11, components = $$props2.components);
    if ("i18n" in $$props2) $$invalidate(12, i18n = $$props2.i18n);
    if ("is_dragging" in $$props2) $$invalidate(13, is_dragging = $$props2.is_dragging);
    if ("wrap_text" in $$props2) $$invalidate(14, wrap_text = $$props2.wrap_text);
    if ("show_selection_buttons" in $$props2) $$invalidate(15, show_selection_buttons = $$props2.show_selection_buttons);
    if ("coords" in $$props2) $$invalidate(16, coords = $$props2.coords);
    if ("on_select_column" in $$props2) $$invalidate(17, on_select_column = $$props2.on_select_column);
    if ("on_select_row" in $$props2) $$invalidate(18, on_select_row = $$props2.on_select_row);
    if ("el" in $$props2) $$invalidate(1, el = $$props2.el);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*edit, max_chars*/
    1028) {
      $$invalidate(25, should_truncate = !edit2 && max_chars !== null && max_chars > 0);
    }
    if ($$self.$$.dirty[0] & /*editable, value, display_value*/
    8388865) {
      $$invalidate(24, display_content = editable ? value : display_value !== null ? display_value : value);
    }
    if ($$self.$$.dirty[0] & /*should_truncate, display_content, max_chars, datatype*/
    50332704) {
      $$invalidate(19, display_text = should_truncate ? truncate_text(display_content, max_chars, datatype === "image") : display_content);
    }
    if ($$self.$$.dirty[0] & /*edit, value*/
    5) {
      if (!edit2) {
        handle_blur({ target: { value } });
      }
    }
  };
  return [
    value,
    el,
    edit2,
    styling,
    header,
    datatype,
    latex_delimiters,
    line_breaks,
    editable,
    is_static,
    max_chars,
    components,
    i18n,
    is_dragging,
    wrap_text,
    show_selection_buttons,
    coords,
    on_select_column,
    on_select_row,
    display_text,
    handle_blur,
    handle_keydown2,
    commit_change,
    display_value,
    display_content,
    should_truncate,
    focus_handler,
    mousedown_handler,
    click_handler,
    textarea_binding,
    textarea_input_handler,
    booleancell_value_binding,
    func_1,
    func_2
  ];
}
let EditableCell$1 = class EditableCell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$l,
      create_fragment$m,
      safe_not_equal,
      {
        edit: 2,
        value: 0,
        display_value: 23,
        styling: 3,
        header: 4,
        datatype: 5,
        latex_delimiters: 6,
        line_breaks: 7,
        editable: 8,
        is_static: 9,
        max_chars: 10,
        components: 11,
        i18n: 12,
        is_dragging: 13,
        wrap_text: 14,
        show_selection_buttons: 15,
        coords: 16,
        on_select_column: 17,
        on_select_row: 18,
        el: 1
      },
      null,
      [-1, -1]
    );
  }
};
function create_else_block$4(ctx) {
  let td;
  let t_value = (
    /*index*/
    (ctx[0] !== null ? (
      /*index*/
      ctx[0] + 1
    ) : "") + ""
  );
  let t;
  return {
    c() {
      td = element("td");
      t = text(t_value);
      attr(td, "class", "row-number svelte-1u9ak0p");
      attr(td, "tabindex", "-1");
      attr(
        td,
        "data-row",
        /*index*/
        ctx[0]
      );
      attr(td, "data-col", "row-number");
    },
    m(target, anchor) {
      insert(target, td, anchor);
      append(td, t);
    },
    p(ctx2, dirty) {
      if (dirty & /*index*/
      1 && t_value !== (t_value = /*index*/
      (ctx2[0] !== null ? (
        /*index*/
        ctx2[0] + 1
      ) : "") + "")) set_data(t, t_value);
      if (dirty & /*index*/
      1) {
        attr(
          td,
          "data-row",
          /*index*/
          ctx2[0]
        );
      }
    },
    d(detaching) {
      if (detaching) {
        detach(td);
      }
    }
  };
}
function create_if_block$c(ctx) {
  let th;
  return {
    c() {
      th = element("th");
      th.innerHTML = `<div class="cell-wrap"><div class="header-content"><div class="header-text"></div></div></div>`;
      attr(th, "tabindex", "-1");
      attr(th, "class", "row-number svelte-1u9ak0p");
    },
    m(target, anchor) {
      insert(target, th, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(th);
      }
    }
  };
}
function create_fragment$l(ctx) {
  let if_block_anchor;
  function select_block_type(ctx2, dirty) {
    if (
      /*is_header*/
      ctx2[1]
    ) return create_if_block$c;
    return create_else_block$4;
  }
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, [dirty]) {
      if (current_block_type === (current_block_type = select_block_type(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_block.d(detaching);
    }
  };
}
function instance$k($$self, $$props, $$invalidate) {
  let { index = null } = $$props;
  let { is_header = false } = $$props;
  $$self.$$set = ($$props2) => {
    if ("index" in $$props2) $$invalidate(0, index = $$props2.index);
    if ("is_header" in $$props2) $$invalidate(1, is_header = $$props2.is_header);
  };
  return [index, is_header];
}
let RowNumber$1 = class RowNumber extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$k, create_fragment$l, safe_not_equal, { index: 0, is_header: 1 });
  }
};
function create_fragment$k(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "⋮";
      attr(button, "aria-label", "Open cell menu");
      attr(button, "class", "cell-menu-button svelte-pgxclp");
      attr(button, "aria-haspopup", "menu");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = [
          listen(button, "click", function() {
            if (is_function(
              /*on_click*/
              ctx[0]
            )) ctx[0].apply(this, arguments);
          }),
          listen(
            button,
            "touchstart",
            /*touchstart_handler*/
            ctx[1]
          )
        ];
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx = new_ctx;
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance$j($$self, $$props, $$invalidate) {
  let { on_click } = $$props;
  const touchstart_handler = (event) => {
    event.preventDefault();
    const touch = event.touches[0];
    const mouseEvent = new MouseEvent(
      "click",
      {
        clientX: touch.clientX,
        clientY: touch.clientY,
        bubbles: true,
        cancelable: true,
        view: window
      }
    );
    on_click(mouseEvent);
  };
  $$self.$$set = ($$props2) => {
    if ("on_click" in $$props2) $$invalidate(0, on_click = $$props2.on_click);
  };
  return [on_click, touchstart_handler];
}
let CellMenuButton$1 = class CellMenuButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$j, create_fragment$k, safe_not_equal, { on_click: 0 });
  }
};
function create_fragment$j(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>`;
      attr(div, "class", "wrapper svelte-uijjh0");
      attr(div, "aria-label", "Static column");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
let Padlock$1 = class Padlock extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment$j, safe_not_equal, {});
  }
};
function create_fragment$i(ctx) {
  let svg;
  let path0;
  let path1;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "d", "M4 8L8 4L12 8");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "1.5");
      attr(path0, "stroke-linecap", "round");
      attr(path0, "stroke-linejoin", "round");
      attr(path1, "d", "M8 4V12");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "1.5");
      attr(path1, "stroke-linecap", "round");
      attr(
        svg,
        "width",
        /*size*/
        ctx[0]
      );
      attr(
        svg,
        "height",
        /*size*/
        ctx[0]
      );
      attr(svg, "viewBox", "0 0 16 16");
      attr(svg, "fill", "none");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*size*/
      1) {
        attr(
          svg,
          "width",
          /*size*/
          ctx2[0]
        );
      }
      if (dirty & /*size*/
      1) {
        attr(
          svg,
          "height",
          /*size*/
          ctx2[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function instance$i($$self, $$props, $$invalidate) {
  let { size = 16 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("size" in $$props2) $$invalidate(0, size = $$props2.size);
  };
  return [size];
}
let SortArrowUp$1 = class SortArrowUp extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$i, create_fragment$i, safe_not_equal, { size: 0 });
  }
};
function create_fragment$h(ctx) {
  let svg;
  let path0;
  let path1;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      attr(path0, "d", "M4 8L8 12L12 8");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "1.5");
      attr(path0, "stroke-linecap", "round");
      attr(path0, "stroke-linejoin", "round");
      attr(path1, "d", "M8 12V4");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "1.5");
      attr(path1, "stroke-linecap", "round");
      attr(
        svg,
        "width",
        /*size*/
        ctx[0]
      );
      attr(
        svg,
        "height",
        /*size*/
        ctx[0]
      );
      attr(svg, "viewBox", "0 0 16 16");
      attr(svg, "fill", "none");
      attr(svg, "xmlns", "http://www.w3.org/2000/svg");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
    },
    p(ctx2, [dirty]) {
      if (dirty & /*size*/
      1) {
        attr(
          svg,
          "width",
          /*size*/
          ctx2[0]
        );
      }
      if (dirty & /*size*/
      1) {
        attr(
          svg,
          "height",
          /*size*/
          ctx2[0]
        );
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function instance$h($$self, $$props, $$invalidate) {
  let { size = 16 } = $$props;
  $$self.$$set = ($$props2) => {
    if ("size" in $$props2) $$invalidate(0, size = $$props2.size);
  };
  return [size];
}
let SortArrowDown$1 = class SortArrowDown extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$h, create_fragment$h, safe_not_equal, { size: 0 });
  }
};
function create_if_block_10(ctx) {
  let svg;
  let path0;
  let path1;
  let path2;
  let path3;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      path3 = svg_element("path");
      attr(path0, "d", "M5 5H19");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "2");
      attr(path0, "stroke-linecap", "round");
      attr(path1, "d", "M8 9H16");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "2");
      attr(path1, "stroke-linecap", "round");
      attr(path2, "d", "M11 13H13");
      attr(path2, "stroke", "currentColor");
      attr(path2, "stroke-width", "2");
      attr(path2, "stroke-linecap", "round");
      attr(path3, "d", "M17 17L21 21M21 17L17 21");
      attr(path3, "stroke", "currentColor");
      attr(path3, "stroke-width", "2");
      attr(path3, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, path2);
      append(svg, path3);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_9$1(ctx) {
  let svg;
  let path0;
  let path1;
  let path2;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      attr(path0, "d", "M5 5H19");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "2");
      attr(path0, "stroke-linecap", "round");
      attr(path1, "d", "M8 9H16");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "2");
      attr(path1, "stroke-linecap", "round");
      attr(path2, "d", "M11 13H13");
      attr(path2, "stroke", "currentColor");
      attr(path2, "stroke-width", "2");
      attr(path2, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, path2);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_8$2(ctx) {
  let svg;
  let path0;
  let path1;
  let path2;
  let path3;
  let path4;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      path3 = svg_element("path");
      path4 = svg_element("path");
      attr(path0, "d", "M5 5H19");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "2");
      attr(path0, "stroke-linecap", "round");
      attr(path1, "d", "M5 9H15");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "2");
      attr(path1, "stroke-linecap", "round");
      attr(path2, "d", "M5 13H11");
      attr(path2, "stroke", "currentColor");
      attr(path2, "stroke-width", "2");
      attr(path2, "stroke-linecap", "round");
      attr(path3, "d", "M5 17H7");
      attr(path3, "stroke", "currentColor");
      attr(path3, "stroke-width", "2");
      attr(path3, "stroke-linecap", "round");
      attr(path4, "d", "M17 17L21 21M21 17L17 21");
      attr(path4, "stroke", "currentColor");
      attr(path4, "stroke-width", "2");
      attr(path4, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, path2);
      append(svg, path3);
      append(svg, path4);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_7$2(ctx) {
  let svg;
  let path0;
  let path1;
  let path2;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      attr(path0, "d", "M8 12L12 16L16 12");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "2");
      attr(path0, "fill", "none");
      attr(path0, "stroke-linecap", "round");
      attr(path0, "stroke-linejoin", "round");
      attr(path1, "d", "M12 16V9");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "2");
      attr(path1, "stroke-linecap", "round");
      attr(path2, "d", "M5 5H19");
      attr(path2, "stroke", "currentColor");
      attr(path2, "stroke-width", "2");
      attr(path2, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, path2);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_6$5(ctx) {
  let svg;
  let path0;
  let path1;
  let path2;
  return {
    c() {
      svg = svg_element("svg");
      path0 = svg_element("path");
      path1 = svg_element("path");
      path2 = svg_element("path");
      attr(path0, "d", "M8 16L12 12L16 16");
      attr(path0, "stroke", "currentColor");
      attr(path0, "stroke-width", "2");
      attr(path0, "fill", "none");
      attr(path0, "stroke-linecap", "round");
      attr(path0, "stroke-linejoin", "round");
      attr(path1, "d", "M12 12V19");
      attr(path1, "stroke", "currentColor");
      attr(path1, "stroke-width", "2");
      attr(path1, "stroke-linecap", "round");
      attr(path2, "d", "M5 7H19");
      attr(path2, "stroke", "currentColor");
      attr(path2, "stroke-width", "2");
      attr(path2, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, path0);
      append(svg, path1);
      append(svg, path2);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_5$5(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "10");
      attr(rect, "y", "5");
      attr(rect, "width", "4");
      attr(rect, "height", "14");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(path, "d", "M7 8L17 16M17 8L7 16");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_4$5(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "5");
      attr(rect, "y", "10");
      attr(rect, "width", "14");
      attr(rect, "height", "4");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(path, "d", "M8 7L16 17M16 7L8 17");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_3$7(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "6");
      attr(rect, "y", "4");
      attr(rect, "width", "12");
      attr(rect, "height", "4");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(path, "d", "M12 12V19M8 16L12 19L16 16");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "fill", "none");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_2$8(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "6");
      attr(rect, "y", "16");
      attr(rect, "width", "12");
      attr(rect, "height", "4");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(path, "d", "M12 12V5M8 8L12 5L16 8");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "fill", "none");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block_1$9(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "16");
      attr(rect, "y", "6");
      attr(rect, "width", "4");
      attr(rect, "height", "12");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(rect, "fill", "none");
      attr(path, "d", "M12 12H5M8 8L5 12L8 16");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "fill", "none");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_if_block$b(ctx) {
  let svg;
  let rect;
  let path;
  return {
    c() {
      svg = svg_element("svg");
      rect = svg_element("rect");
      path = svg_element("path");
      attr(rect, "x", "4");
      attr(rect, "y", "6");
      attr(rect, "width", "4");
      attr(rect, "height", "12");
      attr(rect, "stroke", "currentColor");
      attr(rect, "stroke-width", "2");
      attr(rect, "fill", "none");
      attr(path, "d", "M12 12H19M16 8L19 12L16 16");
      attr(path, "stroke", "currentColor");
      attr(path, "stroke-width", "2");
      attr(path, "fill", "none");
      attr(path, "stroke-linecap", "round");
      attr(svg, "viewBox", "0 0 24 24");
      attr(svg, "width", "16");
      attr(svg, "height", "16");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
      append(svg, rect);
      append(svg, path);
    },
    d(detaching) {
      if (detaching) {
        detach(svg);
      }
    }
  };
}
function create_fragment$g(ctx) {
  let if_block_anchor;
  function select_block_type(ctx2, dirty) {
    if (
      /*icon*/
      ctx2[0] == "add-column-right"
    ) return create_if_block$b;
    if (
      /*icon*/
      ctx2[0] == "add-column-left"
    ) return create_if_block_1$9;
    if (
      /*icon*/
      ctx2[0] == "add-row-above"
    ) return create_if_block_2$8;
    if (
      /*icon*/
      ctx2[0] == "add-row-below"
    ) return create_if_block_3$7;
    if (
      /*icon*/
      ctx2[0] == "delete-row"
    ) return create_if_block_4$5;
    if (
      /*icon*/
      ctx2[0] == "delete-column"
    ) return create_if_block_5$5;
    if (
      /*icon*/
      ctx2[0] == "sort-asc"
    ) return create_if_block_6$5;
    if (
      /*icon*/
      ctx2[0] == "sort-desc"
    ) return create_if_block_7$2;
    if (
      /*icon*/
      ctx2[0] == "clear-sort"
    ) return create_if_block_8$2;
    if (
      /*icon*/
      ctx2[0] == "filter"
    ) return create_if_block_9$1;
    if (
      /*icon*/
      ctx2[0] == "clear-filter"
    ) return create_if_block_10;
  }
  let current_block_type = select_block_type(ctx);
  let if_block = current_block_type && current_block_type(ctx);
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, [dirty]) {
      if (current_block_type !== (current_block_type = select_block_type(ctx2))) {
        if (if_block) if_block.d(1);
        if_block = current_block_type && current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) {
        if_block.d(detaching);
      }
    }
  };
}
function instance$g($$self, $$props, $$invalidate) {
  let { icon } = $$props;
  $$self.$$set = ($$props2) => {
    if ("icon" in $$props2) $$invalidate(0, icon = $$props2.icon);
  };
  return [icon];
}
let CellMenuIcons$1 = class CellMenuIcons extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$g, create_fragment$g, safe_not_equal, { icon: 0 });
  }
};
function create_if_block_6$4(ctx) {
  let div;
  let basecheckbox;
  let current;
  let mounted;
  let dispose;
  basecheckbox = new Checkbox({
    props: {
      value: (
        /*select_all_state*/
        ctx[24] === "checked"
      ),
      indeterminate: (
        /*select_all_state*/
        ctx[24] === "indeterminate"
      ),
      label: "",
      interactive: true
    }
  });
  basecheckbox.$on(
    "select",
    /*select_handler*/
    ctx[33]
  );
  return {
    c() {
      div = element("div");
      create_component(basecheckbox.$$.fragment);
      attr(div, "class", "select-all-checkbox svelte-1fq485w");
      attr(div, "role", "button");
      attr(div, "tabindex", "0");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(basecheckbox, div, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(div, "click", stop_propagation(
            /*click_handler*/
            ctx[31]
          )),
          listen(div, "keydown", stop_propagation(keydown_handler)),
          listen(div, "mousedown", stop_propagation(
            /*mousedown_handler*/
            ctx[32]
          ))
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const basecheckbox_changes = {};
      if (dirty[0] & /*select_all_state*/
      16777216) basecheckbox_changes.value = /*select_all_state*/
      ctx2[24] === "checked";
      if (dirty[0] & /*select_all_state*/
      16777216) basecheckbox_changes.indeterminate = /*select_all_state*/
      ctx2[24] === "indeterminate";
      basecheckbox.$set(basecheckbox_changes);
    },
    i(local) {
      if (current) return;
      transition_in(basecheckbox.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(basecheckbox.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(basecheckbox);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_3$6(ctx) {
  let div;
  let span;
  let current_block_type_index;
  let if_block0;
  let t;
  let current;
  const if_block_creators = [create_if_block_5$4, create_else_block$3];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*current_direction*/
      ctx2[21] === "asc"
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = (
    /*sort_columns*/
    ctx[11].length > 1 && create_if_block_4$4(ctx)
  );
  return {
    c() {
      div = element("div");
      span = element("span");
      if_block0.c();
      t = space();
      if (if_block1) if_block1.c();
      attr(span, "class", "sort-arrow svelte-1fq485w");
      attr(div, "class", "sort-indicators svelte-1fq485w");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      if_blocks[current_block_type_index].m(span, null);
      append(div, t);
      if (if_block1) if_block1.m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index !== previous_block_index) {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        }
        transition_in(if_block0, 1);
        if_block0.m(span, null);
      }
      if (
        /*sort_columns*/
        ctx2[11].length > 1
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
        } else {
          if_block1 = create_if_block_4$4(ctx2);
          if_block1.c();
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d();
    }
  };
}
function create_else_block$3(ctx) {
  let sortarrowdown;
  let current;
  sortarrowdown = new SortArrowDown$1({ props: { size: 12 } });
  return {
    c() {
      create_component(sortarrowdown.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortarrowdown, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(sortarrowdown.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortarrowdown.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortarrowdown, detaching);
    }
  };
}
function create_if_block_5$4(ctx) {
  let sortarrowup;
  let current;
  sortarrowup = new SortArrowUp$1({ props: { size: 12 } });
  return {
    c() {
      create_component(sortarrowup.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sortarrowup, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(sortarrowup.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sortarrowup.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sortarrowup, detaching);
    }
  };
}
function create_if_block_4$4(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*sort_priority*/
        ctx[22]
      );
      attr(span, "class", "sort-priority svelte-1fq485w");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*sort_priority*/
      4194304) set_data(
        t,
        /*sort_priority*/
        ctx2[22]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block_2$7(ctx) {
  let div;
  let span;
  let cellmenuicons;
  let current;
  cellmenuicons = new CellMenuIcons$1({ props: { icon: "filter" } });
  return {
    c() {
      div = element("div");
      span = element("span");
      create_component(cellmenuicons.$$.fragment);
      attr(span, "class", "filter-icon svelte-1fq485w");
      attr(div, "class", "filter-indicators svelte-1fq485w");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, span);
      mount_component(cellmenuicons, span, null);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(cellmenuicons);
    }
  };
}
function create_if_block_1$8(ctx) {
  let padlock;
  let current;
  padlock = new Padlock$1({});
  return {
    c() {
      create_component(padlock.$$.fragment);
    },
    m(target, anchor) {
      mount_component(padlock, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(padlock.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(padlock.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(padlock, detaching);
    }
  };
}
function create_if_block$a(ctx) {
  let cellmenubutton;
  let current;
  cellmenubutton = new CellMenuButton$1({ props: { on_click: (
    /*func*/
    ctx[38]
  ) } });
  return {
    c() {
      create_component(cellmenubutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(cellmenubutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const cellmenubutton_changes = {};
      if (dirty[0] & /*toggle_header_menu, i*/
      516) cellmenubutton_changes.on_click = /*func*/
      ctx2[38];
      cellmenubutton.$set(cellmenubutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenubutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenubutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(cellmenubutton, detaching);
    }
  };
}
function create_fragment$f(ctx) {
  let th;
  let div1;
  let div0;
  let t0;
  let button;
  let editablecell;
  let updating_value;
  let updating_el;
  let t1;
  let t2;
  let t3;
  let t4;
  let th_aria_sort_value;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*is_bool_column*/
    ctx[20] && /*editable*/
    ctx[15] && /*on_select_all*/
    ctx[18] && create_if_block_6$4(ctx)
  );
  function editablecell_value_binding(value) {
    ctx[34](value);
  }
  function editablecell_el_binding(value) {
    ctx[35](value);
  }
  let editablecell_props = {
    max_chars: (
      /*max_chars*/
      ctx[14]
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[12]
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[13]
    ),
    edit: (
      /*header_edit*/
      ctx[4] === /*i*/
      ctx[2]
    ),
    header: true,
    editable: (
      /*editable*/
      ctx[15]
    ),
    is_static: (
      /*is_static*/
      ctx[17]
    ),
    i18n: (
      /*i18n*/
      ctx[16]
    ),
    coords: [
      /*i*/
      ctx[2],
      0
    ]
  };
  if (
    /*value*/
    ctx[0] !== void 0
  ) {
    editablecell_props.value = /*value*/
    ctx[0];
  }
  if (
    /*el*/
    ctx[1] !== void 0
  ) {
    editablecell_props.el = /*el*/
    ctx[1];
  }
  editablecell = new EditableCell$1({ props: editablecell_props });
  binding_callbacks.push(() => bind(editablecell, "value", editablecell_value_binding));
  binding_callbacks.push(() => bind(editablecell, "el", editablecell_el_binding));
  editablecell.$on(
    "keydown",
    /*keydown_handler_1*/
    ctx[36]
  );
  let if_block1 = (
    /*sort_index*/
    ctx[19] !== -1 && create_if_block_3$6(ctx)
  );
  let if_block2 = (
    /*filter_index*/
    ctx[23] !== -1 && create_if_block_2$7()
  );
  let if_block3 = (
    /*is_static*/
    ctx[17] && create_if_block_1$8()
  );
  let if_block4 = (
    /*can_add_columns*/
    ctx[25] && create_if_block$a(ctx)
  );
  return {
    c() {
      th = element("th");
      div1 = element("div");
      div0 = element("div");
      if (if_block0) if_block0.c();
      t0 = space();
      button = element("button");
      create_component(editablecell.$$.fragment);
      t1 = space();
      if (if_block1) if_block1.c();
      t2 = space();
      if (if_block2) if_block2.c();
      t3 = space();
      if (if_block3) if_block3.c();
      t4 = space();
      if (if_block4) if_block4.c();
      attr(button, "class", "header-button svelte-1fq485w");
      attr(
        button,
        "title",
        /*value*/
        ctx[0]
      );
      attr(div0, "class", "header-content svelte-1fq485w");
      attr(div1, "class", "cell-wrap svelte-1fq485w");
      attr(th, "aria-sort", th_aria_sort_value = get_sort_status$1(
        /*value*/
        ctx[0],
        /*sort_columns*/
        ctx[11],
        /*headers*/
        ctx[6]
      ) === "none" ? "none" : get_sort_status$1(
        /*value*/
        ctx[0],
        /*sort_columns*/
        ctx[11],
        /*headers*/
        ctx[6]
      ) === "asc" ? "ascending" : "descending");
      set_style(
        th,
        "width",
        /*get_cell_width*/
        ctx[7](
          /*i*/
          ctx[2]
        )
      );
      set_style(
        th,
        "left",
        /*get_header_position*/
        ctx[26](
          /*i*/
          ctx[2]
        )
      );
      attr(
        th,
        "title",
        /*value*/
        ctx[0]
      );
      attr(th, "class", "svelte-1fq485w");
      toggle_class(
        th,
        "pinned-column",
        /*i*/
        ctx[2] < /*actual_pinned_columns*/
        ctx[3]
      );
      toggle_class(
        th,
        "last-pinned",
        /*i*/
        ctx[2] === /*actual_pinned_columns*/
        ctx[3] - 1
      );
      toggle_class(
        th,
        "focus",
        /*header_edit*/
        ctx[4] === /*i*/
        ctx[2] || /*selected_header*/
        ctx[5] === /*i*/
        ctx[2]
      );
      toggle_class(
        th,
        "sorted",
        /*sort_index*/
        ctx[19] !== -1
      );
      toggle_class(
        th,
        "filtered",
        /*filter_index*/
        ctx[23] !== -1
      );
    },
    m(target, anchor) {
      insert(target, th, anchor);
      append(th, div1);
      append(div1, div0);
      if (if_block0) if_block0.m(div0, null);
      append(div0, t0);
      append(div0, button);
      mount_component(editablecell, button, null);
      append(button, t1);
      if (if_block1) if_block1.m(button, null);
      append(button, t2);
      if (if_block2) if_block2.m(button, null);
      append(div0, t3);
      if (if_block3) if_block3.m(div0, null);
      append(div1, t4);
      if (if_block4) if_block4.m(div1, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button,
            "click",
            /*click_handler_1*/
            ctx[37]
          ),
          listen(button, "mousedown", mousedown_handler_1),
          listen(
            th,
            "click",
            /*click_handler_2*/
            ctx[39]
          ),
          listen(th, "mousedown", mousedown_handler_2)
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*is_bool_column*/
        ctx2[20] && /*editable*/
        ctx2[15] && /*on_select_all*/
        ctx2[18]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*is_bool_column, editable, on_select_all*/
          1343488) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_6$4(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div0, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      const editablecell_changes = {};
      if (dirty[0] & /*max_chars*/
      16384) editablecell_changes.max_chars = /*max_chars*/
      ctx2[14];
      if (dirty[0] & /*latex_delimiters*/
      4096) editablecell_changes.latex_delimiters = /*latex_delimiters*/
      ctx2[12];
      if (dirty[0] & /*line_breaks*/
      8192) editablecell_changes.line_breaks = /*line_breaks*/
      ctx2[13];
      if (dirty[0] & /*header_edit, i*/
      20) editablecell_changes.edit = /*header_edit*/
      ctx2[4] === /*i*/
      ctx2[2];
      if (dirty[0] & /*editable*/
      32768) editablecell_changes.editable = /*editable*/
      ctx2[15];
      if (dirty[0] & /*is_static*/
      131072) editablecell_changes.is_static = /*is_static*/
      ctx2[17];
      if (dirty[0] & /*i18n*/
      65536) editablecell_changes.i18n = /*i18n*/
      ctx2[16];
      if (dirty[0] & /*i*/
      4) editablecell_changes.coords = [
        /*i*/
        ctx2[2],
        0
      ];
      if (!updating_value && dirty[0] & /*value*/
      1) {
        updating_value = true;
        editablecell_changes.value = /*value*/
        ctx2[0];
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_el && dirty[0] & /*el*/
      2) {
        updating_el = true;
        editablecell_changes.el = /*el*/
        ctx2[1];
        add_flush_callback(() => updating_el = false);
      }
      editablecell.$set(editablecell_changes);
      if (
        /*sort_index*/
        ctx2[19] !== -1
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*sort_index*/
          524288) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_3$6(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(button, t2);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*filter_index*/
        ctx2[23] !== -1
      ) {
        if (if_block2) {
          if (dirty[0] & /*filter_index*/
          8388608) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_2$7();
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(button, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*value*/
      1) {
        attr(
          button,
          "title",
          /*value*/
          ctx2[0]
        );
      }
      if (
        /*is_static*/
        ctx2[17]
      ) {
        if (if_block3) {
          if (dirty[0] & /*is_static*/
          131072) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block_1$8();
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(div0, null);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
      if (
        /*can_add_columns*/
        ctx2[25]
      ) {
        if (if_block4) {
          if_block4.p(ctx2, dirty);
          if (dirty[0] & /*can_add_columns*/
          33554432) {
            transition_in(if_block4, 1);
          }
        } else {
          if_block4 = create_if_block$a(ctx2);
          if_block4.c();
          transition_in(if_block4, 1);
          if_block4.m(div1, null);
        }
      } else if (if_block4) {
        group_outros();
        transition_out(if_block4, 1, 1, () => {
          if_block4 = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*value, sort_columns, headers*/
      2113 && th_aria_sort_value !== (th_aria_sort_value = get_sort_status$1(
        /*value*/
        ctx2[0],
        /*sort_columns*/
        ctx2[11],
        /*headers*/
        ctx2[6]
      ) === "none" ? "none" : get_sort_status$1(
        /*value*/
        ctx2[0],
        /*sort_columns*/
        ctx2[11],
        /*headers*/
        ctx2[6]
      ) === "asc" ? "ascending" : "descending")) {
        attr(th, "aria-sort", th_aria_sort_value);
      }
      if (!current || dirty[0] & /*get_cell_width, i*/
      132) {
        set_style(
          th,
          "width",
          /*get_cell_width*/
          ctx2[7](
            /*i*/
            ctx2[2]
          )
        );
      }
      if (!current || dirty[0] & /*i*/
      4) {
        set_style(
          th,
          "left",
          /*get_header_position*/
          ctx2[26](
            /*i*/
            ctx2[2]
          )
        );
      }
      if (!current || dirty[0] & /*value*/
      1) {
        attr(
          th,
          "title",
          /*value*/
          ctx2[0]
        );
      }
      if (!current || dirty[0] & /*i, actual_pinned_columns*/
      12) {
        toggle_class(
          th,
          "pinned-column",
          /*i*/
          ctx2[2] < /*actual_pinned_columns*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*i, actual_pinned_columns*/
      12) {
        toggle_class(
          th,
          "last-pinned",
          /*i*/
          ctx2[2] === /*actual_pinned_columns*/
          ctx2[3] - 1
        );
      }
      if (!current || dirty[0] & /*header_edit, i, selected_header*/
      52) {
        toggle_class(
          th,
          "focus",
          /*header_edit*/
          ctx2[4] === /*i*/
          ctx2[2] || /*selected_header*/
          ctx2[5] === /*i*/
          ctx2[2]
        );
      }
      if (!current || dirty[0] & /*sort_index*/
      524288) {
        toggle_class(
          th,
          "sorted",
          /*sort_index*/
          ctx2[19] !== -1
        );
      }
      if (!current || dirty[0] & /*filter_index*/
      8388608) {
        toggle_class(
          th,
          "filtered",
          /*filter_index*/
          ctx2[23] !== -1
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(editablecell.$$.fragment, local);
      transition_in(if_block1);
      transition_in(if_block2);
      transition_in(if_block3);
      transition_in(if_block4);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(editablecell.$$.fragment, local);
      transition_out(if_block1);
      transition_out(if_block2);
      transition_out(if_block3);
      transition_out(if_block4);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(th);
      }
      if (if_block0) if_block0.d();
      destroy_component(editablecell);
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
      if (if_block3) if_block3.d();
      if (if_block4) if_block4.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
const keydown_handler = (e) => {
  if (e.key === "Enter" || e.key === " ") {
    e.preventDefault();
  }
};
const mousedown_handler_1 = (event) => {
  event.preventDefault();
  event.stopPropagation();
};
const mousedown_handler_2 = (event) => {
  event.preventDefault();
  event.stopPropagation();
};
function instance$f($$self, $$props, $$invalidate) {
  let can_add_columns;
  let is_bool_column;
  let select_all_state;
  let sort_index;
  let filter_index;
  let sort_priority;
  let current_direction;
  let { value } = $$props;
  let { i } = $$props;
  let { datatype = "str" } = $$props;
  let { actual_pinned_columns } = $$props;
  let { header_edit } = $$props;
  let { selected_header } = $$props;
  let { headers } = $$props;
  let { get_cell_width: get_cell_width2 } = $$props;
  let { handle_header_click } = $$props;
  let { toggle_header_menu } = $$props;
  let { end_header_edit } = $$props;
  let { sort_columns = [] } = $$props;
  let { filter_columns = [] } = $$props;
  let { latex_delimiters } = $$props;
  let { line_breaks } = $$props;
  let { max_chars } = $$props;
  let { editable } = $$props;
  let { i18n } = $$props;
  let { el } = $$props;
  let { is_static } = $$props;
  let { col_count } = $$props;
  let { data = [] } = $$props;
  let { on_select_all = void 0 } = $$props;
  function get_header_position(col_index) {
    if (col_index >= actual_pinned_columns) {
      return "auto";
    }
    if (col_index === 0) {
      return "0";
    }
    const previous_widths = Array(col_index).fill(0).map((_, idx) => {
      return get_cell_width2(idx);
    }).join(" + ");
    return `calc(${previous_widths})`;
  }
  function click_handler(event) {
    bubble.call(this, $$self, event);
  }
  function mousedown_handler(event) {
    bubble.call(this, $$self, event);
  }
  const select_handler = () => {
    if (on_select_all) {
      const new_value = select_all_state !== "checked";
      on_select_all(i, new_value);
    }
  };
  function editablecell_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  function editablecell_el_binding(value2) {
    el = value2;
    $$invalidate(1, el);
  }
  const keydown_handler_1 = (event) => {
    if (event.detail.key === "Enter" || event.detail.key === "Escape" || event.detail.key === "Tab") {
      end_header_edit(event);
    }
  };
  const click_handler_1 = (event) => handle_header_click(event, i);
  const func2 = (event) => toggle_header_menu(event, i);
  const click_handler_2 = (event) => handle_header_click(event, i);
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("i" in $$props2) $$invalidate(2, i = $$props2.i);
    if ("datatype" in $$props2) $$invalidate(27, datatype = $$props2.datatype);
    if ("actual_pinned_columns" in $$props2) $$invalidate(3, actual_pinned_columns = $$props2.actual_pinned_columns);
    if ("header_edit" in $$props2) $$invalidate(4, header_edit = $$props2.header_edit);
    if ("selected_header" in $$props2) $$invalidate(5, selected_header = $$props2.selected_header);
    if ("headers" in $$props2) $$invalidate(6, headers = $$props2.headers);
    if ("get_cell_width" in $$props2) $$invalidate(7, get_cell_width2 = $$props2.get_cell_width);
    if ("handle_header_click" in $$props2) $$invalidate(8, handle_header_click = $$props2.handle_header_click);
    if ("toggle_header_menu" in $$props2) $$invalidate(9, toggle_header_menu = $$props2.toggle_header_menu);
    if ("end_header_edit" in $$props2) $$invalidate(10, end_header_edit = $$props2.end_header_edit);
    if ("sort_columns" in $$props2) $$invalidate(11, sort_columns = $$props2.sort_columns);
    if ("filter_columns" in $$props2) $$invalidate(28, filter_columns = $$props2.filter_columns);
    if ("latex_delimiters" in $$props2) $$invalidate(12, latex_delimiters = $$props2.latex_delimiters);
    if ("line_breaks" in $$props2) $$invalidate(13, line_breaks = $$props2.line_breaks);
    if ("max_chars" in $$props2) $$invalidate(14, max_chars = $$props2.max_chars);
    if ("editable" in $$props2) $$invalidate(15, editable = $$props2.editable);
    if ("i18n" in $$props2) $$invalidate(16, i18n = $$props2.i18n);
    if ("el" in $$props2) $$invalidate(1, el = $$props2.el);
    if ("is_static" in $$props2) $$invalidate(17, is_static = $$props2.is_static);
    if ("col_count" in $$props2) $$invalidate(29, col_count = $$props2.col_count);
    if ("data" in $$props2) $$invalidate(30, data = $$props2.data);
    if ("on_select_all" in $$props2) $$invalidate(18, on_select_all = $$props2.on_select_all);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*col_count*/
    536870912) {
      $$invalidate(25, can_add_columns = col_count && col_count[1] === "dynamic");
    }
    if ($$self.$$.dirty[0] & /*datatype*/
    134217728) {
      $$invalidate(20, is_bool_column = datatype === "bool");
    }
    if ($$self.$$.dirty[0] & /*is_bool_column, data, i*/
    1074790404) {
      $$invalidate(24, select_all_state = (() => {
        if (!is_bool_column || data.length === 0) return "unchecked";
        const true_count = data.filter((row) => {
          var _a, _b;
          return ((_a = row[i]) == null ? void 0 : _a.value) === true || ((_b = row[i]) == null ? void 0 : _b.value) === "true";
        }).length;
        if (true_count === 0) return "unchecked";
        if (true_count === data.length) return "checked";
        return "indeterminate";
      })());
    }
    if ($$self.$$.dirty[0] & /*sort_columns, i*/
    2052) {
      $$invalidate(19, sort_index = sort_columns.findIndex((item) => item.col === i));
    }
    if ($$self.$$.dirty[0] & /*filter_columns, i*/
    268435460) {
      $$invalidate(23, filter_index = filter_columns.findIndex((item) => item.col === i));
    }
    if ($$self.$$.dirty[0] & /*sort_index*/
    524288) {
      $$invalidate(22, sort_priority = sort_index !== -1 ? sort_index + 1 : null);
    }
    if ($$self.$$.dirty[0] & /*sort_index, sort_columns*/
    526336) {
      $$invalidate(21, current_direction = sort_index !== -1 ? sort_columns[sort_index].direction : null);
    }
  };
  return [
    value,
    el,
    i,
    actual_pinned_columns,
    header_edit,
    selected_header,
    headers,
    get_cell_width2,
    handle_header_click,
    toggle_header_menu,
    end_header_edit,
    sort_columns,
    latex_delimiters,
    line_breaks,
    max_chars,
    editable,
    i18n,
    is_static,
    on_select_all,
    sort_index,
    is_bool_column,
    current_direction,
    sort_priority,
    filter_index,
    select_all_state,
    can_add_columns,
    get_header_position,
    datatype,
    filter_columns,
    col_count,
    data,
    click_handler,
    mousedown_handler,
    select_handler,
    editablecell_value_binding,
    editablecell_el_binding,
    keydown_handler_1,
    click_handler_1,
    func2,
    click_handler_2
  ];
}
let TableHeader$1 = class TableHeader extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$f,
      create_fragment$f,
      safe_not_equal,
      {
        value: 0,
        i: 2,
        datatype: 27,
        actual_pinned_columns: 3,
        header_edit: 4,
        selected_header: 5,
        headers: 6,
        get_cell_width: 7,
        handle_header_click: 8,
        toggle_header_menu: 9,
        end_header_edit: 10,
        sort_columns: 11,
        filter_columns: 28,
        latex_delimiters: 12,
        line_breaks: 13,
        max_chars: 14,
        editable: 15,
        i18n: 16,
        el: 1,
        is_static: 17,
        col_count: 29,
        data: 30,
        on_select_all: 18
      },
      null,
      [-1, -1]
    );
  }
};
function create_if_block$9(ctx) {
  let cellmenubutton;
  let current;
  cellmenubutton = new CellMenuButton$1({ props: { on_click: (
    /*func*/
    ctx[39]
  ) } });
  return {
    c() {
      create_component(cellmenubutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(cellmenubutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const cellmenubutton_changes = {};
      if (dirty[0] & /*toggle_cell_menu, index, j*/
      536) cellmenubutton_changes.on_click = /*func*/
      ctx2[39];
      cellmenubutton.$set(cellmenubutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenubutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenubutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(cellmenubutton, detaching);
    }
  };
}
function create_fragment$e(ctx) {
  let td;
  let div;
  let editablecell;
  let updating_value;
  let updating_el;
  let t;
  let show_if = (
    /*editable*/
    ctx[19] && /*should_show_cell_menu*/
    ctx[10](
      [
        /*index*/
        ctx[3],
        /*j*/
        ctx[4]
      ],
      /*selected_cells*/
      ctx[0],
      /*editable*/
      ctx[19]
    )
  );
  let td_tabindex_value;
  let td_data_testid_value;
  let td_style_value;
  let current;
  let mounted;
  let dispose;
  function editablecell_value_binding(value) {
    ctx[36](value);
  }
  function editablecell_el_binding(value) {
    ctx[37](value);
  }
  let editablecell_props = {
    display_value: (
      /*display_value*/
      ctx[26] !== void 0 ? (
        /*display_value*/
        ctx[26]
      ) : String(
        /*value*/
        ctx[1]
      )
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[14]
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[15]
    ),
    editable: (
      /*editable*/
      ctx[19]
    ),
    is_static: (
      /*is_static*/
      ctx[20]
    ),
    edit: (
      /*editing*/
      ctx[17] && /*editing*/
      ctx[17][0] === /*index*/
      ctx[3] && /*editing*/
      ctx[17][1] === /*j*/
      ctx[4]
    ),
    datatype: (
      /*datatype*/
      ctx[16]
    ),
    max_chars: (
      /*max_chars*/
      ctx[18]
    ),
    i18n: (
      /*i18n*/
      ctx[21]
    ),
    components: (
      /*components*/
      ctx[22]
    ),
    show_selection_buttons: (
      /*selected_cells*/
      ctx[0].length === 1 && /*selected_cells*/
      ctx[0][0][0] === /*index*/
      ctx[3] && /*selected_cells*/
      ctx[0][0][1] === /*j*/
      ctx[4]
    ),
    coords: [
      /*index*/
      ctx[3],
      /*j*/
      ctx[4]
    ],
    on_select_column: (
      /*handle_select_column*/
      ctx[23]
    ),
    on_select_row: (
      /*handle_select_row*/
      ctx[24]
    ),
    is_dragging: (
      /*is_dragging*/
      ctx[25]
    ),
    wrap_text: (
      /*wrap*/
      ctx[27]
    )
  };
  if (
    /*value*/
    ctx[1] !== void 0
  ) {
    editablecell_props.value = /*value*/
    ctx[1];
  }
  if (
    /*el*/
    ctx[2].input !== void 0
  ) {
    editablecell_props.el = /*el*/
    ctx[2].input;
  }
  editablecell = new EditableCell$1({ props: editablecell_props });
  binding_callbacks.push(() => bind(editablecell, "value", editablecell_value_binding));
  binding_callbacks.push(() => bind(editablecell, "el", editablecell_el_binding));
  editablecell.$on(
    "focus",
    /*focus_handler*/
    ctx[38]
  );
  editablecell.$on("blur", function() {
    if (is_function(
      /*handle_blur*/
      ctx[8]
    )) ctx[8].apply(this, arguments);
  });
  let if_block = show_if && create_if_block$9(ctx);
  return {
    c() {
      td = element("td");
      div = element("div");
      create_component(editablecell.$$.fragment);
      t = space();
      if (if_block) if_block.c();
      attr(div, "class", "cell-wrap svelte-lcqe7p");
      attr(td, "tabindex", td_tabindex_value = /*j*/
      ctx[4] < /*actual_pinned_columns*/
      ctx[5] ? -1 : 0);
      attr(
        td,
        "data-row",
        /*index*/
        ctx[3]
      );
      attr(
        td,
        "data-col",
        /*j*/
        ctx[4]
      );
      attr(td, "data-testid", td_data_testid_value = `cell-${/*index*/
      ctx[3]}-${/*j*/
      ctx[4]}`);
      attr(td, "style", td_style_value = "width: " + /*get_cell_width*/
      ctx[6](
        /*j*/
        ctx[4]
      ) + "; left: " + /*get_cell_position*/
      ctx[33](
        /*j*/
        ctx[4]
      ) + "; " + /*styling*/
      (ctx[13] || ""));
      attr(td, "class", "svelte-lcqe7p");
      toggle_class(
        td,
        "pinned-column",
        /*j*/
        ctx[4] < /*actual_pinned_columns*/
        ctx[5]
      );
      toggle_class(
        td,
        "last-pinned",
        /*j*/
        ctx[4] === /*actual_pinned_columns*/
        ctx[5] - 1
      );
      toggle_class(
        td,
        "flash",
        /*copy_flash*/
        ctx[11] && /*is_in_selection*/
        ctx[32]
      );
      toggle_class(
        td,
        "cell-selected",
        /*is_in_selection*/
        ctx[32]
      );
      toggle_class(
        td,
        "no-top",
        /*has_no_top*/
        ctx[31]
      );
      toggle_class(
        td,
        "no-bottom",
        /*has_no_bottom*/
        ctx[30]
      );
      toggle_class(
        td,
        "no-left",
        /*has_no_left*/
        ctx[29]
      );
      toggle_class(
        td,
        "no-right",
        /*has_no_right*/
        ctx[28]
      );
      toggle_class(
        td,
        "menu-active",
        /*active_cell_menu*/
        ctx[12] && /*active_cell_menu*/
        ctx[12].row === /*index*/
        ctx[3] && /*active_cell_menu*/
        ctx[12].col === /*j*/
        ctx[4]
      );
      toggle_class(
        td,
        "dragging",
        /*is_dragging*/
        ctx[25]
      );
    },
    m(target, anchor) {
      insert(target, td, anchor);
      append(td, div);
      mount_component(editablecell, div, null);
      append(div, t);
      if (if_block) if_block.m(div, null);
      ctx[40](td);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            td,
            "mousedown",
            /*mousedown_handler*/
            ctx[41]
          ),
          listen(td, "contextmenu", prevent_default(
            /*contextmenu_handler*/
            ctx[42]
          ))
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const editablecell_changes = {};
      if (dirty[0] & /*display_value, value*/
      67108866) editablecell_changes.display_value = /*display_value*/
      ctx[26] !== void 0 ? (
        /*display_value*/
        ctx[26]
      ) : String(
        /*value*/
        ctx[1]
      );
      if (dirty[0] & /*latex_delimiters*/
      16384) editablecell_changes.latex_delimiters = /*latex_delimiters*/
      ctx[14];
      if (dirty[0] & /*line_breaks*/
      32768) editablecell_changes.line_breaks = /*line_breaks*/
      ctx[15];
      if (dirty[0] & /*editable*/
      524288) editablecell_changes.editable = /*editable*/
      ctx[19];
      if (dirty[0] & /*is_static*/
      1048576) editablecell_changes.is_static = /*is_static*/
      ctx[20];
      if (dirty[0] & /*editing, index, j*/
      131096) editablecell_changes.edit = /*editing*/
      ctx[17] && /*editing*/
      ctx[17][0] === /*index*/
      ctx[3] && /*editing*/
      ctx[17][1] === /*j*/
      ctx[4];
      if (dirty[0] & /*datatype*/
      65536) editablecell_changes.datatype = /*datatype*/
      ctx[16];
      if (dirty[0] & /*max_chars*/
      262144) editablecell_changes.max_chars = /*max_chars*/
      ctx[18];
      if (dirty[0] & /*i18n*/
      2097152) editablecell_changes.i18n = /*i18n*/
      ctx[21];
      if (dirty[0] & /*components*/
      4194304) editablecell_changes.components = /*components*/
      ctx[22];
      if (dirty[0] & /*selected_cells, index, j*/
      25) editablecell_changes.show_selection_buttons = /*selected_cells*/
      ctx[0].length === 1 && /*selected_cells*/
      ctx[0][0][0] === /*index*/
      ctx[3] && /*selected_cells*/
      ctx[0][0][1] === /*j*/
      ctx[4];
      if (dirty[0] & /*index, j*/
      24) editablecell_changes.coords = [
        /*index*/
        ctx[3],
        /*j*/
        ctx[4]
      ];
      if (dirty[0] & /*handle_select_column*/
      8388608) editablecell_changes.on_select_column = /*handle_select_column*/
      ctx[23];
      if (dirty[0] & /*handle_select_row*/
      16777216) editablecell_changes.on_select_row = /*handle_select_row*/
      ctx[24];
      if (dirty[0] & /*is_dragging*/
      33554432) editablecell_changes.is_dragging = /*is_dragging*/
      ctx[25];
      if (dirty[0] & /*wrap*/
      134217728) editablecell_changes.wrap_text = /*wrap*/
      ctx[27];
      if (!updating_value && dirty[0] & /*value*/
      2) {
        updating_value = true;
        editablecell_changes.value = /*value*/
        ctx[1];
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_el && dirty[0] & /*el*/
      4) {
        updating_el = true;
        editablecell_changes.el = /*el*/
        ctx[2].input;
        add_flush_callback(() => updating_el = false);
      }
      editablecell.$set(editablecell_changes);
      if (dirty[0] & /*editable, should_show_cell_menu, index, j, selected_cells*/
      525337) show_if = /*editable*/
      ctx[19] && /*should_show_cell_menu*/
      ctx[10](
        [
          /*index*/
          ctx[3],
          /*j*/
          ctx[4]
        ],
        /*selected_cells*/
        ctx[0],
        /*editable*/
        ctx[19]
      );
      if (show_if) {
        if (if_block) {
          if_block.p(ctx, dirty);
          if (dirty[0] & /*editable, should_show_cell_menu, index, j, selected_cells*/
          525337) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block$9(ctx);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (!current || dirty[0] & /*j, actual_pinned_columns*/
      48 && td_tabindex_value !== (td_tabindex_value = /*j*/
      ctx[4] < /*actual_pinned_columns*/
      ctx[5] ? -1 : 0)) {
        attr(td, "tabindex", td_tabindex_value);
      }
      if (!current || dirty[0] & /*index*/
      8) {
        attr(
          td,
          "data-row",
          /*index*/
          ctx[3]
        );
      }
      if (!current || dirty[0] & /*j*/
      16) {
        attr(
          td,
          "data-col",
          /*j*/
          ctx[4]
        );
      }
      if (!current || dirty[0] & /*index, j*/
      24 && td_data_testid_value !== (td_data_testid_value = `cell-${/*index*/
      ctx[3]}-${/*j*/
      ctx[4]}`)) {
        attr(td, "data-testid", td_data_testid_value);
      }
      if (!current || dirty[0] & /*get_cell_width, j, styling*/
      8272 && td_style_value !== (td_style_value = "width: " + /*get_cell_width*/
      ctx[6](
        /*j*/
        ctx[4]
      ) + "; left: " + /*get_cell_position*/
      ctx[33](
        /*j*/
        ctx[4]
      ) + "; " + /*styling*/
      (ctx[13] || ""))) {
        attr(td, "style", td_style_value);
      }
      if (!current || dirty[0] & /*j, actual_pinned_columns*/
      48) {
        toggle_class(
          td,
          "pinned-column",
          /*j*/
          ctx[4] < /*actual_pinned_columns*/
          ctx[5]
        );
      }
      if (!current || dirty[0] & /*j, actual_pinned_columns*/
      48) {
        toggle_class(
          td,
          "last-pinned",
          /*j*/
          ctx[4] === /*actual_pinned_columns*/
          ctx[5] - 1
        );
      }
      if (!current || dirty[0] & /*copy_flash*/
      2048 | dirty[1] & /*is_in_selection*/
      2) {
        toggle_class(
          td,
          "flash",
          /*copy_flash*/
          ctx[11] && /*is_in_selection*/
          ctx[32]
        );
      }
      if (!current || dirty[1] & /*is_in_selection*/
      2) {
        toggle_class(
          td,
          "cell-selected",
          /*is_in_selection*/
          ctx[32]
        );
      }
      if (!current || dirty[1] & /*has_no_top*/
      1) {
        toggle_class(
          td,
          "no-top",
          /*has_no_top*/
          ctx[31]
        );
      }
      if (!current || dirty[0] & /*has_no_bottom*/
      1073741824) {
        toggle_class(
          td,
          "no-bottom",
          /*has_no_bottom*/
          ctx[30]
        );
      }
      if (!current || dirty[0] & /*has_no_left*/
      536870912) {
        toggle_class(
          td,
          "no-left",
          /*has_no_left*/
          ctx[29]
        );
      }
      if (!current || dirty[0] & /*has_no_right*/
      268435456) {
        toggle_class(
          td,
          "no-right",
          /*has_no_right*/
          ctx[28]
        );
      }
      if (!current || dirty[0] & /*active_cell_menu, index, j*/
      4120) {
        toggle_class(
          td,
          "menu-active",
          /*active_cell_menu*/
          ctx[12] && /*active_cell_menu*/
          ctx[12].row === /*index*/
          ctx[3] && /*active_cell_menu*/
          ctx[12].col === /*j*/
          ctx[4]
        );
      }
      if (!current || dirty[0] & /*is_dragging*/
      33554432) {
        toggle_class(
          td,
          "dragging",
          /*is_dragging*/
          ctx[25]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(editablecell.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(editablecell.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(td);
      }
      destroy_component(editablecell);
      if (if_block) if_block.d();
      ctx[40](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance$e($$self, $$props, $$invalidate) {
  let cell_classes;
  let is_in_selection;
  let has_no_top;
  let has_no_bottom;
  let has_no_left;
  let has_no_right;
  let { value } = $$props;
  let { index } = $$props;
  let { j } = $$props;
  let { actual_pinned_columns } = $$props;
  let { get_cell_width: get_cell_width2 } = $$props;
  let { handle_cell_click } = $$props;
  let { handle_blur } = $$props;
  let { toggle_cell_menu } = $$props;
  let { is_cell_selected: is_cell_selected2 } = $$props;
  let { should_show_cell_menu: should_show_cell_menu2 } = $$props;
  let { selected_cells } = $$props;
  let { copy_flash } = $$props;
  let { active_cell_menu } = $$props;
  let { styling } = $$props;
  let { latex_delimiters } = $$props;
  let { line_breaks } = $$props;
  let { datatype } = $$props;
  let { editing } = $$props;
  let { max_chars } = $$props;
  let { editable } = $$props;
  let { is_static = false } = $$props;
  let { i18n } = $$props;
  let { components = {} } = $$props;
  let { el } = $$props;
  let { handle_select_column } = $$props;
  let { handle_select_row } = $$props;
  let { is_dragging } = $$props;
  let { display_value } = $$props;
  let { wrap = false } = $$props;
  function get_cell_position(col_index) {
    if (col_index >= actual_pinned_columns) {
      return "auto";
    }
    if (col_index === 0) {
      return "0";
    }
    const previous_widths = Array(col_index).fill(0).map((_, idx) => {
      return get_cell_width2(idx);
    }).join(" + ");
    return `calc(${previous_widths})`;
  }
  function editablecell_value_binding(value$1) {
    value = value$1;
    $$invalidate(1, value);
  }
  function editablecell_el_binding(value2) {
    if ($$self.$$.not_equal(el.input, value2)) {
      el.input = value2;
      $$invalidate(2, el);
    }
  }
  const focus_handler = () => {
    const row = index;
    const col = j;
    if (!selected_cells.some(([r, c]) => r === row && c === col)) {
      $$invalidate(0, selected_cells = [[row, col]]);
    }
  };
  const func2 = (event) => toggle_cell_menu(event, index, j);
  function td_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      el.cell = $$value;
      $$invalidate(2, el);
    });
  }
  const mousedown_handler = (e) => handle_cell_click(e, index, j);
  const contextmenu_handler = (e) => toggle_cell_menu(e, index, j);
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(1, value = $$props2.value);
    if ("index" in $$props2) $$invalidate(3, index = $$props2.index);
    if ("j" in $$props2) $$invalidate(4, j = $$props2.j);
    if ("actual_pinned_columns" in $$props2) $$invalidate(5, actual_pinned_columns = $$props2.actual_pinned_columns);
    if ("get_cell_width" in $$props2) $$invalidate(6, get_cell_width2 = $$props2.get_cell_width);
    if ("handle_cell_click" in $$props2) $$invalidate(7, handle_cell_click = $$props2.handle_cell_click);
    if ("handle_blur" in $$props2) $$invalidate(8, handle_blur = $$props2.handle_blur);
    if ("toggle_cell_menu" in $$props2) $$invalidate(9, toggle_cell_menu = $$props2.toggle_cell_menu);
    if ("is_cell_selected" in $$props2) $$invalidate(34, is_cell_selected2 = $$props2.is_cell_selected);
    if ("should_show_cell_menu" in $$props2) $$invalidate(10, should_show_cell_menu2 = $$props2.should_show_cell_menu);
    if ("selected_cells" in $$props2) $$invalidate(0, selected_cells = $$props2.selected_cells);
    if ("copy_flash" in $$props2) $$invalidate(11, copy_flash = $$props2.copy_flash);
    if ("active_cell_menu" in $$props2) $$invalidate(12, active_cell_menu = $$props2.active_cell_menu);
    if ("styling" in $$props2) $$invalidate(13, styling = $$props2.styling);
    if ("latex_delimiters" in $$props2) $$invalidate(14, latex_delimiters = $$props2.latex_delimiters);
    if ("line_breaks" in $$props2) $$invalidate(15, line_breaks = $$props2.line_breaks);
    if ("datatype" in $$props2) $$invalidate(16, datatype = $$props2.datatype);
    if ("editing" in $$props2) $$invalidate(17, editing = $$props2.editing);
    if ("max_chars" in $$props2) $$invalidate(18, max_chars = $$props2.max_chars);
    if ("editable" in $$props2) $$invalidate(19, editable = $$props2.editable);
    if ("is_static" in $$props2) $$invalidate(20, is_static = $$props2.is_static);
    if ("i18n" in $$props2) $$invalidate(21, i18n = $$props2.i18n);
    if ("components" in $$props2) $$invalidate(22, components = $$props2.components);
    if ("el" in $$props2) $$invalidate(2, el = $$props2.el);
    if ("handle_select_column" in $$props2) $$invalidate(23, handle_select_column = $$props2.handle_select_column);
    if ("handle_select_row" in $$props2) $$invalidate(24, handle_select_row = $$props2.handle_select_row);
    if ("is_dragging" in $$props2) $$invalidate(25, is_dragging = $$props2.is_dragging);
    if ("display_value" in $$props2) $$invalidate(26, display_value = $$props2.display_value);
    if ("wrap" in $$props2) $$invalidate(27, wrap = $$props2.wrap);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*index, j, selected_cells*/
    25 | $$self.$$.dirty[1] & /*is_cell_selected*/
    8) {
      $$invalidate(35, cell_classes = is_cell_selected2([index, j], selected_cells || []));
    }
    if ($$self.$$.dirty[0] & /*index, j, selected_cells*/
    25) {
      $$invalidate(32, is_in_selection = is_cell_in_selection$1([index, j], selected_cells));
    }
    if ($$self.$$.dirty[1] & /*cell_classes*/
    16) {
      $$invalidate(31, has_no_top = cell_classes.includes("no-top"));
    }
    if ($$self.$$.dirty[1] & /*cell_classes*/
    16) {
      $$invalidate(30, has_no_bottom = cell_classes.includes("no-bottom"));
    }
    if ($$self.$$.dirty[1] & /*cell_classes*/
    16) {
      $$invalidate(29, has_no_left = cell_classes.includes("no-left"));
    }
    if ($$self.$$.dirty[1] & /*cell_classes*/
    16) {
      $$invalidate(28, has_no_right = cell_classes.includes("no-right"));
    }
  };
  return [
    selected_cells,
    value,
    el,
    index,
    j,
    actual_pinned_columns,
    get_cell_width2,
    handle_cell_click,
    handle_blur,
    toggle_cell_menu,
    should_show_cell_menu2,
    copy_flash,
    active_cell_menu,
    styling,
    latex_delimiters,
    line_breaks,
    datatype,
    editing,
    max_chars,
    editable,
    is_static,
    i18n,
    components,
    handle_select_column,
    handle_select_row,
    is_dragging,
    display_value,
    wrap,
    has_no_right,
    has_no_left,
    has_no_bottom,
    has_no_top,
    is_in_selection,
    get_cell_position,
    is_cell_selected2,
    cell_classes,
    editablecell_value_binding,
    editablecell_el_binding,
    focus_handler,
    func2,
    td_binding,
    mousedown_handler,
    contextmenu_handler
  ];
}
let TableCell$1 = class TableCell extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$e,
      create_fragment$e,
      safe_not_equal,
      {
        value: 1,
        index: 3,
        j: 4,
        actual_pinned_columns: 5,
        get_cell_width: 6,
        handle_cell_click: 7,
        handle_blur: 8,
        toggle_cell_menu: 9,
        is_cell_selected: 34,
        should_show_cell_menu: 10,
        selected_cells: 0,
        copy_flash: 11,
        active_cell_menu: 12,
        styling: 13,
        latex_delimiters: 14,
        line_breaks: 15,
        datatype: 16,
        editing: 17,
        max_chars: 18,
        editable: 19,
        is_static: 20,
        i18n: 21,
        components: 22,
        el: 2,
        handle_select_column: 23,
        handle_select_row: 24,
        is_dragging: 25,
        display_value: 26,
        wrap: 27
      },
      null,
      [-1, -1]
    );
  }
};
function create_fragment$d(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "+";
      attr(button, "class", "add-row-button svelte-jmcozb");
      attr(button, "aria-label", "Add row");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*on_click*/
            ctx[0]
          )) ctx[0].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, [dirty]) {
      ctx = new_ctx;
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance$d($$self, $$props, $$invalidate) {
  let { on_click } = $$props;
  $$self.$$set = ($$props2) => {
    if ("on_click" in $$props2) $$invalidate(0, on_click = $$props2.on_click);
  };
  return [on_click];
}
let EmptyRowButton$1 = class EmptyRowButton extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$d, create_fragment$d, safe_not_equal, { on_click: 0 });
  }
};
const get_tfoot_slot_changes = (dirty) => ({});
const get_tfoot_slot_context = (ctx) => ({});
function get_each_context$3(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[38] = list2[i];
  return child_ctx;
}
const get_tbody_slot_changes = (dirty) => ({
  item: dirty[0] & /*visible*/
  2048,
  index: dirty[0] & /*visible*/
  2048
});
const get_tbody_slot_context = (ctx) => ({
  item: (
    /*item*/
    ctx[38].data
  ),
  index: (
    /*item*/
    ctx[38].index
  )
});
const get_thead_slot_changes = (dirty) => ({});
const get_thead_slot_context = (ctx) => ({});
function create_if_block_1$7(ctx) {
  let caption;
  let t;
  return {
    c() {
      caption = element("caption");
      t = text(
        /*label*/
        ctx[3]
      );
      attr(caption, "class", "sr-only svelte-u825rv");
    },
    m(target, anchor) {
      insert(target, caption, anchor);
      append(caption, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*label*/
      8) set_data(
        t,
        /*label*/
        ctx2[3]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(caption);
      }
    }
  };
}
function create_if_block$8(ctx) {
  let each_blocks = [];
  let each_1_lookup = /* @__PURE__ */ new Map();
  let each_1_anchor;
  let current;
  let each_value = ensure_array_like(
    /*visible*/
    ctx[11]
  );
  const get_key = (ctx2) => (
    /*item*/
    ctx2[38].data[0].id
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$3(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$3(key, child_ctx));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*$$scope, visible*/
      16779264) {
        each_value = ensure_array_like(
          /*visible*/
          ctx2[11]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, each_1_anchor.parentNode, outro_and_destroy_block, create_each_block$3, each_1_anchor, get_each_context$3);
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(each_1_anchor);
      }
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d(detaching);
      }
    }
  };
}
function fallback_block(ctx) {
  let tr;
  let t1;
  return {
    c() {
      tr = element("tr");
      tr.innerHTML = `<td class="svelte-u825rv">Missing Table Row</td>`;
      t1 = space();
      attr(tr, "class", "svelte-u825rv");
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      insert(target, t1, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(tr);
        detach(t1);
      }
    }
  };
}
function create_each_block$3(key_1, ctx) {
  let first;
  let current;
  const tbody_slot_template = (
    /*#slots*/
    ctx[25].tbody
  );
  const tbody_slot = create_slot(
    tbody_slot_template,
    ctx,
    /*$$scope*/
    ctx[24],
    get_tbody_slot_context
  );
  const tbody_slot_or_fallback = tbody_slot || fallback_block();
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      if (tbody_slot_or_fallback) tbody_slot_or_fallback.c();
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      if (tbody_slot_or_fallback) {
        tbody_slot_or_fallback.m(target, anchor);
      }
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (tbody_slot) {
        if (tbody_slot.p && (!current || dirty[0] & /*$$scope, visible*/
        16779264)) {
          update_slot_base(
            tbody_slot,
            tbody_slot_template,
            ctx,
            /*$$scope*/
            ctx[24],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx[24]
            ) : get_slot_changes(
              tbody_slot_template,
              /*$$scope*/
              ctx[24],
              dirty,
              get_tbody_slot_changes
            ),
            get_tbody_slot_context
          );
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(tbody_slot_or_fallback, local);
      current = true;
    },
    o(local) {
      transition_out(tbody_slot_or_fallback, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(first);
      }
      if (tbody_slot_or_fallback) tbody_slot_or_fallback.d(detaching);
    }
  };
}
function create_fragment$c(ctx) {
  let svelte_virtual_table_viewport;
  let div;
  let table;
  let t0;
  let thead;
  let thead_resize_listener;
  let t1;
  let tbody;
  let t2;
  let tfoot;
  let tfoot_resize_listener;
  let table_resize_listener;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*label*/
    ctx[3] && /*label*/
    ctx[3].length !== 0 && create_if_block_1$7(ctx)
  );
  const thead_slot_template = (
    /*#slots*/
    ctx[25].thead
  );
  const thead_slot = create_slot(
    thead_slot_template,
    ctx,
    /*$$scope*/
    ctx[24],
    get_thead_slot_context
  );
  let if_block1 = (
    /*visible*/
    ctx[11].length && /*visible*/
    ctx[11][0].data.length && create_if_block$8(ctx)
  );
  const tfoot_slot_template = (
    /*#slots*/
    ctx[25].tfoot
  );
  const tfoot_slot = create_slot(
    tfoot_slot_template,
    ctx,
    /*$$scope*/
    ctx[24],
    get_tfoot_slot_context
  );
  return {
    c() {
      svelte_virtual_table_viewport = element("svelte-virtual-table-viewport");
      div = element("div");
      table = element("table");
      if (if_block0) if_block0.c();
      t0 = space();
      thead = element("thead");
      if (thead_slot) thead_slot.c();
      t1 = space();
      tbody = element("tbody");
      if (if_block1) if_block1.c();
      t2 = space();
      tfoot = element("tfoot");
      if (tfoot_slot) tfoot_slot.c();
      attr(thead, "class", "thead svelte-u825rv");
      add_render_callback(() => (
        /*thead_elementresize_handler*/
        ctx[26].call(thead)
      ));
      attr(tbody, "class", "tbody svelte-u825rv");
      attr(tfoot, "class", "tfoot svelte-u825rv");
      add_render_callback(() => (
        /*tfoot_elementresize_handler*/
        ctx[28].call(tfoot)
      ));
      attr(table, "class", "table svelte-u825rv");
      set_style(table, "height", height);
      set_style(
        table,
        "--bw-svt-p-top",
        /*top*/
        ctx[10] + "px"
      );
      set_style(
        table,
        "--bw-svt-p-bottom",
        /*bottom*/
        ctx[6] + "px"
      );
      set_style(
        table,
        "--bw-svt-head-height",
        /*head_height*/
        ctx[8] + "px"
      );
      set_style(
        table,
        "--bw-svt-foot-height",
        /*foot_height*/
        ctx[9] + "px"
      );
      set_style(
        table,
        "--bw-svt-avg-row-height",
        /*average_height*/
        ctx[4] + "px"
      );
      set_style(
        table,
        "--max-height",
        /*max_height*/
        ctx[1] + "px"
      );
      toggle_class(
        table,
        "disable-scroll",
        /*disable_scroll*/
        ctx[2]
      );
    },
    m(target, anchor) {
      insert(target, svelte_virtual_table_viewport, anchor);
      append(svelte_virtual_table_viewport, div);
      append(div, table);
      if (if_block0) if_block0.m(table, null);
      append(table, t0);
      append(table, thead);
      if (thead_slot) {
        thead_slot.m(thead, null);
      }
      thead_resize_listener = add_iframe_resize_listener(
        thead,
        /*thead_elementresize_handler*/
        ctx[26].bind(thead)
      );
      append(table, t1);
      append(table, tbody);
      if (if_block1) if_block1.m(tbody, null);
      ctx[27](tbody);
      append(table, t2);
      append(table, tfoot);
      if (tfoot_slot) {
        tfoot_slot.m(tfoot, null);
      }
      tfoot_resize_listener = add_iframe_resize_listener(
        tfoot,
        /*tfoot_elementresize_handler*/
        ctx[28].bind(tfoot)
      );
      ctx[29](table);
      table_resize_listener = resize_observer_content_box.observe(
        table,
        /*table_elementresizecontentbox_handler*/
        ctx[30].bind(table)
      );
      current = true;
      if (!mounted) {
        dispose = listen(
          table,
          "scroll",
          /*refresh_height_map*/
          ctx[12]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (
        /*label*/
        ctx2[3] && /*label*/
        ctx2[3].length !== 0
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
        } else {
          if_block0 = create_if_block_1$7(ctx2);
          if_block0.c();
          if_block0.m(table, t0);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (thead_slot) {
        if (thead_slot.p && (!current || dirty[0] & /*$$scope*/
        16777216)) {
          update_slot_base(
            thead_slot,
            thead_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[24],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[24]
            ) : get_slot_changes(
              thead_slot_template,
              /*$$scope*/
              ctx2[24],
              dirty,
              get_thead_slot_changes
            ),
            get_thead_slot_context
          );
        }
      }
      if (
        /*visible*/
        ctx2[11].length && /*visible*/
        ctx2[11][0].data.length
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*visible*/
          2048) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$8(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(tbody, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (tfoot_slot) {
        if (tfoot_slot.p && (!current || dirty[0] & /*$$scope*/
        16777216)) {
          update_slot_base(
            tfoot_slot,
            tfoot_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[24],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[24]
            ) : get_slot_changes(
              tfoot_slot_template,
              /*$$scope*/
              ctx2[24],
              dirty,
              get_tfoot_slot_changes
            ),
            get_tfoot_slot_context
          );
        }
      }
      if (!current || dirty[0] & /*top*/
      1024) {
        set_style(
          table,
          "--bw-svt-p-top",
          /*top*/
          ctx2[10] + "px"
        );
      }
      if (!current || dirty[0] & /*bottom*/
      64) {
        set_style(
          table,
          "--bw-svt-p-bottom",
          /*bottom*/
          ctx2[6] + "px"
        );
      }
      if (!current || dirty[0] & /*head_height*/
      256) {
        set_style(
          table,
          "--bw-svt-head-height",
          /*head_height*/
          ctx2[8] + "px"
        );
      }
      if (!current || dirty[0] & /*foot_height*/
      512) {
        set_style(
          table,
          "--bw-svt-foot-height",
          /*foot_height*/
          ctx2[9] + "px"
        );
      }
      if (!current || dirty[0] & /*average_height*/
      16) {
        set_style(
          table,
          "--bw-svt-avg-row-height",
          /*average_height*/
          ctx2[4] + "px"
        );
      }
      if (!current || dirty[0] & /*max_height*/
      2) {
        set_style(
          table,
          "--max-height",
          /*max_height*/
          ctx2[1] + "px"
        );
      }
      if (!current || dirty[0] & /*disable_scroll*/
      4) {
        toggle_class(
          table,
          "disable-scroll",
          /*disable_scroll*/
          ctx2[2]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(thead_slot, local);
      transition_in(if_block1);
      transition_in(tfoot_slot, local);
      current = true;
    },
    o(local) {
      transition_out(thead_slot, local);
      transition_out(if_block1);
      transition_out(tfoot_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(svelte_virtual_table_viewport);
      }
      if (if_block0) if_block0.d();
      if (thead_slot) thead_slot.d(detaching);
      thead_resize_listener();
      if (if_block1) if_block1.d();
      ctx[27](null);
      if (tfoot_slot) tfoot_slot.d(detaching);
      tfoot_resize_listener();
      ctx[29](null);
      table_resize_listener();
      mounted = false;
      dispose();
    }
  };
}
let height = "100%";
function instance$c($$self, $$props, $$invalidate) {
  let sortedItems;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { items: items2 = [] } = $$props;
  let { max_height } = $$props;
  let { actual_height } = $$props;
  let { table_scrollbar_width } = $$props;
  let { start = 0 } = $$props;
  let { end = 20 } = $$props;
  let { selected } = $$props;
  let { disable_scroll = false } = $$props;
  let { show_scroll_button = false } = $$props;
  let { viewport } = $$props;
  let { label = null } = $$props;
  createEventDispatcher();
  let average_height = 30;
  let bottom = 0;
  let contents;
  let head_height = 0;
  let foot_height = 0;
  let height_map = [];
  let mounted;
  let rows;
  let top = 0;
  let viewport_height = 200;
  let visible = [];
  let viewport_box;
  const is_browser2 = typeof window !== "undefined";
  const raf2 = is_browser2 ? window.requestAnimationFrame : (cb) => cb();
  async function refresh_height_map() {
    if (!viewport) {
      return;
    }
    if (sortedItems.length < start) {
      await scroll_to_index(sortedItems.length - 1, { behavior: "auto" });
    }
    const scrollTop = Math.max(0, viewport.scrollTop);
    $$invalidate(17, show_scroll_button = scrollTop > 100);
    $$invalidate(16, table_scrollbar_width = viewport.offsetWidth - viewport.clientWidth);
    for (let v = 0; v < rows.length; v += 1) {
      height_map[start + v] = rows[v].getBoundingClientRect().height;
    }
    let i = 0;
    let y = head_height;
    while (i < sortedItems.length) {
      const row_height = height_map[i] || average_height;
      if (y + row_height > scrollTop - max_height) {
        $$invalidate(13, start = i);
        $$invalidate(10, top = y - head_height);
        break;
      }
      y += row_height;
      i += 1;
    }
    let content_height = head_height;
    while (i < sortedItems.length) {
      const row_height = height_map[i] || average_height;
      content_height += row_height;
      i += 1;
      if (content_height - head_height > 3 * max_height) {
        break;
      }
    }
    $$invalidate(14, end = i);
    const remaining = sortedItems.length - end;
    const scrollbar_height = viewport.offsetHeight - viewport.clientHeight;
    if (scrollbar_height > 0) {
      content_height += scrollbar_height;
    }
    let filtered_height_map = height_map.filter((v) => typeof v === "number");
    $$invalidate(4, average_height = filtered_height_map.reduce((a, b) => a + b, 0) / filtered_height_map.length || 30);
    $$invalidate(6, bottom = remaining * average_height);
    if (!isFinite(bottom)) {
      $$invalidate(6, bottom = 2e5);
    }
    height_map.length = sortedItems.length;
    while (i < sortedItems.length) {
      i += 1;
      height_map[i] = average_height;
    }
    if (max_height && content_height > max_height) {
      $$invalidate(15, actual_height = max_height);
    } else {
      $$invalidate(15, actual_height = content_height);
    }
  }
  async function scroll_and_render(n) {
    raf2(async () => {
      if (typeof n !== "number") return;
      const direction = typeof n !== "number" ? false : is_in_view(n);
      if (direction === true) {
        return;
      }
      if (direction === "back") {
        await scroll_to_index(n, { behavior: "instant" });
      }
      if (direction === "forwards") {
        await scroll_to_index(n, { behavior: "instant" }, true);
      }
    });
  }
  function is_in_view(n) {
    const current = rows && rows[n - start];
    if (!current && n < start) {
      return "back";
    }
    if (!current && n >= end - 1) {
      return "forwards";
    }
    const { top: viewport_top } = viewport.getBoundingClientRect();
    const { top: top2, bottom: bottom2 } = current.getBoundingClientRect();
    if (top2 - viewport_top < 37) {
      return "back";
    }
    if (bottom2 - viewport_top > viewport_height) {
      return "forwards";
    }
    return true;
  }
  async function scroll_to_index(index, opts, align_end = false) {
    await tick();
    const _itemHeight = average_height;
    let distance = index * _itemHeight;
    if (align_end) {
      distance = distance - viewport_height + _itemHeight + head_height;
    }
    const scrollbar_height = viewport.offsetHeight - viewport.clientHeight;
    if (scrollbar_height > 0) {
      distance += scrollbar_height;
    }
    const _opts = {
      top: distance,
      behavior: "smooth",
      ...opts
    };
    viewport.scrollTo(_opts);
  }
  onMount(() => {
    rows = contents.children;
    $$invalidate(21, mounted = true);
  });
  function thead_elementresize_handler() {
    head_height = this.offsetHeight;
    $$invalidate(8, head_height);
  }
  function tbody_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      contents = $$value;
      $$invalidate(7, contents);
    });
  }
  function tfoot_elementresize_handler() {
    foot_height = this.offsetHeight;
    $$invalidate(9, foot_height);
  }
  function table_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      viewport = $$value;
      $$invalidate(0, viewport);
    });
  }
  function table_elementresizecontentbox_handler() {
    var _a;
    viewport_box = (_a = ResizeObserverSingleton.entries.get(this)) == null ? void 0 : _a.contentRect;
    $$invalidate(5, viewport_box);
  }
  $$self.$$set = ($$props2) => {
    if ("items" in $$props2) $$invalidate(18, items2 = $$props2.items);
    if ("max_height" in $$props2) $$invalidate(1, max_height = $$props2.max_height);
    if ("actual_height" in $$props2) $$invalidate(15, actual_height = $$props2.actual_height);
    if ("table_scrollbar_width" in $$props2) $$invalidate(16, table_scrollbar_width = $$props2.table_scrollbar_width);
    if ("start" in $$props2) $$invalidate(13, start = $$props2.start);
    if ("end" in $$props2) $$invalidate(14, end = $$props2.end);
    if ("selected" in $$props2) $$invalidate(19, selected = $$props2.selected);
    if ("disable_scroll" in $$props2) $$invalidate(2, disable_scroll = $$props2.disable_scroll);
    if ("show_scroll_button" in $$props2) $$invalidate(17, show_scroll_button = $$props2.show_scroll_button);
    if ("viewport" in $$props2) $$invalidate(0, viewport = $$props2.viewport);
    if ("label" in $$props2) $$invalidate(3, label = $$props2.label);
    if ("$$scope" in $$props2) $$invalidate(24, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*viewport_box*/
    32) {
      $$invalidate(22, viewport_height = (viewport_box == null ? void 0 : viewport_box.height) || 200);
    }
    if ($$self.$$.dirty[0] & /*items*/
    262144) {
      $$invalidate(23, sortedItems = items2);
    }
    if ($$self.$$.dirty[0] & /*mounted, viewport_height, viewport, sortedItems*/
    14680065) {
      {
        if (mounted && viewport_height && viewport.offsetParent) {
          raf2(refresh_height_map);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*selected*/
    524288) {
      scroll_and_render(selected);
    }
    if ($$self.$$.dirty[0] & /*sortedItems, start, end, max_height, average_height*/
    8413202) {
      $$invalidate(11, visible = is_browser2 ? sortedItems.slice(start, end).map((data, i) => {
        return { index: i + start, data };
      }) : sortedItems.slice(0, max_height / sortedItems.length * average_height + 1).map((data, i) => {
        return { index: i + start, data };
      }));
    }
  };
  return [
    viewport,
    max_height,
    disable_scroll,
    label,
    average_height,
    viewport_box,
    bottom,
    contents,
    head_height,
    foot_height,
    top,
    visible,
    refresh_height_map,
    start,
    end,
    actual_height,
    table_scrollbar_width,
    show_scroll_button,
    items2,
    selected,
    scroll_to_index,
    mounted,
    viewport_height,
    sortedItems,
    $$scope,
    slots,
    thead_elementresize_handler,
    tbody_binding,
    tfoot_elementresize_handler,
    table_binding,
    table_elementresizecontentbox_handler
  ];
}
let VirtualTable$1 = class VirtualTable extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$c,
      create_fragment$c,
      safe_not_equal,
      {
        items: 18,
        max_height: 1,
        actual_height: 15,
        table_scrollbar_width: 16,
        start: 13,
        end: 14,
        selected: 19,
        disable_scroll: 2,
        show_scroll_button: 17,
        viewport: 0,
        label: 3,
        scroll_to_index: 20
      },
      null,
      [-1, -1]
    );
  }
  get scroll_to_index() {
    return this.$$.ctx[20];
  }
};
function get_each_context$2(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[15] = list2[i];
  return child_ctx;
}
function create_if_block$7(ctx) {
  let div;
  let each_value = ensure_array_like(
    /*filter_options*/
    ctx[6][
      /*datatype*/
      ctx[2]
    ]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
  }
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(div, "class", "dropdown-filter-options svelte-1p5crt7");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(div, null);
        }
      }
    },
    p(ctx2, dirty) {
      if (dirty & /*current_filter, filter_options, datatype, filter_dropdown_open*/
      92) {
        each_value = ensure_array_like(
          /*filter_options*/
          ctx2[6][
            /*datatype*/
            ctx2[2]
          ]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context$2(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block$2(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(div, null);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_each_block$2(ctx) {
  let button;
  let t0_value = (
    /*opt*/
    ctx[15] + ""
  );
  let t0;
  let t1;
  let mounted;
  let dispose;
  function click_handler_3() {
    return (
      /*click_handler_3*/
      ctx[11](
        /*opt*/
        ctx[15]
      )
    );
  }
  return {
    c() {
      button = element("button");
      t0 = text(t0_value);
      t1 = space();
      attr(button, "class", "filter-option svelte-1p5crt7");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, t0);
      append(button, t1);
      if (!mounted) {
        dispose = listen(button, "click", stop_propagation(click_handler_3));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (dirty & /*datatype*/
      4 && t0_value !== (t0_value = /*opt*/
      ctx[15] + "")) set_data(t0, t0_value);
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_fragment$b(ctx) {
  let div5;
  let div0;
  let t0;
  let div4;
  let div1;
  let span;
  let t2;
  let button0;
  let t3;
  let button0_aria_label_value;
  let t4;
  let div3;
  let div2;
  let button1;
  let t5;
  let t6;
  let dropdownarrow;
  let button1_aria_label_value;
  let t7;
  let t8;
  let input;
  let t9;
  let button2;
  let check;
  let current;
  let mounted;
  let dispose;
  dropdownarrow = new DropdownArrow({});
  let if_block = (
    /*filter_dropdown_open*/
    ctx[4] && create_if_block$7(ctx)
  );
  check = new Check({});
  return {
    c() {
      div5 = element("div");
      div0 = element("div");
      t0 = space();
      div4 = element("div");
      div1 = element("div");
      span = element("span");
      span.textContent = "Filter as";
      t2 = space();
      button0 = element("button");
      t3 = text(
        /*datatype*/
        ctx[2]
      );
      t4 = space();
      div3 = element("div");
      div2 = element("div");
      button1 = element("button");
      t5 = text(
        /*current_filter*/
        ctx[3]
      );
      t6 = space();
      create_component(dropdownarrow.$$.fragment);
      t7 = space();
      if (if_block) if_block.c();
      t8 = space();
      input = element("input");
      t9 = space();
      button2 = element("button");
      create_component(check.$$.fragment);
      attr(div0, "class", "background svelte-1p5crt7");
      attr(span, "class", "svelte-1p5crt7");
      attr(button0, "aria-label", button0_aria_label_value = `Change filter type. Filtering ${/*datatype*/
      ctx[2]}s`);
      attr(button0, "class", "svelte-1p5crt7");
      attr(div1, "class", "filter-datatype-container svelte-1p5crt7");
      attr(button1, "aria-label", button1_aria_label_value = `Change filter. Using '${/*current_filter*/
      ctx[3]}'`);
      attr(button1, "class", "svelte-1p5crt7");
      attr(div2, "class", "filter-dropdown");
      attr(input, "type", "text");
      input.value = /*filter_input_value*/
      ctx[5];
      attr(input, "placeholder", "Type a value");
      attr(input, "class", "filter-input svelte-1p5crt7");
      attr(div3, "class", "input-container svelte-1p5crt7");
      attr(button2, "class", "check-button svelte-1p5crt7");
      attr(div4, "class", "filter-menu svelte-1p5crt7");
    },
    m(target, anchor) {
      insert(target, div5, anchor);
      append(div5, div0);
      append(div5, t0);
      append(div5, div4);
      append(div4, div1);
      append(div1, span);
      append(div1, t2);
      append(div1, button0);
      append(button0, t3);
      append(div4, t4);
      append(div4, div3);
      append(div3, div2);
      append(div2, button1);
      append(button1, t5);
      append(button1, t6);
      mount_component(dropdownarrow, button1, null);
      append(div2, t7);
      if (if_block) if_block.m(div2, null);
      append(div3, t8);
      append(div3, input);
      append(div4, t9);
      append(div4, button2);
      mount_component(check, button2, null);
      ctx[13](div4);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button0, "click", stop_propagation(
            /*click_handler_1*/
            ctx[9]
          )),
          listen(button1, "click", stop_propagation(
            /*click_handler_2*/
            ctx[10]
          )),
          listen(input, "click", stop_propagation(
            /*click_handler*/
            ctx[8]
          )),
          listen(
            input,
            "input",
            /*handle_filter_input*/
            ctx[7]
          ),
          listen(
            button2,
            "click",
            /*click_handler_4*/
            ctx[12]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      if (!current || dirty & /*datatype*/
      4) set_data(
        t3,
        /*datatype*/
        ctx2[2]
      );
      if (!current || dirty & /*datatype*/
      4 && button0_aria_label_value !== (button0_aria_label_value = `Change filter type. Filtering ${/*datatype*/
      ctx2[2]}s`)) {
        attr(button0, "aria-label", button0_aria_label_value);
      }
      if (!current || dirty & /*current_filter*/
      8) set_data(
        t5,
        /*current_filter*/
        ctx2[3]
      );
      if (!current || dirty & /*current_filter*/
      8 && button1_aria_label_value !== (button1_aria_label_value = `Change filter. Using '${/*current_filter*/
      ctx2[3]}'`)) {
        attr(button1, "aria-label", button1_aria_label_value);
      }
      if (
        /*filter_dropdown_open*/
        ctx2[4]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block$7(ctx2);
          if_block.c();
          if_block.m(div2, null);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (!current || dirty & /*filter_input_value*/
      32 && input.value !== /*filter_input_value*/
      ctx2[5]) {
        input.value = /*filter_input_value*/
        ctx2[5];
      }
    },
    i(local) {
      if (current) return;
      transition_in(dropdownarrow.$$.fragment, local);
      transition_in(check.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropdownarrow.$$.fragment, local);
      transition_out(check.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div5);
      }
      destroy_component(dropdownarrow);
      if (if_block) if_block.d();
      destroy_component(check);
      ctx[13](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance$b($$self, $$props, $$invalidate) {
  let { on_filter = () => {
  } } = $$props;
  let menu_element;
  let datatype = "string";
  let current_filter = "Contains";
  let filter_dropdown_open = false;
  let filter_input_value = "";
  const filter_options = {
    string: [
      "Contains",
      "Does not contain",
      "Starts with",
      "Ends with",
      "Is",
      "Is not",
      "Is empty",
      "Is not empty"
    ],
    number: ["=", "≠", ">", "<", "≥", "≤", "Is empty", "Is not empty"]
  };
  onMount(() => {
    position_menu();
  });
  function position_menu() {
    if (!menu_element) return;
    const viewport_width = window.innerWidth;
    const viewport_height = window.innerHeight;
    const menu_rect = menu_element.getBoundingClientRect();
    const x = (viewport_width - menu_rect.width) / 2;
    const y = (viewport_height - menu_rect.height) / 2;
    $$invalidate(1, menu_element.style.left = `${x}px`, menu_element);
    $$invalidate(1, menu_element.style.top = `${y}px`, menu_element);
  }
  function handle_filter_input(e) {
    const target = e.target;
    $$invalidate(5, filter_input_value = target.value);
  }
  function click_handler(event) {
    bubble.call(this, $$self, event);
  }
  const click_handler_1 = () => {
    $$invalidate(2, datatype = datatype === "string" ? "number" : "string");
    $$invalidate(3, current_filter = filter_options[datatype][0]);
  };
  const click_handler_2 = () => $$invalidate(4, filter_dropdown_open = !filter_dropdown_open);
  const click_handler_3 = (opt) => {
    $$invalidate(3, current_filter = opt);
    $$invalidate(4, filter_dropdown_open = !filter_dropdown_open);
  };
  const click_handler_4 = () => on_filter(datatype, current_filter, filter_input_value);
  function div4_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      menu_element = $$value;
      $$invalidate(1, menu_element);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("on_filter" in $$props2) $$invalidate(0, on_filter = $$props2.on_filter);
  };
  return [
    on_filter,
    menu_element,
    datatype,
    current_filter,
    filter_dropdown_open,
    filter_input_value,
    filter_options,
    handle_filter_input,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_3,
    click_handler_4,
    div4_binding
  ];
}
let FilterMenu$1 = class FilterMenu extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$b, create_fragment$b, safe_not_equal, { on_filter: 0 });
  }
};
function create_if_block_5$3(ctx) {
  let button0;
  let cellmenuicons0;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[15]("dataframe.sort_ascending") + ""
  );
  let t1;
  let t2;
  let t3;
  let button1;
  let cellmenuicons1;
  let t4;
  let t5_value = (
    /*i18n*/
    ctx[15]("dataframe.sort_descending") + ""
  );
  let t5;
  let t6;
  let t7;
  let button2;
  let cellmenuicons2;
  let t8;
  let t9_value = (
    /*i18n*/
    ctx[15]("dataframe.clear_sort") + ""
  );
  let t9;
  let t10;
  let button3;
  let cellmenuicons3;
  let t11;
  let t12_value = (
    /*i18n*/
    ctx[15]("dataframe.filter") + ""
  );
  let t12;
  let t13;
  let t14;
  let button4;
  let cellmenuicons4;
  let t15;
  let t16_value = (
    /*i18n*/
    ctx[15]("dataframe.clear_filter") + ""
  );
  let t16;
  let current;
  let mounted;
  let dispose;
  cellmenuicons0 = new CellMenuIcons$1({ props: { icon: "sort-asc" } });
  let if_block0 = (
    /*sort_direction*/
    ctx[10] === "asc" && /*sort_priority*/
    ctx[11] !== null && create_if_block_8$1(ctx)
  );
  cellmenuicons1 = new CellMenuIcons$1({ props: { icon: "sort-desc" } });
  let if_block1 = (
    /*sort_direction*/
    ctx[10] === "desc" && /*sort_priority*/
    ctx[11] !== null && create_if_block_7$1(ctx)
  );
  cellmenuicons2 = new CellMenuIcons$1({ props: { icon: "clear-sort" } });
  cellmenuicons3 = new CellMenuIcons$1({ props: { icon: "filter" } });
  let if_block2 = (
    /*filter_active*/
    ctx[14] && create_if_block_6$3()
  );
  cellmenuicons4 = new CellMenuIcons$1({ props: { icon: "clear-filter" } });
  return {
    c() {
      button0 = element("button");
      create_component(cellmenuicons0.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      if (if_block0) if_block0.c();
      t3 = space();
      button1 = element("button");
      create_component(cellmenuicons1.$$.fragment);
      t4 = space();
      t5 = text(t5_value);
      t6 = space();
      if (if_block1) if_block1.c();
      t7 = space();
      button2 = element("button");
      create_component(cellmenuicons2.$$.fragment);
      t8 = space();
      t9 = text(t9_value);
      t10 = space();
      button3 = element("button");
      create_component(cellmenuicons3.$$.fragment);
      t11 = space();
      t12 = text(t12_value);
      t13 = space();
      if (if_block2) if_block2.c();
      t14 = space();
      button4 = element("button");
      create_component(cellmenuicons4.$$.fragment);
      t15 = space();
      t16 = text(t16_value);
      attr(button0, "role", "menuitem");
      attr(button0, "class", "svelte-1w7httw");
      toggle_class(
        button0,
        "active",
        /*sort_direction*/
        ctx[10] === "asc"
      );
      attr(button1, "role", "menuitem");
      attr(button1, "class", "svelte-1w7httw");
      toggle_class(
        button1,
        "active",
        /*sort_direction*/
        ctx[10] === "desc"
      );
      attr(button2, "role", "menuitem");
      attr(button2, "class", "svelte-1w7httw");
      attr(button3, "role", "menuitem");
      attr(button3, "class", "svelte-1w7httw");
      toggle_class(
        button3,
        "active",
        /*filter_active*/
        ctx[14] || /*active_filter_menu*/
        ctx[17]
      );
      attr(button4, "role", "menuitem");
      attr(button4, "class", "svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, button0, anchor);
      mount_component(cellmenuicons0, button0, null);
      append(button0, t0);
      append(button0, t1);
      append(button0, t2);
      if (if_block0) if_block0.m(button0, null);
      insert(target, t3, anchor);
      insert(target, button1, anchor);
      mount_component(cellmenuicons1, button1, null);
      append(button1, t4);
      append(button1, t5);
      append(button1, t6);
      if (if_block1) if_block1.m(button1, null);
      insert(target, t7, anchor);
      insert(target, button2, anchor);
      mount_component(cellmenuicons2, button2, null);
      append(button2, t8);
      append(button2, t9);
      insert(target, t10, anchor);
      insert(target, button3, anchor);
      mount_component(cellmenuicons3, button3, null);
      append(button3, t11);
      append(button3, t12);
      append(button3, t13);
      if (if_block2) if_block2.m(button3, null);
      insert(target, t14, anchor);
      insert(target, button4, anchor);
      mount_component(cellmenuicons4, button4, null);
      append(button4, t15);
      append(button4, t16);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler*/
            ctx[28]
          ),
          listen(
            button1,
            "click",
            /*click_handler_1*/
            ctx[29]
          ),
          listen(button2, "click", function() {
            if (is_function(
              /*on_clear_sort*/
              ctx[9]
            )) ctx[9].apply(this, arguments);
          }),
          listen(button3, "click", stop_propagation(
            /*toggle_filter_menu*/
            ctx[21]
          )),
          listen(button4, "click", function() {
            if (is_function(
              /*on_clear_filter*/
              ctx[13]
            )) ctx[13].apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty[0] & /*i18n*/
      32768) && t1_value !== (t1_value = /*i18n*/
      ctx[15]("dataframe.sort_ascending") + "")) set_data(t1, t1_value);
      if (
        /*sort_direction*/
        ctx[10] === "asc" && /*sort_priority*/
        ctx[11] !== null
      ) {
        if (if_block0) {
          if_block0.p(ctx, dirty);
        } else {
          if_block0 = create_if_block_8$1(ctx);
          if_block0.c();
          if_block0.m(button0, null);
        }
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (!current || dirty[0] & /*sort_direction*/
      1024) {
        toggle_class(
          button0,
          "active",
          /*sort_direction*/
          ctx[10] === "asc"
        );
      }
      if ((!current || dirty[0] & /*i18n*/
      32768) && t5_value !== (t5_value = /*i18n*/
      ctx[15]("dataframe.sort_descending") + "")) set_data(t5, t5_value);
      if (
        /*sort_direction*/
        ctx[10] === "desc" && /*sort_priority*/
        ctx[11] !== null
      ) {
        if (if_block1) {
          if_block1.p(ctx, dirty);
        } else {
          if_block1 = create_if_block_7$1(ctx);
          if_block1.c();
          if_block1.m(button1, null);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (!current || dirty[0] & /*sort_direction*/
      1024) {
        toggle_class(
          button1,
          "active",
          /*sort_direction*/
          ctx[10] === "desc"
        );
      }
      if ((!current || dirty[0] & /*i18n*/
      32768) && t9_value !== (t9_value = /*i18n*/
      ctx[15]("dataframe.clear_sort") + "")) set_data(t9, t9_value);
      if ((!current || dirty[0] & /*i18n*/
      32768) && t12_value !== (t12_value = /*i18n*/
      ctx[15]("dataframe.filter") + "")) set_data(t12, t12_value);
      if (
        /*filter_active*/
        ctx[14]
      ) {
        if (if_block2) ;
        else {
          if_block2 = create_if_block_6$3();
          if_block2.c();
          if_block2.m(button3, null);
        }
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (!current || dirty[0] & /*filter_active, active_filter_menu*/
      147456) {
        toggle_class(
          button3,
          "active",
          /*filter_active*/
          ctx[14] || /*active_filter_menu*/
          ctx[17]
        );
      }
      if ((!current || dirty[0] & /*i18n*/
      32768) && t16_value !== (t16_value = /*i18n*/
      ctx[15]("dataframe.clear_filter") + "")) set_data(t16, t16_value);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons0.$$.fragment, local);
      transition_in(cellmenuicons1.$$.fragment, local);
      transition_in(cellmenuicons2.$$.fragment, local);
      transition_in(cellmenuicons3.$$.fragment, local);
      transition_in(cellmenuicons4.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons0.$$.fragment, local);
      transition_out(cellmenuicons1.$$.fragment, local);
      transition_out(cellmenuicons2.$$.fragment, local);
      transition_out(cellmenuicons3.$$.fragment, local);
      transition_out(cellmenuicons4.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button0);
        detach(t3);
        detach(button1);
        detach(t7);
        detach(button2);
        detach(t10);
        detach(button3);
        detach(t14);
        detach(button4);
      }
      destroy_component(cellmenuicons0);
      if (if_block0) if_block0.d();
      destroy_component(cellmenuicons1);
      if (if_block1) if_block1.d();
      destroy_component(cellmenuicons2);
      destroy_component(cellmenuicons3);
      if (if_block2) if_block2.d();
      destroy_component(cellmenuicons4);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_8$1(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*sort_priority*/
        ctx[11]
      );
      attr(span, "class", "priority svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*sort_priority*/
      2048) set_data(
        t,
        /*sort_priority*/
        ctx2[11]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block_7$1(ctx) {
  let span;
  let t;
  return {
    c() {
      span = element("span");
      t = text(
        /*sort_priority*/
        ctx[11]
      );
      attr(span, "class", "priority svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, span, anchor);
      append(span, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*sort_priority*/
      2048) set_data(
        t,
        /*sort_priority*/
        ctx2[11]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block_6$3(ctx) {
  let span;
  return {
    c() {
      span = element("span");
      span.textContent = "1";
      attr(span, "class", "priority svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, span, anchor);
    },
    d(detaching) {
      if (detaching) {
        detach(span);
      }
    }
  };
}
function create_if_block_3$5(ctx) {
  let button0;
  let cellmenuicons0;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[15]("dataframe.add_row_above") + ""
  );
  let t1;
  let t2;
  let button1;
  let cellmenuicons1;
  let t3;
  let t4_value = (
    /*i18n*/
    ctx[15]("dataframe.add_row_below") + ""
  );
  let t4;
  let t5;
  let if_block_anchor;
  let current;
  let mounted;
  let dispose;
  cellmenuicons0 = new CellMenuIcons$1({ props: { icon: "add-row-above" } });
  cellmenuicons1 = new CellMenuIcons$1({ props: { icon: "add-row-below" } });
  let if_block = (
    /*can_delete_rows*/
    ctx[6] && create_if_block_4$3(ctx)
  );
  return {
    c() {
      button0 = element("button");
      create_component(cellmenuicons0.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      button1 = element("button");
      create_component(cellmenuicons1.$$.fragment);
      t3 = space();
      t4 = text(t4_value);
      t5 = space();
      if (if_block) if_block.c();
      if_block_anchor = empty();
      attr(button0, "role", "menuitem");
      attr(button0, "aria-label", "Add row above");
      attr(button0, "class", "svelte-1w7httw");
      attr(button1, "role", "menuitem");
      attr(button1, "aria-label", "Add row below");
      attr(button1, "class", "svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, button0, anchor);
      mount_component(cellmenuicons0, button0, null);
      append(button0, t0);
      append(button0, t1);
      insert(target, t2, anchor);
      insert(target, button1, anchor);
      mount_component(cellmenuicons1, button1, null);
      append(button1, t3);
      append(button1, t4);
      insert(target, t5, anchor);
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler_2*/
            ctx[30]
          ),
          listen(
            button1,
            "click",
            /*click_handler_3*/
            ctx[31]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*i18n*/
      32768) && t1_value !== (t1_value = /*i18n*/
      ctx2[15]("dataframe.add_row_above") + "")) set_data(t1, t1_value);
      if ((!current || dirty[0] & /*i18n*/
      32768) && t4_value !== (t4_value = /*i18n*/
      ctx2[15]("dataframe.add_row_below") + "")) set_data(t4, t4_value);
      if (
        /*can_delete_rows*/
        ctx2[6]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*can_delete_rows*/
          64) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_4$3(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons0.$$.fragment, local);
      transition_in(cellmenuicons1.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons0.$$.fragment, local);
      transition_out(cellmenuicons1.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button0);
        detach(t2);
        detach(button1);
        detach(t5);
        detach(if_block_anchor);
      }
      destroy_component(cellmenuicons0);
      destroy_component(cellmenuicons1);
      if (if_block) if_block.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_4$3(ctx) {
  let button;
  let cellmenuicons;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[15]("dataframe.delete_row") + ""
  );
  let t1;
  let current;
  let mounted;
  let dispose;
  cellmenuicons = new CellMenuIcons$1({ props: { icon: "delete-row" } });
  return {
    c() {
      button = element("button");
      create_component(cellmenuicons.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(button, "role", "menuitem");
      attr(button, "class", "delete svelte-1w7httw");
      attr(button, "aria-label", "Delete row");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(cellmenuicons, button, null);
      append(button, t0);
      append(button, t1);
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*on_delete_row*/
            ctx[4]
          )) ctx[4].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty[0] & /*i18n*/
      32768) && t1_value !== (t1_value = /*i18n*/
      ctx[15]("dataframe.delete_row") + "")) set_data(t1, t1_value);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(cellmenuicons);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$6(ctx) {
  let button0;
  let cellmenuicons0;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[15]("dataframe.add_column_left") + ""
  );
  let t1;
  let t2;
  let button1;
  let cellmenuicons1;
  let t3;
  let t4_value = (
    /*i18n*/
    ctx[15]("dataframe.add_column_right") + ""
  );
  let t4;
  let t5;
  let if_block_anchor;
  let current;
  let mounted;
  let dispose;
  cellmenuicons0 = new CellMenuIcons$1({ props: { icon: "add-column-left" } });
  cellmenuicons1 = new CellMenuIcons$1({ props: { icon: "add-column-right" } });
  let if_block = (
    /*can_delete_cols*/
    ctx[7] && create_if_block_2$6(ctx)
  );
  return {
    c() {
      button0 = element("button");
      create_component(cellmenuicons0.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      t2 = space();
      button1 = element("button");
      create_component(cellmenuicons1.$$.fragment);
      t3 = space();
      t4 = text(t4_value);
      t5 = space();
      if (if_block) if_block.c();
      if_block_anchor = empty();
      attr(button0, "role", "menuitem");
      attr(button0, "aria-label", "Add column to the left");
      attr(button0, "class", "svelte-1w7httw");
      attr(button1, "role", "menuitem");
      attr(button1, "aria-label", "Add column to the right");
      attr(button1, "class", "svelte-1w7httw");
    },
    m(target, anchor) {
      insert(target, button0, anchor);
      mount_component(cellmenuicons0, button0, null);
      append(button0, t0);
      append(button0, t1);
      insert(target, t2, anchor);
      insert(target, button1, anchor);
      mount_component(cellmenuicons1, button1, null);
      append(button1, t3);
      append(button1, t4);
      insert(target, t5, anchor);
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            button0,
            "click",
            /*click_handler_4*/
            ctx[32]
          ),
          listen(
            button1,
            "click",
            /*click_handler_5*/
            ctx[33]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*i18n*/
      32768) && t1_value !== (t1_value = /*i18n*/
      ctx2[15]("dataframe.add_column_left") + "")) set_data(t1, t1_value);
      if ((!current || dirty[0] & /*i18n*/
      32768) && t4_value !== (t4_value = /*i18n*/
      ctx2[15]("dataframe.add_column_right") + "")) set_data(t4, t4_value);
      if (
        /*can_delete_cols*/
        ctx2[7]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*can_delete_cols*/
          128) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_2$6(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons0.$$.fragment, local);
      transition_in(cellmenuicons1.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons0.$$.fragment, local);
      transition_out(cellmenuicons1.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button0);
        detach(t2);
        detach(button1);
        detach(t5);
        detach(if_block_anchor);
      }
      destroy_component(cellmenuicons0);
      destroy_component(cellmenuicons1);
      if (if_block) if_block.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_if_block_2$6(ctx) {
  let button;
  let cellmenuicons;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[15]("dataframe.delete_column") + ""
  );
  let t1;
  let current;
  let mounted;
  let dispose;
  cellmenuicons = new CellMenuIcons$1({ props: { icon: "delete-column" } });
  return {
    c() {
      button = element("button");
      create_component(cellmenuicons.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(button, "role", "menuitem");
      attr(button, "class", "delete svelte-1w7httw");
      attr(button, "aria-label", "Delete column");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(cellmenuicons, button, null);
      append(button, t0);
      append(button, t1);
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*on_delete_col*/
            ctx[5]
          )) ctx[5].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || dirty[0] & /*i18n*/
      32768) && t1_value !== (t1_value = /*i18n*/
      ctx[15]("dataframe.delete_column") + "")) set_data(t1, t1_value);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenuicons.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenuicons.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(cellmenuicons);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block$6(ctx) {
  let filtermenu;
  let current;
  filtermenu = new FilterMenu$1({
    props: { on_filter: (
      /*on_filter*/
      ctx[12]
    ) }
  });
  return {
    c() {
      create_component(filtermenu.$$.fragment);
    },
    m(target, anchor) {
      mount_component(filtermenu, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const filtermenu_changes = {};
      if (dirty[0] & /*on_filter*/
      4096) filtermenu_changes.on_filter = /*on_filter*/
      ctx2[12];
      filtermenu.$set(filtermenu_changes);
    },
    i(local) {
      if (current) return;
      transition_in(filtermenu.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(filtermenu.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(filtermenu, detaching);
    }
  };
}
function create_fragment$a(ctx) {
  let div;
  let t0;
  let t1;
  let t2;
  let if_block3_anchor;
  let current;
  let if_block0 = (
    /*is_header*/
    ctx[20] && create_if_block_5$3(ctx)
  );
  let if_block1 = !/*is_header*/
  ctx[20] && /*can_add_rows*/
  ctx[19] && create_if_block_3$5(ctx);
  let if_block2 = (
    /*can_add_columns*/
    ctx[18] && create_if_block_1$6(ctx)
  );
  let if_block3 = (
    /*active_filter_menu*/
    ctx[17] && create_if_block$6(ctx)
  );
  return {
    c() {
      div = element("div");
      if (if_block0) if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      t2 = space();
      if (if_block3) if_block3.c();
      if_block3_anchor = empty();
      attr(div, "class", "cell-menu svelte-1w7httw");
      attr(div, "role", "menu");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block0) if_block0.m(div, null);
      append(div, t0);
      if (if_block1) if_block1.m(div, null);
      append(div, t1);
      if (if_block2) if_block2.m(div, null);
      ctx[34](div);
      insert(target, t2, anchor);
      if (if_block3) if_block3.m(target, anchor);
      insert(target, if_block3_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*is_header*/
        ctx2[20]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty[0] & /*is_header*/
          1048576) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_5$3(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (!/*is_header*/
      ctx2[20] && /*can_add_rows*/
      ctx2[19]) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*is_header, can_add_rows*/
          1572864) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_3$5(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*can_add_columns*/
        ctx2[18]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*can_add_columns*/
          262144) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_1$6(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (
        /*active_filter_menu*/
        ctx2[17]
      ) {
        if (if_block3) {
          if_block3.p(ctx2, dirty);
          if (dirty[0] & /*active_filter_menu*/
          131072) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block$6(ctx2);
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(if_block3_anchor.parentNode, if_block3_anchor);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      transition_in(if_block3);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      transition_out(if_block3);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
        detach(t2);
        detach(if_block3_anchor);
      }
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
      ctx[34](null);
      if (if_block3) if_block3.d(detaching);
    }
  };
}
function instance$a($$self, $$props, $$invalidate) {
  let is_header;
  let can_add_rows;
  let can_add_columns;
  let { x } = $$props;
  let { y } = $$props;
  let { on_add_row_above } = $$props;
  let { on_add_row_below } = $$props;
  let { on_add_column_left } = $$props;
  let { on_add_column_right } = $$props;
  let { row } = $$props;
  let { col_count } = $$props;
  let { row_count } = $$props;
  let { on_delete_row } = $$props;
  let { on_delete_col } = $$props;
  let { can_delete_rows } = $$props;
  let { can_delete_cols } = $$props;
  let { on_sort = () => {
  } } = $$props;
  let { on_clear_sort = () => {
  } } = $$props;
  let { sort_direction = null } = $$props;
  let { sort_priority = null } = $$props;
  let { on_filter = () => {
  } } = $$props;
  let { on_clear_filter = () => {
  } } = $$props;
  let { filter_active = null } = $$props;
  let { editable = true } = $$props;
  let { i18n } = $$props;
  let menu_element;
  let active_filter_menu = null;
  onMount(() => {
    position_menu();
  });
  function position_menu() {
    if (!menu_element) return;
    const viewport_width = window.innerWidth;
    const viewport_height = window.innerHeight;
    const menu_rect = menu_element.getBoundingClientRect();
    let new_x = x - 30;
    let new_y = y - 20;
    if (new_x + menu_rect.width > viewport_width) {
      new_x = x - menu_rect.width + 10;
    }
    if (new_y + menu_rect.height > viewport_height) {
      new_y = y - menu_rect.height + 10;
    }
    $$invalidate(16, menu_element.style.left = `${new_x}px`, menu_element);
    $$invalidate(16, menu_element.style.top = `${new_y}px`, menu_element);
  }
  function toggle_filter_menu() {
    if (filter_active) {
      on_filter("string", "", "");
      return;
    }
    const menu_rect = menu_element.getBoundingClientRect();
    $$invalidate(17, active_filter_menu = {
      x: menu_rect.right,
      y: menu_rect.top + menu_rect.height / 2
    });
  }
  const click_handler = () => on_sort("asc");
  const click_handler_1 = () => on_sort("desc");
  const click_handler_2 = () => on_add_row_above();
  const click_handler_3 = () => on_add_row_below();
  const click_handler_4 = () => on_add_column_left();
  const click_handler_5 = () => on_add_column_right();
  function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      menu_element = $$value;
      $$invalidate(16, menu_element);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("x" in $$props2) $$invalidate(22, x = $$props2.x);
    if ("y" in $$props2) $$invalidate(23, y = $$props2.y);
    if ("on_add_row_above" in $$props2) $$invalidate(0, on_add_row_above = $$props2.on_add_row_above);
    if ("on_add_row_below" in $$props2) $$invalidate(1, on_add_row_below = $$props2.on_add_row_below);
    if ("on_add_column_left" in $$props2) $$invalidate(2, on_add_column_left = $$props2.on_add_column_left);
    if ("on_add_column_right" in $$props2) $$invalidate(3, on_add_column_right = $$props2.on_add_column_right);
    if ("row" in $$props2) $$invalidate(24, row = $$props2.row);
    if ("col_count" in $$props2) $$invalidate(25, col_count = $$props2.col_count);
    if ("row_count" in $$props2) $$invalidate(26, row_count = $$props2.row_count);
    if ("on_delete_row" in $$props2) $$invalidate(4, on_delete_row = $$props2.on_delete_row);
    if ("on_delete_col" in $$props2) $$invalidate(5, on_delete_col = $$props2.on_delete_col);
    if ("can_delete_rows" in $$props2) $$invalidate(6, can_delete_rows = $$props2.can_delete_rows);
    if ("can_delete_cols" in $$props2) $$invalidate(7, can_delete_cols = $$props2.can_delete_cols);
    if ("on_sort" in $$props2) $$invalidate(8, on_sort = $$props2.on_sort);
    if ("on_clear_sort" in $$props2) $$invalidate(9, on_clear_sort = $$props2.on_clear_sort);
    if ("sort_direction" in $$props2) $$invalidate(10, sort_direction = $$props2.sort_direction);
    if ("sort_priority" in $$props2) $$invalidate(11, sort_priority = $$props2.sort_priority);
    if ("on_filter" in $$props2) $$invalidate(12, on_filter = $$props2.on_filter);
    if ("on_clear_filter" in $$props2) $$invalidate(13, on_clear_filter = $$props2.on_clear_filter);
    if ("filter_active" in $$props2) $$invalidate(14, filter_active = $$props2.filter_active);
    if ("editable" in $$props2) $$invalidate(27, editable = $$props2.editable);
    if ("i18n" in $$props2) $$invalidate(15, i18n = $$props2.i18n);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*row*/
    16777216) {
      $$invalidate(20, is_header = row === -1);
    }
    if ($$self.$$.dirty[0] & /*editable, row_count*/
    201326592) {
      $$invalidate(19, can_add_rows = editable && row_count[1] === "dynamic");
    }
    if ($$self.$$.dirty[0] & /*editable, col_count*/
    167772160) {
      $$invalidate(18, can_add_columns = editable && col_count[1] === "dynamic");
    }
  };
  return [
    on_add_row_above,
    on_add_row_below,
    on_add_column_left,
    on_add_column_right,
    on_delete_row,
    on_delete_col,
    can_delete_rows,
    can_delete_cols,
    on_sort,
    on_clear_sort,
    sort_direction,
    sort_priority,
    on_filter,
    on_clear_filter,
    filter_active,
    i18n,
    menu_element,
    active_filter_menu,
    can_add_columns,
    can_add_rows,
    is_header,
    toggle_filter_menu,
    x,
    y,
    row,
    col_count,
    row_count,
    editable,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_3,
    click_handler_4,
    click_handler_5,
    div_binding
  ];
}
let CellMenu$1 = class CellMenu extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$a,
      create_fragment$a,
      safe_not_equal,
      {
        x: 22,
        y: 23,
        on_add_row_above: 0,
        on_add_row_below: 1,
        on_add_column_left: 2,
        on_add_column_right: 3,
        row: 24,
        col_count: 25,
        row_count: 26,
        on_delete_row: 4,
        on_delete_col: 5,
        can_delete_rows: 6,
        can_delete_cols: 7,
        on_sort: 8,
        on_clear_sort: 9,
        sort_direction: 10,
        sort_priority: 11,
        on_filter: 12,
        on_clear_filter: 13,
        filter_active: 14,
        editable: 27,
        i18n: 15
      },
      null,
      [-1, -1]
    );
  }
};
function create_if_block_2$5(ctx) {
  let div;
  let input;
  let input_value_value;
  let input_placeholder_value;
  let input_title_value;
  let t;
  let current;
  let mounted;
  let dispose;
  let if_block = (
    /*current_search_query*/
    ctx[0] && /*show_search*/
    ctx[3] === "filter" && create_if_block_3$4(ctx)
  );
  return {
    c() {
      div = element("div");
      input = element("input");
      t = space();
      if (if_block) if_block.c();
      attr(input, "type", "text");
      input.value = input_value_value = /*current_search_query*/
      ctx[0] || "";
      attr(input, "placeholder", input_placeholder_value = /*show_search*/
      ctx[3] === "filter" ? "Filter..." : "Search...");
      attr(input, "class", "search-input svelte-1jaxu11");
      attr(input, "title", input_title_value = `Enter text to ${/*show_search*/
      ctx[3]} the table`);
      toggle_class(
        input,
        "filter-mode",
        /*show_search*/
        ctx[3] === "filter"
      );
      attr(div, "class", "search-container svelte-1jaxu11");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, input);
      append(div, t);
      if (if_block) if_block.m(div, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          input,
          "input",
          /*handle_search_input*/
          ctx[7]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (!current || dirty & /*current_search_query*/
      1 && input_value_value !== (input_value_value = /*current_search_query*/
      ctx2[0] || "") && input.value !== input_value_value) {
        input.value = input_value_value;
      }
      if (!current || dirty & /*show_search*/
      8 && input_placeholder_value !== (input_placeholder_value = /*show_search*/
      ctx2[3] === "filter" ? "Filter..." : "Search...")) {
        attr(input, "placeholder", input_placeholder_value);
      }
      if (!current || dirty & /*show_search*/
      8 && input_title_value !== (input_title_value = `Enter text to ${/*show_search*/
      ctx2[3]} the table`)) {
        attr(input, "title", input_title_value);
      }
      if (!current || dirty & /*show_search*/
      8) {
        toggle_class(
          input,
          "filter-mode",
          /*show_search*/
          ctx2[3] === "filter"
        );
      }
      if (
        /*current_search_query*/
        ctx2[0] && /*show_search*/
        ctx2[3] === "filter"
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty & /*current_search_query, show_search*/
          9) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_3$4(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(div, null);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (if_block) if_block.d();
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_3$4(ctx) {
  let button;
  let check;
  let current;
  let mounted;
  let dispose;
  check = new Check({});
  return {
    c() {
      button = element("button");
      create_component(check.$$.fragment);
      attr(button, "class", "toolbar-button check-button svelte-1jaxu11");
      attr(button, "aria-label", "Apply filter and update dataframe values");
      attr(button, "title", "Apply filter and update dataframe values");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(check, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(button, "click", function() {
          if (is_function(
            /*on_commit_filter*/
            ctx[5]
          )) ctx[5].apply(this, arguments);
        });
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
    },
    i(local) {
      if (current) return;
      transition_in(check.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(check.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(check);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$5(ctx) {
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: (
        /*copied*/
        ctx[6] ? Check : Copy
      ),
      label: (
        /*copied*/
        ctx[6] ? "Copied to clipboard" : "Copy table data"
      )
    }
  });
  iconbutton.$on(
    "click",
    /*handle_copy*/
    ctx[8]
  );
  return {
    c() {
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const iconbutton_changes = {};
      if (dirty & /*copied*/
      64) iconbutton_changes.Icon = /*copied*/
      ctx2[6] ? Check : Copy;
      if (dirty & /*copied*/
      64) iconbutton_changes.label = /*copied*/
      ctx2[6] ? "Copied to clipboard" : "Copy table data";
      iconbutton.$set(iconbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(iconbutton, detaching);
    }
  };
}
function create_if_block$5(ctx) {
  let fullscreenbutton;
  let current;
  fullscreenbutton = new FullscreenButton({
    props: { fullscreen: (
      /*fullscreen*/
      ctx[4]
    ) }
  });
  fullscreenbutton.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[10]
  );
  return {
    c() {
      create_component(fullscreenbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(fullscreenbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const fullscreenbutton_changes = {};
      if (dirty & /*fullscreen*/
      16) fullscreenbutton_changes.fullscreen = /*fullscreen*/
      ctx2[4];
      fullscreenbutton.$set(fullscreenbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(fullscreenbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(fullscreenbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(fullscreenbutton, detaching);
    }
  };
}
function create_fragment$9(ctx) {
  let div1;
  let div0;
  let t0;
  let t1;
  let current;
  let if_block0 = (
    /*show_search*/
    ctx[3] !== "none" && create_if_block_2$5(ctx)
  );
  let if_block1 = (
    /*show_copy_button*/
    ctx[2] && create_if_block_1$5(ctx)
  );
  let if_block2 = (
    /*show_fullscreen_button*/
    ctx[1] && create_if_block$5(ctx)
  );
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      if (if_block0) if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      attr(div0, "class", "toolbar-buttons svelte-1jaxu11");
      attr(div1, "class", "toolbar svelte-1jaxu11");
      attr(div1, "role", "toolbar");
      attr(div1, "aria-label", "Table actions");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      if (if_block0) if_block0.m(div0, null);
      append(div0, t0);
      if (if_block1) if_block1.m(div0, null);
      append(div0, t1);
      if (if_block2) if_block2.m(div0, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (
        /*show_search*/
        ctx2[3] !== "none"
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*show_search*/
          8) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_2$5(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div0, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*show_copy_button*/
        ctx2[2]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*show_copy_button*/
          4) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_1$5(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div0, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*show_fullscreen_button*/
        ctx2[1]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty & /*show_fullscreen_button*/
          2) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block$5(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(div0, null);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
    }
  };
}
function instance$9($$self, $$props, $$invalidate) {
  let { show_fullscreen_button = false } = $$props;
  let { show_copy_button = false } = $$props;
  let { show_search = "none" } = $$props;
  let { fullscreen = false } = $$props;
  let { on_copy } = $$props;
  let { on_commit_filter } = $$props;
  const dispatch2 = createEventDispatcher();
  let copied = false;
  let timer;
  let { current_search_query = null } = $$props;
  let input_value = "";
  function handle_search_input(e) {
    const target = e.target;
    input_value = target.value;
    const new_query = input_value || null;
    if (current_search_query !== new_query) {
      $$invalidate(0, current_search_query = new_query);
      dispatch2("search", current_search_query);
    }
  }
  function copy_feedback() {
    $$invalidate(6, copied = true);
    if (timer) clearTimeout(timer);
    timer = setTimeout(
      () => {
        $$invalidate(6, copied = false);
      },
      2e3
    );
  }
  async function handle_copy() {
    await on_copy();
    copy_feedback();
  }
  onDestroy(() => {
    if (timer) clearTimeout(timer);
  });
  function fullscreen_handler(event) {
    bubble.call(this, $$self, event);
  }
  $$self.$$set = ($$props2) => {
    if ("show_fullscreen_button" in $$props2) $$invalidate(1, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("show_copy_button" in $$props2) $$invalidate(2, show_copy_button = $$props2.show_copy_button);
    if ("show_search" in $$props2) $$invalidate(3, show_search = $$props2.show_search);
    if ("fullscreen" in $$props2) $$invalidate(4, fullscreen = $$props2.fullscreen);
    if ("on_copy" in $$props2) $$invalidate(9, on_copy = $$props2.on_copy);
    if ("on_commit_filter" in $$props2) $$invalidate(5, on_commit_filter = $$props2.on_commit_filter);
    if ("current_search_query" in $$props2) $$invalidate(0, current_search_query = $$props2.current_search_query);
  };
  return [
    current_search_query,
    show_fullscreen_button,
    show_copy_button,
    show_search,
    fullscreen,
    on_commit_filter,
    copied,
    handle_search_input,
    handle_copy,
    on_copy,
    fullscreen_handler
  ];
}
let Toolbar$1 = class Toolbar extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$9, create_fragment$9, safe_not_equal, {
      show_fullscreen_button: 1,
      show_copy_button: 2,
      show_search: 3,
      fullscreen: 4,
      on_copy: 9,
      on_commit_filter: 5,
      current_search_query: 0
    });
  }
};
function cast_value_to_type$1(v, t) {
  if (t === "number") {
    const n = Number(v);
    return isNaN(n) ? v : n;
  }
  if (t === "bool") {
    if (typeof v === "boolean") return v;
    if (typeof v === "number") return v !== 0;
    const s = String(v).toLowerCase();
    if (s === "true" || s === "1") return true;
    if (s === "false" || s === "0") return false;
    return v;
  }
  if (t === "date") {
    const d = new Date(v);
    return isNaN(d.getTime()) ? v : d.toISOString();
  }
  return v;
}
function make_headers$1(_head, col_count, els, make_id2) {
  let _h = _head || [];
  if (col_count[1] === "fixed" && _h.length < col_count[0]) {
    const fill = Array(col_count[0] - _h.length).fill("").map((_, i) => `${i + _h.length}`);
    _h = _h.concat(fill);
  }
  if (!_h || _h.length === 0) {
    return Array(col_count[0]).fill(0).map((_, i) => {
      const _id = make_id2();
      els[_id] = { cell: null, input: null };
      return { id: _id, value: JSON.stringify(i + 1) };
    });
  }
  return _h.map((h, i) => {
    const _id = make_id2();
    els[_id] = { cell: null, input: null };
    return { id: _id, value: h ?? "" };
  });
}
function process_data$1(values, els, data_binding, make_id2, display_value = null, datatype) {
  if (!values || values.length === 0) {
    return [];
  }
  const result = values.map((row, i) => {
    return row.map((value, j) => {
      var _a;
      const _id = make_id2();
      els[_id] = { cell: null, input: null };
      data_binding[_id] = value;
      let display = (_a = display_value == null ? void 0 : display_value[i]) == null ? void 0 : _a[j];
      if (display === void 0) {
        display = String(value);
      }
      const dtype = Array.isArray(datatype) ? datatype[j] : datatype;
      return {
        id: _id,
        value: cast_value_to_type$1(value, dtype),
        display_value: display
      };
    });
  });
  return result;
}
async function save_cell_value$1(input_value, ctx, row, col) {
  var _a;
  if (!ctx.data || !ctx.data[row] || !ctx.data[row][col]) return;
  const old_value = ctx.data[row][col].value;
  ctx.data[row][col].value = input_value;
  if (ctx.data[row][col].display_value !== void 0) {
    ctx.data[row][col].display_value = input_value;
  }
  if (old_value !== input_value && ctx.dispatch) {
    ctx.dispatch("change", {
      data: ctx.data.map((row2) => row2.map((cell) => cell.value)),
      headers: ((_a = ctx.headers) == null ? void 0 : _a.map((h) => h.value)) || [],
      metadata: null
    });
  }
  ctx.actions.set_selected([row, col]);
}
async function handle_cell_blur$1(event, ctx, coords) {
  if (!ctx.data || !ctx.headers || !ctx.els) return;
  const input_el = event.target;
  if (!input_el || input_el.value === void 0) return;
  await save_cell_value$1(input_el.value, ctx, coords[0], coords[1]);
}
function handle_header_navigation$1(event, ctx) {
  const state = get_store_value(ctx.state);
  const selected_header = state.ui_state.selected_header;
  const header_edit = state.ui_state.header_edit;
  const headers = ctx.headers || [];
  if (selected_header === false || header_edit !== false) return false;
  switch (event.key) {
    case "ArrowDown":
      ctx.actions.set_selected_header(false);
      ctx.actions.set_selected([0, selected_header]);
      ctx.actions.set_selected_cells([[0, selected_header]]);
      return true;
    case "ArrowLeft":
      ctx.actions.set_selected_header(
        selected_header > 0 ? selected_header - 1 : selected_header
      );
      return true;
    case "ArrowRight":
      ctx.actions.set_selected_header(
        selected_header < headers.length - 1 ? selected_header + 1 : selected_header
      );
      return true;
    case "Escape":
      event.preventDefault();
      ctx.actions.set_selected_header(false);
      return true;
    case "Enter":
      event.preventDefault();
      if (state.config.editable) {
        ctx.actions.set_header_edit(selected_header);
      }
      return true;
  }
  return false;
}
function handle_delete_operation$1(event, ctx) {
  var _a;
  if (!ctx.data || !ctx.headers || !ctx.els || !ctx.dispatch) return false;
  const state = get_store_value(ctx.state);
  if (!state.config.editable) return false;
  if (event.key !== "Delete" && event.key !== "Backspace") return false;
  const editing = state.ui_state.editing;
  const selected_cells = state.ui_state.selected_cells;
  const static_columns = state.config.static_columns || [];
  if (selected_cells.some(([_, col]) => static_columns.includes(col))) {
    return false;
  }
  if (editing) {
    const [row, col] = editing;
    const input_el = (_a = ctx.els[ctx.data[row][col].id]) == null ? void 0 : _a.input;
    if (input_el && input_el.selectionStart !== input_el.selectionEnd) {
      return false;
    }
    if (event.key === "Delete" && (input_el == null ? void 0 : input_el.selectionStart) !== (input_el == null ? void 0 : input_el.value.length)) {
      return false;
    }
    if (event.key === "Backspace" && (input_el == null ? void 0 : input_el.selectionStart) !== 0) {
      return false;
    }
  }
  event.preventDefault();
  if (selected_cells.length > 0) {
    const new_data = handle_delete_key$1(ctx.data, selected_cells);
    ctx.dispatch("change", {
      data: new_data.map((row) => row.map((cell) => cell.value)),
      headers: ctx.headers.map((h) => h.value),
      metadata: null
    });
  }
  return true;
}
function handle_arrow_keys$1(event, ctx, i, j) {
  const state = get_store_value(ctx.state);
  const editing = state.ui_state.editing;
  const selected_cells = state.ui_state.selected_cells;
  if (editing) return false;
  if (!ctx.data) return false;
  event.preventDefault();
  const next_coords = ctx.actions.move_cursor(event, [i, j], ctx.data);
  if (next_coords) {
    if (event.shiftKey) {
      ctx.actions.set_selected_cells(
        ctx.actions.get_range_selection(
          selected_cells.length > 0 ? selected_cells[0] : [i, j],
          next_coords
        )
      );
      ctx.actions.set_editing(false);
    } else {
      ctx.actions.set_selected_cells([next_coords]);
      ctx.actions.set_editing(false);
    }
    ctx.actions.set_selected(next_coords);
  } else if (next_coords === false && event.key === "ArrowUp" && i === 0) {
    ctx.actions.set_selected_header(j);
    ctx.actions.set_selected(false);
    ctx.actions.set_selected_cells([]);
    ctx.actions.set_editing(false);
  }
  return true;
}
async function handle_enter_key$1(event, ctx, i, j) {
  var _a, _b;
  if (!ctx.data || !ctx.els) return false;
  const state = get_store_value(ctx.state);
  if (!state.config.editable) return false;
  const editing = state.ui_state.editing;
  if (editing && event.shiftKey) return false;
  event.preventDefault();
  if (editing && dequal(editing, [i, j])) {
    const cell_id = ctx.data[i][j].id;
    const input_el = (_a = ctx.els[cell_id]) == null ? void 0 : _a.input;
    if (input_el) {
      await save_cell_value$1(input_el.value, ctx, i, j);
    }
    ctx.actions.set_editing(false);
    await tick();
    (_b = ctx.parent_element) == null ? void 0 : _b.focus();
  } else {
    ctx.actions.set_editing([i, j]);
  }
  return true;
}
function handle_tab_key$1(event, ctx, i, j) {
  if (!ctx.data) return false;
  event.preventDefault();
  ctx.actions.set_editing(false);
  const next_cell = ctx.actions.get_next_cell_coordinates(
    [i, j],
    ctx.data,
    event.shiftKey
  );
  if (next_cell) {
    ctx.actions.set_selected_cells([next_cell]);
    ctx.actions.set_selected(next_cell);
    if (get_store_value(ctx.state).config.editable) {
      ctx.actions.set_editing(next_cell);
    }
  }
  return true;
}
function handle_default_key$1(event, ctx, i, j) {
  const state = get_store_value(ctx.state);
  if (!state.config.editable) return false;
  const editing = state.ui_state.editing;
  if (event.key.length === 1 && (!editing || !dequal(editing, [i, j]))) {
    ctx.actions.set_editing([i, j]);
    return true;
  }
  return false;
}
async function handle_cell_navigation$1(event, ctx) {
  if (!ctx.data) return false;
  const state = get_store_value(ctx.state);
  const selected = state.ui_state.selected;
  const selected_cells = state.ui_state.selected_cells;
  if (!selected) return false;
  if (event.key === "c" && (event.metaKey || event.ctrlKey)) {
    event.preventDefault();
    if (selected_cells.length > 0) {
      await copy_table_data$1(ctx.data, selected_cells);
    }
    ctx.actions.set_copy_flash(true);
    return true;
  }
  const [i, j] = selected;
  switch (event.key) {
    case "ArrowRight":
    case "ArrowLeft":
    case "ArrowDown":
    case "ArrowUp":
      return handle_arrow_keys$1(event, ctx, i, j);
    case "Escape":
      if (!state.config.editable) return false;
      event.preventDefault();
      ctx.actions.set_editing(false);
      tick().then(() => {
        if (ctx.parent_element) {
          ctx.parent_element.focus();
        }
      });
      return true;
    case "Enter":
      return await handle_enter_key$1(event, ctx, i, j);
    case "Tab":
      return handle_tab_key$1(event, ctx, i, j);
    case "Delete":
    case "Backspace":
      return handle_delete_operation$1(event, ctx);
    default:
      return handle_default_key$1(event, ctx, i, j);
  }
}
async function handle_keydown$1(event, context) {
  if (handle_header_navigation$1(event, context)) return;
  if (handle_delete_operation$1(event, context)) return;
  await handle_cell_navigation$1(event, context);
}
function create_drag_handlers$1(state, set_is_dragging, set_selected_cells, set_selected, handle_cell_click, show_row_numbers, parent_element) {
  const start_drag = (event, row, col) => {
    const target = event.target;
    const is_checkbox_click = target.type === "checkbox" || target.closest('input[type="checkbox"]') || target.closest(".bool-cell");
    if (event.target instanceof HTMLAnchorElement || show_row_numbers && col === -1 || is_checkbox_click)
      return;
    event.preventDefault();
    event.stopPropagation();
    state.mouse_down_pos = { x: event.clientX, y: event.clientY };
    state.drag_start = [row, col];
    if (!event.shiftKey && !event.metaKey && !event.ctrlKey) {
      set_selected_cells([[row, col]]);
      set_selected([row, col]);
      handle_cell_click(event, row, col);
    }
  };
  const update_selection = (event) => {
    const cell = event.target.closest("td");
    if (!cell) return;
    const row = parseInt(cell.getAttribute("data-row") || "0");
    const col = parseInt(cell.getAttribute("data-col") || "0");
    if (isNaN(row) || isNaN(col)) return;
    const selection_range = get_range_selection$1(state.drag_start, [row, col]);
    set_selected_cells(selection_range);
    set_selected([row, col]);
  };
  const end_drag = (event) => {
    if (!state.is_dragging && state.drag_start) {
      handle_cell_click(event, state.drag_start[0], state.drag_start[1]);
    } else if (state.is_dragging && parent_element) {
      parent_element.focus();
    }
    state.is_dragging = false;
    set_is_dragging(false);
    state.drag_start = null;
    state.mouse_down_pos = null;
  };
  return {
    handle_mouse_down: start_drag,
    handle_mouse_move(event) {
      if (!state.drag_start || !state.mouse_down_pos) return;
      if (!(event.buttons & 1)) {
        end_drag(event);
        return;
      }
      const dx = Math.abs(event.clientX - state.mouse_down_pos.x);
      const dy = Math.abs(event.clientY - state.mouse_down_pos.y);
      if (!state.is_dragging && (dx > 3 || dy > 3)) {
        state.is_dragging = true;
        set_is_dragging(true);
      }
      if (state.is_dragging) {
        update_selection(event);
      }
    },
    handle_mouse_up: end_drag
  };
}
const { Map: Map_1, window: window_1 } = globals;
function get_each_context_1(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[147] = list2[i].value;
  child_ctx[148] = list2[i].id;
  child_ctx[151] = list2;
  child_ctx[152] = i;
  return child_ctx;
}
function get_each_context$1(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[147] = list2[i].value;
  child_ctx[148] = list2[i].id;
  child_ctx[149] = list2;
  child_ctx[150] = i;
  return child_ctx;
}
function get_each_context_2(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[147] = list2[i].value;
  child_ctx[148] = list2[i].id;
  child_ctx[153] = list2;
  child_ctx[150] = i;
  return child_ctx;
}
function get_each_context_3(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[147] = list2[i].value;
  child_ctx[148] = list2[i].id;
  child_ctx[154] = list2;
  child_ctx[152] = i;
  return child_ctx;
}
function create_if_block_8(ctx) {
  let div;
  let t;
  let toolbar;
  let current;
  let if_block = (
    /*label*/
    ctx[3] && /*label*/
    ctx[3].length !== 0 && /*show_label*/
    ctx[4] && create_if_block_9(ctx)
  );
  toolbar = new Toolbar$1({
    props: {
      show_fullscreen_button: (
        /*show_fullscreen_button*/
        ctx[18]
      ),
      fullscreen: (
        /*fullscreen*/
        ctx[23]
      ),
      on_copy: (
        /*func*/
        ctx[90]
      ),
      show_copy_button: (
        /*show_copy_button*/
        ctx[19]
      ),
      show_search: (
        /*show_search*/
        ctx[21]
      ),
      on_commit_filter: (
        /*commit_filter*/
        ctx[68]
      ),
      current_search_query: (
        /*$df_state*/
        ctx[33].current_search_query
      )
    }
  });
  toolbar.$on(
    "search",
    /*search_handler*/
    ctx[91]
  );
  toolbar.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[92]
  );
  return {
    c() {
      div = element("div");
      if (if_block) if_block.c();
      t = space();
      create_component(toolbar.$$.fragment);
      attr(div, "class", "header-row svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (if_block) if_block.m(div, null);
      append(div, t);
      mount_component(toolbar, div, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*label*/
        ctx2[3] && /*label*/
        ctx2[3].length !== 0 && /*show_label*/
        ctx2[4]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
        } else {
          if_block = create_if_block_9(ctx2);
          if_block.c();
          if_block.m(div, t);
        }
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      const toolbar_changes = {};
      if (dirty[0] & /*show_fullscreen_button*/
      262144) toolbar_changes.show_fullscreen_button = /*show_fullscreen_button*/
      ctx2[18];
      if (dirty[0] & /*fullscreen*/
      8388608) toolbar_changes.fullscreen = /*fullscreen*/
      ctx2[23];
      if (dirty[0] & /*data*/
      67108864) toolbar_changes.on_copy = /*func*/
      ctx2[90];
      if (dirty[0] & /*show_copy_button*/
      524288) toolbar_changes.show_copy_button = /*show_copy_button*/
      ctx2[19];
      if (dirty[0] & /*show_search*/
      2097152) toolbar_changes.show_search = /*show_search*/
      ctx2[21];
      if (dirty[1] & /*$df_state*/
      4) toolbar_changes.current_search_query = /*$df_state*/
      ctx2[33].current_search_query;
      toolbar.$set(toolbar_changes);
    },
    i(local) {
      if (current) return;
      transition_in(toolbar.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(toolbar.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      if (if_block) if_block.d();
      destroy_component(toolbar);
    }
  };
}
function create_if_block_9(ctx) {
  let div;
  let p;
  let t;
  return {
    c() {
      div = element("div");
      p = element("p");
      t = text(
        /*label*/
        ctx[3]
      );
      attr(p, "class", "svelte-4x7jh");
      attr(div, "class", "label svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, p);
      append(p, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*label*/
      8) set_data(
        t,
        /*label*/
        ctx2[3]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
    }
  };
}
function create_if_block_7(ctx) {
  let caption;
  let t;
  return {
    c() {
      caption = element("caption");
      t = text(
        /*label*/
        ctx[3]
      );
      attr(caption, "class", "sr-only svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, caption, anchor);
      append(caption, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*label*/
      8) set_data(
        t,
        /*label*/
        ctx2[3]
      );
    },
    d(detaching) {
      if (detaching) {
        detach(caption);
      }
    }
  };
}
function create_if_block_6$2(ctx) {
  let rownumber;
  let current;
  rownumber = new RowNumber$1({ props: { is_header: true } });
  return {
    c() {
      create_component(rownumber.$$.fragment);
    },
    m(target, anchor) {
      mount_component(rownumber, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(rownumber.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(rownumber.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(rownumber, detaching);
    }
  };
}
function create_each_block_3(key_1, ctx) {
  let first;
  let tableheader;
  let updating_value;
  let updating_el;
  let current;
  function tableheader_value_binding(value) {
    ctx[93](
      value,
      /*i*/
      ctx[152]
    );
  }
  function tableheader_el_binding(value) {
    ctx[94](
      value,
      /*id*/
      ctx[148]
    );
  }
  let tableheader_props = {
    i: (
      /*i*/
      ctx[152]
    ),
    actual_pinned_columns: (
      /*actual_pinned_columns*/
      ctx[53]
    ),
    header_edit: (
      /*header_edit*/
      ctx[52]
    ),
    selected_header: (
      /*selected_header*/
      ctx[51]
    ),
    headers: (
      /*headers*/
      ctx[0]
    ),
    get_cell_width,
    handle_header_click: (
      /*handle_header_click*/
      ctx[60]
    ),
    toggle_header_menu: (
      /*toggle_header_menu*/
      ctx[65]
    ),
    end_header_edit: (
      /*end_header_edit*/
      ctx[61]
    ),
    sort_columns: (
      /*$df_state*/
      ctx[33].sort_state.sort_columns
    ),
    filter_columns: (
      /*$df_state*/
      ctx[33].filter_state.filter_columns
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[7]
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[14]
    ),
    max_chars: (
      /*max_chars*/
      ctx[20]
    ),
    editable: (
      /*editable*/
      ctx[9]
    ),
    is_static: (
      /*static_columns*/
      ctx[22].includes(
        /*i*/
        ctx[152]
      )
    ),
    i18n: (
      /*i18n*/
      ctx[12]
    ),
    col_count: (
      /*col_count*/
      ctx[5]
    ),
    datatype: Array.isArray(
      /*datatype*/
      ctx[2]
    ) ? (
      /*datatype*/
      ctx[2][
        /*i*/
        ctx[152]
      ]
    ) : (
      /*datatype*/
      ctx[2]
    ),
    data: (
      /*data*/
      ctx[26]
    ),
    on_select_all: (
      /*handle_select_all*/
      ctx[72]
    )
  };
  if (
    /*_headers*/
    ctx[25][
      /*i*/
      ctx[152]
    ].value !== void 0
  ) {
    tableheader_props.value = /*_headers*/
    ctx[25][
      /*i*/
      ctx[152]
    ].value;
  }
  if (
    /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ].input !== void 0
  ) {
    tableheader_props.el = /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ].input;
  }
  tableheader = new TableHeader$1({ props: tableheader_props });
  binding_callbacks.push(() => bind(tableheader, "value", tableheader_value_binding));
  binding_callbacks.push(() => bind(tableheader, "el", tableheader_el_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tableheader.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tableheader, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tableheader_changes = {};
      if (dirty[0] & /*_headers*/
      33554432) tableheader_changes.i = /*i*/
      ctx[152];
      if (dirty[1] & /*actual_pinned_columns*/
      4194304) tableheader_changes.actual_pinned_columns = /*actual_pinned_columns*/
      ctx[53];
      if (dirty[1] & /*header_edit*/
      2097152) tableheader_changes.header_edit = /*header_edit*/
      ctx[52];
      if (dirty[1] & /*selected_header*/
      1048576) tableheader_changes.selected_header = /*selected_header*/
      ctx[51];
      if (dirty[0] & /*headers*/
      1) tableheader_changes.headers = /*headers*/
      ctx[0];
      if (dirty[1] & /*$df_state*/
      4) tableheader_changes.sort_columns = /*$df_state*/
      ctx[33].sort_state.sort_columns;
      if (dirty[1] & /*$df_state*/
      4) tableheader_changes.filter_columns = /*$df_state*/
      ctx[33].filter_state.filter_columns;
      if (dirty[0] & /*latex_delimiters*/
      128) tableheader_changes.latex_delimiters = /*latex_delimiters*/
      ctx[7];
      if (dirty[0] & /*line_breaks*/
      16384) tableheader_changes.line_breaks = /*line_breaks*/
      ctx[14];
      if (dirty[0] & /*max_chars*/
      1048576) tableheader_changes.max_chars = /*max_chars*/
      ctx[20];
      if (dirty[0] & /*editable*/
      512) tableheader_changes.editable = /*editable*/
      ctx[9];
      if (dirty[0] & /*static_columns, _headers*/
      37748736) tableheader_changes.is_static = /*static_columns*/
      ctx[22].includes(
        /*i*/
        ctx[152]
      );
      if (dirty[0] & /*i18n*/
      4096) tableheader_changes.i18n = /*i18n*/
      ctx[12];
      if (dirty[0] & /*col_count*/
      32) tableheader_changes.col_count = /*col_count*/
      ctx[5];
      if (dirty[0] & /*datatype, _headers*/
      33554436) tableheader_changes.datatype = Array.isArray(
        /*datatype*/
        ctx[2]
      ) ? (
        /*datatype*/
        ctx[2][
          /*i*/
          ctx[152]
        ]
      ) : (
        /*datatype*/
        ctx[2]
      );
      if (dirty[0] & /*data*/
      67108864) tableheader_changes.data = /*data*/
      ctx[26];
      if (!updating_value && dirty[0] & /*_headers*/
      33554432) {
        updating_value = true;
        tableheader_changes.value = /*_headers*/
        ctx[25][
          /*i*/
          ctx[152]
        ].value;
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_el && dirty[0] & /*els, _headers*/
      50331648) {
        updating_el = true;
        tableheader_changes.el = /*els*/
        ctx[24][
          /*id*/
          ctx[148]
        ].input;
        add_flush_callback(() => updating_el = false);
      }
      tableheader.$set(tableheader_changes);
    },
    i(local) {
      if (current) return;
      transition_in(tableheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tableheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(first);
      }
      destroy_component(tableheader, detaching);
    }
  };
}
function create_if_block_5$2(ctx) {
  let rownumber;
  let current;
  rownumber = new RowNumber$1({ props: { index: 0 } });
  return {
    c() {
      create_component(rownumber.$$.fragment);
    },
    m(target, anchor) {
      mount_component(rownumber, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(rownumber.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(rownumber.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(rownumber, detaching);
    }
  };
}
function create_each_block_2(key_1, ctx) {
  let td;
  let div;
  let editablecell;
  let t;
  let j = (
    /*j*/
    ctx[150]
  );
  let current;
  editablecell = new EditableCell$1({
    props: {
      value: (
        /*value*/
        ctx[147]
      ),
      latex_delimiters: (
        /*latex_delimiters*/
        ctx[7]
      ),
      line_breaks: (
        /*line_breaks*/
        ctx[14]
      ),
      datatype: Array.isArray(
        /*datatype*/
        ctx[2]
      ) ? (
        /*datatype*/
        ctx[2][
          /*j*/
          ctx[150]
        ]
      ) : (
        /*datatype*/
        ctx[2]
      ),
      edit: false,
      el: null,
      editable: (
        /*editable*/
        ctx[9]
      ),
      i18n: (
        /*i18n*/
        ctx[12]
      ),
      show_selection_buttons: (
        /*selected_cells*/
        ctx[31].length === 1 && /*selected_cells*/
        ctx[31][0][0] === 0 && /*selected_cells*/
        ctx[31][0][1] === /*j*/
        ctx[150]
      ),
      coords: (
        /*selected_cell_coords*/
        ctx[39]
      ),
      on_select_column: (
        /*df_actions*/
        ctx[55].handle_select_column
      ),
      on_select_row: (
        /*df_actions*/
        ctx[55].handle_select_row
      ),
      is_dragging: (
        /*is_dragging*/
        ctx[42]
      )
    }
  });
  editablecell.$on(
    "blur",
    /*handle_blur*/
    ctx[64]
  );
  const assign_td = () => (
    /*td_binding*/
    ctx[95](td, j)
  );
  const unassign_td = () => (
    /*td_binding*/
    ctx[95](null, j)
  );
  return {
    key: key_1,
    first: null,
    c() {
      td = element("td");
      div = element("div");
      create_component(editablecell.$$.fragment);
      t = space();
      attr(div, "class", "cell-wrap svelte-4x7jh");
      attr(td, "tabindex", "-1");
      attr(td, "class", "svelte-4x7jh");
      this.first = td;
    },
    m(target, anchor) {
      insert(target, td, anchor);
      append(td, div);
      mount_component(editablecell, div, null);
      append(td, t);
      assign_td();
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const editablecell_changes = {};
      if (dirty[1] & /*max*/
      524288) editablecell_changes.value = /*value*/
      ctx[147];
      if (dirty[0] & /*latex_delimiters*/
      128) editablecell_changes.latex_delimiters = /*latex_delimiters*/
      ctx[7];
      if (dirty[0] & /*line_breaks*/
      16384) editablecell_changes.line_breaks = /*line_breaks*/
      ctx[14];
      if (dirty[0] & /*datatype*/
      4 | dirty[1] & /*max*/
      524288) editablecell_changes.datatype = Array.isArray(
        /*datatype*/
        ctx[2]
      ) ? (
        /*datatype*/
        ctx[2][
          /*j*/
          ctx[150]
        ]
      ) : (
        /*datatype*/
        ctx[2]
      );
      if (dirty[0] & /*editable*/
      512) editablecell_changes.editable = /*editable*/
      ctx[9];
      if (dirty[0] & /*i18n*/
      4096) editablecell_changes.i18n = /*i18n*/
      ctx[12];
      if (dirty[1] & /*selected_cells, max*/
      524289) editablecell_changes.show_selection_buttons = /*selected_cells*/
      ctx[31].length === 1 && /*selected_cells*/
      ctx[31][0][0] === 0 && /*selected_cells*/
      ctx[31][0][1] === /*j*/
      ctx[150];
      if (dirty[1] & /*selected_cell_coords*/
      256) editablecell_changes.coords = /*selected_cell_coords*/
      ctx[39];
      if (dirty[1] & /*is_dragging*/
      2048) editablecell_changes.is_dragging = /*is_dragging*/
      ctx[42];
      editablecell.$set(editablecell_changes);
      if (j !== /*j*/
      ctx[150]) {
        unassign_td();
        j = /*j*/
        ctx[150];
        assign_td();
      }
    },
    i(local) {
      if (current) return;
      transition_in(editablecell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(editablecell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(td);
      }
      destroy_component(editablecell);
      unassign_td();
    }
  };
}
function create_if_block_4$2(ctx) {
  let rownumber;
  let current;
  rownumber = new RowNumber$1({ props: { is_header: true } });
  return {
    c() {
      create_component(rownumber.$$.fragment);
    },
    m(target, anchor) {
      mount_component(rownumber, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(rownumber.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(rownumber.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(rownumber, detaching);
    }
  };
}
function create_each_block_1(key_1, ctx) {
  let first;
  let tableheader;
  let updating_value;
  let updating_el;
  let current;
  function tableheader_value_binding_1(value) {
    ctx[100](
      value,
      /*i*/
      ctx[152]
    );
  }
  function tableheader_el_binding_1(value) {
    ctx[101](
      value,
      /*id*/
      ctx[148]
    );
  }
  let tableheader_props = {
    i: (
      /*i*/
      ctx[152]
    ),
    actual_pinned_columns: (
      /*actual_pinned_columns*/
      ctx[53]
    ),
    header_edit: (
      /*header_edit*/
      ctx[52]
    ),
    selected_header: (
      /*selected_header*/
      ctx[51]
    ),
    headers: (
      /*headers*/
      ctx[0]
    ),
    get_cell_width,
    handle_header_click: (
      /*handle_header_click*/
      ctx[60]
    ),
    toggle_header_menu: (
      /*toggle_header_menu*/
      ctx[65]
    ),
    end_header_edit: (
      /*end_header_edit*/
      ctx[61]
    ),
    sort_columns: (
      /*$df_state*/
      ctx[33].sort_state.sort_columns
    ),
    filter_columns: (
      /*$df_state*/
      ctx[33].filter_state.filter_columns
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[7]
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[14]
    ),
    max_chars: (
      /*max_chars*/
      ctx[20]
    ),
    editable: (
      /*editable*/
      ctx[9]
    ),
    is_static: (
      /*static_columns*/
      ctx[22].includes(
        /*i*/
        ctx[152]
      )
    ),
    i18n: (
      /*i18n*/
      ctx[12]
    ),
    col_count: (
      /*col_count*/
      ctx[5]
    ),
    datatype: Array.isArray(
      /*datatype*/
      ctx[2]
    ) ? (
      /*datatype*/
      ctx[2][
        /*i*/
        ctx[152]
      ]
    ) : (
      /*datatype*/
      ctx[2]
    ),
    data: (
      /*data*/
      ctx[26]
    ),
    on_select_all: (
      /*handle_select_all*/
      ctx[72]
    )
  };
  if (
    /*_headers*/
    ctx[25][
      /*i*/
      ctx[152]
    ].value !== void 0
  ) {
    tableheader_props.value = /*_headers*/
    ctx[25][
      /*i*/
      ctx[152]
    ].value;
  }
  if (
    /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ].input !== void 0
  ) {
    tableheader_props.el = /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ].input;
  }
  tableheader = new TableHeader$1({ props: tableheader_props });
  binding_callbacks.push(() => bind(tableheader, "value", tableheader_value_binding_1));
  binding_callbacks.push(() => bind(tableheader, "el", tableheader_el_binding_1));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tableheader.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tableheader, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tableheader_changes = {};
      if (dirty[0] & /*_headers*/
      33554432) tableheader_changes.i = /*i*/
      ctx[152];
      if (dirty[1] & /*actual_pinned_columns*/
      4194304) tableheader_changes.actual_pinned_columns = /*actual_pinned_columns*/
      ctx[53];
      if (dirty[1] & /*header_edit*/
      2097152) tableheader_changes.header_edit = /*header_edit*/
      ctx[52];
      if (dirty[1] & /*selected_header*/
      1048576) tableheader_changes.selected_header = /*selected_header*/
      ctx[51];
      if (dirty[0] & /*headers*/
      1) tableheader_changes.headers = /*headers*/
      ctx[0];
      if (dirty[1] & /*$df_state*/
      4) tableheader_changes.sort_columns = /*$df_state*/
      ctx[33].sort_state.sort_columns;
      if (dirty[1] & /*$df_state*/
      4) tableheader_changes.filter_columns = /*$df_state*/
      ctx[33].filter_state.filter_columns;
      if (dirty[0] & /*latex_delimiters*/
      128) tableheader_changes.latex_delimiters = /*latex_delimiters*/
      ctx[7];
      if (dirty[0] & /*line_breaks*/
      16384) tableheader_changes.line_breaks = /*line_breaks*/
      ctx[14];
      if (dirty[0] & /*max_chars*/
      1048576) tableheader_changes.max_chars = /*max_chars*/
      ctx[20];
      if (dirty[0] & /*editable*/
      512) tableheader_changes.editable = /*editable*/
      ctx[9];
      if (dirty[0] & /*static_columns, _headers*/
      37748736) tableheader_changes.is_static = /*static_columns*/
      ctx[22].includes(
        /*i*/
        ctx[152]
      );
      if (dirty[0] & /*i18n*/
      4096) tableheader_changes.i18n = /*i18n*/
      ctx[12];
      if (dirty[0] & /*col_count*/
      32) tableheader_changes.col_count = /*col_count*/
      ctx[5];
      if (dirty[0] & /*datatype, _headers*/
      33554436) tableheader_changes.datatype = Array.isArray(
        /*datatype*/
        ctx[2]
      ) ? (
        /*datatype*/
        ctx[2][
          /*i*/
          ctx[152]
        ]
      ) : (
        /*datatype*/
        ctx[2]
      );
      if (dirty[0] & /*data*/
      67108864) tableheader_changes.data = /*data*/
      ctx[26];
      if (!updating_value && dirty[0] & /*_headers*/
      33554432) {
        updating_value = true;
        tableheader_changes.value = /*_headers*/
        ctx[25][
          /*i*/
          ctx[152]
        ].value;
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_el && dirty[0] & /*els, _headers*/
      50331648) {
        updating_el = true;
        tableheader_changes.el = /*els*/
        ctx[24][
          /*id*/
          ctx[148]
        ].input;
        add_flush_callback(() => updating_el = false);
      }
      tableheader.$set(tableheader_changes);
    },
    i(local) {
      if (current) return;
      transition_in(tableheader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tableheader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(first);
      }
      destroy_component(tableheader, detaching);
    }
  };
}
function create_thead_slot(ctx) {
  let tr;
  let t;
  let each_blocks = [];
  let each_1_lookup = new Map_1();
  let current;
  let if_block = (
    /*show_row_numbers*/
    ctx[15] && create_if_block_4$2()
  );
  let each_value_1 = ensure_array_like(
    /*_headers*/
    ctx[25]
  );
  const get_key = (ctx2) => (
    /*id*/
    ctx2[148]
  );
  for (let i = 0; i < each_value_1.length; i += 1) {
    let child_ctx = get_each_context_1(ctx, each_value_1, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block_1(key, child_ctx));
  }
  return {
    c() {
      tr = element("tr");
      if (if_block) if_block.c();
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(tr, "slot", "thead");
      attr(tr, "class", "svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      if (if_block) if_block.m(tr, null);
      append(tr, t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tr, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*show_row_numbers*/
        ctx2[15]
      ) {
        if (if_block) {
          if (dirty[0] & /*show_row_numbers*/
          32768) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_4$2();
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(tr, t);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (dirty[0] & /*_headers, headers, latex_delimiters, line_breaks, max_chars, editable, static_columns, i18n, col_count, datatype, data, els*/
      122704549 | dirty[1] & /*actual_pinned_columns, header_edit, selected_header, handle_header_click, end_header_edit, $df_state*/
      1617952772 | dirty[2] & /*toggle_header_menu, handle_select_all*/
      1032) {
        each_value_1 = ensure_array_like(
          /*_headers*/
          ctx2[25]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value_1, each_1_lookup, tr, outro_and_destroy_block, create_each_block_1, null, get_each_context_1);
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      for (let i = 0; i < each_value_1.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(if_block);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
      if (if_block) if_block.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function create_if_block_3$3(ctx) {
  let rownumber;
  let current;
  rownumber = new RowNumber$1({ props: { index: (
    /*index*/
    ctx[145]
  ) } });
  return {
    c() {
      create_component(rownumber.$$.fragment);
    },
    m(target, anchor) {
      mount_component(rownumber, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const rownumber_changes = {};
      if (dirty[4] & /*index*/
      2097152) rownumber_changes.index = /*index*/
      ctx2[145];
      rownumber.$set(rownumber_changes);
    },
    i(local) {
      if (current) return;
      transition_in(rownumber.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(rownumber.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(rownumber, detaching);
    }
  };
}
function create_each_block$1(key_1, ctx) {
  let first;
  let tablecell;
  let updating_value;
  let updating_el;
  let current;
  function tablecell_value_binding(value) {
    ctx[98](
      value,
      /*index*/
      ctx[145],
      /*j*/
      ctx[150]
    );
  }
  function tablecell_el_binding(value) {
    ctx[99](
      value,
      /*id*/
      ctx[148]
    );
  }
  let tablecell_props = {
    display_value: (
      /*get_cell_display_value*/
      ctx[73](
        /*index*/
        ctx[145],
        /*j*/
        ctx[150]
      )
    ),
    index: (
      /*$df_state*/
      ctx[33].current_search_query !== void 0 && /*filtered_to_original_map*/
      ctx[27][
        /*index*/
        ctx[145]
      ] !== void 0 ? (
        /*filtered_to_original_map*/
        ctx[27][
          /*index*/
          ctx[145]
        ]
      ) : (
        /*index*/
        ctx[145]
      )
    ),
    j: (
      /*j*/
      ctx[150]
    ),
    actual_pinned_columns: (
      /*actual_pinned_columns*/
      ctx[53]
    ),
    get_cell_width,
    handle_cell_click: (
      /*func_1*/
      ctx[97]
    ),
    handle_blur: (
      /*handle_blur*/
      ctx[64]
    ),
    toggle_cell_menu: (
      /*df_actions*/
      ctx[55].toggle_cell_menu
    ),
    is_cell_selected: is_cell_selected$1,
    should_show_cell_menu: should_show_cell_menu$1,
    selected_cells: (
      /*selected_cells*/
      ctx[31]
    ),
    copy_flash: (
      /*copy_flash*/
      ctx[32]
    ),
    active_cell_menu: (
      /*active_cell_menu*/
      ctx[47]
    ),
    styling: (
      /*search_results*/
      ctx[35][
        /*index*/
        ctx[145]
      ][
        /*j*/
        ctx[150]
      ].styling
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[7]
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[14]
    ),
    datatype: Array.isArray(
      /*datatype*/
      ctx[2]
    ) ? (
      /*datatype*/
      ctx[2][
        /*j*/
        ctx[150]
      ]
    ) : (
      /*datatype*/
      ctx[2]
    ),
    editing: (
      /*editing*/
      ctx[48]
    ),
    max_chars: (
      /*max_chars*/
      ctx[20]
    ),
    editable: (
      /*editable*/
      ctx[9]
    ),
    is_static: (
      /*static_columns*/
      ctx[22].includes(
        /*j*/
        ctx[150]
      )
    ),
    i18n: (
      /*i18n*/
      ctx[12]
    ),
    components: (
      /*components*/
      ctx[8]
    ),
    handle_select_column: (
      /*df_actions*/
      ctx[55].handle_select_column
    ),
    handle_select_row: (
      /*df_actions*/
      ctx[55].handle_select_row
    ),
    is_dragging: (
      /*is_dragging*/
      ctx[42]
    ),
    wrap: (
      /*wrap*/
      ctx[10]
    )
  };
  if (
    /*search_results*/
    ctx[35][
      /*index*/
      ctx[145]
    ][
      /*j*/
      ctx[150]
    ].value !== void 0
  ) {
    tablecell_props.value = /*search_results*/
    ctx[35][
      /*index*/
      ctx[145]
    ][
      /*j*/
      ctx[150]
    ].value;
  }
  if (
    /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ] !== void 0
  ) {
    tablecell_props.el = /*els*/
    ctx[24][
      /*id*/
      ctx[148]
    ];
  }
  tablecell = new TableCell$1({ props: tablecell_props });
  binding_callbacks.push(() => bind(tablecell, "value", tablecell_value_binding));
  binding_callbacks.push(() => bind(tablecell, "el", tablecell_el_binding));
  return {
    key: key_1,
    first: null,
    c() {
      first = empty();
      create_component(tablecell.$$.fragment);
      this.first = first;
    },
    m(target, anchor) {
      insert(target, first, anchor);
      mount_component(tablecell, target, anchor);
      current = true;
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      const tablecell_changes = {};
      if (dirty[4] & /*index, item*/
      6291456) tablecell_changes.display_value = /*get_cell_display_value*/
      ctx[73](
        /*index*/
        ctx[145],
        /*j*/
        ctx[150]
      );
      if (dirty[0] & /*filtered_to_original_map*/
      134217728 | dirty[1] & /*$df_state*/
      4 | dirty[4] & /*index*/
      2097152) tablecell_changes.index = /*$df_state*/
      ctx[33].current_search_query !== void 0 && /*filtered_to_original_map*/
      ctx[27][
        /*index*/
        ctx[145]
      ] !== void 0 ? (
        /*filtered_to_original_map*/
        ctx[27][
          /*index*/
          ctx[145]
        ]
      ) : (
        /*index*/
        ctx[145]
      );
      if (dirty[4] & /*item*/
      4194304) tablecell_changes.j = /*j*/
      ctx[150];
      if (dirty[1] & /*actual_pinned_columns*/
      4194304) tablecell_changes.actual_pinned_columns = /*actual_pinned_columns*/
      ctx[53];
      if (dirty[1] & /*handle_mouse_down*/
      16384) tablecell_changes.handle_cell_click = /*func_1*/
      ctx[97];
      if (dirty[1] & /*selected_cells*/
      1) tablecell_changes.selected_cells = /*selected_cells*/
      ctx[31];
      if (dirty[1] & /*copy_flash*/
      2) tablecell_changes.copy_flash = /*copy_flash*/
      ctx[32];
      if (dirty[1] & /*active_cell_menu*/
      65536) tablecell_changes.active_cell_menu = /*active_cell_menu*/
      ctx[47];
      if (dirty[1] & /*search_results*/
      16 | dirty[4] & /*index, item*/
      6291456) tablecell_changes.styling = /*search_results*/
      ctx[35][
        /*index*/
        ctx[145]
      ][
        /*j*/
        ctx[150]
      ].styling;
      if (dirty[0] & /*latex_delimiters*/
      128) tablecell_changes.latex_delimiters = /*latex_delimiters*/
      ctx[7];
      if (dirty[0] & /*line_breaks*/
      16384) tablecell_changes.line_breaks = /*line_breaks*/
      ctx[14];
      if (dirty[0] & /*datatype*/
      4 | dirty[4] & /*item*/
      4194304) tablecell_changes.datatype = Array.isArray(
        /*datatype*/
        ctx[2]
      ) ? (
        /*datatype*/
        ctx[2][
          /*j*/
          ctx[150]
        ]
      ) : (
        /*datatype*/
        ctx[2]
      );
      if (dirty[1] & /*editing*/
      131072) tablecell_changes.editing = /*editing*/
      ctx[48];
      if (dirty[0] & /*max_chars*/
      1048576) tablecell_changes.max_chars = /*max_chars*/
      ctx[20];
      if (dirty[0] & /*editable*/
      512) tablecell_changes.editable = /*editable*/
      ctx[9];
      if (dirty[0] & /*static_columns*/
      4194304 | dirty[4] & /*item*/
      4194304) tablecell_changes.is_static = /*static_columns*/
      ctx[22].includes(
        /*j*/
        ctx[150]
      );
      if (dirty[0] & /*i18n*/
      4096) tablecell_changes.i18n = /*i18n*/
      ctx[12];
      if (dirty[0] & /*components*/
      256) tablecell_changes.components = /*components*/
      ctx[8];
      if (dirty[1] & /*is_dragging*/
      2048) tablecell_changes.is_dragging = /*is_dragging*/
      ctx[42];
      if (dirty[0] & /*wrap*/
      1024) tablecell_changes.wrap = /*wrap*/
      ctx[10];
      if (!updating_value && dirty[1] & /*search_results*/
      16 | dirty[4] & /*index, item*/
      6291456) {
        updating_value = true;
        tablecell_changes.value = /*search_results*/
        ctx[35][
          /*index*/
          ctx[145]
        ][
          /*j*/
          ctx[150]
        ].value;
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_el && dirty[0] & /*els*/
      16777216 | dirty[4] & /*item*/
      4194304) {
        updating_el = true;
        tablecell_changes.el = /*els*/
        ctx[24][
          /*id*/
          ctx[148]
        ];
        add_flush_callback(() => updating_el = false);
      }
      tablecell.$set(tablecell_changes);
    },
    i(local) {
      if (current) return;
      transition_in(tablecell.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(tablecell.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(first);
      }
      destroy_component(tablecell, detaching);
    }
  };
}
function create_tbody_slot(ctx) {
  let tr;
  let t;
  let each_blocks = [];
  let each_1_lookup = new Map_1();
  let current;
  let if_block = (
    /*show_row_numbers*/
    ctx[15] && create_if_block_3$3(ctx)
  );
  let each_value = ensure_array_like(
    /*item*/
    ctx[146]
  );
  const get_key = (ctx2) => (
    /*id*/
    ctx2[148]
  );
  for (let i = 0; i < each_value.length; i += 1) {
    let child_ctx = get_each_context$1(ctx, each_value, i);
    let key = get_key(child_ctx);
    each_1_lookup.set(key, each_blocks[i] = create_each_block$1(key, child_ctx));
  }
  return {
    c() {
      tr = element("tr");
      if (if_block) if_block.c();
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      attr(tr, "slot", "tbody");
      attr(tr, "class", "svelte-4x7jh");
      toggle_class(
        tr,
        "row-odd",
        /*index*/
        ctx[145] % 2 === 0
      );
    },
    m(target, anchor) {
      insert(target, tr, anchor);
      if (if_block) if_block.m(tr, null);
      append(tr, t);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tr, null);
        }
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*show_row_numbers*/
        ctx2[15]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*show_row_numbers*/
          32768) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_3$3(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(tr, t);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
      if (dirty[0] & /*filtered_to_original_map, latex_delimiters, line_breaks, datatype, max_chars, editable, static_columns, i18n, components, wrap, els*/
      156260228 | dirty[1] & /*$df_state, actual_pinned_columns, handle_mouse_down, df_actions, selected_cells, copy_flash, active_cell_menu, search_results, editing, is_dragging*/
      21186583 | dirty[2] & /*get_cell_display_value, handle_blur*/
      2052 | dirty[4] & /*index, item*/
      6291456) {
        each_value = ensure_array_like(
          /*item*/
          ctx2[146]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key, 1, ctx2, each_value, each_1_lookup, tr, outro_and_destroy_block, create_each_block$1, null, get_each_context$1);
        check_outros();
      }
      if (!current || dirty[4] & /*index*/
      2097152) {
        toggle_class(
          tr,
          "row-odd",
          /*index*/
          ctx2[145] % 2 === 0
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      for (let i = 0; i < each_value.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      current = true;
    },
    o(local) {
      transition_out(if_block);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(tr);
      }
      if (if_block) if_block.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
    }
  };
}
function create_default_slot$4(ctx) {
  let div;
  let virtualtable;
  let updating_items;
  let updating_actual_height;
  let updating_table_scrollbar_width;
  let updating_viewport;
  let updating_show_scroll_button;
  let current;
  function virtualtable_items_binding(value) {
    ctx[102](value);
  }
  function virtualtable_actual_height_binding(value) {
    ctx[103](value);
  }
  function virtualtable_table_scrollbar_width_binding(value) {
    ctx[104](value);
  }
  function virtualtable_viewport_binding(value) {
    ctx[105](value);
  }
  function virtualtable_show_scroll_button_binding(value) {
    ctx[106](value);
  }
  let virtualtable_props = {
    max_height: (
      /*max_height*/
      ctx[13]
    ),
    selected: (
      /*selected_index*/
      ctx[49]
    ),
    disable_scroll: (
      /*active_cell_menu*/
      ctx[47] !== null || /*active_header_menu*/
      ctx[46] !== null
    ),
    label: (
      /*label*/
      ctx[3]
    ),
    $$slots: {
      tbody: [
        create_tbody_slot,
        ({ index, item }) => ({ 145: index, 146: item }),
        ({ index, item }) => [0, 0, 0, 0, (index ? 2097152 : 0) | (item ? 4194304 : 0)]
      ],
      thead: [create_thead_slot]
    },
    $$scope: { ctx }
  };
  if (
    /*search_results*/
    ctx[35] !== void 0
  ) {
    virtualtable_props.items = /*search_results*/
    ctx[35];
  }
  if (
    /*table_height*/
    ctx[37] !== void 0
  ) {
    virtualtable_props.actual_height = /*table_height*/
    ctx[37];
  }
  if (
    /*scrollbar_width*/
    ctx[38] !== void 0
  ) {
    virtualtable_props.table_scrollbar_width = /*scrollbar_width*/
    ctx[38];
  }
  if (
    /*viewport*/
    ctx[40] !== void 0
  ) {
    virtualtable_props.viewport = /*viewport*/
    ctx[40];
  }
  if (
    /*show_scroll_button*/
    ctx[41] !== void 0
  ) {
    virtualtable_props.show_scroll_button = /*show_scroll_button*/
    ctx[41];
  }
  virtualtable = new VirtualTable$1({ props: virtualtable_props });
  binding_callbacks.push(() => bind(virtualtable, "items", virtualtable_items_binding));
  binding_callbacks.push(() => bind(virtualtable, "actual_height", virtualtable_actual_height_binding));
  binding_callbacks.push(() => bind(virtualtable, "table_scrollbar_width", virtualtable_table_scrollbar_width_binding));
  binding_callbacks.push(() => bind(virtualtable, "viewport", virtualtable_viewport_binding));
  binding_callbacks.push(() => bind(virtualtable, "show_scroll_button", virtualtable_show_scroll_button_binding));
  virtualtable.$on("scroll_top", scroll_top_handler);
  return {
    c() {
      div = element("div");
      create_component(virtualtable.$$.fragment);
      attr(div, "class", "table-wrap svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(virtualtable, div, null);
      current = true;
    },
    p(ctx2, dirty) {
      const virtualtable_changes = {};
      if (dirty[0] & /*max_height*/
      8192) virtualtable_changes.max_height = /*max_height*/
      ctx2[13];
      if (dirty[1] & /*selected_index*/
      262144) virtualtable_changes.selected = /*selected_index*/
      ctx2[49];
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) virtualtable_changes.disable_scroll = /*active_cell_menu*/
      ctx2[47] !== null || /*active_header_menu*/
      ctx2[46] !== null;
      if (dirty[0] & /*label*/
      8) virtualtable_changes.label = /*label*/
      ctx2[3];
      if (dirty[0] & /*filtered_to_original_map, latex_delimiters, line_breaks, datatype, max_chars, editable, static_columns, i18n, components, wrap, els, show_row_numbers, _headers, headers, col_count, data*/
      256956325 | dirty[1] & /*$df_state, actual_pinned_columns, handle_mouse_down, selected_cells, copy_flash, active_cell_menu, search_results, editing, is_dragging, header_edit, selected_header*/
      7555095 | dirty[4] & /*index, item*/
      6291456 | dirty[5] & /*$$scope*/
      1) {
        virtualtable_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_items && dirty[1] & /*search_results*/
      16) {
        updating_items = true;
        virtualtable_changes.items = /*search_results*/
        ctx2[35];
        add_flush_callback(() => updating_items = false);
      }
      if (!updating_actual_height && dirty[1] & /*table_height*/
      64) {
        updating_actual_height = true;
        virtualtable_changes.actual_height = /*table_height*/
        ctx2[37];
        add_flush_callback(() => updating_actual_height = false);
      }
      if (!updating_table_scrollbar_width && dirty[1] & /*scrollbar_width*/
      128) {
        updating_table_scrollbar_width = true;
        virtualtable_changes.table_scrollbar_width = /*scrollbar_width*/
        ctx2[38];
        add_flush_callback(() => updating_table_scrollbar_width = false);
      }
      if (!updating_viewport && dirty[1] & /*viewport*/
      512) {
        updating_viewport = true;
        virtualtable_changes.viewport = /*viewport*/
        ctx2[40];
        add_flush_callback(() => updating_viewport = false);
      }
      if (!updating_show_scroll_button && dirty[1] & /*show_scroll_button*/
      1024) {
        updating_show_scroll_button = true;
        virtualtable_changes.show_scroll_button = /*show_scroll_button*/
        ctx2[41];
        add_flush_callback(() => updating_show_scroll_button = false);
      }
      virtualtable.$set(virtualtable_changes);
    },
    i(local) {
      if (current) return;
      transition_in(virtualtable.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(virtualtable.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(virtualtable);
    }
  };
}
function create_if_block_2$4(ctx) {
  let button;
  let mounted;
  let dispose;
  return {
    c() {
      button = element("button");
      button.textContent = "↑";
      attr(button, "class", "scroll-top-button svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*scroll_to_top*/
          ctx[69]
        );
        mounted = true;
      }
    },
    p: noop,
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$4(ctx) {
  let emptyrowbutton;
  let current;
  emptyrowbutton = new EmptyRowButton$1({ props: { on_click: (
    /*func_2*/
    ctx[111]
  ) } });
  return {
    c() {
      create_component(emptyrowbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(emptyrowbutton, target, anchor);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(emptyrowbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(emptyrowbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(emptyrowbutton, detaching);
    }
  };
}
function create_if_block$4(ctx) {
  var _a, _b, _c, _d, _e, _f, _g;
  let cellmenu;
  let current;
  cellmenu = new CellMenu$1({
    props: {
      x: (
        /*active_cell_menu*/
        ((_a = ctx[47]) == null ? void 0 : _a.x) ?? /*active_header_menu*/
        ((_b = ctx[46]) == null ? void 0 : _b.x) ?? 0
      ),
      y: (
        /*active_cell_menu*/
        ((_c = ctx[47]) == null ? void 0 : _c.y) ?? /*active_header_menu*/
        ((_d = ctx[46]) == null ? void 0 : _d.y) ?? 0
      ),
      row: (
        /*active_header_menu*/
        ctx[46] ? -1 : (
          /*active_cell_menu*/
          ((_e = ctx[47]) == null ? void 0 : _e.row) ?? 0
        )
      ),
      col_count: (
        /*col_count*/
        ctx[5]
      ),
      row_count: (
        /*row_count*/
        ctx[6]
      ),
      on_add_row_above: (
        /*func_3*/
        ctx[112]
      ),
      on_add_row_below: (
        /*func_4*/
        ctx[113]
      ),
      on_add_column_left: (
        /*func_5*/
        ctx[114]
      ),
      on_add_column_right: (
        /*func_6*/
        ctx[115]
      ),
      on_delete_row: (
        /*func_7*/
        ctx[116]
      ),
      on_delete_col: (
        /*func_8*/
        ctx[117]
      ),
      editable: (
        /*editable*/
        ctx[9]
      ),
      can_delete_rows: !/*active_header_menu*/
      ctx[46] && /*data*/
      ctx[26].length > 1 && /*editable*/
      ctx[9],
      can_delete_cols: (
        /*data*/
        ctx[26].length > 0 && /*data*/
        ((_f = ctx[26][0]) == null ? void 0 : _f.length) > 1 && /*editable*/
        ctx[9]
      ),
      i18n: (
        /*i18n*/
        ctx[12]
      ),
      on_sort: (
        /*active_header_menu*/
        ctx[46] ? (
          /*func_9*/
          ctx[118]
        ) : void 0
      ),
      on_clear_sort: (
        /*active_header_menu*/
        ctx[46] ? (
          /*func_10*/
          ctx[119]
        ) : void 0
      ),
      sort_direction: (
        /*active_header_menu*/
        ctx[46] ? (
          /*$df_state*/
          ((_g = ctx[33].sort_state.sort_columns.find(
            /*func_11*/
            ctx[120]
          )) == null ? void 0 : _g.direction) ?? null
        ) : null
      ),
      sort_priority: (
        /*active_header_menu*/
        ctx[46] ? (
          /*$df_state*/
          ctx[33].sort_state.sort_columns.findIndex(
            /*func_12*/
            ctx[121]
          ) + 1 || null
        ) : null
      ),
      on_filter: (
        /*active_header_menu*/
        ctx[46] ? (
          /*func_13*/
          ctx[122]
        ) : void 0
      ),
      on_clear_filter: (
        /*active_header_menu*/
        ctx[46] ? (
          /*func_14*/
          ctx[123]
        ) : void 0
      ),
      filter_active: (
        /*active_header_menu*/
        ctx[46] ? (
          /*$df_state*/
          ctx[33].filter_state.filter_columns.some(
            /*func_15*/
            ctx[124]
          )
        ) : null
      )
    }
  });
  return {
    c() {
      create_component(cellmenu.$$.fragment);
    },
    m(target, anchor) {
      mount_component(cellmenu, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
      const cellmenu_changes = {};
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) cellmenu_changes.x = /*active_cell_menu*/
      ((_a2 = ctx2[47]) == null ? void 0 : _a2.x) ?? /*active_header_menu*/
      ((_b2 = ctx2[46]) == null ? void 0 : _b2.x) ?? 0;
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) cellmenu_changes.y = /*active_cell_menu*/
      ((_c2 = ctx2[47]) == null ? void 0 : _c2.y) ?? /*active_header_menu*/
      ((_d2 = ctx2[46]) == null ? void 0 : _d2.y) ?? 0;
      if (dirty[1] & /*active_header_menu, active_cell_menu*/
      98304) cellmenu_changes.row = /*active_header_menu*/
      ctx2[46] ? -1 : (
        /*active_cell_menu*/
        ((_e2 = ctx2[47]) == null ? void 0 : _e2.row) ?? 0
      );
      if (dirty[0] & /*col_count*/
      32) cellmenu_changes.col_count = /*col_count*/
      ctx2[5];
      if (dirty[0] & /*row_count*/
      64) cellmenu_changes.row_count = /*row_count*/
      ctx2[6];
      if (dirty[1] & /*active_cell_menu*/
      65536) cellmenu_changes.on_add_row_above = /*func_3*/
      ctx2[112];
      if (dirty[1] & /*active_cell_menu*/
      65536) cellmenu_changes.on_add_row_below = /*func_4*/
      ctx2[113];
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) cellmenu_changes.on_add_column_left = /*func_5*/
      ctx2[114];
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) cellmenu_changes.on_add_column_right = /*func_6*/
      ctx2[115];
      if (dirty[1] & /*active_cell_menu*/
      65536) cellmenu_changes.on_delete_row = /*func_7*/
      ctx2[116];
      if (dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) cellmenu_changes.on_delete_col = /*func_8*/
      ctx2[117];
      if (dirty[0] & /*editable*/
      512) cellmenu_changes.editable = /*editable*/
      ctx2[9];
      if (dirty[0] & /*data, editable*/
      67109376 | dirty[1] & /*active_header_menu*/
      32768) cellmenu_changes.can_delete_rows = !/*active_header_menu*/
      ctx2[46] && /*data*/
      ctx2[26].length > 1 && /*editable*/
      ctx2[9];
      if (dirty[0] & /*data, editable*/
      67109376) cellmenu_changes.can_delete_cols = /*data*/
      ctx2[26].length > 0 && /*data*/
      ((_f2 = ctx2[26][0]) == null ? void 0 : _f2.length) > 1 && /*editable*/
      ctx2[9];
      if (dirty[0] & /*i18n*/
      4096) cellmenu_changes.i18n = /*i18n*/
      ctx2[12];
      if (dirty[1] & /*active_header_menu*/
      32768) cellmenu_changes.on_sort = /*active_header_menu*/
      ctx2[46] ? (
        /*func_9*/
        ctx2[118]
      ) : void 0;
      if (dirty[1] & /*active_header_menu*/
      32768) cellmenu_changes.on_clear_sort = /*active_header_menu*/
      ctx2[46] ? (
        /*func_10*/
        ctx2[119]
      ) : void 0;
      if (dirty[1] & /*active_header_menu, $df_state*/
      32772) cellmenu_changes.sort_direction = /*active_header_menu*/
      ctx2[46] ? (
        /*$df_state*/
        ((_g2 = ctx2[33].sort_state.sort_columns.find(
          /*func_11*/
          ctx2[120]
        )) == null ? void 0 : _g2.direction) ?? null
      ) : null;
      if (dirty[1] & /*active_header_menu, $df_state*/
      32772) cellmenu_changes.sort_priority = /*active_header_menu*/
      ctx2[46] ? (
        /*$df_state*/
        ctx2[33].sort_state.sort_columns.findIndex(
          /*func_12*/
          ctx2[121]
        ) + 1 || null
      ) : null;
      if (dirty[1] & /*active_header_menu*/
      32768) cellmenu_changes.on_filter = /*active_header_menu*/
      ctx2[46] ? (
        /*func_13*/
        ctx2[122]
      ) : void 0;
      if (dirty[1] & /*active_header_menu*/
      32768) cellmenu_changes.on_clear_filter = /*active_header_menu*/
      ctx2[46] ? (
        /*func_14*/
        ctx2[123]
      ) : void 0;
      if (dirty[1] & /*active_header_menu, $df_state*/
      32772) cellmenu_changes.filter_active = /*active_header_menu*/
      ctx2[46] ? (
        /*$df_state*/
        ctx2[33].filter_state.filter_columns.some(
          /*func_15*/
          ctx2[124]
        )
      ) : null;
      cellmenu.$set(cellmenu_changes);
    },
    i(local) {
      if (current) return;
      transition_in(cellmenu.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(cellmenu.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(cellmenu, detaching);
    }
  };
}
function create_fragment$8(ctx) {
  let div1;
  let t0;
  let div0;
  let table_1;
  let t1;
  let thead;
  let tr0;
  let t2;
  let each_blocks_1 = [];
  let each0_lookup = new Map_1();
  let t3;
  let tbody;
  let tr1;
  let t4;
  let each_blocks = [];
  let each1_lookup = new Map_1();
  let t5;
  let upload_1;
  let updating_dragging;
  let t6;
  let t7;
  let t8;
  let if_block6_anchor;
  let current;
  let mounted;
  let dispose;
  let if_block0 = (
    /*label*/
    (ctx[3] && /*label*/
    ctx[3].length !== 0 && /*show_label*/
    ctx[4] || /*show_fullscreen_button*/
    ctx[18] || /*show_copy_button*/
    ctx[19] || /*show_search*/
    ctx[21] !== "none") && create_if_block_8(ctx)
  );
  let if_block1 = (
    /*label*/
    ctx[3] && /*label*/
    ctx[3].length !== 0 && create_if_block_7(ctx)
  );
  let if_block2 = (
    /*show_row_numbers*/
    ctx[15] && create_if_block_6$2()
  );
  let each_value_3 = ensure_array_like(
    /*_headers*/
    ctx[25]
  );
  const get_key = (ctx2) => (
    /*id*/
    ctx2[148]
  );
  for (let i = 0; i < each_value_3.length; i += 1) {
    let child_ctx = get_each_context_3(ctx, each_value_3, i);
    let key = get_key(child_ctx);
    each0_lookup.set(key, each_blocks_1[i] = create_each_block_3(key, child_ctx));
  }
  let if_block3 = (
    /*show_row_numbers*/
    ctx[15] && create_if_block_5$2()
  );
  let each_value_2 = ensure_array_like(
    /*max*/
    ctx[50]
  );
  const get_key_1 = (ctx2) => (
    /*id*/
    ctx2[148]
  );
  for (let i = 0; i < each_value_2.length; i += 1) {
    let child_ctx = get_each_context_2(ctx, each_value_2, i);
    let key = get_key_1(child_ctx);
    each1_lookup.set(key, each_blocks[i] = create_each_block_2(key, child_ctx));
  }
  function upload_1_dragging_binding(value) {
    ctx[107](value);
  }
  let upload_1_props = {
    upload: (
      /*upload*/
      ctx[16]
    ),
    stream_handler: (
      /*stream_handler*/
      ctx[17]
    ),
    flex: false,
    center: false,
    boundedheight: false,
    disable_click: true,
    root: (
      /*root*/
      ctx[11]
    ),
    aria_label: (
      /*i18n*/
      ctx[12]("dataframe.drop_to_upload")
    ),
    $$slots: { default: [create_default_slot$4] },
    $$scope: { ctx }
  };
  if (
    /*dragging*/
    ctx[36] !== void 0
  ) {
    upload_1_props.dragging = /*dragging*/
    ctx[36];
  }
  upload_1 = new Upload2({ props: upload_1_props });
  binding_callbacks.push(() => bind(upload_1, "dragging", upload_1_dragging_binding));
  upload_1.$on(
    "load",
    /*load_handler*/
    ctx[108]
  );
  let if_block4 = (
    /*show_scroll_button*/
    ctx[41] && create_if_block_2$4(ctx)
  );
  let if_block5 = (
    /*data*/
    ctx[26].length === 0 && /*editable*/
    ctx[9] && /*row_count*/
    ctx[6][1] === "dynamic" && create_if_block_1$4(ctx)
  );
  let if_block6 = (
    /*active_cell_menu*/
    (ctx[47] || /*active_header_menu*/
    ctx[46]) && create_if_block$4(ctx)
  );
  return {
    c() {
      div1 = element("div");
      if (if_block0) if_block0.c();
      t0 = space();
      div0 = element("div");
      table_1 = element("table");
      if (if_block1) if_block1.c();
      t1 = space();
      thead = element("thead");
      tr0 = element("tr");
      if (if_block2) if_block2.c();
      t2 = space();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].c();
      }
      t3 = space();
      tbody = element("tbody");
      tr1 = element("tr");
      if (if_block3) if_block3.c();
      t4 = space();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      t5 = space();
      create_component(upload_1.$$.fragment);
      t6 = space();
      if (if_block4) if_block4.c();
      t7 = space();
      if (if_block5) if_block5.c();
      t8 = space();
      if (if_block6) if_block6.c();
      if_block6_anchor = empty();
      attr(tr0, "class", "svelte-4x7jh");
      attr(thead, "class", "svelte-4x7jh");
      attr(tr1, "class", "svelte-4x7jh");
      attr(tbody, "class", "svelte-4x7jh");
      attr(table_1, "aria-hidden", "true");
      attr(table_1, "class", "svelte-4x7jh");
      attr(div0, "class", "table-wrap svelte-4x7jh");
      attr(div0, "role", "grid");
      attr(div0, "tabindex", "0");
      toggle_class(
        div0,
        "dragging",
        /*is_dragging*/
        ctx[42]
      );
      toggle_class(div0, "no-wrap", !/*wrap*/
      ctx[10]);
      toggle_class(
        div0,
        "menu-open",
        /*active_cell_menu*/
        ctx[47] || /*active_header_menu*/
        ctx[46]
      );
      attr(div1, "class", "table-container svelte-4x7jh");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      if (if_block0) if_block0.m(div1, null);
      append(div1, t0);
      append(div1, div0);
      append(div0, table_1);
      if (if_block1) if_block1.m(table_1, null);
      append(table_1, t1);
      append(table_1, thead);
      append(thead, tr0);
      if (if_block2) if_block2.m(tr0, null);
      append(tr0, t2);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        if (each_blocks_1[i]) {
          each_blocks_1[i].m(tr0, null);
        }
      }
      append(table_1, t3);
      append(table_1, tbody);
      append(tbody, tr1);
      if (if_block3) if_block3.m(tr1, null);
      append(tr1, t4);
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(tr1, null);
        }
      }
      ctx[96](table_1);
      append(div0, t5);
      mount_component(upload_1, div0, null);
      append(div0, t6);
      if (if_block4) if_block4.m(div0, null);
      ctx[109](div0);
      insert(target, t7, anchor);
      if (if_block5) if_block5.m(target, anchor);
      insert(target, t8, anchor);
      if (if_block6) if_block6.m(target, anchor);
      insert(target, if_block6_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            window_1,
            "resize",
            /*resize_handler*/
            ctx[89]
          ),
          listen(
            div0,
            "keydown",
            /*keydown_handler*/
            ctx[110]
          ),
          listen(div0, "mousemove", function() {
            if (is_function(
              /*handle_mouse_move*/
              ctx[44]
            )) ctx[44].apply(this, arguments);
          }),
          listen(div0, "mouseup", function() {
            if (is_function(
              /*handle_mouse_up*/
              ctx[43]
            )) ctx[43].apply(this, arguments);
          }),
          listen(div0, "mouseleave", function() {
            if (is_function(
              /*handle_mouse_up*/
              ctx[43]
            )) ctx[43].apply(this, arguments);
          })
        ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (
        /*label*/
        ctx[3] && /*label*/
        ctx[3].length !== 0 && /*show_label*/
        ctx[4] || /*show_fullscreen_button*/
        ctx[18] || /*show_copy_button*/
        ctx[19] || /*show_search*/
        ctx[21] !== "none"
      ) {
        if (if_block0) {
          if_block0.p(ctx, dirty);
          if (dirty[0] & /*label, show_label, show_fullscreen_button, show_copy_button, show_search*/
          2883608) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_8(ctx);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(div1, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*label*/
        ctx[3] && /*label*/
        ctx[3].length !== 0
      ) {
        if (if_block1) {
          if_block1.p(ctx, dirty);
        } else {
          if_block1 = create_if_block_7(ctx);
          if_block1.c();
          if_block1.m(table_1, t1);
        }
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if (
        /*show_row_numbers*/
        ctx[15]
      ) {
        if (if_block2) {
          if (dirty[0] & /*show_row_numbers*/
          32768) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_6$2();
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(tr0, t2);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
      if (dirty[0] & /*_headers, headers, latex_delimiters, line_breaks, max_chars, editable, static_columns, i18n, col_count, datatype, data, els*/
      122704549 | dirty[1] & /*actual_pinned_columns, header_edit, selected_header, handle_header_click, end_header_edit, $df_state*/
      1617952772 | dirty[2] & /*toggle_header_menu, handle_select_all*/
      1032) {
        each_value_3 = ensure_array_like(
          /*_headers*/
          ctx[25]
        );
        group_outros();
        each_blocks_1 = update_keyed_each(each_blocks_1, dirty, get_key, 1, ctx, each_value_3, each0_lookup, tr0, outro_and_destroy_block, create_each_block_3, null, get_each_context_3);
        check_outros();
      }
      if (
        /*show_row_numbers*/
        ctx[15]
      ) {
        if (if_block3) {
          if (dirty[0] & /*show_row_numbers*/
          32768) {
            transition_in(if_block3, 1);
          }
        } else {
          if_block3 = create_if_block_5$2();
          if_block3.c();
          transition_in(if_block3, 1);
          if_block3.m(tr1, t4);
        }
      } else if (if_block3) {
        group_outros();
        transition_out(if_block3, 1, 1, () => {
          if_block3 = null;
        });
        check_outros();
      }
      if (dirty[0] & /*cells, latex_delimiters, line_breaks, datatype, editable, i18n*/
      268456580 | dirty[1] & /*max, selected_cells, selected_cell_coords, df_actions, is_dragging*/
      17303809 | dirty[2] & /*handle_blur*/
      4) {
        each_value_2 = ensure_array_like(
          /*max*/
          ctx[50]
        );
        group_outros();
        each_blocks = update_keyed_each(each_blocks, dirty, get_key_1, 1, ctx, each_value_2, each1_lookup, tr1, outro_and_destroy_block, create_each_block_2, null, get_each_context_2);
        check_outros();
      }
      const upload_1_changes = {};
      if (dirty[0] & /*upload*/
      65536) upload_1_changes.upload = /*upload*/
      ctx[16];
      if (dirty[0] & /*stream_handler*/
      131072) upload_1_changes.stream_handler = /*stream_handler*/
      ctx[17];
      if (dirty[0] & /*root*/
      2048) upload_1_changes.root = /*root*/
      ctx[11];
      if (dirty[0] & /*i18n*/
      4096) upload_1_changes.aria_label = /*i18n*/
      ctx[12]("dataframe.drop_to_upload");
      if (dirty[0] & /*max_height, label, filtered_to_original_map, latex_delimiters, line_breaks, datatype, max_chars, editable, static_columns, i18n, components, wrap, els, show_row_numbers, _headers, headers, col_count, data*/
      256964525 | dirty[1] & /*selected_index, active_cell_menu, active_header_menu, search_results, table_height, scrollbar_width, viewport, show_scroll_button, $df_state, actual_pinned_columns, handle_mouse_down, selected_cells, copy_flash, editing, is_dragging, header_edit, selected_header*/
      7851735 | dirty[5] & /*$$scope*/
      1) {
        upload_1_changes.$$scope = { dirty, ctx };
      }
      if (!updating_dragging && dirty[1] & /*dragging*/
      32) {
        updating_dragging = true;
        upload_1_changes.dragging = /*dragging*/
        ctx[36];
        add_flush_callback(() => updating_dragging = false);
      }
      upload_1.$set(upload_1_changes);
      if (
        /*show_scroll_button*/
        ctx[41]
      ) {
        if (if_block4) {
          if_block4.p(ctx, dirty);
        } else {
          if_block4 = create_if_block_2$4(ctx);
          if_block4.c();
          if_block4.m(div0, null);
        }
      } else if (if_block4) {
        if_block4.d(1);
        if_block4 = null;
      }
      if (!current || dirty[1] & /*is_dragging*/
      2048) {
        toggle_class(
          div0,
          "dragging",
          /*is_dragging*/
          ctx[42]
        );
      }
      if (!current || dirty[0] & /*wrap*/
      1024) {
        toggle_class(div0, "no-wrap", !/*wrap*/
        ctx[10]);
      }
      if (!current || dirty[1] & /*active_cell_menu, active_header_menu*/
      98304) {
        toggle_class(
          div0,
          "menu-open",
          /*active_cell_menu*/
          ctx[47] || /*active_header_menu*/
          ctx[46]
        );
      }
      if (
        /*data*/
        ctx[26].length === 0 && /*editable*/
        ctx[9] && /*row_count*/
        ctx[6][1] === "dynamic"
      ) {
        if (if_block5) {
          if_block5.p(ctx, dirty);
          if (dirty[0] & /*data, editable, row_count*/
          67109440) {
            transition_in(if_block5, 1);
          }
        } else {
          if_block5 = create_if_block_1$4(ctx);
          if_block5.c();
          transition_in(if_block5, 1);
          if_block5.m(t8.parentNode, t8);
        }
      } else if (if_block5) {
        group_outros();
        transition_out(if_block5, 1, 1, () => {
          if_block5 = null;
        });
        check_outros();
      }
      if (
        /*active_cell_menu*/
        ctx[47] || /*active_header_menu*/
        ctx[46]
      ) {
        if (if_block6) {
          if_block6.p(ctx, dirty);
          if (dirty[1] & /*active_cell_menu, active_header_menu*/
          98304) {
            transition_in(if_block6, 1);
          }
        } else {
          if_block6 = create_if_block$4(ctx);
          if_block6.c();
          transition_in(if_block6, 1);
          if_block6.m(if_block6_anchor.parentNode, if_block6_anchor);
        }
      } else if (if_block6) {
        group_outros();
        transition_out(if_block6, 1, 1, () => {
          if_block6 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block2);
      for (let i = 0; i < each_value_3.length; i += 1) {
        transition_in(each_blocks_1[i]);
      }
      transition_in(if_block3);
      for (let i = 0; i < each_value_2.length; i += 1) {
        transition_in(each_blocks[i]);
      }
      transition_in(upload_1.$$.fragment, local);
      transition_in(if_block5);
      transition_in(if_block6);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block2);
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        transition_out(each_blocks_1[i]);
      }
      transition_out(if_block3);
      for (let i = 0; i < each_blocks.length; i += 1) {
        transition_out(each_blocks[i]);
      }
      transition_out(upload_1.$$.fragment, local);
      transition_out(if_block5);
      transition_out(if_block6);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
        detach(t7);
        detach(t8);
        detach(if_block6_anchor);
      }
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
      for (let i = 0; i < each_blocks_1.length; i += 1) {
        each_blocks_1[i].d();
      }
      if (if_block3) if_block3.d();
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].d();
      }
      ctx[96](null);
      destroy_component(upload_1);
      if (if_block4) if_block4.d();
      ctx[109](null);
      if (if_block5) if_block5.d(detaching);
      if (if_block6) if_block6.d(detaching);
      mounted = false;
      run_all(dispose);
    }
  };
}
function make_id() {
  return Math.random().toString(36).substring(2, 15);
}
function get_cell_width(index) {
  return `var(--cell-width-${index})`;
}
const scroll_top_handler = (_) => {
};
function instance$8($$self, $$props, $$invalidate) {
  let selected_cells;
  let selected;
  let editing;
  let header_edit;
  let selected_header;
  let active_cell_menu;
  let active_header_menu;
  let copy_flash;
  let actual_pinned_columns;
  let max;
  let selected_index;
  let handle_mouse_down;
  let handle_mouse_move;
  let handle_mouse_up;
  let $df_state;
  let { datatype } = $$props;
  let { label = null } = $$props;
  let { show_label = true } = $$props;
  let { headers = [] } = $$props;
  let { values = [] } = $$props;
  let { col_count } = $$props;
  let { row_count } = $$props;
  let { latex_delimiters } = $$props;
  let { components = {} } = $$props;
  let { editable = true } = $$props;
  let { wrap = false } = $$props;
  let { root } = $$props;
  let { i18n } = $$props;
  let { max_height = 500 } = $$props;
  let { line_breaks = true } = $$props;
  let { column_widths = [] } = $$props;
  let { show_row_numbers = false } = $$props;
  let { upload } = $$props;
  let { stream_handler } = $$props;
  let { show_fullscreen_button = false } = $$props;
  let { show_copy_button = false } = $$props;
  let { value_is_output = false } = $$props;
  let { max_chars = void 0 } = $$props;
  let { show_search = "none" } = $$props;
  let { pinned_columns = 0 } = $$props;
  let { static_columns = [] } = $$props;
  let { fullscreen = false } = $$props;
  const df_ctx = create_dataframe_context$1({
    show_fullscreen_button,
    show_copy_button,
    show_search,
    show_row_numbers,
    editable,
    pinned_columns,
    show_label,
    line_breaks,
    wrap,
    max_height,
    column_widths,
    max_chars,
    static_columns
  });
  const { state: df_state, actions: df_actions } = df_ctx;
  component_subscribe($$self, df_state, (value) => $$invalidate(33, $df_state = value));
  onMount(() => {
    $$invalidate(34, df_ctx.parent_element = parent, df_ctx);
    $$invalidate(34, df_ctx.get_data_at = get_data_at, df_ctx);
    $$invalidate(34, df_ctx.get_column = get_column, df_ctx);
    $$invalidate(34, df_ctx.get_row = get_row, df_ctx);
    $$invalidate(34, df_ctx.dispatch = dispatch2, df_ctx);
    init_drag_handlers();
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting && !is_visible) {
          $$invalidate(85, width_calculated = false);
        }
        is_visible = entry.isIntersecting;
      });
    });
    observer.observe(parent);
    document.addEventListener("click", handle_click_outside$1$1);
    window.addEventListener("resize", handle_resize);
    const global_mouse_up = (event) => {
      if (is_dragging || drag_start) {
        handle_mouse_up(event);
      }
    };
    document.addEventListener("mouseup", global_mouse_up);
    return () => {
      observer.disconnect();
      document.removeEventListener("click", handle_click_outside$1$1);
      window.removeEventListener("resize", handle_resize);
      document.removeEventListener("mouseup", global_mouse_up);
    };
  });
  const dispatch2 = createEventDispatcher();
  let els = {};
  let data_binding = {};
  let _headers = make_headers$1(headers, col_count, els, make_id);
  let old_headers = headers;
  let data = [[]];
  let old_val = void 0;
  let search_results = [[]];
  let dragging = false;
  let color_accent_copied;
  let filtered_to_original_map = [];
  onMount(() => {
    const color = getComputedStyle(document.documentElement).getPropertyValue("--color-accent").trim();
    color_accent_copied = color + "40";
    document.documentElement.style.setProperty("--color-accent-copied", color_accent_copied);
  });
  const get_data_at = (row, col) => {
    var _a, _b;
    return (_b = (_a = data == null ? void 0 : data[row]) == null ? void 0 : _a[col]) == null ? void 0 : _b.value;
  };
  const get_column = (col) => (data == null ? void 0 : data.map((row) => {
    var _a;
    return (_a = row[col]) == null ? void 0 : _a.value;
  })) ?? [];
  const get_row = (row) => {
    var _a;
    return ((_a = data == null ? void 0 : data[row]) == null ? void 0 : _a.map((cell) => cell.value)) ?? [];
  };
  let { display_value = null } = $$props;
  let { styling = null } = $$props;
  let previous_headers = _headers.map((h) => h.value);
  let previous_data = data.map((row) => row.map((cell) => cell.value));
  function handle_sort(col, direction) {
    df_actions.handle_sort(col, direction);
    sort_data2(data, display_value, styling);
  }
  function clear_sort() {
    df_actions.reset_sort_state();
    sort_data2(data, display_value, styling);
  }
  function handle_filter(col, datatype2, filter, value) {
    df_actions.handle_filter(col, datatype2, filter, value);
    filter_data2(data, display_value, styling);
  }
  function clear_filter() {
    df_actions.reset_filter_state();
    filter_data2(data, display_value, styling);
  }
  async function edit_header(i, _select = false) {
    if (!editable || header_edit === i || col_count[1] !== "dynamic") return;
    df_actions.set_header_edit(i);
  }
  function handle_header_click(event, col) {
    if (event.target instanceof HTMLAnchorElement) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    if (!editable) return;
    df_actions.set_editing(false);
    df_actions.handle_header_click(col, editable);
    parent.focus();
  }
  function end_header_edit(event) {
    if (!editable) return;
    df_actions.end_header_edit(event.detail.key);
    parent.focus();
  }
  async function add_row(index) {
    var _a;
    parent.focus();
    if (row_count[1] !== "dynamic") return;
    const new_row = Array(((_a = data[0]) == null ? void 0 : _a.length) || headers.length).fill(0).map((_, i) => {
      const _id = make_id();
      $$invalidate(24, els[_id] = { cell: null, input: null }, els);
      return { id: _id, value: "" };
    });
    if (data.length === 0) {
      $$invalidate(26, data = [new_row]);
    } else if (index !== void 0 && index >= 0 && index <= data.length) {
      data.splice(index, 0, new_row);
    } else {
      data.push(new_row);
    }
    $$invalidate(88, selected = [index !== void 0 ? index : data.length - 1, 0]);
  }
  async function add_col(index) {
    parent.focus();
    if (col_count[1] !== "dynamic") return;
    const result = df_actions.add_col(data, headers, make_id, index);
    result.data.forEach((row) => {
      row.forEach((cell) => {
        if (!els[cell.id]) {
          $$invalidate(24, els[cell.id] = { cell: null, input: null }, els);
        }
      });
    });
    $$invalidate(26, data = result.data);
    $$invalidate(0, headers = result.headers);
    await tick();
    requestAnimationFrame(() => {
      edit_header(index !== void 0 ? index : data[0].length - 1, true);
      const new_w = parent.querySelectorAll("tbody")[1].offsetWidth;
      parent.querySelectorAll("table")[1].scrollTo({ left: new_w });
    });
  }
  function handle_click_outside$1$1(event) {
    if (handle_click_outside$1(event, parent)) {
      df_actions.clear_ui_state();
      $$invalidate(52, header_edit = false);
      $$invalidate(51, selected_header = false);
    }
  }
  let width_calc_timeout;
  let width_calculated = false;
  let cells = [];
  let parent;
  let table;
  let last_width_data_length = 0;
  let last_width_column_count = 0;
  function set_cell_widths() {
    var _a;
    const column_count = ((_a = data[0]) == null ? void 0 : _a.length) || 0;
    if ($df_state.filter_state.filter_columns.length > 0) {
      return;
    }
    if (last_width_data_length === data.length && last_width_column_count === column_count && $df_state.sort_state.sort_columns.length > 0) {
      return;
    }
    if (!parent) {
      return;
    }
    last_width_data_length = data.length;
    last_width_column_count = column_count;
    const widths = cells.map((el) => (el == null ? void 0 : el.clientWidth) || 0);
    if (widths.length === 0) return;
    if (show_row_numbers) {
      parent.style.setProperty(`--cell-width-row-number`, `${widths[0]}px`);
    }
    for (let i = 0; i < 50; i++) {
      if (!column_widths[i]) {
        parent.style.removeProperty(`--cell-width-${i}`);
      } else if (column_widths[i].endsWith("%")) {
        const percentage = parseFloat(column_widths[i]);
        const pixel_width = Math.floor(percentage / 100 * parent.clientWidth);
        parent.style.setProperty(`--cell-width-${i}`, `${pixel_width}px`);
      } else {
        parent.style.setProperty(`--cell-width-${i}`, column_widths[i]);
      }
    }
    widths.forEach((width, i) => {
      if (!column_widths[i]) {
        const calculated_width = `${Math.max(width, 45)}px`;
        parent.style.setProperty(`--cell-width-${i}`, calculated_width);
      }
    });
  }
  let table_height = values.slice(0, max_height / values.length * 37).length * 37 + 37;
  let scrollbar_width = 0;
  function sort_data2(_data, _display_value, _styling) {
    const result = sort_data_and_preserve_selection$1(_data, _display_value, _styling, $df_state.sort_state.sort_columns, selected, get_current_indices$1);
    $$invalidate(26, data = result.data);
    $$invalidate(88, selected = result.selected);
  }
  function filter_data2(_data, _display_value, _styling) {
    var _a, _b, _c;
    const result = filter_data_and_preserve_selection$1(_data, _display_value, _styling, $df_state.filter_state.filter_columns, selected, get_current_indices$1, (_a = $df_state.filter_state.initial_data) == null ? void 0 : _a.data, (_b = $df_state.filter_state.initial_data) == null ? void 0 : _b.display_value, (_c = $df_state.filter_state.initial_data) == null ? void 0 : _c.styling);
    $$invalidate(26, data = result.data);
    $$invalidate(88, selected = result.selected);
  }
  let is_visible = false;
  const set_copy_flash = (value) => {
    df_actions.set_copy_flash(value);
  };
  let previous_selected_cells = [];
  function handle_blur(event) {
    const { blur_event, coords } = event.detail;
    handle_cell_blur$1(blur_event, df_ctx, coords);
  }
  function toggle_header_menu(event, col) {
    event.stopPropagation();
    if (active_header_menu && active_header_menu.col === col) {
      df_actions.set_active_header_menu(null);
    } else {
      const header = event.target.closest("th");
      if (header) {
        const rect = header.getBoundingClientRect();
        df_actions.set_active_header_menu({ col, x: rect.right, y: rect.bottom });
      }
    }
  }
  afterUpdate(() => {
    $$invalidate(74, value_is_output = false);
  });
  function delete_col_at(index) {
    if (col_count[1] !== "dynamic") return;
    if (data[0].length <= 1) return;
    const result = df_actions.delete_col_at(data, headers, index);
    $$invalidate(26, data = result.data);
    $$invalidate(0, headers = result.headers);
    $$invalidate(25, _headers = make_headers$1(headers, col_count, els, make_id));
    df_actions.set_active_cell_menu(null);
    df_actions.set_active_header_menu(null);
    df_actions.set_selected(false);
    df_actions.set_selected_cells([]);
    df_actions.set_editing(false);
  }
  function delete_row_at(index) {
    $$invalidate(26, data = df_actions.delete_row_at(data, index));
    df_actions.set_active_cell_menu(null);
    df_actions.set_active_header_menu(null);
  }
  let selected_cell_coords;
  function commit_filter() {
    if ($df_state.current_search_query && show_search === "filter") {
      const filtered_data = [];
      const filtered_display_values = [];
      const filtered_styling = [];
      search_results.forEach((row) => {
        const data_row = [];
        const display_row = [];
        const styling_row = [];
        row.forEach((cell) => {
          data_row.push(cell.value);
          display_row.push(cell.display_value !== void 0 ? cell.display_value : String(cell.value));
          styling_row.push(cell.styling || "");
        });
        filtered_data.push(data_row);
        filtered_display_values.push(display_row);
        filtered_styling.push(styling_row);
      });
      const change_payload = {
        data: filtered_data,
        headers: _headers.map((h) => h.value),
        metadata: {
          display_value: filtered_display_values,
          styling: filtered_styling
        }
      };
      dispatch2("change", change_payload);
      if (!value_is_output) {
        dispatch2("input");
      }
      df_actions.handle_search(null);
    }
  }
  let viewport;
  let show_scroll_button = false;
  function scroll_to_top() {
    viewport.scrollTo({ top: 0 });
  }
  function handle_resize() {
    df_actions.set_active_cell_menu(null);
    df_actions.set_active_header_menu(null);
    $$invalidate(31, selected_cells = []);
    $$invalidate(88, selected = false);
    $$invalidate(48, editing = false);
    $$invalidate(85, width_calculated = false);
    set_cell_widths();
  }
  function add_row_at(index, position) {
    const row_index = position === "above" ? index : index + 1;
    add_row(row_index);
    $$invalidate(47, active_cell_menu = null);
    $$invalidate(46, active_header_menu = null);
  }
  function add_col_at(index, position) {
    const col_index = position === "left" ? index : index + 1;
    add_col(col_index);
    $$invalidate(47, active_cell_menu = null);
    $$invalidate(46, active_header_menu = null);
  }
  function reset_sort_state() {
    df_actions.reset_sort_state();
  }
  function handle_select_all(col, checked) {
    $$invalidate(26, data = data.map((row) => {
      const new_row = [...row];
      if (new_row[col]) {
        new_row[col] = {
          ...new_row[col],
          value: checked.toString()
        };
      }
      return new_row;
    }));
  }
  let is_dragging = false;
  let drag_start = null;
  let mouse_down_pos = null;
  const drag_state = { is_dragging, drag_start, mouse_down_pos };
  let drag_handlers;
  function init_drag_handlers() {
    $$invalidate(87, drag_handlers = create_drag_handlers$1(drag_state, (value) => $$invalidate(42, is_dragging = value), (cells2) => df_actions.set_selected_cells(cells2), (cell) => df_actions.set_selected(cell), (event, row, col) => df_actions.handle_cell_click(event, row, col), show_row_numbers, parent));
  }
  function get_cell_display_value(row, col) {
    var _a, _b;
    const is_search_active = $df_state.current_search_query !== void 0;
    if (is_search_active && ((_a = search_results == null ? void 0 : search_results[row]) == null ? void 0 : _a[col])) {
      return search_results[row][col].display_value !== void 0 ? search_results[row][col].display_value : String(search_results[row][col].value);
    }
    if ((_b = data == null ? void 0 : data[row]) == null ? void 0 : _b[col]) {
      return data[row][col].display_value !== void 0 ? data[row][col].display_value : String(data[row][col].value);
    }
    return "";
  }
  const resize_handler = () => set_cell_widths();
  const func2 = async () => await copy_table_data$1(data, null);
  const search_handler = (e) => df_actions.handle_search(e.detail);
  function fullscreen_handler(event) {
    bubble.call(this, $$self, event);
  }
  function tableheader_value_binding(value, i) {
    if ($$self.$$.not_equal(_headers[i].value, value)) {
      _headers[i].value = value;
      $$invalidate(25, _headers), $$invalidate(0, headers), $$invalidate(80, old_headers), $$invalidate(5, col_count), $$invalidate(24, els);
    }
  }
  function tableheader_el_binding(value, id) {
    if ($$self.$$.not_equal(els[id].input, value)) {
      els[id].input = value;
      $$invalidate(24, els);
    }
  }
  function td_binding($$value, j) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      cells[j] = $$value;
      $$invalidate(28, cells);
    });
  }
  function table_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      table = $$value;
      $$invalidate(30, table);
    });
  }
  const func_1 = (e, r, c) => handle_mouse_down(e, r, c);
  function tablecell_value_binding(value, index, j) {
    if ($$self.$$.not_equal(search_results[index][j].value, value)) {
      search_results[index][j].value = value;
      $$invalidate(35, search_results), $$invalidate(33, $df_state), $$invalidate(26, data), $$invalidate(27, filtered_to_original_map), $$invalidate(78, styling), $$invalidate(1, values), $$invalidate(81, old_val), $$invalidate(29, parent), $$invalidate(24, els), $$invalidate(132, data_binding), $$invalidate(77, display_value), $$invalidate(2, datatype), $$invalidate(28, cells);
    }
  }
  function tablecell_el_binding(value, id) {
    if ($$self.$$.not_equal(els[id], value)) {
      els[id] = value;
      $$invalidate(24, els);
    }
  }
  function tableheader_value_binding_1(value, i) {
    if ($$self.$$.not_equal(_headers[i].value, value)) {
      _headers[i].value = value;
      $$invalidate(25, _headers), $$invalidate(0, headers), $$invalidate(80, old_headers), $$invalidate(5, col_count), $$invalidate(24, els);
    }
  }
  function tableheader_el_binding_1(value, id) {
    if ($$self.$$.not_equal(els[id].input, value)) {
      els[id].input = value;
      $$invalidate(24, els);
    }
  }
  function virtualtable_items_binding(value) {
    search_results = value;
    $$invalidate(35, search_results), $$invalidate(33, $df_state), $$invalidate(26, data), $$invalidate(27, filtered_to_original_map), $$invalidate(78, styling), $$invalidate(1, values), $$invalidate(81, old_val), $$invalidate(29, parent), $$invalidate(24, els), $$invalidate(132, data_binding), $$invalidate(77, display_value), $$invalidate(2, datatype), $$invalidate(28, cells);
  }
  function virtualtable_actual_height_binding(value) {
    table_height = value;
    $$invalidate(37, table_height);
  }
  function virtualtable_table_scrollbar_width_binding(value) {
    scrollbar_width = value;
    $$invalidate(38, scrollbar_width);
  }
  function virtualtable_viewport_binding(value) {
    viewport = value;
    $$invalidate(40, viewport);
  }
  function virtualtable_show_scroll_button_binding(value) {
    show_scroll_button = value;
    $$invalidate(41, show_scroll_button);
  }
  function upload_1_dragging_binding(value) {
    dragging = value;
    $$invalidate(36, dragging);
  }
  const load_handler = ({ detail }) => handle_file_upload$1(
    detail.data,
    (head) => {
      $$invalidate(25, _headers = make_headers$1(head.map((h) => h ?? ""), col_count, els, make_id));
      return _headers;
    },
    (vals) => {
      $$invalidate(1, values = vals);
    }
  );
  function div0_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      parent = $$value;
      $$invalidate(29, parent);
    });
  }
  const keydown_handler2 = (e) => handle_keydown$1(e, df_ctx);
  const func_2 = () => add_row();
  const func_3 = () => add_row_at((active_cell_menu == null ? void 0 : active_cell_menu.row) ?? -1, "above");
  const func_4 = () => add_row_at((active_cell_menu == null ? void 0 : active_cell_menu.row) ?? -1, "below");
  const func_5 = () => add_col_at((active_cell_menu == null ? void 0 : active_cell_menu.col) ?? (active_header_menu == null ? void 0 : active_header_menu.col) ?? -1, "left");
  const func_6 = () => add_col_at((active_cell_menu == null ? void 0 : active_cell_menu.col) ?? (active_header_menu == null ? void 0 : active_header_menu.col) ?? -1, "right");
  const func_7 = () => delete_row_at((active_cell_menu == null ? void 0 : active_cell_menu.row) ?? -1);
  const func_8 = () => delete_col_at((active_cell_menu == null ? void 0 : active_cell_menu.col) ?? (active_header_menu == null ? void 0 : active_header_menu.col) ?? -1);
  const func_9 = (direction) => {
    if (active_header_menu) {
      handle_sort(active_header_menu.col, direction);
      df_actions.set_active_header_menu(null);
    }
  };
  const func_10 = () => {
    clear_sort();
    df_actions.set_active_header_menu(null);
  };
  const func_11 = (item) => item.col === ((active_header_menu == null ? void 0 : active_header_menu.col) ?? -1);
  const func_12 = (item) => item.col === ((active_header_menu == null ? void 0 : active_header_menu.col) ?? -1);
  const func_13 = (datatype2, filter, value) => {
    if (active_header_menu) {
      handle_filter(active_header_menu.col, datatype2, filter, value);
      df_actions.set_active_header_menu(null);
    }
  };
  const func_14 = () => {
    clear_filter();
    df_actions.set_active_header_menu(null);
  };
  const func_15 = (c) => c.col === ((active_header_menu == null ? void 0 : active_header_menu.col) ?? -1);
  $$self.$$set = ($$props2) => {
    if ("datatype" in $$props2) $$invalidate(2, datatype = $$props2.datatype);
    if ("label" in $$props2) $$invalidate(3, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(4, show_label = $$props2.show_label);
    if ("headers" in $$props2) $$invalidate(0, headers = $$props2.headers);
    if ("values" in $$props2) $$invalidate(1, values = $$props2.values);
    if ("col_count" in $$props2) $$invalidate(5, col_count = $$props2.col_count);
    if ("row_count" in $$props2) $$invalidate(6, row_count = $$props2.row_count);
    if ("latex_delimiters" in $$props2) $$invalidate(7, latex_delimiters = $$props2.latex_delimiters);
    if ("components" in $$props2) $$invalidate(8, components = $$props2.components);
    if ("editable" in $$props2) $$invalidate(9, editable = $$props2.editable);
    if ("wrap" in $$props2) $$invalidate(10, wrap = $$props2.wrap);
    if ("root" in $$props2) $$invalidate(11, root = $$props2.root);
    if ("i18n" in $$props2) $$invalidate(12, i18n = $$props2.i18n);
    if ("max_height" in $$props2) $$invalidate(13, max_height = $$props2.max_height);
    if ("line_breaks" in $$props2) $$invalidate(14, line_breaks = $$props2.line_breaks);
    if ("column_widths" in $$props2) $$invalidate(75, column_widths = $$props2.column_widths);
    if ("show_row_numbers" in $$props2) $$invalidate(15, show_row_numbers = $$props2.show_row_numbers);
    if ("upload" in $$props2) $$invalidate(16, upload = $$props2.upload);
    if ("stream_handler" in $$props2) $$invalidate(17, stream_handler = $$props2.stream_handler);
    if ("show_fullscreen_button" in $$props2) $$invalidate(18, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("show_copy_button" in $$props2) $$invalidate(19, show_copy_button = $$props2.show_copy_button);
    if ("value_is_output" in $$props2) $$invalidate(74, value_is_output = $$props2.value_is_output);
    if ("max_chars" in $$props2) $$invalidate(20, max_chars = $$props2.max_chars);
    if ("show_search" in $$props2) $$invalidate(21, show_search = $$props2.show_search);
    if ("pinned_columns" in $$props2) $$invalidate(76, pinned_columns = $$props2.pinned_columns);
    if ("static_columns" in $$props2) $$invalidate(22, static_columns = $$props2.static_columns);
    if ("fullscreen" in $$props2) $$invalidate(23, fullscreen = $$props2.fullscreen);
    if ("display_value" in $$props2) $$invalidate(77, display_value = $$props2.display_value);
    if ("styling" in $$props2) $$invalidate(78, styling = $$props2.styling);
  };
  $$self.$$.update = () => {
    var _a, _b;
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(31, selected_cells = $df_state.ui_state.selected_cells);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(88, selected = $df_state.ui_state.selected);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(48, editing = $df_state.ui_state.editing);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(52, header_edit = $df_state.ui_state.header_edit);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(51, selected_header = $df_state.ui_state.selected_header);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(47, active_cell_menu = $df_state.ui_state.active_cell_menu);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(46, active_header_menu = $df_state.ui_state.active_header_menu);
    }
    if ($$self.$$.dirty[1] & /*$df_state*/
    4) {
      $$invalidate(32, copy_flash = $df_state.ui_state.copy_flash);
    }
    if ($$self.$$.dirty[0] & /*values, parent, els, datatype, data, cells*/
    889192454 | $$self.$$.dirty[1] & /*$df_state*/
    4 | $$self.$$.dirty[2] & /*old_val, display_value, styling*/
    622592) {
      if (!dequal(values, old_val)) {
        if (parent) {
          const is_reset2 = values.length === 0 || values.length === 1 && values[0].length === 0;
          const is_different_structure2 = old_val !== void 0 && (values.length !== old_val.length || values[0] && old_val[0] && values[0].length !== old_val[0].length);
          if (is_reset2 || is_different_structure2) {
            for (let i = 0; i < 50; i++) {
              parent.style.removeProperty(`--cell-width-${i}`);
            }
            last_width_data_length = 0;
            last_width_column_count = 0;
            $$invalidate(85, width_calculated = false);
          }
        }
        const is_reset = values.length === 0 || values.length === 1 && values[0].length === 0;
        const is_different_structure = old_val !== void 0 && (values.length !== old_val.length || values[0] && old_val[0] && values[0].length !== old_val[0].length);
        $$invalidate(26, data = process_data$1(values, els, data_binding, make_id, display_value, datatype));
        $$invalidate(81, old_val = JSON.parse(JSON.stringify(values)));
        if (is_reset || is_different_structure) {
          df_actions.reset_sort_state();
        } else if ($df_state.sort_state.sort_columns.length > 0) {
          sort_data2(data, display_value, styling);
        } else {
          df_actions.handle_sort(-1, "asc");
          df_actions.reset_sort_state();
        }
        if ($df_state.filter_state.filter_columns.length > 0) {
          filter_data2(data, display_value, styling);
        } else {
          df_actions.reset_filter_state();
        }
        if ($df_state.current_search_query) {
          df_actions.handle_search(null);
        }
        if (parent && cells.length > 0 && (is_reset || is_different_structure)) {
          $$invalidate(85, width_calculated = false);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*data*/
    67108864 | $$self.$$.dirty[2] & /*pinned_columns*/
    16384) {
      $$invalidate(53, actual_pinned_columns = pinned_columns && ((_a = data == null ? void 0 : data[0]) == null ? void 0 : _a.length) ? Math.min(pinned_columns, data[0].length) : 0);
    }
    if ($$self.$$.dirty[0] & /*headers, col_count, els*/
    16777249 | $$self.$$.dirty[2] & /*old_headers*/
    262144) {
      {
        if (!dequal(headers, old_headers)) {
          $$invalidate(25, _headers = make_headers$1(headers, col_count, els, make_id));
          $$invalidate(80, old_headers = JSON.parse(JSON.stringify(headers)));
        }
      }
    }
    if ($$self.$$.dirty[0] & /*data, _headers, els*/
    117440512 | $$self.$$.dirty[2] & /*display_value, styling*/
    98304) {
      {
        if (data || _headers || els) {
          $$invalidate(34, df_ctx.data = data, df_ctx);
          $$invalidate(34, df_ctx.headers = _headers, df_ctx);
          $$invalidate(34, df_ctx.els = els, df_ctx);
          $$invalidate(34, df_ctx.display_value = display_value, df_ctx);
          $$invalidate(34, df_ctx.styling = styling, df_ctx);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*data, filtered_to_original_map*/
    201326592 | $$self.$$.dirty[1] & /*$df_state*/
    4 | $$self.$$.dirty[2] & /*styling*/
    65536) {
      if ($df_state.current_search_query !== void 0) {
        const cell_map = /* @__PURE__ */ new Map();
        $$invalidate(27, filtered_to_original_map = []);
        data.forEach((row, row_idx) => {
          if (row.some((cell) => {
            var _a2;
            return String(cell == null ? void 0 : cell.value).toLowerCase().includes(((_a2 = $df_state.current_search_query) == null ? void 0 : _a2.toLowerCase()) || "");
          })) {
            filtered_to_original_map.push(row_idx);
          }
          row.forEach((cell, col_idx) => {
            var _a2;
            cell_map.set(cell.id, {
              value: cell.value,
              display_value: cell.display_value !== void 0 ? cell.display_value : String(cell.value),
              styling: ((_a2 = styling == null ? void 0 : styling[row_idx]) == null ? void 0 : _a2[col_idx]) || ""
            });
          });
        });
        const filtered = df_actions.filter_data(data);
        $$invalidate(35, search_results = filtered.map((row) => row.map((cell) => {
          const original = cell_map.get(cell.id);
          return {
            ...cell,
            display_value: (original == null ? void 0 : original.display_value) !== void 0 ? original.display_value : String(cell.value),
            styling: (original == null ? void 0 : original.styling) || ""
          };
        })));
      } else {
        $$invalidate(27, filtered_to_original_map = []);
      }
    }
    if ($$self.$$.dirty[0] & /*data, _headers*/
    100663296 | $$self.$$.dirty[2] & /*previous_data, previous_headers, value_is_output*/
    3149824) {
      {
        if (data || _headers) {
          df_actions.trigger_change(data, _headers, previous_data, previous_headers, value_is_output, dispatch2);
          $$invalidate(83, previous_data = data.map((row) => row.map((cell) => cell.value)));
          $$invalidate(82, previous_headers = _headers.map((h) => h.value));
        }
      }
    }
    if ($$self.$$.dirty[0] & /*data*/
    67108864 | $$self.$$.dirty[1] & /*$df_state*/
    4 | $$self.$$.dirty[2] & /*display_value, styling*/
    98304) {
      {
        if ($df_state.filter_state.filter_columns.length > 0) {
          filter_data2(data, display_value, styling);
        }
        if ($df_state.sort_state.sort_columns.length > 0) {
          sort_data2(data, display_value, styling);
          df_actions.update_row_order(data);
        }
      }
    }
    if ($$self.$$.dirty[0] & /*data*/
    67108864) {
      $$invalidate(50, max = get_max$1(data));
    }
    if ($$self.$$.dirty[0] & /*cells*/
    268435456 | $$self.$$.dirty[2] & /*width_calc_timeout*/
    4194304) {
      if (cells[0] && ((_b = cells[0]) == null ? void 0 : _b.clientWidth)) {
        clearTimeout(width_calc_timeout);
        $$invalidate(84, width_calc_timeout = setTimeout(() => set_cell_widths(), 100));
      }
    }
    if ($$self.$$.dirty[0] & /*cells*/
    268435456 | $$self.$$.dirty[2] & /*width_calculated*/
    8388608) {
      if (cells[0] && !width_calculated) {
        set_cell_widths();
        $$invalidate(85, width_calculated = true);
      }
    }
    if ($$self.$$.dirty[2] & /*selected*/
    67108864) {
      $$invalidate(49, selected_index = !!selected && selected[0]);
    }
    if ($$self.$$.dirty[1] & /*copy_flash, selected_cells*/
    3 | $$self.$$.dirty[2] & /*previous_selected_cells*/
    16777216) {
      {
        if (copy_flash && !dequal(selected_cells, previous_selected_cells)) {
          set_copy_flash(false);
        }
        $$invalidate(86, previous_selected_cells = selected_cells);
      }
    }
    if ($$self.$$.dirty[2] & /*selected*/
    67108864) {
      if (selected !== false) $$invalidate(39, selected_cell_coords = selected);
    }
    if ($$self.$$.dirty[0] & /*data, els, parent, table*/
    1694498816 | $$self.$$.dirty[2] & /*selected*/
    67108864) {
      if (selected !== false) {
        const positions = calculate_selection_positions$1(selected, data, els, parent, table);
        document.documentElement.style.setProperty("--selected-col-pos", positions.col_pos);
        document.documentElement.style.setProperty("--selected-row-pos", positions.row_pos || "0px");
      }
    }
    if ($$self.$$.dirty[0] & /*parent*/
    536870912) {
      if (parent) init_drag_handlers();
    }
    if ($$self.$$.dirty[2] & /*drag_handlers*/
    33554432) {
      $$invalidate(45, handle_mouse_down = (drag_handlers == null ? void 0 : drag_handlers.handle_mouse_down) || (() => {
      }));
    }
    if ($$self.$$.dirty[2] & /*drag_handlers*/
    33554432) {
      $$invalidate(44, handle_mouse_move = (drag_handlers == null ? void 0 : drag_handlers.handle_mouse_move) || (() => {
      }));
    }
    if ($$self.$$.dirty[2] & /*drag_handlers*/
    33554432) {
      $$invalidate(43, handle_mouse_up = (drag_handlers == null ? void 0 : drag_handlers.handle_mouse_up) || (() => {
      }));
    }
  };
  {
    $$invalidate(42, is_dragging = drag_state.is_dragging);
    drag_start = drag_state.drag_start;
    mouse_down_pos = drag_state.mouse_down_pos;
  }
  return [
    headers,
    values,
    datatype,
    label,
    show_label,
    col_count,
    row_count,
    latex_delimiters,
    components,
    editable,
    wrap,
    root,
    i18n,
    max_height,
    line_breaks,
    show_row_numbers,
    upload,
    stream_handler,
    show_fullscreen_button,
    show_copy_button,
    max_chars,
    show_search,
    static_columns,
    fullscreen,
    els,
    _headers,
    data,
    filtered_to_original_map,
    cells,
    parent,
    table,
    selected_cells,
    copy_flash,
    $df_state,
    df_ctx,
    search_results,
    dragging,
    table_height,
    scrollbar_width,
    selected_cell_coords,
    viewport,
    show_scroll_button,
    is_dragging,
    handle_mouse_up,
    handle_mouse_move,
    handle_mouse_down,
    active_header_menu,
    active_cell_menu,
    editing,
    selected_index,
    max,
    selected_header,
    header_edit,
    actual_pinned_columns,
    df_state,
    df_actions,
    handle_sort,
    clear_sort,
    handle_filter,
    clear_filter,
    handle_header_click,
    end_header_edit,
    add_row,
    set_cell_widths,
    handle_blur,
    toggle_header_menu,
    delete_col_at,
    delete_row_at,
    commit_filter,
    scroll_to_top,
    add_row_at,
    add_col_at,
    handle_select_all,
    get_cell_display_value,
    value_is_output,
    column_widths,
    pinned_columns,
    display_value,
    styling,
    reset_sort_state,
    old_headers,
    old_val,
    previous_headers,
    previous_data,
    width_calc_timeout,
    width_calculated,
    previous_selected_cells,
    drag_handlers,
    selected,
    resize_handler,
    func2,
    search_handler,
    fullscreen_handler,
    tableheader_value_binding,
    tableheader_el_binding,
    td_binding,
    table_1_binding,
    func_1,
    tablecell_value_binding,
    tablecell_el_binding,
    tableheader_value_binding_1,
    tableheader_el_binding_1,
    virtualtable_items_binding,
    virtualtable_actual_height_binding,
    virtualtable_table_scrollbar_width_binding,
    virtualtable_viewport_binding,
    virtualtable_show_scroll_button_binding,
    upload_1_dragging_binding,
    load_handler,
    div0_binding,
    keydown_handler2,
    func_2,
    func_3,
    func_4,
    func_5,
    func_6,
    func_7,
    func_8,
    func_9,
    func_10,
    func_11,
    func_12,
    func_13,
    func_14,
    func_15
  ];
}
let Table$1 = class Table extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$8,
      create_fragment$8,
      safe_not_equal,
      {
        datatype: 2,
        label: 3,
        show_label: 4,
        headers: 0,
        values: 1,
        col_count: 5,
        row_count: 6,
        latex_delimiters: 7,
        components: 8,
        editable: 9,
        wrap: 10,
        root: 11,
        i18n: 12,
        max_height: 13,
        line_breaks: 14,
        column_widths: 75,
        show_row_numbers: 15,
        upload: 16,
        stream_handler: 17,
        show_fullscreen_button: 18,
        show_copy_button: 19,
        value_is_output: 74,
        max_chars: 20,
        show_search: 21,
        pinned_columns: 76,
        static_columns: 22,
        fullscreen: 23,
        display_value: 77,
        styling: 78,
        reset_sort_state: 79
      },
      null,
      [-1, -1, -1, -1, -1, -1]
    );
  }
  get reset_sort_state() {
    return this.$$.ctx[79];
  }
};
const get_coordinates_of_clicked_image = (evt) => {
  let image;
  if (evt.currentTarget instanceof Element) {
    image = evt.currentTarget.querySelector("img");
  } else {
    return [NaN, NaN];
  }
  const imageRect = image.getBoundingClientRect();
  const xScale = image.naturalWidth / imageRect.width;
  const yScale = image.naturalHeight / imageRect.height;
  if (xScale > yScale) {
    const displayed_height = image.naturalHeight / xScale;
    const y_offset = (imageRect.height - displayed_height) / 2;
    var x = Math.round((evt.clientX - imageRect.left) * xScale);
    var y = Math.round((evt.clientY - imageRect.top - y_offset) * xScale);
  } else {
    const displayed_width = image.naturalWidth / yScale;
    const x_offset = (imageRect.width - displayed_width) / 2;
    var x = Math.round((evt.clientX - imageRect.left - x_offset) * yScale);
    var y = Math.round((evt.clientY - imageRect.top) * yScale);
  }
  if (x < 0 || x >= image.naturalWidth || y < 0 || y >= image.naturalHeight) {
    return null;
  }
  return [x, y];
};
function create_fragment$7(ctx) {
  let img;
  let img_src_value;
  let mounted;
  let dispose;
  let img_levels = [
    { src: img_src_value = /*src*/
    ctx[0] },
    /*$$restProps*/
    ctx[1]
  ];
  let img_data = {};
  for (let i = 0; i < img_levels.length; i += 1) {
    img_data = assign(img_data, img_levels[i]);
  }
  return {
    c() {
      img = element("img");
      set_attributes(img, img_data);
      toggle_class(img, "svelte-kxeri3", true);
    },
    m(target, anchor) {
      insert(target, img, anchor);
      if (!mounted) {
        dispose = listen(
          img,
          "load",
          /*load_handler*/
          ctx[2]
        );
        mounted = true;
      }
    },
    p(ctx2, [dirty]) {
      set_attributes(img, img_data = get_spread_update(img_levels, [
        dirty & /*src*/
        1 && !src_url_equal(img.src, img_src_value = /*src*/
        ctx2[0]) && { src: img_src_value },
        dirty & /*$$restProps*/
        2 && /*$$restProps*/
        ctx2[1]
      ]));
      toggle_class(img, "svelte-kxeri3", true);
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) {
        detach(img);
      }
      mounted = false;
      dispose();
    }
  };
}
function instance$7($$self, $$props, $$invalidate) {
  const omit_props_names = ["src"];
  let $$restProps = compute_rest_props($$props, omit_props_names);
  let { src = void 0 } = $$props;
  function load_handler(event) {
    bubble.call(this, $$self, event);
  }
  $$self.$$set = ($$new_props) => {
    $$props = assign(assign({}, $$props), exclude_internal_props($$new_props));
    $$invalidate(1, $$restProps = compute_rest_props($$props, omit_props_names));
    if ("src" in $$new_props) $$invalidate(0, src = $$new_props.src);
  };
  return [src, $$restProps, load_handler];
}
class Image2 extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$7, create_fragment$7, safe_not_equal, { src: 0 });
  }
}
function create_else_block$2(ctx) {
  let div1;
  let iconbuttonwrapper;
  let t;
  let button;
  let div0;
  let image;
  let current;
  let mounted;
  let dispose;
  iconbuttonwrapper = new IconButtonWrapper({
    props: {
      display_top_corner: (
        /*display_icon_button_wrapper_top_corner*/
        ctx[8]
      ),
      $$slots: { default: [create_default_slot_1$2] },
      $$scope: { ctx }
    }
  });
  image = new Image2({
    props: {
      src: (
        /*value*/
        ctx[0].url
      ),
      alt: "",
      loading: "lazy"
    }
  });
  image.$on(
    "load",
    /*load_handler*/
    ctx[16]
  );
  return {
    c() {
      div1 = element("div");
      create_component(iconbuttonwrapper.$$.fragment);
      t = space();
      button = element("button");
      div0 = element("div");
      create_component(image.$$.fragment);
      attr(div0, "class", "image-frame svelte-x2tujq");
      toggle_class(
        div0,
        "selectable",
        /*selectable*/
        ctx[4]
      );
      attr(button, "class", "svelte-x2tujq");
      attr(div1, "class", "image-container svelte-x2tujq");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      mount_component(iconbuttonwrapper, div1, null);
      append(div1, t);
      append(div1, button);
      append(button, div0);
      mount_component(image, div0, null);
      ctx[17](div1);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*handle_click*/
          ctx[11]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const iconbuttonwrapper_changes = {};
      if (dirty & /*display_icon_button_wrapper_top_corner*/
      256) iconbuttonwrapper_changes.display_top_corner = /*display_icon_button_wrapper_top_corner*/
      ctx2[8];
      if (dirty & /*$$scope, i18n, value, show_share_button, show_download_button, fullscreen, show_fullscreen_button*/
      525033) {
        iconbuttonwrapper_changes.$$scope = { dirty, ctx: ctx2 };
      }
      iconbuttonwrapper.$set(iconbuttonwrapper_changes);
      const image_changes = {};
      if (dirty & /*value*/
      1) image_changes.src = /*value*/
      ctx2[0].url;
      image.$set(image_changes);
      if (!current || dirty & /*selectable*/
      16) {
        toggle_class(
          div0,
          "selectable",
          /*selectable*/
          ctx2[4]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(iconbuttonwrapper.$$.fragment, local);
      transition_in(image.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbuttonwrapper.$$.fragment, local);
      transition_out(image.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      destroy_component(iconbuttonwrapper);
      destroy_component(image);
      ctx[17](null);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block$3(ctx) {
  let empty_1;
  let current;
  empty_1 = new Empty({
    props: {
      unpadded_box: true,
      size: "large",
      $$slots: { default: [create_default_slot$3] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(empty_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(empty_1, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const empty_1_changes = {};
      if (dirty & /*$$scope*/
      524288) {
        empty_1_changes.$$scope = { dirty, ctx: ctx2 };
      }
      empty_1.$set(empty_1_changes);
    },
    i(local) {
      if (current) return;
      transition_in(empty_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(empty_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(empty_1, detaching);
    }
  };
}
function create_if_block_3$2(ctx) {
  let fullscreenbutton;
  let current;
  fullscreenbutton = new FullscreenButton({
    props: { fullscreen: (
      /*fullscreen*/
      ctx[9]
    ) }
  });
  fullscreenbutton.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[12]
  );
  return {
    c() {
      create_component(fullscreenbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(fullscreenbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const fullscreenbutton_changes = {};
      if (dirty & /*fullscreen*/
      512) fullscreenbutton_changes.fullscreen = /*fullscreen*/
      ctx2[9];
      fullscreenbutton.$set(fullscreenbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(fullscreenbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(fullscreenbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(fullscreenbutton, detaching);
    }
  };
}
function create_if_block_2$3(ctx) {
  let downloadlink;
  let current;
  downloadlink = new DownloadLink({
    props: {
      href: (
        /*value*/
        ctx[0].url
      ),
      download: (
        /*value*/
        ctx[0].orig_name || "image"
      ),
      $$slots: { default: [create_default_slot_2$1] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(downloadlink.$$.fragment);
    },
    m(target, anchor) {
      mount_component(downloadlink, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const downloadlink_changes = {};
      if (dirty & /*value*/
      1) downloadlink_changes.href = /*value*/
      ctx2[0].url;
      if (dirty & /*value*/
      1) downloadlink_changes.download = /*value*/
      ctx2[0].orig_name || "image";
      if (dirty & /*$$scope, i18n*/
      524352) {
        downloadlink_changes.$$scope = { dirty, ctx: ctx2 };
      }
      downloadlink.$set(downloadlink_changes);
    },
    i(local) {
      if (current) return;
      transition_in(downloadlink.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(downloadlink.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(downloadlink, detaching);
    }
  };
}
function create_default_slot_2$1(ctx) {
  let iconbutton;
  let current;
  iconbutton = new IconButton({
    props: {
      Icon: Download,
      label: (
        /*i18n*/
        ctx[6]("common.download")
      )
    }
  });
  return {
    c() {
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const iconbutton_changes = {};
      if (dirty & /*i18n*/
      64) iconbutton_changes.label = /*i18n*/
      ctx2[6]("common.download");
      iconbutton.$set(iconbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(iconbutton, detaching);
    }
  };
}
function create_if_block_1$3(ctx) {
  let sharebutton;
  let current;
  sharebutton = new ShareButton({
    props: {
      i18n: (
        /*i18n*/
        ctx[6]
      ),
      formatter: (
        /*func*/
        ctx[13]
      ),
      value: (
        /*value*/
        ctx[0]
      )
    }
  });
  sharebutton.$on(
    "share",
    /*share_handler*/
    ctx[14]
  );
  sharebutton.$on(
    "error",
    /*error_handler*/
    ctx[15]
  );
  return {
    c() {
      create_component(sharebutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(sharebutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const sharebutton_changes = {};
      if (dirty & /*i18n*/
      64) sharebutton_changes.i18n = /*i18n*/
      ctx2[6];
      if (dirty & /*value*/
      1) sharebutton_changes.value = /*value*/
      ctx2[0];
      sharebutton.$set(sharebutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(sharebutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(sharebutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(sharebutton, detaching);
    }
  };
}
function create_default_slot_1$2(ctx) {
  let t0;
  let t1;
  let if_block2_anchor;
  let current;
  let if_block0 = (
    /*show_fullscreen_button*/
    ctx[7] && create_if_block_3$2(ctx)
  );
  let if_block1 = (
    /*show_download_button*/
    ctx[3] && create_if_block_2$3(ctx)
  );
  let if_block2 = (
    /*show_share_button*/
    ctx[5] && create_if_block_1$3(ctx)
  );
  return {
    c() {
      if (if_block0) if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      if_block2_anchor = empty();
    },
    m(target, anchor) {
      if (if_block0) if_block0.m(target, anchor);
      insert(target, t0, anchor);
      if (if_block1) if_block1.m(target, anchor);
      insert(target, t1, anchor);
      if (if_block2) if_block2.m(target, anchor);
      insert(target, if_block2_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*show_fullscreen_button*/
        ctx2[7]
      ) {
        if (if_block0) {
          if_block0.p(ctx2, dirty);
          if (dirty & /*show_fullscreen_button*/
          128) {
            transition_in(if_block0, 1);
          }
        } else {
          if_block0 = create_if_block_3$2(ctx2);
          if_block0.c();
          transition_in(if_block0, 1);
          if_block0.m(t0.parentNode, t0);
        }
      } else if (if_block0) {
        group_outros();
        transition_out(if_block0, 1, 1, () => {
          if_block0 = null;
        });
        check_outros();
      }
      if (
        /*show_download_button*/
        ctx2[3]
      ) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty & /*show_download_button*/
          8) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_2$3(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(t1.parentNode, t1);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*show_share_button*/
        ctx2[5]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty & /*show_share_button*/
          32) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_1$3(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(t1);
        detach(if_block2_anchor);
      }
      if (if_block0) if_block0.d(detaching);
      if (if_block1) if_block1.d(detaching);
      if (if_block2) if_block2.d(detaching);
    }
  };
}
function create_default_slot$3(ctx) {
  let imageicon;
  let current;
  imageicon = new Image$1({});
  return {
    c() {
      create_component(imageicon.$$.fragment);
    },
    m(target, anchor) {
      mount_component(imageicon, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(imageicon.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(imageicon.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(imageicon, detaching);
    }
  };
}
function create_fragment$6(ctx) {
  let blocklabel;
  let t;
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  blocklabel = new BlockLabel({
    props: {
      show_label: (
        /*show_label*/
        ctx[2]
      ),
      Icon: Image$1,
      label: !/*show_label*/
      ctx[2] ? "" : (
        /*label*/
        ctx[1] || /*i18n*/
        ctx[6]("image.image")
      )
    }
  });
  const if_block_creators = [create_if_block$3, create_else_block$2];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*value*/
      ctx2[0] === null || !/*value*/
      ctx2[0].url
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      create_component(blocklabel.$$.fragment);
      t = space();
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      mount_component(blocklabel, target, anchor);
      insert(target, t, anchor);
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const blocklabel_changes = {};
      if (dirty & /*show_label*/
      4) blocklabel_changes.show_label = /*show_label*/
      ctx2[2];
      if (dirty & /*show_label, label, i18n*/
      70) blocklabel_changes.label = !/*show_label*/
      ctx2[2] ? "" : (
        /*label*/
        ctx2[1] || /*i18n*/
        ctx2[6]("image.image")
      );
      blocklabel.$set(blocklabel_changes);
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(blocklabel.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(blocklabel.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
        detach(if_block_anchor);
      }
      destroy_component(blocklabel, detaching);
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance$6($$self, $$props, $$invalidate) {
  let { value } = $$props;
  let { label = void 0 } = $$props;
  let { show_label } = $$props;
  let { show_download_button = true } = $$props;
  let { selectable = false } = $$props;
  let { show_share_button = false } = $$props;
  let { i18n } = $$props;
  let { show_fullscreen_button = true } = $$props;
  let { display_icon_button_wrapper_top_corner = false } = $$props;
  let { fullscreen = false } = $$props;
  const dispatch2 = createEventDispatcher();
  const handle_click = (evt) => {
    let coordinates = get_coordinates_of_clicked_image(evt);
    if (coordinates) {
      dispatch2("select", { index: coordinates, value: null });
    }
  };
  let image_container;
  function fullscreen_handler(event) {
    bubble.call(this, $$self, event);
  }
  const func2 = async (value2) => {
    if (!value2) return "";
    let url = await uploadToHuggingFace(value2);
    return `<img src="${url}" />`;
  };
  function share_handler(event) {
    bubble.call(this, $$self, event);
  }
  function error_handler(event) {
    bubble.call(this, $$self, event);
  }
  function load_handler(event) {
    bubble.call(this, $$self, event);
  }
  function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      image_container = $$value;
      $$invalidate(10, image_container);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("label" in $$props2) $$invalidate(1, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(2, show_label = $$props2.show_label);
    if ("show_download_button" in $$props2) $$invalidate(3, show_download_button = $$props2.show_download_button);
    if ("selectable" in $$props2) $$invalidate(4, selectable = $$props2.selectable);
    if ("show_share_button" in $$props2) $$invalidate(5, show_share_button = $$props2.show_share_button);
    if ("i18n" in $$props2) $$invalidate(6, i18n = $$props2.i18n);
    if ("show_fullscreen_button" in $$props2) $$invalidate(7, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("display_icon_button_wrapper_top_corner" in $$props2) $$invalidate(8, display_icon_button_wrapper_top_corner = $$props2.display_icon_button_wrapper_top_corner);
    if ("fullscreen" in $$props2) $$invalidate(9, fullscreen = $$props2.fullscreen);
  };
  return [
    value,
    label,
    show_label,
    show_download_button,
    selectable,
    show_share_button,
    i18n,
    show_fullscreen_button,
    display_icon_button_wrapper_top_corner,
    fullscreen,
    image_container,
    handle_click,
    fullscreen_handler,
    func2,
    share_handler,
    error_handler,
    load_handler,
    div1_binding
  ];
}
class ImagePreview extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$6, create_fragment$6, safe_not_equal, {
      value: 0,
      label: 1,
      show_label: 2,
      show_download_button: 3,
      selectable: 4,
      show_share_button: 5,
      i18n: 6,
      show_fullscreen_button: 7,
      display_icon_button_wrapper_top_corner: 8,
      fullscreen: 9
    });
  }
}
function create_fragment$5(ctx) {
  let button;
  let div;
  let span;
  let webcam;
  let t0;
  let t1_value = "Click to Access Webcam";
  let t1;
  let current;
  let mounted;
  let dispose;
  webcam = new Webcam$1({});
  return {
    c() {
      button = element("button");
      div = element("div");
      span = element("span");
      create_component(webcam.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(span, "class", "icon-wrap svelte-fjcd9c");
      attr(div, "class", "wrap svelte-fjcd9c");
      attr(button, "class", "svelte-fjcd9c");
      set_style(button, "height", `100%`);
    },
    m(target, anchor) {
      insert(target, button, anchor);
      append(button, div);
      append(div, span);
      mount_component(webcam, span, null);
      append(div, t0);
      append(div, t1);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler*/
          ctx[1]
        );
        mounted = true;
      }
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(webcam.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(webcam.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(webcam);
      mounted = false;
      dispose();
    }
  };
}
function instance$5($$self) {
  const dispatch2 = createEventDispatcher();
  const click_handler = () => dispatch2("click");
  return [dispatch2, click_handler];
}
class WebcamPermissions extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance$5, create_fragment$5, safe_not_equal, {});
  }
}
function get_devices() {
  return navigator.mediaDevices.enumerateDevices();
}
function set_local_stream(local_stream, video_source) {
  video_source.srcObject = local_stream;
  video_source.muted = true;
  video_source.play();
}
async function get_video_stream(include_audio, video_source, webcam_constraints, device_id) {
  const constraints = {
    video: device_id ? { deviceId: { exact: device_id }, ...webcam_constraints == null ? void 0 : webcam_constraints.video } : (webcam_constraints == null ? void 0 : webcam_constraints.video) || {
      width: { ideal: 1920 },
      height: { ideal: 1440 }
    },
    audio: include_audio && ((webcam_constraints == null ? void 0 : webcam_constraints.audio) ?? true)
    // Defaults to true if not specified
  };
  return navigator.mediaDevices.getUserMedia(constraints).then((local_stream) => {
    set_local_stream(local_stream, video_source);
    return local_stream;
  });
}
function set_available_devices(devices) {
  const cameras = devices.filter(
    (device) => device.kind === "videoinput"
  );
  return cameras;
}
function get_each_context(ctx, list2, i) {
  const child_ctx = ctx.slice();
  child_ctx[39] = list2[i];
  return child_ctx;
}
function create_else_block$1(ctx) {
  let div;
  let button;
  let current_block_type_index;
  let if_block0;
  let button_aria_label_value;
  let t0;
  let t1;
  let if_block2_anchor;
  let current;
  let mounted;
  let dispose;
  const if_block_creators = [create_if_block_4$1, create_else_block_3];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*mode*/
      ctx2[2] === "video" || /*streaming*/
      ctx2[1]
    ) return 0;
    return 1;
  }
  current_block_type_index = select_block_type_1(ctx);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = !/*recording*/
  ctx[11] && create_if_block_3$1(ctx);
  let if_block2 = (
    /*options_open*/
    ctx[13] && /*selected_device*/
    ctx[8] && create_if_block_1$2(ctx)
  );
  return {
    c() {
      div = element("div");
      button = element("button");
      if_block0.c();
      t0 = space();
      if (if_block1) if_block1.c();
      t1 = space();
      if (if_block2) if_block2.c();
      if_block2_anchor = empty();
      attr(button, "aria-label", button_aria_label_value = /*mode*/
      ctx[2] === "image" ? "capture photo" : "start recording");
      attr(button, "class", "svelte-1tdan5a");
      attr(div, "class", "button-wrap svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      append(div, button);
      if_blocks[current_block_type_index].m(button, null);
      append(div, t0);
      if (if_block1) if_block1.m(div, null);
      insert(target, t1, anchor);
      if (if_block2) if_block2.m(target, anchor);
      insert(target, if_block2_anchor, anchor);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_1*/
          ctx[28]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        } else {
          if_block0.p(ctx2, dirty);
        }
        transition_in(if_block0, 1);
        if_block0.m(button, null);
      }
      if (!current || dirty[0] & /*mode*/
      4 && button_aria_label_value !== (button_aria_label_value = /*mode*/
      ctx2[2] === "image" ? "capture photo" : "start recording")) {
        attr(button, "aria-label", button_aria_label_value);
      }
      if (!/*recording*/
      ctx2[11]) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*recording*/
          2048) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block_3$1(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
      if (
        /*options_open*/
        ctx2[13] && /*selected_device*/
        ctx2[8]
      ) {
        if (if_block2) {
          if_block2.p(ctx2, dirty);
          if (dirty[0] & /*options_open, selected_device*/
          8448) {
            transition_in(if_block2, 1);
          }
        } else {
          if_block2 = create_if_block_1$2(ctx2);
          if_block2.c();
          transition_in(if_block2, 1);
          if_block2.m(if_block2_anchor.parentNode, if_block2_anchor);
        }
      } else if (if_block2) {
        group_outros();
        transition_out(if_block2, 1, 1, () => {
          if_block2 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block0);
      transition_in(if_block1);
      transition_in(if_block2);
      current = true;
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      transition_out(if_block2);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
        detach(t1);
        detach(if_block2_anchor);
      }
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d(detaching);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block$2(ctx) {
  let div;
  let webcampermissions;
  let div_intro;
  let current;
  webcampermissions = new WebcamPermissions({});
  webcampermissions.$on(
    "click",
    /*click_handler*/
    ctx[27]
  );
  return {
    c() {
      div = element("div");
      create_component(webcampermissions.$$.fragment);
      attr(div, "title", "grant webcam access");
      set_style(div, "height", "100%");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(webcampermissions, div, null);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(webcampermissions.$$.fragment, local);
      if (local) {
        if (!div_intro) {
          add_render_callback(() => {
            div_intro = create_in_transition(div, fade, { delay: 100, duration: 200 });
            div_intro.start();
          });
        }
      }
      current = true;
    },
    o(local) {
      transition_out(webcampermissions.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(webcampermissions);
    }
  };
}
function create_else_block_3(ctx) {
  let div;
  let camera;
  let current;
  camera = new Camera({});
  return {
    c() {
      div = element("div");
      create_component(camera.$$.fragment);
      attr(div, "class", "icon svelte-1tdan5a");
      attr(div, "title", "capture photo");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(camera, div, null);
      current = true;
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(camera.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(camera.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(camera);
    }
  };
}
function create_if_block_4$1(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_5$1, create_if_block_6$1, create_else_block_2];
  const if_blocks = [];
  function select_block_type_2(ctx2, dirty) {
    if (
      /*streaming*/
      ctx2[1] && /*stream_state*/
      ctx2[10] === "waiting"
    ) return 0;
    if (
      /*streaming*/
      ctx2[1] && /*stream_state*/
      ctx2[10] === "open" || !/*streaming*/
      ctx2[1] && /*recording*/
      ctx2[11]
    ) return 1;
    return 2;
  }
  current_block_type_index = select_block_type_2(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_2(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function create_else_block_2(ctx) {
  let div1;
  let div0;
  let circle;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[4]("audio.record") + ""
  );
  let t1;
  let current;
  circle = new Circle({});
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      create_component(circle.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(div0, "class", "icon color-primary svelte-1tdan5a");
      attr(div0, "title", "start recording");
      attr(div1, "class", "icon-with-text svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      mount_component(circle, div0, null);
      append(div1, t0);
      append(div1, t1);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*i18n*/
      16) && t1_value !== (t1_value = /*i18n*/
      ctx2[4]("audio.record") + "")) set_data(t1, t1_value);
    },
    i(local) {
      if (current) return;
      transition_in(circle.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(circle.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      destroy_component(circle);
    }
  };
}
function create_if_block_6$1(ctx) {
  let div1;
  let div0;
  let square;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[4]("audio.stop") + ""
  );
  let t1;
  let current;
  square = new Square({});
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      create_component(square.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(div0, "class", "icon color-primary svelte-1tdan5a");
      attr(div0, "title", "stop recording");
      attr(div1, "class", "icon-with-text svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      mount_component(square, div0, null);
      append(div1, t0);
      append(div1, t1);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*i18n*/
      16) && t1_value !== (t1_value = /*i18n*/
      ctx2[4]("audio.stop") + "")) set_data(t1, t1_value);
    },
    i(local) {
      if (current) return;
      transition_in(square.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(square.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      destroy_component(square);
    }
  };
}
function create_if_block_5$1(ctx) {
  let div1;
  let div0;
  let spinner;
  let t0;
  let t1_value = (
    /*i18n*/
    ctx[4]("audio.waiting") + ""
  );
  let t1;
  let current;
  spinner = new Spinner({});
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      create_component(spinner.$$.fragment);
      t0 = space();
      t1 = text(t1_value);
      attr(div0, "class", "icon color-primary svelte-1tdan5a");
      attr(div0, "title", "spinner");
      attr(div1, "class", "icon-with-text svelte-1tdan5a");
      set_style(div1, "width", "var(--size-24)");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      mount_component(spinner, div0, null);
      append(div1, t0);
      append(div1, t1);
      current = true;
    },
    p(ctx2, dirty) {
      if ((!current || dirty[0] & /*i18n*/
      16) && t1_value !== (t1_value = /*i18n*/
      ctx2[4]("audio.waiting") + "")) set_data(t1, t1_value);
    },
    i(local) {
      if (current) return;
      transition_in(spinner.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(spinner.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div1);
      }
      destroy_component(spinner);
    }
  };
}
function create_if_block_3$1(ctx) {
  let button;
  let dropdownarrow;
  let current;
  let mounted;
  let dispose;
  dropdownarrow = new DropdownArrow({});
  return {
    c() {
      button = element("button");
      create_component(dropdownarrow.$$.fragment);
      attr(button, "class", "icon svelte-1tdan5a");
      attr(button, "aria-label", "select input source");
    },
    m(target, anchor) {
      insert(target, button, anchor);
      mount_component(dropdownarrow, button, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          button,
          "click",
          /*click_handler_2*/
          ctx[29]
        );
        mounted = true;
      }
    },
    p: noop,
    i(local) {
      if (current) return;
      transition_in(dropdownarrow.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropdownarrow.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(button);
      }
      destroy_component(dropdownarrow);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_1$2(ctx) {
  let select;
  let button;
  let dropdownarrow;
  let t;
  let current;
  let mounted;
  let dispose;
  dropdownarrow = new DropdownArrow({});
  function select_block_type_3(ctx2, dirty) {
    if (
      /*available_video_devices*/
      ctx2[7].length === 0
    ) return create_if_block_2$2;
    return create_else_block_1$1;
  }
  let current_block_type = select_block_type_3(ctx);
  let if_block = current_block_type(ctx);
  return {
    c() {
      select = element("select");
      button = element("button");
      create_component(dropdownarrow.$$.fragment);
      t = space();
      if_block.c();
      attr(button, "class", "inset-icon svelte-1tdan5a");
      attr(select, "class", "select-wrap svelte-1tdan5a");
      attr(select, "aria-label", "select source");
    },
    m(target, anchor) {
      insert(target, select, anchor);
      append(select, button);
      mount_component(dropdownarrow, button, null);
      append(button, t);
      if_block.m(select, null);
      current = true;
      if (!mounted) {
        dispose = [
          listen(button, "click", stop_propagation(
            /*click_handler_3*/
            ctx[30]
          )),
          action_destroyer(click_outside.call(
            null,
            select,
            /*handle_click_outside*/
            ctx[17]
          )),
          listen(
            select,
            "change",
            /*handle_device_change*/
            ctx[14]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_3(ctx2)) && if_block) {
        if_block.p(ctx2, dirty);
      } else {
        if_block.d(1);
        if_block = current_block_type(ctx2);
        if (if_block) {
          if_block.c();
          if_block.m(select, null);
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(dropdownarrow.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(dropdownarrow.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(select);
      }
      destroy_component(dropdownarrow);
      if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}
function create_else_block_1$1(ctx) {
  let each_1_anchor;
  let each_value = ensure_array_like(
    /*available_video_devices*/
    ctx[7]
  );
  let each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) {
    each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
  }
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) {
        each_blocks[i].c();
      }
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) {
        if (each_blocks[i]) {
          each_blocks[i].m(target, anchor);
        }
      }
      insert(target, each_1_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*available_video_devices, selected_device*/
      384) {
        each_value = ensure_array_like(
          /*available_video_devices*/
          ctx2[7]
        );
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
          } else {
            each_blocks[i] = create_each_block(child_ctx);
            each_blocks[i].c();
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        for (; i < each_blocks.length; i += 1) {
          each_blocks[i].d(1);
        }
        each_blocks.length = each_value.length;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(each_1_anchor);
      }
      destroy_each(each_blocks, detaching);
    }
  };
}
function create_if_block_2$2(ctx) {
  let option;
  let t_value = (
    /*i18n*/
    ctx[4]("common.no_devices") + ""
  );
  let t;
  return {
    c() {
      option = element("option");
      t = text(t_value);
      option.__value = "";
      set_input_value(option, option.__value);
      attr(option, "class", "svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*i18n*/
      16 && t_value !== (t_value = /*i18n*/
      ctx2[4]("common.no_devices") + "")) set_data(t, t_value);
    },
    d(detaching) {
      if (detaching) {
        detach(option);
      }
    }
  };
}
function create_each_block(ctx) {
  let option;
  let t0_value = (
    /*device*/
    ctx[39].label + ""
  );
  let t0;
  let t1;
  let option_value_value;
  let option_selected_value;
  return {
    c() {
      option = element("option");
      t0 = text(t0_value);
      t1 = space();
      option.__value = option_value_value = /*device*/
      ctx[39].deviceId;
      set_input_value(option, option.__value);
      option.selected = option_selected_value = /*selected_device*/
      ctx[8].deviceId === /*device*/
      ctx[39].deviceId;
      attr(option, "class", "svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, option, anchor);
      append(option, t0);
      append(option, t1);
    },
    p(ctx2, dirty) {
      if (dirty[0] & /*available_video_devices*/
      128 && t0_value !== (t0_value = /*device*/
      ctx2[39].label + "")) set_data(t0, t0_value);
      if (dirty[0] & /*available_video_devices*/
      128 && option_value_value !== (option_value_value = /*device*/
      ctx2[39].deviceId)) {
        option.__value = option_value_value;
        set_input_value(option, option.__value);
      }
      if (dirty[0] & /*selected_device, available_video_devices*/
      384 && option_selected_value !== (option_selected_value = /*selected_device*/
      ctx2[8].deviceId === /*device*/
      ctx2[39].deviceId)) {
        option.selected = option_selected_value;
      }
    },
    d(detaching) {
      if (detaching) {
        detach(option);
      }
    }
  };
}
function create_fragment$4(ctx) {
  let div;
  let streamingbar;
  let t0;
  let video;
  let t1;
  let img;
  let img_src_value;
  let t2;
  let current_block_type_index;
  let if_block;
  let current;
  streamingbar = new StreamingBar({
    props: { time_limit: (
      /*time_limit*/
      ctx[9]
    ) }
  });
  const if_block_creators = [create_if_block$2, create_else_block$1];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (!/*webcam_accessed*/
    ctx2[12]) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      var _a;
      div = element("div");
      create_component(streamingbar.$$.fragment);
      t0 = space();
      video = element("video");
      t1 = space();
      img = element("img");
      t2 = space();
      if_block.c();
      attr(video, "class", "svelte-1tdan5a");
      toggle_class(
        video,
        "flip",
        /*mirror_webcam*/
        ctx[3]
      );
      toggle_class(video, "hide", !/*webcam_accessed*/
      ctx[12] || /*webcam_accessed*/
      ctx[12] && !!/*value*/
      ctx[0]);
      if (!src_url_equal(img.src, img_src_value = /*value*/
      (_a = ctx[0]) == null ? void 0 : _a.url)) attr(img, "src", img_src_value);
      attr(img, "class", "svelte-1tdan5a");
      toggle_class(img, "hide", !/*webcam_accessed*/
      ctx[12] || /*webcam_accessed*/
      ctx[12] && !/*value*/
      ctx[0]);
      attr(div, "class", "wrap svelte-1tdan5a");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(streamingbar, div, null);
      append(div, t0);
      append(div, video);
      ctx[26](video);
      append(div, t1);
      append(div, img);
      append(div, t2);
      if_blocks[current_block_type_index].m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      var _a;
      const streamingbar_changes = {};
      if (dirty[0] & /*time_limit*/
      512) streamingbar_changes.time_limit = /*time_limit*/
      ctx2[9];
      streamingbar.$set(streamingbar_changes);
      if (!current || dirty[0] & /*mirror_webcam*/
      8) {
        toggle_class(
          video,
          "flip",
          /*mirror_webcam*/
          ctx2[3]
        );
      }
      if (!current || dirty[0] & /*webcam_accessed, value*/
      4097) {
        toggle_class(video, "hide", !/*webcam_accessed*/
        ctx2[12] || /*webcam_accessed*/
        ctx2[12] && !!/*value*/
        ctx2[0]);
      }
      if (!current || dirty[0] & /*value*/
      1 && !src_url_equal(img.src, img_src_value = /*value*/
      (_a = ctx2[0]) == null ? void 0 : _a.url)) {
        attr(img, "src", img_src_value);
      }
      if (!current || dirty[0] & /*webcam_accessed, value*/
      4097) {
        toggle_class(img, "hide", !/*webcam_accessed*/
        ctx2[12] || /*webcam_accessed*/
        ctx2[12] && !/*value*/
        ctx2[0]);
      }
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(div, null);
      }
    },
    i(local) {
      if (current) return;
      transition_in(streamingbar.$$.fragment, local);
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(streamingbar.$$.fragment, local);
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(streamingbar);
      ctx[26](null);
      if_blocks[current_block_type_index].d();
    }
  };
}
function click_outside(node, cb) {
  const handle_click = (event) => {
    if (node && !node.contains(event.target) && !event.defaultPrevented) {
      cb(event);
    }
  };
  document.addEventListener("click", handle_click, true);
  return {
    destroy() {
      document.removeEventListener("click", handle_click, true);
    }
  };
}
function instance$4($$self, $$props, $$invalidate) {
  let video_source;
  let available_video_devices = [];
  let selected_device = null;
  let time_limit = null;
  let stream_state = "closed";
  const modify_stream = (state) => {
    if (state === "closed") {
      $$invalidate(9, time_limit = null);
      $$invalidate(10, stream_state = "closed");
      $$invalidate(0, value = null);
    } else if (state === "waiting") {
      $$invalidate(10, stream_state = "waiting");
    } else {
      $$invalidate(10, stream_state = "open");
    }
  };
  const set_time_limit = (time) => {
    if (recording) $$invalidate(9, time_limit = time);
  };
  let canvas;
  let { streaming = false } = $$props;
  let { pending = false } = $$props;
  let { root = "" } = $$props;
  let { stream_every = 1 } = $$props;
  let { mode = "image" } = $$props;
  let { mirror_webcam } = $$props;
  let { include_audio } = $$props;
  let { webcam_constraints = null } = $$props;
  let { i18n } = $$props;
  let { upload } = $$props;
  let { value = null } = $$props;
  const dispatch2 = createEventDispatcher();
  onMount(() => {
    canvas = document.createElement("canvas");
    if (streaming && mode === "image") {
      window.setInterval(
        () => {
          if (video_source && !pending) {
            take_picture();
          }
        },
        stream_every * 1e3
      );
    }
  });
  const handle_device_change = async (event) => {
    const target = event.target;
    const device_id = target.value;
    await get_video_stream(include_audio, video_source, webcam_constraints, device_id).then(async (local_stream) => {
      stream = local_stream;
      $$invalidate(8, selected_device = available_video_devices.find((device) => device.deviceId === device_id) || null);
      $$invalidate(13, options_open = false);
    });
  };
  async function access_webcam() {
    try {
      get_video_stream(include_audio, video_source, webcam_constraints).then(async (local_stream) => {
        $$invalidate(12, webcam_accessed = true);
        $$invalidate(7, available_video_devices = await get_devices());
        stream = local_stream;
      }).then(() => set_available_devices(available_video_devices)).then((devices) => {
        $$invalidate(7, available_video_devices = devices);
        const used_devices = stream.getTracks().map((track) => {
          var _a;
          return (_a = track.getSettings()) == null ? void 0 : _a.deviceId;
        })[0];
        $$invalidate(8, selected_device = used_devices ? devices.find((device) => device.deviceId === used_devices) || available_video_devices[0] : available_video_devices[0]);
      });
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        dispatch2("error", i18n("image.no_webcam_support"));
      }
    } catch (err) {
      if (err instanceof DOMException && err.name == "NotAllowedError") {
        dispatch2("error", i18n("image.allow_webcam_access"));
      } else {
        throw err;
      }
    }
  }
  function take_picture() {
    var context = canvas.getContext("2d");
    if ((!streaming || streaming && recording) && video_source.videoWidth && video_source.videoHeight) {
      canvas.width = video_source.videoWidth;
      canvas.height = video_source.videoHeight;
      context.drawImage(video_source, 0, 0, video_source.videoWidth, video_source.videoHeight);
      if (mirror_webcam) {
        context.scale(-1, 1);
        context.drawImage(video_source, -video_source.videoWidth, 0);
      }
      if (streaming && (!recording || stream_state === "waiting")) {
        return;
      }
      if (streaming) {
        const image_data = canvas.toDataURL("image/jpeg");
        dispatch2("stream", image_data);
        return;
      }
      canvas.toBlob(
        (blob) => {
          dispatch2(streaming ? "stream" : "capture", blob);
        },
        `image/${streaming ? "jpeg" : "png"}`,
        0.8
      );
    }
  }
  let recording = false;
  let recorded_blobs = [];
  let stream;
  let mimeType;
  let media_recorder;
  function take_recording() {
    if (recording) {
      media_recorder.stop();
      let video_blob = new Blob(recorded_blobs, { type: mimeType });
      let ReaderObj = new FileReader();
      ReaderObj.onload = async function(e) {
        var _a;
        if (e.target) {
          let _video_blob = new File([video_blob], "sample." + mimeType.substring(6));
          const val = await prepare_files([_video_blob]);
          let val_ = (_a = await upload(val, root)) == null ? void 0 : _a.filter(Boolean)[0];
          dispatch2("capture", val_);
          dispatch2("stop_recording");
        }
      };
      ReaderObj.readAsDataURL(video_blob);
    } else if (typeof MediaRecorder !== "undefined") {
      dispatch2("start_recording");
      recorded_blobs = [];
      let validMimeTypes = ["video/webm", "video/mp4"];
      for (let validMimeType of validMimeTypes) {
        if (MediaRecorder.isTypeSupported(validMimeType)) {
          mimeType = validMimeType;
          break;
        }
      }
      if (mimeType === null) {
        console.error("No supported MediaRecorder mimeType");
        return;
      }
      media_recorder = new MediaRecorder(stream, { mimeType });
      media_recorder.addEventListener("dataavailable", function(e) {
        recorded_blobs.push(e.data);
      });
      media_recorder.start(200);
    }
    $$invalidate(11, recording = !recording);
  }
  let webcam_accessed = false;
  function record_video_or_photo({ destroy } = {}) {
    if (mode === "image" && streaming) {
      $$invalidate(11, recording = !recording);
    }
    if (!destroy) {
      if (mode === "image") {
        take_picture();
      } else {
        take_recording();
      }
    }
    if (!recording && stream) {
      dispatch2("close_stream");
      stream.getTracks().forEach((track) => track.stop());
      $$invalidate(6, video_source.srcObject = null, video_source);
      $$invalidate(12, webcam_accessed = false);
      window.setTimeout(
        () => {
          $$invalidate(0, value = null);
        },
        500
      );
      $$invalidate(0, value = null);
    }
  }
  let options_open = false;
  function handle_click_outside2(event) {
    event.preventDefault();
    event.stopPropagation();
    $$invalidate(13, options_open = false);
  }
  onDestroy(() => {
    if (typeof window === "undefined") return;
    record_video_or_photo({ destroy: true });
    stream == null ? void 0 : stream.getTracks().forEach((track) => track.stop());
  });
  function video_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      video_source = $$value;
      $$invalidate(6, video_source);
    });
  }
  const click_handler = async () => access_webcam();
  const click_handler_1 = () => record_video_or_photo();
  const click_handler_2 = () => $$invalidate(13, options_open = true);
  const click_handler_3 = () => $$invalidate(13, options_open = false);
  $$self.$$set = ($$props2) => {
    if ("streaming" in $$props2) $$invalidate(1, streaming = $$props2.streaming);
    if ("pending" in $$props2) $$invalidate(20, pending = $$props2.pending);
    if ("root" in $$props2) $$invalidate(21, root = $$props2.root);
    if ("stream_every" in $$props2) $$invalidate(22, stream_every = $$props2.stream_every);
    if ("mode" in $$props2) $$invalidate(2, mode = $$props2.mode);
    if ("mirror_webcam" in $$props2) $$invalidate(3, mirror_webcam = $$props2.mirror_webcam);
    if ("include_audio" in $$props2) $$invalidate(23, include_audio = $$props2.include_audio);
    if ("webcam_constraints" in $$props2) $$invalidate(24, webcam_constraints = $$props2.webcam_constraints);
    if ("i18n" in $$props2) $$invalidate(4, i18n = $$props2.i18n);
    if ("upload" in $$props2) $$invalidate(25, upload = $$props2.upload);
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
  };
  return [
    value,
    streaming,
    mode,
    mirror_webcam,
    i18n,
    click_outside,
    video_source,
    available_video_devices,
    selected_device,
    time_limit,
    stream_state,
    recording,
    webcam_accessed,
    options_open,
    handle_device_change,
    access_webcam,
    record_video_or_photo,
    handle_click_outside2,
    modify_stream,
    set_time_limit,
    pending,
    root,
    stream_every,
    include_audio,
    webcam_constraints,
    upload,
    video_binding,
    click_handler,
    click_handler_1,
    click_handler_2,
    click_handler_3
  ];
}
class Webcam2 extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$4,
      create_fragment$4,
      safe_not_equal,
      {
        modify_stream: 18,
        set_time_limit: 19,
        streaming: 1,
        pending: 20,
        root: 21,
        stream_every: 22,
        mode: 2,
        mirror_webcam: 3,
        include_audio: 23,
        webcam_constraints: 24,
        i18n: 4,
        upload: 25,
        value: 0,
        click_outside: 5
      },
      null,
      [-1, -1]
    );
  }
  get modify_stream() {
    return this.$$.ctx[18];
  }
  get set_time_limit() {
    return this.$$.ctx[19];
  }
  get click_outside() {
    return click_outside;
  }
}
function create_if_block_5(ctx) {
  let t;
  let iconbutton;
  let current;
  let if_block = (
    /*show_fullscreen_button*/
    ctx[19] && create_if_block_6(ctx)
  );
  iconbutton = new IconButton({
    props: { Icon: Clear, label: "Remove Image" }
  });
  iconbutton.$on(
    "click",
    /*handle_remove_image_click*/
    ctx[28]
  );
  return {
    c() {
      if (if_block) if_block.c();
      t = space();
      create_component(iconbutton.$$.fragment);
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, t, anchor);
      mount_component(iconbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*show_fullscreen_button*/
        ctx2[19]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*show_fullscreen_button*/
          524288) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_6(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(t.parentNode, t);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      transition_in(iconbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      transition_out(iconbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
      if (if_block) if_block.d(detaching);
      destroy_component(iconbutton, detaching);
    }
  };
}
function create_if_block_6(ctx) {
  let fullscreenbutton;
  let current;
  fullscreenbutton = new FullscreenButton({
    props: { fullscreen: (
      /*fullscreen*/
      ctx[20]
    ) }
  });
  fullscreenbutton.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[35]
  );
  return {
    c() {
      create_component(fullscreenbutton.$$.fragment);
    },
    m(target, anchor) {
      mount_component(fullscreenbutton, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const fullscreenbutton_changes = {};
      if (dirty[0] & /*fullscreen*/
      1048576) fullscreenbutton_changes.fullscreen = /*fullscreen*/
      ctx2[20];
      fullscreenbutton.$set(fullscreenbutton_changes);
    },
    i(local) {
      if (current) return;
      transition_in(fullscreenbutton.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(fullscreenbutton.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(fullscreenbutton, detaching);
    }
  };
}
function create_default_slot_1$1(ctx) {
  var _a;
  let if_block_anchor;
  let current;
  let if_block = (
    /*value*/
    ((_a = ctx[3]) == null ? void 0 : _a.url) && !/*active_streaming*/
    ctx[21] && create_if_block_5(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      var _a2;
      if (
        /*value*/
        ((_a2 = ctx2[3]) == null ? void 0 : _a2.url) && !/*active_streaming*/
        ctx2[21]
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*value, active_streaming*/
          2097160) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_5(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block_4(ctx) {
  let current;
  const default_slot_template = (
    /*#slots*/
    ctx[34].default
  );
  const default_slot = create_slot(
    default_slot_template,
    ctx,
    /*$$scope*/
    ctx[50],
    null
  );
  return {
    c() {
      if (default_slot) default_slot.c();
    },
    m(target, anchor) {
      if (default_slot) {
        default_slot.m(target, anchor);
      }
      current = true;
    },
    p(ctx2, dirty) {
      if (default_slot) {
        if (default_slot.p && (!current || dirty[1] & /*$$scope*/
        524288)) {
          update_slot_base(
            default_slot,
            default_slot_template,
            ctx2,
            /*$$scope*/
            ctx2[50],
            !current ? get_all_dirty_from_scope(
              /*$$scope*/
              ctx2[50]
            ) : get_slot_changes(
              default_slot_template,
              /*$$scope*/
              ctx2[50],
              dirty,
              null
            ),
            null
          );
        }
      }
    },
    i(local) {
      if (current) return;
      transition_in(default_slot, local);
      current = true;
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (default_slot) default_slot.d(detaching);
    }
  };
}
function create_default_slot$2(ctx) {
  let if_block_anchor;
  let current;
  let if_block = (
    /*value*/
    ctx[3] === null && create_if_block_4(ctx)
  );
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (
        /*value*/
        ctx2[3] === null
      ) {
        if (if_block) {
          if_block.p(ctx2, dirty);
          if (dirty[0] & /*value*/
          8) {
            transition_in(if_block, 1);
          }
        } else {
          if_block = create_if_block_4(ctx2);
          if_block.c();
          transition_in(if_block, 1);
          if_block.m(if_block_anchor.parentNode, if_block_anchor);
        }
      } else if (if_block) {
        group_outros();
        transition_out(if_block, 1, 1, () => {
          if_block = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if (if_block) if_block.d(detaching);
    }
  };
}
function create_if_block_3(ctx) {
  let div;
  let image;
  let current;
  let mounted;
  let dispose;
  image = new Image2({
    props: {
      src: (
        /*value*/
        ctx[3].url
      ),
      alt: (
        /*value*/
        ctx[3].alt_text
      )
    }
  });
  return {
    c() {
      div = element("div");
      create_component(image.$$.fragment);
      attr(div, "class", "image-frame svelte-1562gr6");
      toggle_class(
        div,
        "selectable",
        /*selectable*/
        ctx[12]
      );
    },
    m(target, anchor) {
      insert(target, div, anchor);
      mount_component(image, div, null);
      current = true;
      if (!mounted) {
        dispose = listen(
          div,
          "click",
          /*handle_click*/
          ctx[30]
        );
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const image_changes = {};
      if (dirty[0] & /*value*/
      8) image_changes.src = /*value*/
      ctx2[3].url;
      if (dirty[0] & /*value*/
      8) image_changes.alt = /*value*/
      ctx2[3].alt_text;
      image.$set(image_changes);
      if (!current || dirty[0] & /*selectable*/
      4096) {
        toggle_class(
          div,
          "selectable",
          /*selectable*/
          ctx2[12]
        );
      }
    },
    i(local) {
      if (current) return;
      transition_in(image.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(image.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div);
      }
      destroy_component(image);
      mounted = false;
      dispose();
    }
  };
}
function create_if_block_2$1(ctx) {
  let webcam;
  let updating_modify_stream;
  let updating_set_time_limit;
  let current;
  function webcam_modify_stream_binding(value) {
    ctx[40](value);
  }
  function webcam_set_time_limit_binding(value) {
    ctx[41](value);
  }
  let webcam_props = {
    root: (
      /*root*/
      ctx[13]
    ),
    value: (
      /*value*/
      ctx[3]
    ),
    mirror_webcam: (
      /*webcam_options*/
      ctx[11].mirror
    ),
    stream_every: (
      /*stream_every*/
      ctx[18]
    ),
    streaming: (
      /*streaming*/
      ctx[10]
    ),
    mode: "image",
    include_audio: false,
    i18n: (
      /*i18n*/
      ctx[14]
    ),
    upload: (
      /*upload*/
      ctx[16]
    ),
    webcam_constraints: (
      /*webcam_options*/
      ctx[11].constraints
    )
  };
  if (
    /*modify_stream*/
    ctx[5] !== void 0
  ) {
    webcam_props.modify_stream = /*modify_stream*/
    ctx[5];
  }
  if (
    /*set_time_limit*/
    ctx[6] !== void 0
  ) {
    webcam_props.set_time_limit = /*set_time_limit*/
    ctx[6];
  }
  webcam = new Webcam2({ props: webcam_props });
  binding_callbacks.push(() => bind(webcam, "modify_stream", webcam_modify_stream_binding));
  binding_callbacks.push(() => bind(webcam, "set_time_limit", webcam_set_time_limit_binding));
  webcam.$on(
    "capture",
    /*capture_handler*/
    ctx[42]
  );
  webcam.$on(
    "stream",
    /*stream_handler_1*/
    ctx[43]
  );
  webcam.$on(
    "error",
    /*error_handler_1*/
    ctx[44]
  );
  webcam.$on(
    "drag",
    /*drag_handler*/
    ctx[45]
  );
  webcam.$on(
    "upload",
    /*upload_handler*/
    ctx[46]
  );
  webcam.$on(
    "close_stream",
    /*close_stream_handler*/
    ctx[47]
  );
  return {
    c() {
      create_component(webcam.$$.fragment);
    },
    m(target, anchor) {
      mount_component(webcam, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const webcam_changes = {};
      if (dirty[0] & /*root*/
      8192) webcam_changes.root = /*root*/
      ctx2[13];
      if (dirty[0] & /*value*/
      8) webcam_changes.value = /*value*/
      ctx2[3];
      if (dirty[0] & /*webcam_options*/
      2048) webcam_changes.mirror_webcam = /*webcam_options*/
      ctx2[11].mirror;
      if (dirty[0] & /*stream_every*/
      262144) webcam_changes.stream_every = /*stream_every*/
      ctx2[18];
      if (dirty[0] & /*streaming*/
      1024) webcam_changes.streaming = /*streaming*/
      ctx2[10];
      if (dirty[0] & /*i18n*/
      16384) webcam_changes.i18n = /*i18n*/
      ctx2[14];
      if (dirty[0] & /*upload*/
      65536) webcam_changes.upload = /*upload*/
      ctx2[16];
      if (dirty[0] & /*webcam_options*/
      2048) webcam_changes.webcam_constraints = /*webcam_options*/
      ctx2[11].constraints;
      if (!updating_modify_stream && dirty[0] & /*modify_stream*/
      32) {
        updating_modify_stream = true;
        webcam_changes.modify_stream = /*modify_stream*/
        ctx2[5];
        add_flush_callback(() => updating_modify_stream = false);
      }
      if (!updating_set_time_limit && dirty[0] & /*set_time_limit*/
      64) {
        updating_set_time_limit = true;
        webcam_changes.set_time_limit = /*set_time_limit*/
        ctx2[6];
        add_flush_callback(() => updating_set_time_limit = false);
      }
      webcam.$set(webcam_changes);
    },
    i(local) {
      if (current) return;
      transition_in(webcam.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(webcam.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(webcam, detaching);
    }
  };
}
function create_if_block_1$1(ctx) {
  let uploadprogress;
  let current;
  uploadprogress = new UploadProgress({
    props: {
      root: (
        /*root*/
        ctx[13]
      ),
      upload_id: (
        /*upload_id*/
        ctx[24]
      ),
      stream_handler: (
        /*stream_handler*/
        ctx[17]
      ),
      files: (
        /*files*/
        ctx[23]
      )
    }
  });
  return {
    c() {
      create_component(uploadprogress.$$.fragment);
    },
    m(target, anchor) {
      mount_component(uploadprogress, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const uploadprogress_changes = {};
      if (dirty[0] & /*root*/
      8192) uploadprogress_changes.root = /*root*/
      ctx2[13];
      if (dirty[0] & /*upload_id*/
      16777216) uploadprogress_changes.upload_id = /*upload_id*/
      ctx2[24];
      if (dirty[0] & /*stream_handler*/
      131072) uploadprogress_changes.stream_handler = /*stream_handler*/
      ctx2[17];
      if (dirty[0] & /*files*/
      8388608) uploadprogress_changes.files = /*files*/
      ctx2[23];
      uploadprogress.$set(uploadprogress_changes);
    },
    i(local) {
      if (current) return;
      transition_in(uploadprogress.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(uploadprogress.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(uploadprogress, detaching);
    }
  };
}
function create_if_block$1(ctx) {
  let selectsource;
  let updating_active_source;
  let current;
  function selectsource_active_source_binding(value) {
    ctx[48](value);
  }
  let selectsource_props = {
    sources: (
      /*sources*/
      ctx[9]
    ),
    handle_clear: (
      /*handle_clear*/
      ctx[27]
    ),
    handle_select: (
      /*handle_select_source*/
      ctx[31]
    )
  };
  if (
    /*active_source*/
    ctx[1] !== void 0
  ) {
    selectsource_props.active_source = /*active_source*/
    ctx[1];
  }
  selectsource = new SelectSource({ props: selectsource_props });
  binding_callbacks.push(() => bind(selectsource, "active_source", selectsource_active_source_binding));
  return {
    c() {
      create_component(selectsource.$$.fragment);
    },
    m(target, anchor) {
      mount_component(selectsource, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const selectsource_changes = {};
      if (dirty[0] & /*sources*/
      512) selectsource_changes.sources = /*sources*/
      ctx2[9];
      if (!updating_active_source && dirty[0] & /*active_source*/
      2) {
        updating_active_source = true;
        selectsource_changes.active_source = /*active_source*/
        ctx2[1];
        add_flush_callback(() => updating_active_source = false);
      }
      selectsource.$set(selectsource_changes);
    },
    i(local) {
      if (current) return;
      transition_in(selectsource.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(selectsource.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(selectsource, detaching);
    }
  };
}
function create_fragment$3(ctx) {
  let blocklabel;
  let t0;
  let div1;
  let iconbuttonwrapper;
  let t1;
  let div0;
  let upload_1;
  let updating_uploading;
  let updating_dragging;
  let t2;
  let current_block_type_index;
  let if_block0;
  let t3;
  let show_if = (
    /*sources*/
    ctx[9].length > 1 || /*sources*/
    ctx[9].includes("clipboard")
  );
  let current;
  let mounted;
  let dispose;
  blocklabel = new BlockLabel({
    props: {
      show_label: (
        /*show_label*/
        ctx[8]
      ),
      Icon: Image$1,
      label: (
        /*label*/
        ctx[7] || "Image"
      )
    }
  });
  iconbuttonwrapper = new IconButtonWrapper({
    props: {
      $$slots: { default: [create_default_slot_1$1] },
      $$scope: { ctx }
    }
  });
  function upload_1_uploading_binding(value) {
    ctx[37](value);
  }
  function upload_1_dragging_binding(value) {
    ctx[38](value);
  }
  let upload_1_props = {
    hidden: (
      /*value*/
      ctx[3] !== null || /*active_source*/
      ctx[1] === "webcam"
    ),
    filetype: (
      /*active_source*/
      ctx[1] === "clipboard" ? "clipboard" : "image/*"
    ),
    root: (
      /*root*/
      ctx[13]
    ),
    max_file_size: (
      /*max_file_size*/
      ctx[15]
    ),
    disable_click: !/*sources*/
    ctx[9].includes("upload") || /*value*/
    ctx[3] !== null,
    upload: (
      /*upload*/
      ctx[16]
    ),
    stream_handler: (
      /*stream_handler*/
      ctx[17]
    ),
    aria_label: (
      /*i18n*/
      ctx[14]("image.drop_to_upload")
    ),
    $$slots: { default: [create_default_slot$2] },
    $$scope: { ctx }
  };
  if (
    /*uploading*/
    ctx[0] !== void 0
  ) {
    upload_1_props.uploading = /*uploading*/
    ctx[0];
  }
  if (
    /*dragging*/
    ctx[2] !== void 0
  ) {
    upload_1_props.dragging = /*dragging*/
    ctx[2];
  }
  upload_1 = new Upload2({ props: upload_1_props });
  ctx[36](upload_1);
  binding_callbacks.push(() => bind(upload_1, "uploading", upload_1_uploading_binding));
  binding_callbacks.push(() => bind(upload_1, "dragging", upload_1_dragging_binding));
  upload_1.$on(
    "load",
    /*handle_upload*/
    ctx[26]
  );
  upload_1.$on(
    "error",
    /*error_handler*/
    ctx[39]
  );
  const if_block_creators = [create_if_block_1$1, create_if_block_2$1, create_if_block_3];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (
      /*active_source*/
      ctx2[1] === "webcam" && !/*streaming*/
      ctx2[10] && /*pending*/
      ctx2[4]
    ) return 0;
    if (
      /*active_source*/
      ctx2[1] === "webcam" && /*streaming*/
      (ctx2[10] || !/*streaming*/
      ctx2[10] && !/*value*/
      ctx2[3])
    ) return 1;
    if (
      /*value*/
      ctx2[3] !== null && !/*streaming*/
      ctx2[10]
    ) return 2;
    return -1;
  }
  if (~(current_block_type_index = select_block_type(ctx))) {
    if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  }
  let if_block1 = show_if && create_if_block$1(ctx);
  return {
    c() {
      create_component(blocklabel.$$.fragment);
      t0 = space();
      div1 = element("div");
      create_component(iconbuttonwrapper.$$.fragment);
      t1 = space();
      div0 = element("div");
      create_component(upload_1.$$.fragment);
      t2 = space();
      if (if_block0) if_block0.c();
      t3 = space();
      if (if_block1) if_block1.c();
      attr(div0, "class", "upload-container svelte-1562gr6");
      toggle_class(
        div0,
        "reduced-height",
        /*sources*/
        ctx[9].length > 1
      );
      set_style(
        div0,
        "width",
        /*value*/
        ctx[3] ? "auto" : "100%"
      );
      attr(div1, "data-testid", "image");
      attr(div1, "class", "image-container svelte-1562gr6");
    },
    m(target, anchor) {
      mount_component(blocklabel, target, anchor);
      insert(target, t0, anchor);
      insert(target, div1, anchor);
      mount_component(iconbuttonwrapper, div1, null);
      append(div1, t1);
      append(div1, div0);
      mount_component(upload_1, div0, null);
      append(div0, t2);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].m(div0, null);
      }
      append(div1, t3);
      if (if_block1) if_block1.m(div1, null);
      ctx[49](div1);
      current = true;
      if (!mounted) {
        dispose = [
          listen(
            div0,
            "dragover",
            /*on_drag_over*/
            ctx[32]
          ),
          listen(
            div0,
            "drop",
            /*on_drop*/
            ctx[33]
          )
        ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      const blocklabel_changes = {};
      if (dirty[0] & /*show_label*/
      256) blocklabel_changes.show_label = /*show_label*/
      ctx2[8];
      if (dirty[0] & /*label*/
      128) blocklabel_changes.label = /*label*/
      ctx2[7] || "Image";
      blocklabel.$set(blocklabel_changes);
      const iconbuttonwrapper_changes = {};
      if (dirty[0] & /*fullscreen, show_fullscreen_button, value, active_streaming*/
      3670024 | dirty[1] & /*$$scope*/
      524288) {
        iconbuttonwrapper_changes.$$scope = { dirty, ctx: ctx2 };
      }
      iconbuttonwrapper.$set(iconbuttonwrapper_changes);
      const upload_1_changes = {};
      if (dirty[0] & /*value, active_source*/
      10) upload_1_changes.hidden = /*value*/
      ctx2[3] !== null || /*active_source*/
      ctx2[1] === "webcam";
      if (dirty[0] & /*active_source*/
      2) upload_1_changes.filetype = /*active_source*/
      ctx2[1] === "clipboard" ? "clipboard" : "image/*";
      if (dirty[0] & /*root*/
      8192) upload_1_changes.root = /*root*/
      ctx2[13];
      if (dirty[0] & /*max_file_size*/
      32768) upload_1_changes.max_file_size = /*max_file_size*/
      ctx2[15];
      if (dirty[0] & /*sources, value*/
      520) upload_1_changes.disable_click = !/*sources*/
      ctx2[9].includes("upload") || /*value*/
      ctx2[3] !== null;
      if (dirty[0] & /*upload*/
      65536) upload_1_changes.upload = /*upload*/
      ctx2[16];
      if (dirty[0] & /*stream_handler*/
      131072) upload_1_changes.stream_handler = /*stream_handler*/
      ctx2[17];
      if (dirty[0] & /*i18n*/
      16384) upload_1_changes.aria_label = /*i18n*/
      ctx2[14]("image.drop_to_upload");
      if (dirty[0] & /*value*/
      8 | dirty[1] & /*$$scope*/
      524288) {
        upload_1_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_uploading && dirty[0] & /*uploading*/
      1) {
        updating_uploading = true;
        upload_1_changes.uploading = /*uploading*/
        ctx2[0];
        add_flush_callback(() => updating_uploading = false);
      }
      if (!updating_dragging && dirty[0] & /*dragging*/
      4) {
        updating_dragging = true;
        upload_1_changes.dragging = /*dragging*/
        ctx2[2];
        add_flush_callback(() => updating_dragging = false);
      }
      upload_1.$set(upload_1_changes);
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if (~current_block_type_index) {
          if_blocks[current_block_type_index].p(ctx2, dirty);
        }
      } else {
        if (if_block0) {
          group_outros();
          transition_out(if_blocks[previous_block_index], 1, 1, () => {
            if_blocks[previous_block_index] = null;
          });
          check_outros();
        }
        if (~current_block_type_index) {
          if_block0 = if_blocks[current_block_type_index];
          if (!if_block0) {
            if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
            if_block0.c();
          } else {
            if_block0.p(ctx2, dirty);
          }
          transition_in(if_block0, 1);
          if_block0.m(div0, null);
        } else {
          if_block0 = null;
        }
      }
      if (!current || dirty[0] & /*sources*/
      512) {
        toggle_class(
          div0,
          "reduced-height",
          /*sources*/
          ctx2[9].length > 1
        );
      }
      if (dirty[0] & /*value*/
      8) {
        set_style(
          div0,
          "width",
          /*value*/
          ctx2[3] ? "auto" : "100%"
        );
      }
      if (dirty[0] & /*sources*/
      512) show_if = /*sources*/
      ctx2[9].length > 1 || /*sources*/
      ctx2[9].includes("clipboard");
      if (show_if) {
        if (if_block1) {
          if_block1.p(ctx2, dirty);
          if (dirty[0] & /*sources*/
          512) {
            transition_in(if_block1, 1);
          }
        } else {
          if_block1 = create_if_block$1(ctx2);
          if_block1.c();
          transition_in(if_block1, 1);
          if_block1.m(div1, null);
        }
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, () => {
          if_block1 = null;
        });
        check_outros();
      }
    },
    i(local) {
      if (current) return;
      transition_in(blocklabel.$$.fragment, local);
      transition_in(iconbuttonwrapper.$$.fragment, local);
      transition_in(upload_1.$$.fragment, local);
      transition_in(if_block0);
      transition_in(if_block1);
      current = true;
    },
    o(local) {
      transition_out(blocklabel.$$.fragment, local);
      transition_out(iconbuttonwrapper.$$.fragment, local);
      transition_out(upload_1.$$.fragment, local);
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t0);
        detach(div1);
      }
      destroy_component(blocklabel, detaching);
      destroy_component(iconbuttonwrapper);
      ctx[36](null);
      destroy_component(upload_1);
      if (~current_block_type_index) {
        if_blocks[current_block_type_index].d();
      }
      if (if_block1) if_block1.d();
      ctx[49](null);
      mounted = false;
      run_all(dispose);
    }
  };
}
function instance$3($$self, $$props, $$invalidate) {
  let active_streaming;
  let { $$slots: slots = {}, $$scope } = $$props;
  let { value = null } = $$props;
  let { label = void 0 } = $$props;
  let { show_label } = $$props;
  let { sources = ["upload", "clipboard", "webcam"] } = $$props;
  let { streaming = false } = $$props;
  let { pending = false } = $$props;
  let { webcam_options } = $$props;
  let { selectable = false } = $$props;
  let { root } = $$props;
  let { i18n } = $$props;
  let { max_file_size = null } = $$props;
  let { upload } = $$props;
  let { stream_handler } = $$props;
  let { stream_every } = $$props;
  let { modify_stream } = $$props;
  let { set_time_limit } = $$props;
  let { show_fullscreen_button = true } = $$props;
  let upload_input;
  let { uploading = false } = $$props;
  let { active_source = null } = $$props;
  let { fullscreen = false } = $$props;
  let files = [];
  let upload_id;
  async function handle_upload({ detail }) {
    var _a;
    if (!streaming) {
      if (((_a = detail.path) == null ? void 0 : _a.toLowerCase().endsWith(".svg")) && detail.url) {
        const response = await fetch(detail.url);
        const svgContent = await response.text();
        $$invalidate(3, value = {
          ...detail,
          url: `data:image/svg+xml,${encodeURIComponent(svgContent)}`
        });
      } else {
        $$invalidate(3, value = detail);
      }
      await tick();
      dispatch2("upload");
    }
  }
  function handle_clear() {
    $$invalidate(3, value = null);
    dispatch2("clear");
    dispatch2("change", null);
  }
  function handle_remove_image_click(event) {
    handle_clear();
    event.stopPropagation();
  }
  async function handle_save(img_blob, event) {
    if (event === "stream") {
      dispatch2("stream", {
        value: { url: img_blob },
        is_value_data: true
      });
      return;
    }
    $$invalidate(24, upload_id = Math.random().toString(36).substring(2, 15));
    const f_ = new File([img_blob], `image.${streaming ? "jpeg" : "png"}`);
    $$invalidate(23, files = [
      new FileData({
        path: f_.name,
        orig_name: f_.name,
        blob: f_,
        size: f_.size,
        mime_type: f_.type,
        is_stream: false
      })
    ]);
    $$invalidate(4, pending = true);
    const f = await upload_input.load_files([f_], upload_id);
    if (event === "change" || event === "upload") {
      $$invalidate(3, value = (f == null ? void 0 : f[0]) || null);
      await tick();
      dispatch2("change");
    }
    $$invalidate(4, pending = false);
  }
  const dispatch2 = createEventDispatcher();
  let { dragging = false } = $$props;
  function handle_click(evt) {
    let coordinates = get_coordinates_of_clicked_image(evt);
    if (coordinates) {
      dispatch2("select", { index: coordinates, value: null });
    }
  }
  async function handle_select_source(source) {
    switch (source) {
      case "clipboard":
        upload_input.paste_clipboard();
        break;
    }
  }
  let image_container;
  function on_drag_over(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    if (evt.dataTransfer) {
      evt.dataTransfer.dropEffect = "copy";
    }
    $$invalidate(2, dragging = true);
  }
  async function on_drop(evt) {
    evt.preventDefault();
    evt.stopPropagation();
    $$invalidate(2, dragging = false);
    if (value) {
      handle_clear();
      await tick();
    }
    $$invalidate(1, active_source = "upload");
    await tick();
    upload_input.load_files_from_drop(evt);
  }
  function fullscreen_handler(event) {
    bubble.call(this, $$self, event);
  }
  function upload_1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      upload_input = $$value;
      $$invalidate(22, upload_input);
    });
  }
  function upload_1_uploading_binding(value2) {
    uploading = value2;
    $$invalidate(0, uploading);
  }
  function upload_1_dragging_binding(value2) {
    dragging = value2;
    $$invalidate(2, dragging);
  }
  function error_handler(event) {
    bubble.call(this, $$self, event);
  }
  function webcam_modify_stream_binding(value2) {
    modify_stream = value2;
    $$invalidate(5, modify_stream);
  }
  function webcam_set_time_limit_binding(value2) {
    set_time_limit = value2;
    $$invalidate(6, set_time_limit);
  }
  const capture_handler = (e) => handle_save(e.detail, "change");
  const stream_handler_1 = (e) => handle_save(e.detail, "stream");
  function error_handler_1(event) {
    bubble.call(this, $$self, event);
  }
  function drag_handler(event) {
    bubble.call(this, $$self, event);
  }
  const upload_handler = (e) => handle_save(e.detail, "upload");
  function close_stream_handler(event) {
    bubble.call(this, $$self, event);
  }
  function selectsource_active_source_binding(value2) {
    active_source = value2;
    $$invalidate(1, active_source), $$invalidate(9, sources);
  }
  function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      image_container = $$value;
      $$invalidate(25, image_container);
    });
  }
  $$self.$$set = ($$props2) => {
    if ("value" in $$props2) $$invalidate(3, value = $$props2.value);
    if ("label" in $$props2) $$invalidate(7, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(8, show_label = $$props2.show_label);
    if ("sources" in $$props2) $$invalidate(9, sources = $$props2.sources);
    if ("streaming" in $$props2) $$invalidate(10, streaming = $$props2.streaming);
    if ("pending" in $$props2) $$invalidate(4, pending = $$props2.pending);
    if ("webcam_options" in $$props2) $$invalidate(11, webcam_options = $$props2.webcam_options);
    if ("selectable" in $$props2) $$invalidate(12, selectable = $$props2.selectable);
    if ("root" in $$props2) $$invalidate(13, root = $$props2.root);
    if ("i18n" in $$props2) $$invalidate(14, i18n = $$props2.i18n);
    if ("max_file_size" in $$props2) $$invalidate(15, max_file_size = $$props2.max_file_size);
    if ("upload" in $$props2) $$invalidate(16, upload = $$props2.upload);
    if ("stream_handler" in $$props2) $$invalidate(17, stream_handler = $$props2.stream_handler);
    if ("stream_every" in $$props2) $$invalidate(18, stream_every = $$props2.stream_every);
    if ("modify_stream" in $$props2) $$invalidate(5, modify_stream = $$props2.modify_stream);
    if ("set_time_limit" in $$props2) $$invalidate(6, set_time_limit = $$props2.set_time_limit);
    if ("show_fullscreen_button" in $$props2) $$invalidate(19, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("uploading" in $$props2) $$invalidate(0, uploading = $$props2.uploading);
    if ("active_source" in $$props2) $$invalidate(1, active_source = $$props2.active_source);
    if ("fullscreen" in $$props2) $$invalidate(20, fullscreen = $$props2.fullscreen);
    if ("dragging" in $$props2) $$invalidate(2, dragging = $$props2.dragging);
    if ("$$scope" in $$props2) $$invalidate(50, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*active_source, sources*/
    514) {
      if (!active_source && sources) {
        $$invalidate(1, active_source = sources[0]);
      }
    }
    if ($$self.$$.dirty[0] & /*streaming, active_source*/
    1026) {
      $$invalidate(21, active_streaming = streaming && active_source === "webcam");
    }
    if ($$self.$$.dirty[0] & /*uploading, active_streaming*/
    2097153) {
      if (uploading && !active_streaming) $$invalidate(3, value = null);
    }
    if ($$self.$$.dirty[0] & /*dragging*/
    4) {
      dispatch2("drag", dragging);
    }
  };
  return [
    uploading,
    active_source,
    dragging,
    value,
    pending,
    modify_stream,
    set_time_limit,
    label,
    show_label,
    sources,
    streaming,
    webcam_options,
    selectable,
    root,
    i18n,
    max_file_size,
    upload,
    stream_handler,
    stream_every,
    show_fullscreen_button,
    fullscreen,
    active_streaming,
    upload_input,
    files,
    upload_id,
    image_container,
    handle_upload,
    handle_clear,
    handle_remove_image_click,
    handle_save,
    handle_click,
    handle_select_source,
    on_drag_over,
    on_drop,
    slots,
    fullscreen_handler,
    upload_1_binding,
    upload_1_uploading_binding,
    upload_1_dragging_binding,
    error_handler,
    webcam_modify_stream_binding,
    webcam_set_time_limit_binding,
    capture_handler,
    stream_handler_1,
    error_handler_1,
    drag_handler,
    upload_handler,
    close_stream_handler,
    selectsource_active_source_binding,
    div1_binding,
    $$scope
  ];
}
class ImageUploader extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$3,
      create_fragment$3,
      safe_not_equal,
      {
        value: 3,
        label: 7,
        show_label: 8,
        sources: 9,
        streaming: 10,
        pending: 4,
        webcam_options: 11,
        selectable: 12,
        root: 13,
        i18n: 14,
        max_file_size: 15,
        upload: 16,
        stream_handler: 17,
        stream_every: 18,
        modify_stream: 5,
        set_time_limit: 6,
        show_fullscreen_button: 19,
        uploading: 0,
        active_source: 1,
        fullscreen: 20,
        dragging: 2
      },
      null,
      [-1, -1]
    );
  }
}
function create_else_block(ctx) {
  let block2;
  let updating_fullscreen;
  let current;
  function block_fullscreen_binding_1(value) {
    ctx[63](value);
  }
  let block_props = {
    visible: (
      /*visible*/
      ctx[5]
    ),
    variant: (
      /*value*/
      ctx[0] === null ? "dashed" : "solid"
    ),
    border_mode: (
      /*dragging*/
      ctx[29] ? "focus" : "base"
    ),
    padding: false,
    elem_id: (
      /*elem_id*/
      ctx[3]
    ),
    elem_classes: (
      /*elem_classes*/
      ctx[4]
    ),
    height: (
      /*height*/
      ctx[10] || void 0
    ),
    width: (
      /*width*/
      ctx[11]
    ),
    allow_overflow: false,
    container: (
      /*container*/
      ctx[14]
    ),
    scale: (
      /*scale*/
      ctx[15]
    ),
    min_width: (
      /*min_width*/
      ctx[16]
    ),
    $$slots: { default: [create_default_slot_1] },
    $$scope: { ctx }
  };
  if (
    /*fullscreen*/
    ctx[28] !== void 0
  ) {
    block_props.fullscreen = /*fullscreen*/
    ctx[28];
  }
  block2 = new Block({ props: block_props });
  binding_callbacks.push(() => bind(block2, "fullscreen", block_fullscreen_binding_1));
  block2.$on(
    "dragenter",
    /*handle_drag_event*/
    ctx[32]
  );
  block2.$on(
    "dragleave",
    /*handle_drag_event*/
    ctx[32]
  );
  block2.$on(
    "dragover",
    /*handle_drag_event*/
    ctx[32]
  );
  block2.$on(
    "drop",
    /*handle_drop*/
    ctx[33]
  );
  return {
    c() {
      create_component(block2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(block2, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const block_changes = {};
      if (dirty[0] & /*visible*/
      32) block_changes.visible = /*visible*/
      ctx2[5];
      if (dirty[0] & /*value*/
      1) block_changes.variant = /*value*/
      ctx2[0] === null ? "dashed" : "solid";
      if (dirty[0] & /*dragging*/
      536870912) block_changes.border_mode = /*dragging*/
      ctx2[29] ? "focus" : "base";
      if (dirty[0] & /*elem_id*/
      8) block_changes.elem_id = /*elem_id*/
      ctx2[3];
      if (dirty[0] & /*elem_classes*/
      16) block_changes.elem_classes = /*elem_classes*/
      ctx2[4];
      if (dirty[0] & /*height*/
      1024) block_changes.height = /*height*/
      ctx2[10] || void 0;
      if (dirty[0] & /*width*/
      2048) block_changes.width = /*width*/
      ctx2[11];
      if (dirty[0] & /*container*/
      16384) block_changes.container = /*container*/
      ctx2[14];
      if (dirty[0] & /*scale*/
      32768) block_changes.scale = /*scale*/
      ctx2[15];
      if (dirty[0] & /*min_width*/
      65536) block_changes.min_width = /*min_width*/
      ctx2[16];
      if (dirty[0] & /*_selectable, root, sources, fullscreen, label, show_label, pending, streaming, webcam_options, stream_every, gradio, uploading, active_source, value, dragging, _modify_stream, set_time_limit, loading_status, placeholder*/
      2138321607 | dirty[1] & /*upload_component*/
      1 | dirty[2] & /*$$scope*/
      8) {
        block_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_fullscreen && dirty[0] & /*fullscreen*/
      268435456) {
        updating_fullscreen = true;
        block_changes.fullscreen = /*fullscreen*/
        ctx2[28];
        add_flush_callback(() => updating_fullscreen = false);
      }
      block2.$set(block_changes);
    },
    i(local) {
      if (current) return;
      transition_in(block2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(block2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(block2, detaching);
    }
  };
}
function create_if_block(ctx) {
  let block2;
  let updating_fullscreen;
  let current;
  function block_fullscreen_binding(value) {
    ctx[43](value);
  }
  let block_props = {
    visible: (
      /*visible*/
      ctx[5]
    ),
    variant: "solid",
    border_mode: (
      /*dragging*/
      ctx[29] ? "focus" : "base"
    ),
    padding: false,
    elem_id: (
      /*elem_id*/
      ctx[3]
    ),
    elem_classes: (
      /*elem_classes*/
      ctx[4]
    ),
    height: (
      /*height*/
      ctx[10] || void 0
    ),
    width: (
      /*width*/
      ctx[11]
    ),
    allow_overflow: false,
    container: (
      /*container*/
      ctx[14]
    ),
    scale: (
      /*scale*/
      ctx[15]
    ),
    min_width: (
      /*min_width*/
      ctx[16]
    ),
    $$slots: { default: [create_default_slot$1] },
    $$scope: { ctx }
  };
  if (
    /*fullscreen*/
    ctx[28] !== void 0
  ) {
    block_props.fullscreen = /*fullscreen*/
    ctx[28];
  }
  block2 = new Block({ props: block_props });
  binding_callbacks.push(() => bind(block2, "fullscreen", block_fullscreen_binding));
  return {
    c() {
      create_component(block2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(block2, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const block_changes = {};
      if (dirty[0] & /*visible*/
      32) block_changes.visible = /*visible*/
      ctx2[5];
      if (dirty[0] & /*dragging*/
      536870912) block_changes.border_mode = /*dragging*/
      ctx2[29] ? "focus" : "base";
      if (dirty[0] & /*elem_id*/
      8) block_changes.elem_id = /*elem_id*/
      ctx2[3];
      if (dirty[0] & /*elem_classes*/
      16) block_changes.elem_classes = /*elem_classes*/
      ctx2[4];
      if (dirty[0] & /*height*/
      1024) block_changes.height = /*height*/
      ctx2[10] || void 0;
      if (dirty[0] & /*width*/
      2048) block_changes.width = /*width*/
      ctx2[11];
      if (dirty[0] & /*container*/
      16384) block_changes.container = /*container*/
      ctx2[14];
      if (dirty[0] & /*scale*/
      32768) block_changes.scale = /*scale*/
      ctx2[15];
      if (dirty[0] & /*min_width*/
      65536) block_changes.min_width = /*min_width*/
      ctx2[16];
      if (dirty[0] & /*fullscreen, value, label, show_label, show_download_button, _selectable, show_share_button, gradio, show_fullscreen_button, loading_status*/
      310518213 | dirty[2] & /*$$scope*/
      8) {
        block_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_fullscreen && dirty[0] & /*fullscreen*/
      268435456) {
        updating_fullscreen = true;
        block_changes.fullscreen = /*fullscreen*/
        ctx2[28];
        add_flush_callback(() => updating_fullscreen = false);
      }
      block2.$set(block_changes);
    },
    i(local) {
      if (current) return;
      transition_in(block2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(block2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(block2, detaching);
    }
  };
}
function create_else_block_1(ctx) {
  let empty_1;
  let current;
  empty_1 = new Empty({
    props: {
      unpadded_box: true,
      size: "large",
      $$slots: { default: [create_default_slot_3] },
      $$scope: { ctx }
    }
  });
  return {
    c() {
      create_component(empty_1.$$.fragment);
    },
    m(target, anchor) {
      mount_component(empty_1, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const empty_1_changes = {};
      if (dirty[2] & /*$$scope*/
      8) {
        empty_1_changes.$$scope = { dirty, ctx: ctx2 };
      }
      empty_1.$set(empty_1_changes);
    },
    i(local) {
      if (current) return;
      transition_in(empty_1.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(empty_1.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(empty_1, detaching);
    }
  };
}
function create_if_block_2(ctx) {
  let uploadtext;
  let current;
  uploadtext = new UploadText({
    props: {
      i18n: (
        /*gradio*/
        ctx[25].i18n
      ),
      type: "clipboard",
      mode: "short"
    }
  });
  return {
    c() {
      create_component(uploadtext.$$.fragment);
    },
    m(target, anchor) {
      mount_component(uploadtext, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const uploadtext_changes = {};
      if (dirty[0] & /*gradio*/
      33554432) uploadtext_changes.i18n = /*gradio*/
      ctx2[25].i18n;
      uploadtext.$set(uploadtext_changes);
    },
    i(local) {
      if (current) return;
      transition_in(uploadtext.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(uploadtext.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(uploadtext, detaching);
    }
  };
}
function create_if_block_1(ctx) {
  let uploadtext;
  let current;
  uploadtext = new UploadText({
    props: {
      i18n: (
        /*gradio*/
        ctx[25].i18n
      ),
      type: "image",
      placeholder: (
        /*placeholder*/
        ctx[22]
      )
    }
  });
  return {
    c() {
      create_component(uploadtext.$$.fragment);
    },
    m(target, anchor) {
      mount_component(uploadtext, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const uploadtext_changes = {};
      if (dirty[0] & /*gradio*/
      33554432) uploadtext_changes.i18n = /*gradio*/
      ctx2[25].i18n;
      if (dirty[0] & /*placeholder*/
      4194304) uploadtext_changes.placeholder = /*placeholder*/
      ctx2[22];
      uploadtext.$set(uploadtext_changes);
    },
    i(local) {
      if (current) return;
      transition_in(uploadtext.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(uploadtext.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(uploadtext, detaching);
    }
  };
}
function create_default_slot_3(ctx) {
  let image;
  let current;
  image = new Image$1({});
  return {
    c() {
      create_component(image.$$.fragment);
    },
    m(target, anchor) {
      mount_component(image, target, anchor);
      current = true;
    },
    i(local) {
      if (current) return;
      transition_in(image.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(image.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(image, detaching);
    }
  };
}
function create_default_slot_2(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block_1, create_if_block_2, create_else_block_1];
  const if_blocks = [];
  function select_block_type_1(ctx2, dirty) {
    if (
      /*active_source*/
      ctx2[30] === "upload" || !/*active_source*/
      ctx2[30]
    ) return 0;
    if (
      /*active_source*/
      ctx2[30] === "clipboard"
    ) return 1;
    return 2;
  }
  current_block_type_index = select_block_type_1(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type_1(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function create_default_slot_1(ctx) {
  var _a;
  let statustracker;
  let t;
  let imageuploader;
  let updating_uploading;
  let updating_active_source;
  let updating_value;
  let updating_dragging;
  let updating_modify_stream;
  let updating_set_time_limit;
  let current;
  const statustracker_spread_levels = [
    {
      autoscroll: (
        /*gradio*/
        ctx[25].autoscroll
      )
    },
    { i18n: (
      /*gradio*/
      ctx[25].i18n
    ) },
    /*loading_status*/
    ctx[2]
  ];
  let statustracker_props = {};
  for (let i = 0; i < statustracker_spread_levels.length; i += 1) {
    statustracker_props = assign(statustracker_props, statustracker_spread_levels[i]);
  }
  statustracker = new Static({ props: statustracker_props });
  statustracker.$on(
    "clear_status",
    /*clear_status_handler*/
    ctx[44]
  );
  function imageuploader_uploading_binding(value) {
    ctx[47](value);
  }
  function imageuploader_active_source_binding(value) {
    ctx[48](value);
  }
  function imageuploader_value_binding(value) {
    ctx[49](value);
  }
  function imageuploader_dragging_binding(value) {
    ctx[50](value);
  }
  function imageuploader_modify_stream_binding(value) {
    ctx[51](value);
  }
  function imageuploader_set_time_limit_binding(value) {
    ctx[52](value);
  }
  let imageuploader_props = {
    selectable: (
      /*_selectable*/
      ctx[13]
    ),
    root: (
      /*root*/
      ctx[9]
    ),
    sources: (
      /*sources*/
      ctx[18]
    ),
    fullscreen: (
      /*fullscreen*/
      ctx[28]
    ),
    label: (
      /*label*/
      ctx[6]
    ),
    show_label: (
      /*show_label*/
      ctx[7]
    ),
    pending: (
      /*pending*/
      ctx[21]
    ),
    streaming: (
      /*streaming*/
      ctx[20]
    ),
    webcam_options: (
      /*webcam_options*/
      ctx[24]
    ),
    stream_every: (
      /*stream_every*/
      ctx[12]
    ),
    max_file_size: (
      /*gradio*/
      ctx[25].max_file_size
    ),
    i18n: (
      /*gradio*/
      ctx[25].i18n
    ),
    upload: (
      /*func*/
      ctx[45]
    ),
    stream_handler: (
      /*gradio*/
      (_a = ctx[25].client) == null ? void 0 : _a.stream
    ),
    $$slots: { default: [create_default_slot_2] },
    $$scope: { ctx }
  };
  if (
    /*uploading*/
    ctx[26] !== void 0
  ) {
    imageuploader_props.uploading = /*uploading*/
    ctx[26];
  }
  if (
    /*active_source*/
    ctx[30] !== void 0
  ) {
    imageuploader_props.active_source = /*active_source*/
    ctx[30];
  }
  if (
    /*value*/
    ctx[0] !== void 0
  ) {
    imageuploader_props.value = /*value*/
    ctx[0];
  }
  if (
    /*dragging*/
    ctx[29] !== void 0
  ) {
    imageuploader_props.dragging = /*dragging*/
    ctx[29];
  }
  if (
    /*_modify_stream*/
    ctx[27] !== void 0
  ) {
    imageuploader_props.modify_stream = /*_modify_stream*/
    ctx[27];
  }
  if (
    /*set_time_limit*/
    ctx[1] !== void 0
  ) {
    imageuploader_props.set_time_limit = /*set_time_limit*/
    ctx[1];
  }
  imageuploader = new ImageUploader({ props: imageuploader_props });
  ctx[46](imageuploader);
  binding_callbacks.push(() => bind(imageuploader, "uploading", imageuploader_uploading_binding));
  binding_callbacks.push(() => bind(imageuploader, "active_source", imageuploader_active_source_binding));
  binding_callbacks.push(() => bind(imageuploader, "value", imageuploader_value_binding));
  binding_callbacks.push(() => bind(imageuploader, "dragging", imageuploader_dragging_binding));
  binding_callbacks.push(() => bind(imageuploader, "modify_stream", imageuploader_modify_stream_binding));
  binding_callbacks.push(() => bind(imageuploader, "set_time_limit", imageuploader_set_time_limit_binding));
  imageuploader.$on(
    "edit",
    /*edit_handler*/
    ctx[53]
  );
  imageuploader.$on(
    "clear",
    /*clear_handler*/
    ctx[54]
  );
  imageuploader.$on(
    "stream",
    /*stream_handler*/
    ctx[55]
  );
  imageuploader.$on(
    "drag",
    /*drag_handler*/
    ctx[56]
  );
  imageuploader.$on(
    "upload",
    /*upload_handler*/
    ctx[57]
  );
  imageuploader.$on(
    "select",
    /*select_handler_1*/
    ctx[58]
  );
  imageuploader.$on(
    "share",
    /*share_handler_1*/
    ctx[59]
  );
  imageuploader.$on(
    "error",
    /*error_handler_1*/
    ctx[60]
  );
  imageuploader.$on(
    "close_stream",
    /*close_stream_handler*/
    ctx[61]
  );
  imageuploader.$on(
    "fullscreen",
    /*fullscreen_handler_1*/
    ctx[62]
  );
  return {
    c() {
      create_component(statustracker.$$.fragment);
      t = space();
      create_component(imageuploader.$$.fragment);
    },
    m(target, anchor) {
      mount_component(statustracker, target, anchor);
      insert(target, t, anchor);
      mount_component(imageuploader, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      var _a2;
      const statustracker_changes = dirty[0] & /*gradio, loading_status*/
      33554436 ? get_spread_update(statustracker_spread_levels, [
        dirty[0] & /*gradio*/
        33554432 && {
          autoscroll: (
            /*gradio*/
            ctx2[25].autoscroll
          )
        },
        dirty[0] & /*gradio*/
        33554432 && { i18n: (
          /*gradio*/
          ctx2[25].i18n
        ) },
        dirty[0] & /*loading_status*/
        4 && get_spread_object(
          /*loading_status*/
          ctx2[2]
        )
      ]) : {};
      statustracker.$set(statustracker_changes);
      const imageuploader_changes = {};
      if (dirty[0] & /*_selectable*/
      8192) imageuploader_changes.selectable = /*_selectable*/
      ctx2[13];
      if (dirty[0] & /*root*/
      512) imageuploader_changes.root = /*root*/
      ctx2[9];
      if (dirty[0] & /*sources*/
      262144) imageuploader_changes.sources = /*sources*/
      ctx2[18];
      if (dirty[0] & /*fullscreen*/
      268435456) imageuploader_changes.fullscreen = /*fullscreen*/
      ctx2[28];
      if (dirty[0] & /*label*/
      64) imageuploader_changes.label = /*label*/
      ctx2[6];
      if (dirty[0] & /*show_label*/
      128) imageuploader_changes.show_label = /*show_label*/
      ctx2[7];
      if (dirty[0] & /*pending*/
      2097152) imageuploader_changes.pending = /*pending*/
      ctx2[21];
      if (dirty[0] & /*streaming*/
      1048576) imageuploader_changes.streaming = /*streaming*/
      ctx2[20];
      if (dirty[0] & /*webcam_options*/
      16777216) imageuploader_changes.webcam_options = /*webcam_options*/
      ctx2[24];
      if (dirty[0] & /*stream_every*/
      4096) imageuploader_changes.stream_every = /*stream_every*/
      ctx2[12];
      if (dirty[0] & /*gradio*/
      33554432) imageuploader_changes.max_file_size = /*gradio*/
      ctx2[25].max_file_size;
      if (dirty[0] & /*gradio*/
      33554432) imageuploader_changes.i18n = /*gradio*/
      ctx2[25].i18n;
      if (dirty[0] & /*gradio*/
      33554432) imageuploader_changes.upload = /*func*/
      ctx2[45];
      if (dirty[0] & /*gradio*/
      33554432) imageuploader_changes.stream_handler = /*gradio*/
      (_a2 = ctx2[25].client) == null ? void 0 : _a2.stream;
      if (dirty[0] & /*gradio, placeholder, active_source*/
      1111490560 | dirty[2] & /*$$scope*/
      8) {
        imageuploader_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_uploading && dirty[0] & /*uploading*/
      67108864) {
        updating_uploading = true;
        imageuploader_changes.uploading = /*uploading*/
        ctx2[26];
        add_flush_callback(() => updating_uploading = false);
      }
      if (!updating_active_source && dirty[0] & /*active_source*/
      1073741824) {
        updating_active_source = true;
        imageuploader_changes.active_source = /*active_source*/
        ctx2[30];
        add_flush_callback(() => updating_active_source = false);
      }
      if (!updating_value && dirty[0] & /*value*/
      1) {
        updating_value = true;
        imageuploader_changes.value = /*value*/
        ctx2[0];
        add_flush_callback(() => updating_value = false);
      }
      if (!updating_dragging && dirty[0] & /*dragging*/
      536870912) {
        updating_dragging = true;
        imageuploader_changes.dragging = /*dragging*/
        ctx2[29];
        add_flush_callback(() => updating_dragging = false);
      }
      if (!updating_modify_stream && dirty[0] & /*_modify_stream*/
      134217728) {
        updating_modify_stream = true;
        imageuploader_changes.modify_stream = /*_modify_stream*/
        ctx2[27];
        add_flush_callback(() => updating_modify_stream = false);
      }
      if (!updating_set_time_limit && dirty[0] & /*set_time_limit*/
      2) {
        updating_set_time_limit = true;
        imageuploader_changes.set_time_limit = /*set_time_limit*/
        ctx2[1];
        add_flush_callback(() => updating_set_time_limit = false);
      }
      imageuploader.$set(imageuploader_changes);
    },
    i(local) {
      if (current) return;
      transition_in(statustracker.$$.fragment, local);
      transition_in(imageuploader.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(statustracker.$$.fragment, local);
      transition_out(imageuploader.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
      destroy_component(statustracker, detaching);
      ctx[46](null);
      destroy_component(imageuploader, detaching);
    }
  };
}
function create_default_slot$1(ctx) {
  let statustracker;
  let t;
  let staticimage;
  let current;
  const statustracker_spread_levels = [
    {
      autoscroll: (
        /*gradio*/
        ctx[25].autoscroll
      )
    },
    { i18n: (
      /*gradio*/
      ctx[25].i18n
    ) },
    /*loading_status*/
    ctx[2]
  ];
  let statustracker_props = {};
  for (let i = 0; i < statustracker_spread_levels.length; i += 1) {
    statustracker_props = assign(statustracker_props, statustracker_spread_levels[i]);
  }
  statustracker = new Static({ props: statustracker_props });
  staticimage = new ImagePreview({
    props: {
      fullscreen: (
        /*fullscreen*/
        ctx[28]
      ),
      value: (
        /*value*/
        ctx[0]
      ),
      label: (
        /*label*/
        ctx[6]
      ),
      show_label: (
        /*show_label*/
        ctx[7]
      ),
      show_download_button: (
        /*show_download_button*/
        ctx[8]
      ),
      selectable: (
        /*_selectable*/
        ctx[13]
      ),
      show_share_button: (
        /*show_share_button*/
        ctx[17]
      ),
      i18n: (
        /*gradio*/
        ctx[25].i18n
      ),
      show_fullscreen_button: (
        /*show_fullscreen_button*/
        ctx[23]
      )
    }
  });
  staticimage.$on(
    "select",
    /*select_handler*/
    ctx[39]
  );
  staticimage.$on(
    "share",
    /*share_handler*/
    ctx[40]
  );
  staticimage.$on(
    "error",
    /*error_handler*/
    ctx[41]
  );
  staticimage.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[42]
  );
  return {
    c() {
      create_component(statustracker.$$.fragment);
      t = space();
      create_component(staticimage.$$.fragment);
    },
    m(target, anchor) {
      mount_component(statustracker, target, anchor);
      insert(target, t, anchor);
      mount_component(staticimage, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const statustracker_changes = dirty[0] & /*gradio, loading_status*/
      33554436 ? get_spread_update(statustracker_spread_levels, [
        dirty[0] & /*gradio*/
        33554432 && {
          autoscroll: (
            /*gradio*/
            ctx2[25].autoscroll
          )
        },
        dirty[0] & /*gradio*/
        33554432 && { i18n: (
          /*gradio*/
          ctx2[25].i18n
        ) },
        dirty[0] & /*loading_status*/
        4 && get_spread_object(
          /*loading_status*/
          ctx2[2]
        )
      ]) : {};
      statustracker.$set(statustracker_changes);
      const staticimage_changes = {};
      if (dirty[0] & /*fullscreen*/
      268435456) staticimage_changes.fullscreen = /*fullscreen*/
      ctx2[28];
      if (dirty[0] & /*value*/
      1) staticimage_changes.value = /*value*/
      ctx2[0];
      if (dirty[0] & /*label*/
      64) staticimage_changes.label = /*label*/
      ctx2[6];
      if (dirty[0] & /*show_label*/
      128) staticimage_changes.show_label = /*show_label*/
      ctx2[7];
      if (dirty[0] & /*show_download_button*/
      256) staticimage_changes.show_download_button = /*show_download_button*/
      ctx2[8];
      if (dirty[0] & /*_selectable*/
      8192) staticimage_changes.selectable = /*_selectable*/
      ctx2[13];
      if (dirty[0] & /*show_share_button*/
      131072) staticimage_changes.show_share_button = /*show_share_button*/
      ctx2[17];
      if (dirty[0] & /*gradio*/
      33554432) staticimage_changes.i18n = /*gradio*/
      ctx2[25].i18n;
      if (dirty[0] & /*show_fullscreen_button*/
      8388608) staticimage_changes.show_fullscreen_button = /*show_fullscreen_button*/
      ctx2[23];
      staticimage.$set(staticimage_changes);
    },
    i(local) {
      if (current) return;
      transition_in(statustracker.$$.fragment, local);
      transition_in(staticimage.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(statustracker.$$.fragment, local);
      transition_out(staticimage.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
      destroy_component(statustracker, detaching);
      destroy_component(staticimage, detaching);
    }
  };
}
function create_fragment$2(ctx) {
  let current_block_type_index;
  let if_block;
  let if_block_anchor;
  let current;
  const if_block_creators = [create_if_block, create_else_block];
  const if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (!/*interactive*/
    ctx2[19]) return 0;
    return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  return {
    c() {
      if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if_blocks[current_block_type_index].m(target, anchor);
      insert(target, if_block_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) {
        if_blocks[current_block_type_index].p(ctx2, dirty);
      } else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, () => {
          if_blocks[previous_block_index] = null;
        });
        check_outros();
        if_block = if_blocks[current_block_type_index];
        if (!if_block) {
          if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block.c();
        } else {
          if_block.p(ctx2, dirty);
        }
        transition_in(if_block, 1);
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      }
    },
    i(local) {
      if (current) return;
      transition_in(if_block);
      current = true;
    },
    o(local) {
      transition_out(if_block);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(if_block_anchor);
      }
      if_blocks[current_block_type_index].d(detaching);
    }
  };
}
function instance$2($$self, $$props, $$invalidate) {
  let stream_state = "closed";
  let _modify_stream = () => {
  };
  function modify_stream_state(state) {
    stream_state = state;
    _modify_stream(state);
  }
  const get_stream_state = () => stream_state;
  let { set_time_limit } = $$props;
  let { value_is_output = false } = $$props;
  let { elem_id = "" } = $$props;
  let { elem_classes = [] } = $$props;
  let { visible = true } = $$props;
  let { value = null } = $$props;
  let old_value = null;
  let { label } = $$props;
  let { show_label } = $$props;
  let { show_download_button } = $$props;
  let { root } = $$props;
  let { height: height2 } = $$props;
  let { width } = $$props;
  let { stream_every } = $$props;
  let { _selectable = false } = $$props;
  let { container = true } = $$props;
  let { scale = null } = $$props;
  let { min_width = void 0 } = $$props;
  let { loading_status } = $$props;
  let { show_share_button = false } = $$props;
  let { sources = ["upload", "clipboard", "webcam"] } = $$props;
  let { interactive } = $$props;
  let { streaming } = $$props;
  let { pending } = $$props;
  let { placeholder = void 0 } = $$props;
  let { show_fullscreen_button } = $$props;
  let { input_ready } = $$props;
  let { webcam_options } = $$props;
  let fullscreen = false;
  let uploading = false;
  let { gradio } = $$props;
  afterUpdate(() => {
    $$invalidate(34, value_is_output = false);
  });
  let dragging;
  let active_source = null;
  let upload_component;
  const handle_drag_event = (event) => {
    const drag_event = event;
    drag_event.preventDefault();
    drag_event.stopPropagation();
    if (drag_event.type === "dragenter" || drag_event.type === "dragover") {
      $$invalidate(29, dragging = true);
    } else if (drag_event.type === "dragleave") {
      $$invalidate(29, dragging = false);
    }
  };
  const handle_drop = (event) => {
    if (interactive) {
      const drop_event = event;
      drop_event.preventDefault();
      drop_event.stopPropagation();
      $$invalidate(29, dragging = false);
      if (upload_component) {
        upload_component.loadFilesFromDrop(drop_event);
      }
    }
  };
  const select_handler = ({ detail }) => gradio.dispatch("select", detail);
  const share_handler = ({ detail }) => gradio.dispatch("share", detail);
  const error_handler = ({ detail }) => gradio.dispatch("error", detail);
  const fullscreen_handler = ({ detail }) => {
    $$invalidate(28, fullscreen = detail);
  };
  function block_fullscreen_binding(value2) {
    fullscreen = value2;
    $$invalidate(28, fullscreen);
  }
  const clear_status_handler = () => gradio.dispatch("clear_status", loading_status);
  const func2 = (...args) => gradio.client.upload(...args);
  function imageuploader_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"](() => {
      upload_component = $$value;
      $$invalidate(31, upload_component);
    });
  }
  function imageuploader_uploading_binding(value2) {
    uploading = value2;
    $$invalidate(26, uploading);
  }
  function imageuploader_active_source_binding(value2) {
    active_source = value2;
    $$invalidate(30, active_source);
  }
  function imageuploader_value_binding(value$1) {
    value = value$1;
    $$invalidate(0, value);
  }
  function imageuploader_dragging_binding(value2) {
    dragging = value2;
    $$invalidate(29, dragging);
  }
  function imageuploader_modify_stream_binding(value2) {
    _modify_stream = value2;
    $$invalidate(27, _modify_stream);
  }
  function imageuploader_set_time_limit_binding(value2) {
    set_time_limit = value2;
    $$invalidate(1, set_time_limit);
  }
  const edit_handler = () => gradio.dispatch("edit");
  const clear_handler = () => {
    $$invalidate(28, fullscreen = false);
    gradio.dispatch("clear");
  };
  const stream_handler = ({ detail }) => gradio.dispatch("stream", detail);
  const drag_handler = ({ detail }) => $$invalidate(29, dragging = detail);
  const upload_handler = () => gradio.dispatch("upload");
  const select_handler_1 = ({ detail }) => gradio.dispatch("select", detail);
  const share_handler_1 = ({ detail }) => gradio.dispatch("share", detail);
  const error_handler_1 = ({ detail }) => {
    $$invalidate(2, loading_status = loading_status || {});
    $$invalidate(2, loading_status.status = "error", loading_status);
    gradio.dispatch("error", detail);
  };
  const close_stream_handler = () => {
    gradio.dispatch("close_stream", "stream");
  };
  const fullscreen_handler_1 = ({ detail }) => {
    $$invalidate(28, fullscreen = detail);
  };
  function block_fullscreen_binding_1(value2) {
    fullscreen = value2;
    $$invalidate(28, fullscreen);
  }
  $$self.$$set = ($$props2) => {
    if ("set_time_limit" in $$props2) $$invalidate(1, set_time_limit = $$props2.set_time_limit);
    if ("value_is_output" in $$props2) $$invalidate(34, value_is_output = $$props2.value_is_output);
    if ("elem_id" in $$props2) $$invalidate(3, elem_id = $$props2.elem_id);
    if ("elem_classes" in $$props2) $$invalidate(4, elem_classes = $$props2.elem_classes);
    if ("visible" in $$props2) $$invalidate(5, visible = $$props2.visible);
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("label" in $$props2) $$invalidate(6, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(7, show_label = $$props2.show_label);
    if ("show_download_button" in $$props2) $$invalidate(8, show_download_button = $$props2.show_download_button);
    if ("root" in $$props2) $$invalidate(9, root = $$props2.root);
    if ("height" in $$props2) $$invalidate(10, height2 = $$props2.height);
    if ("width" in $$props2) $$invalidate(11, width = $$props2.width);
    if ("stream_every" in $$props2) $$invalidate(12, stream_every = $$props2.stream_every);
    if ("_selectable" in $$props2) $$invalidate(13, _selectable = $$props2._selectable);
    if ("container" in $$props2) $$invalidate(14, container = $$props2.container);
    if ("scale" in $$props2) $$invalidate(15, scale = $$props2.scale);
    if ("min_width" in $$props2) $$invalidate(16, min_width = $$props2.min_width);
    if ("loading_status" in $$props2) $$invalidate(2, loading_status = $$props2.loading_status);
    if ("show_share_button" in $$props2) $$invalidate(17, show_share_button = $$props2.show_share_button);
    if ("sources" in $$props2) $$invalidate(18, sources = $$props2.sources);
    if ("interactive" in $$props2) $$invalidate(19, interactive = $$props2.interactive);
    if ("streaming" in $$props2) $$invalidate(20, streaming = $$props2.streaming);
    if ("pending" in $$props2) $$invalidate(21, pending = $$props2.pending);
    if ("placeholder" in $$props2) $$invalidate(22, placeholder = $$props2.placeholder);
    if ("show_fullscreen_button" in $$props2) $$invalidate(23, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("input_ready" in $$props2) $$invalidate(35, input_ready = $$props2.input_ready);
    if ("webcam_options" in $$props2) $$invalidate(24, webcam_options = $$props2.webcam_options);
    if ("gradio" in $$props2) $$invalidate(25, gradio = $$props2.gradio);
  };
  $$self.$$.update = () => {
    if ($$self.$$.dirty[0] & /*uploading*/
    67108864) {
      $$invalidate(35, input_ready = !uploading);
    }
    if ($$self.$$.dirty[0] & /*value, gradio*/
    33554433 | $$self.$$.dirty[1] & /*old_value, value_is_output*/
    136) {
      {
        if (JSON.stringify(value) !== JSON.stringify(old_value)) {
          $$invalidate(38, old_value = value);
          gradio.dispatch("change");
          if (!value_is_output) {
            gradio.dispatch("input");
          }
        }
      }
    }
  };
  return [
    value,
    set_time_limit,
    loading_status,
    elem_id,
    elem_classes,
    visible,
    label,
    show_label,
    show_download_button,
    root,
    height2,
    width,
    stream_every,
    _selectable,
    container,
    scale,
    min_width,
    show_share_button,
    sources,
    interactive,
    streaming,
    pending,
    placeholder,
    show_fullscreen_button,
    webcam_options,
    gradio,
    uploading,
    _modify_stream,
    fullscreen,
    dragging,
    active_source,
    upload_component,
    handle_drag_event,
    handle_drop,
    value_is_output,
    input_ready,
    modify_stream_state,
    get_stream_state,
    old_value,
    select_handler,
    share_handler,
    error_handler,
    fullscreen_handler,
    block_fullscreen_binding,
    clear_status_handler,
    func2,
    imageuploader_binding,
    imageuploader_uploading_binding,
    imageuploader_active_source_binding,
    imageuploader_value_binding,
    imageuploader_dragging_binding,
    imageuploader_modify_stream_binding,
    imageuploader_set_time_limit_binding,
    edit_handler,
    clear_handler,
    stream_handler,
    drag_handler,
    upload_handler,
    select_handler_1,
    share_handler_1,
    error_handler_1,
    close_stream_handler,
    fullscreen_handler_1,
    block_fullscreen_binding_1
  ];
}
let Index$2 = class Index extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$2,
      create_fragment$2,
      safe_not_equal,
      {
        modify_stream_state: 36,
        get_stream_state: 37,
        set_time_limit: 1,
        value_is_output: 34,
        elem_id: 3,
        elem_classes: 4,
        visible: 5,
        value: 0,
        label: 6,
        show_label: 7,
        show_download_button: 8,
        root: 9,
        height: 10,
        width: 11,
        stream_every: 12,
        _selectable: 13,
        container: 14,
        scale: 15,
        min_width: 16,
        loading_status: 2,
        show_share_button: 17,
        sources: 18,
        interactive: 19,
        streaming: 20,
        pending: 21,
        placeholder: 22,
        show_fullscreen_button: 23,
        input_ready: 35,
        webcam_options: 24,
        gradio: 25
      },
      null,
      [-1, -1, -1]
    );
  }
  get modify_stream_state() {
    return this.$$.ctx[36];
  }
  get get_stream_state() {
    return this.$$.ctx[37];
  }
  get set_time_limit() {
    return this.$$.ctx[1];
  }
  set set_time_limit(set_time_limit) {
    this.$$set({ set_time_limit });
    flush();
  }
  get value_is_output() {
    return this.$$.ctx[34];
  }
  set value_is_output(value_is_output) {
    this.$$set({ value_is_output });
    flush();
  }
  get elem_id() {
    return this.$$.ctx[3];
  }
  set elem_id(elem_id) {
    this.$$set({ elem_id });
    flush();
  }
  get elem_classes() {
    return this.$$.ctx[4];
  }
  set elem_classes(elem_classes) {
    this.$$set({ elem_classes });
    flush();
  }
  get visible() {
    return this.$$.ctx[5];
  }
  set visible(visible) {
    this.$$set({ visible });
    flush();
  }
  get value() {
    return this.$$.ctx[0];
  }
  set value(value) {
    this.$$set({ value });
    flush();
  }
  get label() {
    return this.$$.ctx[6];
  }
  set label(label) {
    this.$$set({ label });
    flush();
  }
  get show_label() {
    return this.$$.ctx[7];
  }
  set show_label(show_label) {
    this.$$set({ show_label });
    flush();
  }
  get show_download_button() {
    return this.$$.ctx[8];
  }
  set show_download_button(show_download_button) {
    this.$$set({ show_download_button });
    flush();
  }
  get root() {
    return this.$$.ctx[9];
  }
  set root(root) {
    this.$$set({ root });
    flush();
  }
  get height() {
    return this.$$.ctx[10];
  }
  set height(height2) {
    this.$$set({ height: height2 });
    flush();
  }
  get width() {
    return this.$$.ctx[11];
  }
  set width(width) {
    this.$$set({ width });
    flush();
  }
  get stream_every() {
    return this.$$.ctx[12];
  }
  set stream_every(stream_every) {
    this.$$set({ stream_every });
    flush();
  }
  get _selectable() {
    return this.$$.ctx[13];
  }
  set _selectable(_selectable) {
    this.$$set({ _selectable });
    flush();
  }
  get container() {
    return this.$$.ctx[14];
  }
  set container(container) {
    this.$$set({ container });
    flush();
  }
  get scale() {
    return this.$$.ctx[15];
  }
  set scale(scale) {
    this.$$set({ scale });
    flush();
  }
  get min_width() {
    return this.$$.ctx[16];
  }
  set min_width(min_width) {
    this.$$set({ min_width });
    flush();
  }
  get loading_status() {
    return this.$$.ctx[2];
  }
  set loading_status(loading_status) {
    this.$$set({ loading_status });
    flush();
  }
  get show_share_button() {
    return this.$$.ctx[17];
  }
  set show_share_button(show_share_button) {
    this.$$set({ show_share_button });
    flush();
  }
  get sources() {
    return this.$$.ctx[18];
  }
  set sources(sources) {
    this.$$set({ sources });
    flush();
  }
  get interactive() {
    return this.$$.ctx[19];
  }
  set interactive(interactive) {
    this.$$set({ interactive });
    flush();
  }
  get streaming() {
    return this.$$.ctx[20];
  }
  set streaming(streaming) {
    this.$$set({ streaming });
    flush();
  }
  get pending() {
    return this.$$.ctx[21];
  }
  set pending(pending) {
    this.$$set({ pending });
    flush();
  }
  get placeholder() {
    return this.$$.ctx[22];
  }
  set placeholder(placeholder) {
    this.$$set({ placeholder });
    flush();
  }
  get show_fullscreen_button() {
    return this.$$.ctx[23];
  }
  set show_fullscreen_button(show_fullscreen_button) {
    this.$$set({ show_fullscreen_button });
    flush();
  }
  get input_ready() {
    return this.$$.ctx[35];
  }
  set input_ready(input_ready) {
    this.$$set({ input_ready });
    flush();
  }
  get webcam_options() {
    return this.$$.ctx[24];
  }
  set webcam_options(webcam_options) {
    this.$$set({ webcam_options });
    flush();
  }
  get gradio() {
    return this.$$.ctx[25];
  }
  set gradio(gradio) {
    this.$$set({ gradio });
    flush();
  }
};
function create_default_slot(ctx) {
  var _a, _b;
  let statustracker;
  let t;
  let table;
  let updating_value_is_output;
  let current;
  const statustracker_spread_levels = [
    {
      autoscroll: (
        /*gradio*/
        ctx[17].autoscroll
      )
    },
    { i18n: (
      /*gradio*/
      ctx[17].i18n
    ) },
    /*loading_status*/
    ctx[20]
  ];
  let statustracker_props = {};
  for (let i = 0; i < statustracker_spread_levels.length; i += 1) {
    statustracker_props = assign(statustracker_props, statustracker_spread_levels[i]);
  }
  statustracker = new Static({ props: statustracker_props });
  statustracker.$on(
    "clear_status",
    /*clear_status_handler*/
    ctx[29]
  );
  function table_value_is_output_binding(value) {
    ctx[32](value);
  }
  let table_props = {
    root: (
      /*root*/
      ctx[14]
    ),
    label: (
      /*label*/
      ctx[8]
    ),
    show_label: (
      /*show_label*/
      ctx[9]
    ),
    row_count: (
      /*row_count*/
      ctx[7]
    ),
    col_count: (
      /*col_count*/
      ctx[6]
    ),
    values: (
      /*value*/
      ctx[0].data
    ),
    display_value: (
      /*value*/
      (_a = ctx[0].metadata) == null ? void 0 : _a.display_value
    ),
    styling: (
      /*value*/
      (_b = ctx[0].metadata) == null ? void 0 : _b.styling
    ),
    headers: (
      /*value*/
      ctx[0].headers
    ),
    fullscreen: (
      /*fullscreen*/
      ctx[2]
    ),
    wrap: (
      /*wrap*/
      ctx[10]
    ),
    datatype: (
      /*datatype*/
      ctx[11]
    ),
    latex_delimiters: (
      /*latex_delimiters*/
      ctx[18]
    ),
    editable: (
      /*interactive*/
      ctx[21]
    ),
    max_height: (
      /*max_height*/
      ctx[19]
    ),
    i18n: (
      /*gradio*/
      ctx[17].i18n
    ),
    line_breaks: (
      /*line_breaks*/
      ctx[15]
    ),
    column_widths: (
      /*column_widths*/
      ctx[16]
    ),
    upload: (
      /*func*/
      ctx[30]
    ),
    stream_handler: (
      /*func_1*/
      ctx[31]
    ),
    show_fullscreen_button: (
      /*show_fullscreen_button*/
      ctx[22]
    ),
    max_chars: (
      /*max_chars*/
      ctx[23]
    ),
    show_copy_button: (
      /*show_copy_button*/
      ctx[24]
    ),
    show_row_numbers: (
      /*show_row_numbers*/
      ctx[25]
    ),
    show_search: (
      /*show_search*/
      ctx[26]
    ),
    pinned_columns: (
      /*pinned_columns*/
      ctx[27]
    ),
    components: { image: Index$2 },
    static_columns: (
      /*static_columns*/
      ctx[28]
    )
  };
  if (
    /*value_is_output*/
    ctx[1] !== void 0
  ) {
    table_props.value_is_output = /*value_is_output*/
    ctx[1];
  }
  table = new Table$1({ props: table_props });
  binding_callbacks.push(() => bind(table, "value_is_output", table_value_is_output_binding));
  table.$on(
    "change",
    /*change_handler*/
    ctx[33]
  );
  table.$on(
    "input",
    /*input_handler*/
    ctx[34]
  );
  table.$on(
    "select",
    /*select_handler*/
    ctx[35]
  );
  table.$on(
    "edit",
    /*edit_handler*/
    ctx[36]
  );
  table.$on(
    "fullscreen",
    /*fullscreen_handler*/
    ctx[37]
  );
  return {
    c() {
      create_component(statustracker.$$.fragment);
      t = space();
      create_component(table.$$.fragment);
    },
    m(target, anchor) {
      mount_component(statustracker, target, anchor);
      insert(target, t, anchor);
      mount_component(table, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      var _a2, _b2;
      const statustracker_changes = dirty[0] & /*gradio, loading_status*/
      1179648 ? get_spread_update(statustracker_spread_levels, [
        dirty[0] & /*gradio*/
        131072 && {
          autoscroll: (
            /*gradio*/
            ctx2[17].autoscroll
          )
        },
        dirty[0] & /*gradio*/
        131072 && { i18n: (
          /*gradio*/
          ctx2[17].i18n
        ) },
        dirty[0] & /*loading_status*/
        1048576 && get_spread_object(
          /*loading_status*/
          ctx2[20]
        )
      ]) : {};
      statustracker.$set(statustracker_changes);
      const table_changes = {};
      if (dirty[0] & /*root*/
      16384) table_changes.root = /*root*/
      ctx2[14];
      if (dirty[0] & /*label*/
      256) table_changes.label = /*label*/
      ctx2[8];
      if (dirty[0] & /*show_label*/
      512) table_changes.show_label = /*show_label*/
      ctx2[9];
      if (dirty[0] & /*row_count*/
      128) table_changes.row_count = /*row_count*/
      ctx2[7];
      if (dirty[0] & /*col_count*/
      64) table_changes.col_count = /*col_count*/
      ctx2[6];
      if (dirty[0] & /*value*/
      1) table_changes.values = /*value*/
      ctx2[0].data;
      if (dirty[0] & /*value*/
      1) table_changes.display_value = /*value*/
      (_a2 = ctx2[0].metadata) == null ? void 0 : _a2.display_value;
      if (dirty[0] & /*value*/
      1) table_changes.styling = /*value*/
      (_b2 = ctx2[0].metadata) == null ? void 0 : _b2.styling;
      if (dirty[0] & /*value*/
      1) table_changes.headers = /*value*/
      ctx2[0].headers;
      if (dirty[0] & /*fullscreen*/
      4) table_changes.fullscreen = /*fullscreen*/
      ctx2[2];
      if (dirty[0] & /*wrap*/
      1024) table_changes.wrap = /*wrap*/
      ctx2[10];
      if (dirty[0] & /*datatype*/
      2048) table_changes.datatype = /*datatype*/
      ctx2[11];
      if (dirty[0] & /*latex_delimiters*/
      262144) table_changes.latex_delimiters = /*latex_delimiters*/
      ctx2[18];
      if (dirty[0] & /*interactive*/
      2097152) table_changes.editable = /*interactive*/
      ctx2[21];
      if (dirty[0] & /*max_height*/
      524288) table_changes.max_height = /*max_height*/
      ctx2[19];
      if (dirty[0] & /*gradio*/
      131072) table_changes.i18n = /*gradio*/
      ctx2[17].i18n;
      if (dirty[0] & /*line_breaks*/
      32768) table_changes.line_breaks = /*line_breaks*/
      ctx2[15];
      if (dirty[0] & /*column_widths*/
      65536) table_changes.column_widths = /*column_widths*/
      ctx2[16];
      if (dirty[0] & /*gradio*/
      131072) table_changes.upload = /*func*/
      ctx2[30];
      if (dirty[0] & /*gradio*/
      131072) table_changes.stream_handler = /*func_1*/
      ctx2[31];
      if (dirty[0] & /*show_fullscreen_button*/
      4194304) table_changes.show_fullscreen_button = /*show_fullscreen_button*/
      ctx2[22];
      if (dirty[0] & /*max_chars*/
      8388608) table_changes.max_chars = /*max_chars*/
      ctx2[23];
      if (dirty[0] & /*show_copy_button*/
      16777216) table_changes.show_copy_button = /*show_copy_button*/
      ctx2[24];
      if (dirty[0] & /*show_row_numbers*/
      33554432) table_changes.show_row_numbers = /*show_row_numbers*/
      ctx2[25];
      if (dirty[0] & /*show_search*/
      67108864) table_changes.show_search = /*show_search*/
      ctx2[26];
      if (dirty[0] & /*pinned_columns*/
      134217728) table_changes.pinned_columns = /*pinned_columns*/
      ctx2[27];
      if (dirty[0] & /*static_columns*/
      268435456) table_changes.static_columns = /*static_columns*/
      ctx2[28];
      if (!updating_value_is_output && dirty[0] & /*value_is_output*/
      2) {
        updating_value_is_output = true;
        table_changes.value_is_output = /*value_is_output*/
        ctx2[1];
        add_flush_callback(() => updating_value_is_output = false);
      }
      table.$set(table_changes);
    },
    i(local) {
      if (current) return;
      transition_in(statustracker.$$.fragment, local);
      transition_in(table.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(statustracker.$$.fragment, local);
      transition_out(table.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(t);
      }
      destroy_component(statustracker, detaching);
      destroy_component(table, detaching);
    }
  };
}
function create_fragment$1(ctx) {
  let block2;
  let updating_fullscreen;
  let current;
  function block_fullscreen_binding(value) {
    ctx[38](value);
  }
  let block_props = {
    visible: (
      /*visible*/
      ctx[5]
    ),
    padding: false,
    elem_id: (
      /*elem_id*/
      ctx[3]
    ),
    elem_classes: (
      /*elem_classes*/
      ctx[4]
    ),
    container: false,
    scale: (
      /*scale*/
      ctx[12]
    ),
    min_width: (
      /*min_width*/
      ctx[13]
    ),
    overflow_behavior: "visible",
    $$slots: { default: [create_default_slot] },
    $$scope: { ctx }
  };
  if (
    /*fullscreen*/
    ctx[2] !== void 0
  ) {
    block_props.fullscreen = /*fullscreen*/
    ctx[2];
  }
  block2 = new Block({ props: block_props });
  binding_callbacks.push(() => bind(block2, "fullscreen", block_fullscreen_binding));
  return {
    c() {
      create_component(block2.$$.fragment);
    },
    m(target, anchor) {
      mount_component(block2, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const block_changes = {};
      if (dirty[0] & /*visible*/
      32) block_changes.visible = /*visible*/
      ctx2[5];
      if (dirty[0] & /*elem_id*/
      8) block_changes.elem_id = /*elem_id*/
      ctx2[3];
      if (dirty[0] & /*elem_classes*/
      16) block_changes.elem_classes = /*elem_classes*/
      ctx2[4];
      if (dirty[0] & /*scale*/
      4096) block_changes.scale = /*scale*/
      ctx2[12];
      if (dirty[0] & /*min_width*/
      8192) block_changes.min_width = /*min_width*/
      ctx2[13];
      if (dirty[0] & /*root, label, show_label, row_count, col_count, value, fullscreen, wrap, datatype, latex_delimiters, interactive, max_height, gradio, line_breaks, column_widths, show_fullscreen_button, max_chars, show_copy_button, show_row_numbers, show_search, pinned_columns, static_columns, value_is_output, loading_status*/
      536858567 | dirty[1] & /*$$scope*/
      256) {
        block_changes.$$scope = { dirty, ctx: ctx2 };
      }
      if (!updating_fullscreen && dirty[0] & /*fullscreen*/
      4) {
        updating_fullscreen = true;
        block_changes.fullscreen = /*fullscreen*/
        ctx2[2];
        add_flush_callback(() => updating_fullscreen = false);
      }
      block2.$set(block_changes);
    },
    i(local) {
      if (current) return;
      transition_in(block2.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(block2.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(block2, detaching);
    }
  };
}
function instance$1($$self, $$props, $$invalidate) {
  let { elem_id = "" } = $$props;
  let { elem_classes = [] } = $$props;
  let { visible = true } = $$props;
  let { value = {
    data: [["", "", ""]],
    headers: ["1", "2", "3"],
    metadata: null
  } } = $$props;
  let { value_is_output = false } = $$props;
  let { col_count } = $$props;
  let { row_count } = $$props;
  let { label = null } = $$props;
  let { show_label = true } = $$props;
  let { wrap } = $$props;
  let { datatype } = $$props;
  let { scale = null } = $$props;
  let { min_width = void 0 } = $$props;
  let { root } = $$props;
  let { line_breaks = true } = $$props;
  let { column_widths = [] } = $$props;
  let { gradio } = $$props;
  let { latex_delimiters } = $$props;
  let { max_height = void 0 } = $$props;
  let { loading_status } = $$props;
  let { interactive } = $$props;
  let { show_fullscreen_button = false } = $$props;
  let { max_chars = void 0 } = $$props;
  let { show_copy_button = false } = $$props;
  let { show_row_numbers = false } = $$props;
  let { show_search = "none" } = $$props;
  let { pinned_columns = 0 } = $$props;
  let { static_columns = [] } = $$props;
  let { fullscreen = false } = $$props;
  const clear_status_handler = () => gradio.dispatch("clear_status", loading_status);
  const func2 = (...args) => gradio.client.upload(...args);
  const func_1 = (...args) => gradio.client.stream(...args);
  function table_value_is_output_binding(value2) {
    value_is_output = value2;
    $$invalidate(1, value_is_output);
  }
  const change_handler = (e) => {
    $$invalidate(0, value.data = e.detail.data, value);
    $$invalidate(0, value.headers = e.detail.headers, value);
    gradio.dispatch("change");
  };
  const input_handler = (e) => gradio.dispatch("input");
  const select_handler = (e) => gradio.dispatch("select", e.detail);
  const edit_handler = (e) => gradio.dispatch("edit", e.detail);
  const fullscreen_handler = ({ detail }) => {
    $$invalidate(2, fullscreen = detail);
  };
  function block_fullscreen_binding(value2) {
    fullscreen = value2;
    $$invalidate(2, fullscreen);
  }
  $$self.$$set = ($$props2) => {
    if ("elem_id" in $$props2) $$invalidate(3, elem_id = $$props2.elem_id);
    if ("elem_classes" in $$props2) $$invalidate(4, elem_classes = $$props2.elem_classes);
    if ("visible" in $$props2) $$invalidate(5, visible = $$props2.visible);
    if ("value" in $$props2) $$invalidate(0, value = $$props2.value);
    if ("value_is_output" in $$props2) $$invalidate(1, value_is_output = $$props2.value_is_output);
    if ("col_count" in $$props2) $$invalidate(6, col_count = $$props2.col_count);
    if ("row_count" in $$props2) $$invalidate(7, row_count = $$props2.row_count);
    if ("label" in $$props2) $$invalidate(8, label = $$props2.label);
    if ("show_label" in $$props2) $$invalidate(9, show_label = $$props2.show_label);
    if ("wrap" in $$props2) $$invalidate(10, wrap = $$props2.wrap);
    if ("datatype" in $$props2) $$invalidate(11, datatype = $$props2.datatype);
    if ("scale" in $$props2) $$invalidate(12, scale = $$props2.scale);
    if ("min_width" in $$props2) $$invalidate(13, min_width = $$props2.min_width);
    if ("root" in $$props2) $$invalidate(14, root = $$props2.root);
    if ("line_breaks" in $$props2) $$invalidate(15, line_breaks = $$props2.line_breaks);
    if ("column_widths" in $$props2) $$invalidate(16, column_widths = $$props2.column_widths);
    if ("gradio" in $$props2) $$invalidate(17, gradio = $$props2.gradio);
    if ("latex_delimiters" in $$props2) $$invalidate(18, latex_delimiters = $$props2.latex_delimiters);
    if ("max_height" in $$props2) $$invalidate(19, max_height = $$props2.max_height);
    if ("loading_status" in $$props2) $$invalidate(20, loading_status = $$props2.loading_status);
    if ("interactive" in $$props2) $$invalidate(21, interactive = $$props2.interactive);
    if ("show_fullscreen_button" in $$props2) $$invalidate(22, show_fullscreen_button = $$props2.show_fullscreen_button);
    if ("max_chars" in $$props2) $$invalidate(23, max_chars = $$props2.max_chars);
    if ("show_copy_button" in $$props2) $$invalidate(24, show_copy_button = $$props2.show_copy_button);
    if ("show_row_numbers" in $$props2) $$invalidate(25, show_row_numbers = $$props2.show_row_numbers);
    if ("show_search" in $$props2) $$invalidate(26, show_search = $$props2.show_search);
    if ("pinned_columns" in $$props2) $$invalidate(27, pinned_columns = $$props2.pinned_columns);
    if ("static_columns" in $$props2) $$invalidate(28, static_columns = $$props2.static_columns);
    if ("fullscreen" in $$props2) $$invalidate(2, fullscreen = $$props2.fullscreen);
  };
  return [
    value,
    value_is_output,
    fullscreen,
    elem_id,
    elem_classes,
    visible,
    col_count,
    row_count,
    label,
    show_label,
    wrap,
    datatype,
    scale,
    min_width,
    root,
    line_breaks,
    column_widths,
    gradio,
    latex_delimiters,
    max_height,
    loading_status,
    interactive,
    show_fullscreen_button,
    max_chars,
    show_copy_button,
    show_row_numbers,
    show_search,
    pinned_columns,
    static_columns,
    clear_status_handler,
    func2,
    func_1,
    table_value_is_output_binding,
    change_handler,
    input_handler,
    select_handler,
    edit_handler,
    fullscreen_handler,
    block_fullscreen_binding
  ];
}
let Index$1$1 = class Index2 extends SvelteComponent {
  constructor(options) {
    super();
    init(
      this,
      options,
      instance$1,
      create_fragment$1,
      safe_not_equal,
      {
        elem_id: 3,
        elem_classes: 4,
        visible: 5,
        value: 0,
        value_is_output: 1,
        col_count: 6,
        row_count: 7,
        label: 8,
        show_label: 9,
        wrap: 10,
        datatype: 11,
        scale: 12,
        min_width: 13,
        root: 14,
        line_breaks: 15,
        column_widths: 16,
        gradio: 17,
        latex_delimiters: 18,
        max_height: 19,
        loading_status: 20,
        interactive: 21,
        show_fullscreen_button: 22,
        max_chars: 23,
        show_copy_button: 24,
        show_row_numbers: 25,
        show_search: 26,
        pinned_columns: 27,
        static_columns: 28,
        fullscreen: 2
      },
      null,
      [-1, -1]
    );
  }
  get elem_id() {
    return this.$$.ctx[3];
  }
  set elem_id(elem_id) {
    this.$$set({ elem_id });
    flush();
  }
  get elem_classes() {
    return this.$$.ctx[4];
  }
  set elem_classes(elem_classes) {
    this.$$set({ elem_classes });
    flush();
  }
  get visible() {
    return this.$$.ctx[5];
  }
  set visible(visible) {
    this.$$set({ visible });
    flush();
  }
  get value() {
    return this.$$.ctx[0];
  }
  set value(value) {
    this.$$set({ value });
    flush();
  }
  get value_is_output() {
    return this.$$.ctx[1];
  }
  set value_is_output(value_is_output) {
    this.$$set({ value_is_output });
    flush();
  }
  get col_count() {
    return this.$$.ctx[6];
  }
  set col_count(col_count) {
    this.$$set({ col_count });
    flush();
  }
  get row_count() {
    return this.$$.ctx[7];
  }
  set row_count(row_count) {
    this.$$set({ row_count });
    flush();
  }
  get label() {
    return this.$$.ctx[8];
  }
  set label(label) {
    this.$$set({ label });
    flush();
  }
  get show_label() {
    return this.$$.ctx[9];
  }
  set show_label(show_label) {
    this.$$set({ show_label });
    flush();
  }
  get wrap() {
    return this.$$.ctx[10];
  }
  set wrap(wrap) {
    this.$$set({ wrap });
    flush();
  }
  get datatype() {
    return this.$$.ctx[11];
  }
  set datatype(datatype) {
    this.$$set({ datatype });
    flush();
  }
  get scale() {
    return this.$$.ctx[12];
  }
  set scale(scale) {
    this.$$set({ scale });
    flush();
  }
  get min_width() {
    return this.$$.ctx[13];
  }
  set min_width(min_width) {
    this.$$set({ min_width });
    flush();
  }
  get root() {
    return this.$$.ctx[14];
  }
  set root(root) {
    this.$$set({ root });
    flush();
  }
  get line_breaks() {
    return this.$$.ctx[15];
  }
  set line_breaks(line_breaks) {
    this.$$set({ line_breaks });
    flush();
  }
  get column_widths() {
    return this.$$.ctx[16];
  }
  set column_widths(column_widths) {
    this.$$set({ column_widths });
    flush();
  }
  get gradio() {
    return this.$$.ctx[17];
  }
  set gradio(gradio) {
    this.$$set({ gradio });
    flush();
  }
  get latex_delimiters() {
    return this.$$.ctx[18];
  }
  set latex_delimiters(latex_delimiters) {
    this.$$set({ latex_delimiters });
    flush();
  }
  get max_height() {
    return this.$$.ctx[19];
  }
  set max_height(max_height) {
    this.$$set({ max_height });
    flush();
  }
  get loading_status() {
    return this.$$.ctx[20];
  }
  set loading_status(loading_status) {
    this.$$set({ loading_status });
    flush();
  }
  get interactive() {
    return this.$$.ctx[21];
  }
  set interactive(interactive) {
    this.$$set({ interactive });
    flush();
  }
  get show_fullscreen_button() {
    return this.$$.ctx[22];
  }
  set show_fullscreen_button(show_fullscreen_button) {
    this.$$set({ show_fullscreen_button });
    flush();
  }
  get max_chars() {
    return this.$$.ctx[23];
  }
  set max_chars(max_chars) {
    this.$$set({ max_chars });
    flush();
  }
  get show_copy_button() {
    return this.$$.ctx[24];
  }
  set show_copy_button(show_copy_button) {
    this.$$set({ show_copy_button });
    flush();
  }
  get show_row_numbers() {
    return this.$$.ctx[25];
  }
  set show_row_numbers(show_row_numbers) {
    this.$$set({ show_row_numbers });
    flush();
  }
  get show_search() {
    return this.$$.ctx[26];
  }
  set show_search(show_search) {
    this.$$set({ show_search });
    flush();
  }
  get pinned_columns() {
    return this.$$.ctx[27];
  }
  set pinned_columns(pinned_columns) {
    this.$$set({ pinned_columns });
    flush();
  }
  get static_columns() {
    return this.$$.ctx[28];
  }
  set static_columns(static_columns) {
    this.$$set({ static_columns });
    flush();
  }
  get fullscreen() {
    return this.$$.ctx[2];
  }
  set fullscreen(fullscreen) {
    this.$$set({ fullscreen });
    flush();
  }
};
function create_fragment(ctx) {
  let df;
  let current;
  const df_spread_levels = [
    /*$$props*/
    ctx[0]
  ];
  let df_props = {};
  for (let i = 0; i < df_spread_levels.length; i += 1) {
    df_props = assign(df_props, df_spread_levels[i]);
  }
  df = new Index$1$1({ props: df_props });
  return {
    c() {
      create_component(df.$$.fragment);
    },
    m(target, anchor) {
      mount_component(df, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const df_changes = dirty & /*$$props*/
      1 ? get_spread_update(df_spread_levels, [get_spread_object(
        /*$$props*/
        ctx2[0]
      )]) : {};
      df.$set(df_changes);
    },
    i(local) {
      if (current) return;
      transition_in(df.$$.fragment, local);
      current = true;
    },
    o(local) {
      transition_out(df.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(df, detaching);
    }
  };
}
function instance($$self, $$props, $$invalidate) {
  $$self.$$set = ($$new_props) => {
    $$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
  };
  $$props = exclude_internal_props($$props);
  return [$$props];
}
class Index3 extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance, create_fragment, safe_not_equal, {});
  }
}

function get_sort_status(name, sort_columns, headers) {
  if (!sort_columns.length) return "none";
  const sort_item = sort_columns.find((item) => {
    const col = item.col;
    if (col < 0 || col >= headers.length) return false;
    return headers[col] === name;
  });
  if (!sort_item) return "none";
  return sort_item.direction;
}
function sort_data(data, sort_columns) {
  if (!data || !data.length || !data[0]) {
    return [];
  }
  if (sort_columns.length > 0) {
    const row_indices = [...Array(data.length)].map((_, i) => i);
    row_indices.sort((row_a_idx, row_b_idx) => {
      const row_a = data[row_a_idx];
      const row_b = data[row_b_idx];
      for (const { col: sort_by, direction } of sort_columns) {
        if (!row_a || !row_b || sort_by < 0 || sort_by >= row_a.length || sort_by >= row_b.length || !row_a[sort_by] || !row_b[sort_by]) {
          continue;
        }
        const val_a = row_a[sort_by].value;
        const val_b = row_b[sort_by].value;
        const comparison = val_a < val_b ? -1 : val_a > val_b ? 1 : 0;
        if (comparison !== 0) {
          return direction === "asc" ? comparison : -comparison;
        }
      }
      return 0;
    });
    return row_indices;
  }
  return [...Array(data.length)].map((_, i) => i);
}
function sort_data_and_preserve_selection(data, display_value, styling, sort_columns, selected, get_current_indices) {
  let id = null;
  if (selected && selected[0] in data && selected[1] in data[selected[0]]) {
    id = data[selected[0]][selected[1]].id;
  }
  sort_table_data(data, display_value, styling, sort_columns);
  let new_selected = selected;
  if (id) {
    const [i, j] = get_current_indices(id, data);
    new_selected = [i, j];
  }
  return { data, selected: new_selected };
}

function filter_data(data, filter_columns) {
  if (!data || !data.length || !data[0]) {
    return [];
  }
  let row_indices = [...Array(data.length)].map((_, i) => i);
  if (filter_columns.length > 0) {
    filter_columns.forEach((column) => {
      if (column.datatype === "string") {
        switch (column.filter) {
          case "Contains":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString().includes(column.value)
            );
            break;
          case "Does not contain":
            row_indices = row_indices.filter(
              (i) => !data[i][column.col]?.value.toString().includes(column.value)
            );
            break;
          case "Starts with":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString().startsWith(column.value)
            );
            break;
          case "Ends with":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString().endsWith(column.value)
            );
            break;
          case "Is":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString() === column.value
            );
            break;
          case "Is not":
            row_indices = row_indices.filter(
              (i) => !(data[i][column.col]?.value.toString() === column.value)
            );
            break;
          case "Is empty":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString() === ""
            );
            break;
          case "Is not empty":
            row_indices = row_indices.filter(
              (i) => !(data[i][column.col]?.value.toString() === "")
            );
            break;
        }
      } else if (column.datatype === "number") {
        switch (column.filter) {
          case "=":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return Number(data[i][column.col]?.value) === Number(column.value);
              }
              return false;
            });
            break;
          case "≠":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return !(Number(data[i][column.col]?.value) === Number(column.value));
              }
              return false;
            });
            break;
          case ">":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return Number(data[i][column.col]?.value) > Number(column.value);
              }
              return false;
            });
            break;
          case "<":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return Number(data[i][column.col]?.value) < Number(column.value);
              }
              return false;
            });
            break;
          case "≥":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return Number(data[i][column.col]?.value) >= Number(column.value);
              }
              return false;
            });
            break;
          case "≤":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value)) && !isNaN(Number(column.value))) {
                return Number(data[i][column.col]?.value) <= Number(column.value);
              }
              return false;
            });
            break;
          case "Is empty":
            row_indices = row_indices.filter(
              (i) => data[i][column.col]?.value.toString() === ""
            );
            break;
          case "Is not empty":
            row_indices = row_indices.filter((i) => {
              if (!isNaN(Number(data[i][column.col]?.value))) {
                return !(data[i][column.col]?.value.toString() === "");
              }
              return false;
            });
            break;
        }
      }
    });
    return row_indices;
  }
  return [...Array(data.length)].map((_, i) => i);
}
function filter_data_and_preserve_selection(data, display_value, styling, filter_columns, selected, get_current_indices, original_data, original_display_value, original_styling) {
  let id = null;
  if (selected && selected[0] in data && selected[1] in data[selected[0]]) {
    id = data[selected[0]][selected[1]].id;
  }
  filter_table_data(
    data,
    display_value,
    styling,
    filter_columns,
    original_data,
    original_display_value,
    original_styling
  );
  let new_selected = selected;
  if (id) {
    const [i, j] = get_current_indices(id, data);
    new_selected = [i, j];
  }
  return { data, selected: new_selected };
}

function get_max(data) {
  if (!data || !data.length) return [];
  let max = data[0].slice();
  for (let i = 0; i < data.length; i++) {
    for (let j = 0; j < data[i].length; j++) {
      if (`${max[j].value}`.length < `${data[i][j].value}`.length) {
        max[j] = data[i][j];
      }
    }
  }
  return max;
}
function sort_table_data(data, display_value, styling, sort_columns) {
  if (!sort_columns.length) return;
  if (!data || !data.length) return;
  const indices = sort_data(data, sort_columns);
  const new_data = indices.map((i) => data[i]);
  data.splice(0, data.length, ...new_data);
  if (display_value) {
    const new_display = indices.map((i) => display_value[i]);
    display_value.splice(0, display_value.length, ...new_display);
  }
  if (styling) {
    const new_styling = indices.map((i) => styling[i]);
    styling.splice(0, styling.length, ...new_styling);
  }
}
function filter_table_data(data, display_value, styling, filter_columns, original_data, original_display_value, original_styling) {
  const base_data = original_data ?? data;
  const base_display_value = original_display_value ?? display_value;
  const base_styling = original_styling ?? styling;
  if (!filter_columns.length) {
    data.splice(0, data.length, ...base_data.map((row) => [...row]));
    if (display_value && base_display_value) {
      display_value.splice(
        0,
        display_value.length,
        ...base_display_value.map((row) => [...row])
      );
    }
    if (styling && base_styling) {
      styling.splice(0, styling.length, ...base_styling.map((row) => [...row]));
    }
    return;
  }
  if (!data || !data.length) return;
  const indices = filter_data(base_data, filter_columns);
  const new_data = indices.map((i) => base_data[i]);
  data.splice(0, data.length, ...new_data);
  if (display_value && base_display_value) {
    const new_display = indices.map((i) => base_display_value[i]);
    display_value.splice(0, display_value.length, ...new_display);
  }
  if (styling && base_styling) {
    const new_styling = indices.map((i) => base_styling[i]);
    styling.splice(0, styling.length, ...new_styling);
  }
}
async function copy_table_data(data, selected_cells) {
  if (!data || !data.length) return;
  const cells_to_copy = selected_cells || data.flatMap((row, r) => row.map((_, c) => [r, c]));
  const csv = cells_to_copy.reduce(
    (acc, [row, col]) => {
      acc[row] = acc[row] || {};
      const value = String(data[row][col].value);
      acc[row][col] = value.includes(",") || value.includes('"') || value.includes("\n") ? `"${value.replace(/"/g, '""')}"` : value;
      return acc;
    },
    {}
  );
  const rows = Object.keys(csv).sort((a, b) => +a - +b);
  if (!rows.length) return;
  const cols = Object.keys(csv[rows[0]]).sort((a, b) => +a - +b);
  const text = rows.map((r) => cols.map((c) => csv[r][c] || "").join(",")).join("\n");
  try {
    await navigator.clipboard.writeText(text);
  } catch (err) {
    throw new Error("Failed to copy to clipboard: " + err.message);
  }
}
function guess_delimiter(text, possibleDelimiters) {
  return possibleDelimiters.filter(weedOut);
  function weedOut(delimiter) {
    var cache = -1;
    return text.split("\n").every(checkLength);
    function checkLength(line) {
      if (!line) return true;
      var length = line.split(delimiter).length;
      if (cache < 0) cache = length;
      return cache === length && length > 1;
    }
  }
}
function data_uri_to_blob(data_uri) {
  const byte_str = atob(data_uri.split(",")[1]);
  const mime_str = data_uri.split(",")[0].split(":")[1].split(";")[0];
  const ab = new ArrayBuffer(byte_str.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byte_str.length; i++) {
    ia[i] = byte_str.charCodeAt(i);
  }
  return new Blob([ab], { type: mime_str });
}
function handle_file_upload(data_uri, update_headers, update_values) {
  const blob = data_uri_to_blob(data_uri);
  const reader = new FileReader();
  reader.addEventListener("loadend", (e) => {
    if (!e?.target?.result || typeof e.target.result !== "string") return;
    const [delimiter] = guess_delimiter(e.target.result, [",", "	"]);
    const [head, ...rest] = dsvFormat$1(delimiter).parseRows(e.target.result);
    update_headers(head);
    update_values(rest);
  });
  reader.readAsText(blob);
}

function is_cell_in_selection(coords, selected_cells) {
  const [row, col] = coords;
  return selected_cells.some(([r, c]) => r === row && c === col);
}
function is_cell_selected(cell, selected_cells) {
  const [row, col] = cell;
  if (!selected_cells.some(([r, c]) => r === row && c === col)) return "";
  const up = selected_cells.some(([r, c]) => r === row - 1 && c === col);
  const down = selected_cells.some(([r, c]) => r === row + 1 && c === col);
  const left = selected_cells.some(([r, c]) => r === row && c === col - 1);
  const right = selected_cells.some(([r, c]) => r === row && c === col + 1);
  return `cell-selected${up ? " no-top" : ""}${down ? " no-bottom" : ""}${left ? " no-left" : ""}${right ? " no-right" : ""}`;
}
function get_range_selection(start, end) {
  const [start_row, start_col] = start;
  const [end_row, end_col] = end;
  const min_row = Math.min(start_row, end_row);
  const max_row = Math.max(start_row, end_row);
  const min_col = Math.min(start_col, end_col);
  const max_col = Math.max(start_col, end_col);
  const cells = [];
  cells.push(start);
  for (let i = min_row; i <= max_row; i++) {
    for (let j = min_col; j <= max_col; j++) {
      if (i === start_row && j === start_col) continue;
      cells.push([i, j]);
    }
  }
  return cells;
}
function handle_selection(current, selected_cells, event) {
  if (event.shiftKey && selected_cells.length > 0) {
    return get_range_selection(
      selected_cells[selected_cells.length - 1],
      current
    );
  }
  if (event.metaKey || event.ctrlKey) {
    const is_cell_match = ([r, c]) => r === current[0] && c === current[1];
    const index = selected_cells.findIndex(is_cell_match);
    return index === -1 ? [...selected_cells, current] : selected_cells.filter((_, i) => i !== index);
  }
  return [current];
}
function handle_delete_key(data, selected_cells) {
  const new_data = data.map((row) => [...row]);
  selected_cells.forEach(([row, col]) => {
    if (new_data[row] && new_data[row][col]) {
      new_data[row][col] = { ...new_data[row][col], value: "" };
    }
  });
  return new_data;
}
function should_show_cell_menu(cell, selected_cells, editable) {
  const [row, col] = cell;
  return editable && selected_cells.length === 1 && selected_cells[0][0] === row && selected_cells[0][1] === col;
}
function get_next_cell_coordinates(current, data, shift_key) {
  const [row, col] = current;
  const direction = shift_key ? -1 : 1;
  if (data[row]?.[col + direction]) {
    return [row, col + direction];
  }
  const next_row = row + (direction > 0 ? 1 : 0);
  const prev_row = row + (direction < 0 ? -1 : 0);
  if (direction > 0 && data[next_row]?.[0]) {
    return [next_row, 0];
  }
  if (direction < 0 && data[prev_row]?.[data[0].length - 1]) {
    return [prev_row, data[0].length - 1];
  }
  return false;
}
function move_cursor(event, current_coords, data) {
  const key = event.key;
  const dir = {
    ArrowRight: [0, 1],
    ArrowLeft: [0, -1],
    ArrowDown: [1, 0],
    ArrowUp: [-1, 0]
  }[key];
  let i, j;
  if (event.metaKey || event.ctrlKey) {
    if (key === "ArrowRight") {
      i = current_coords[0];
      j = data[0].length - 1;
    } else if (key === "ArrowLeft") {
      i = current_coords[0];
      j = 0;
    } else if (key === "ArrowDown") {
      i = data.length - 1;
      j = current_coords[1];
    } else if (key === "ArrowUp") {
      i = 0;
      j = current_coords[1];
    } else {
      return false;
    }
  } else {
    i = current_coords[0] + dir[0];
    j = current_coords[1] + dir[1];
  }
  if (i < 0 && j <= 0) {
    return false;
  }
  const is_data = data[i]?.[j];
  if (is_data) {
    return [i, j];
  }
  return false;
}
function get_current_indices(id, data) {
  return data.reduce(
    (acc, arr, i) => {
      const j = arr.reduce(
        (_acc, _data, k) => id === _data.id ? k : _acc,
        -1
      );
      return j === -1 ? acc : [i, j];
    },
    [-1, -1]
  );
}
function handle_click_outside(event, parent) {
  const [trigger] = event.composedPath();
  return !parent.contains(trigger);
}
function calculate_selection_positions(selected, data, els, parent, table) {
  const [row, col] = selected;
  if (!data[row]?.[col]) {
    return { col_pos: "0px", row_pos: void 0 };
  }
  const cell_id = data[row][col].id;
  const cell_el = els[cell_id]?.cell;
  if (!cell_el) {
    return { col_pos: "0px", row_pos: void 0 };
  }
  const cell_rect = cell_el.getBoundingClientRect();
  const table_rect = table.getBoundingClientRect();
  const col_pos = `${cell_rect.left - table_rect.left + cell_rect.width / 2}px`;
  const row_pos = `${cell_rect.top - table_rect.top + cell_rect.height / 2}px`;
  return { col_pos, row_pos };
}

const DATAFRAME_KEY = /* @__PURE__ */ Symbol("dataframe");
function create_actions(state, context) {
  const update_state = (updater) => state.update((s) => ({ ...s, ...updater(s) }));
  const add_row = (data, make_id, index) => {
    const new_row = data[0]?.length ? Array(data[0].length).fill(null).map(() => ({ value: "", id: make_id() })) : [{ value: "", id: make_id() }];
    const new_data = [...data];
    index !== void 0 ? new_data.splice(index, 0, new_row) : new_data.push(new_row);
    return new_data;
  };
  const add_col = (data, headers, make_id, index) => {
    const new_headers = [...headers, `Header ${headers.length + 1}`];
    const new_data = data.map((row) => [...row, { value: "", id: make_id() }]);
    if (index !== void 0) {
      new_headers.splice(index, 0, new_headers.pop());
      new_data.forEach((row) => row.splice(index, 0, row.pop()));
    }
    return { data: new_data, headers: new_headers };
  };
  const update_array = (source, target) => {
    if (source && target) {
      target.splice(0, target.length, ...JSON.parse(JSON.stringify(source)));
    }
  };
  return {
    handle_search: (query) => update_state((s) => ({ current_search_query: query })),
    handle_sort: (col, direction) => update_state((s) => {
      const sort_cols = s.sort_state.sort_columns.filter(
        (c) => c.col !== col
      );
      if (!s.sort_state.sort_columns.some(
        (c) => c.col === col && c.direction === direction
      )) {
        sort_cols.push({ col, direction });
      }
      const initial_data = s.sort_state.initial_data || (context.data && sort_cols.length > 0 ? {
        data: JSON.parse(JSON.stringify(context.data)),
        display_value: context.display_value ? JSON.parse(JSON.stringify(context.display_value)) : null,
        styling: context.styling ? JSON.parse(JSON.stringify(context.styling)) : null
      } : null);
      return {
        sort_state: {
          ...s.sort_state,
          sort_columns: sort_cols.slice(-3),
          initial_data
        }
      };
    }),
    handle_filter: (col, datatype, filter, value) => update_state((s) => {
      const filter_cols = s.filter_state.filter_columns.some(
        (c) => c.col === col
      ) ? s.filter_state.filter_columns.filter((c) => c.col !== col) : [
        ...s.filter_state.filter_columns,
        { col, datatype, filter, value }
      ];
      const initial_data = s.filter_state.initial_data || (context.data && filter_cols.length > 0 ? {
        data: JSON.parse(JSON.stringify(context.data)),
        display_value: context.display_value ? JSON.parse(JSON.stringify(context.display_value)) : null,
        styling: context.styling ? JSON.parse(JSON.stringify(context.styling)) : null
      } : null);
      return {
        filter_state: {
          ...s.filter_state,
          filter_columns: filter_cols,
          initial_data
        }
      };
    }),
    get_sort_status: (name, headers) => {
      const s = get(state);
      const sort_item = s.sort_state.sort_columns.find(
        (item) => headers[item.col] === name
      );
      return sort_item ? sort_item.direction : "none";
    },
    sort_data: (data, display_value, styling) => {
      const {
        sort_state: { sort_columns }
      } = get(state);
      if (sort_columns.length)
        sort_table_data(data, display_value, styling, sort_columns);
    },
    update_row_order: (data) => update_state((s) => ({
      sort_state: {
        ...s.sort_state,
        row_order: s.sort_state.sort_columns.length && data[0] ? [...Array(data.length)].map((_, i) => i).sort((a, b) => {
          for (const { col, direction } of s.sort_state.sort_columns) {
            const comp = (data[a]?.[col]?.value ?? "") < (data[b]?.[col]?.value ?? "") ? -1 : 1;
            return direction === "asc" ? comp : -comp;
          }
          return 0;
        }) : [...Array(data.length)].map((_, i) => i)
      }
    })),
    filter_data: (data) => {
      const query = get(state).current_search_query?.toLowerCase();
      return query ? data.filter(
        (row) => row.some(
          (cell) => String(cell?.value).toLowerCase().includes(query)
        )
      ) : data;
    },
    add_row,
    add_col,
    add_row_at: (data, index, position, make_id) => add_row(data, make_id, position === "above" ? index : index + 1),
    add_col_at: (data, headers, index, position, make_id) => add_col(data, headers, make_id, position === "left" ? index : index + 1),
    delete_row: (data, index) => data.length > 1 ? data.filter((_, i) => i !== index) : data,
    delete_col: (data, headers, index) => headers.length > 1 ? {
      data: data.map((row) => row.filter((_, i) => i !== index)),
      headers: headers.filter((_, i) => i !== index)
    } : { data, headers },
    delete_row_at: (data, index) => data.length > 1 ? [...data.slice(0, index), ...data.slice(index + 1)] : data,
    delete_col_at: (data, headers, index) => headers.length > 1 ? {
      data: data.map((row) => [
        ...row.slice(0, index),
        ...row.slice(index + 1)
      ]),
      headers: [...headers.slice(0, index), ...headers.slice(index + 1)]
    } : { data, headers },
    trigger_change: async (data, headers, previous_data, previous_headers, value_is_output, dispatch) => {
      const s = get(state);
      if (s.current_search_query) return;
      const current_headers = headers.map((h) => h.value);
      const current_data = data.map((row) => row.map((cell) => cell.value));
      if (!dequal$2(current_data, previous_data) || !dequal$2(current_headers, previous_headers)) {
        if (!dequal$2(current_headers, previous_headers)) {
          update_state((s2) => ({
            sort_state: { sort_columns: [], row_order: [], initial_data: null },
            filter_state: { filter_columns: [], initial_data: null }
          }));
        }
        dispatch("change", {
          data: data.map((row) => row.map((cell) => cell.value)),
          headers: current_headers,
          metadata: null
        });
        const index = s.ui_state.selected;
        if (index) {
          dispatch("edit", {
            index,
            value: data[index[0]][index[1]].value,
            previous_value: previous_data[index[0]][index[1]]
          });
        }
        if (!value_is_output) dispatch("input");
      }
    },
    reset_sort_state: () => update_state((s) => {
      if (s.sort_state.initial_data && context.data) {
        const original = s.sort_state.initial_data;
        update_array(original.data, context.data);
        update_array(original.display_value, context.display_value);
        update_array(original.styling, context.styling);
      }
      return {
        sort_state: { sort_columns: [], row_order: [], initial_data: null }
      };
    }),
    reset_filter_state: () => update_state((s) => {
      if (s.filter_state.initial_data && context.data) {
        const original = s.filter_state.initial_data;
        update_array(original.data, context.data);
        update_array(original.display_value, context.display_value);
        update_array(original.styling, context.styling);
      }
      return {
        filter_state: { filter_columns: [], initial_data: null }
      };
    }),
    set_active_cell_menu: (menu) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_cell_menu: menu }
    })),
    set_active_header_menu: (menu) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_header_menu: menu }
    })),
    set_selected_cells: (cells) => update_state((s) => ({
      ui_state: { ...s.ui_state, selected_cells: cells }
    })),
    set_selected: (selected) => update_state((s) => ({ ui_state: { ...s.ui_state, selected } })),
    set_editing: (editing) => update_state((s) => ({ ui_state: { ...s.ui_state, editing } })),
    clear_ui_state: () => update_state((s) => ({
      ui_state: {
        active_cell_menu: null,
        active_header_menu: null,
        selected_cells: [],
        selected: false,
        editing: false,
        header_edit: false,
        selected_header: false,
        active_button: null,
        copy_flash: false
      }
    })),
    set_header_edit: (header_index) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        selected_cells: [],
        selected_header: header_index,
        header_edit: header_index
      }
    })),
    set_selected_header: (header_index) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        selected_header: header_index,
        selected: false,
        selected_cells: []
      }
    })),
    handle_header_click: (col, editable) => update_state((s) => ({
      ui_state: {
        ...s.ui_state,
        active_cell_menu: null,
        active_header_menu: null,
        selected: false,
        selected_cells: [],
        selected_header: col,
        header_edit: editable ? col : false
      }
    })),
    end_header_edit: (key) => {
      if (["Escape", "Enter", "Tab"].includes(key)) {
        update_state((s) => ({
          ui_state: { ...s.ui_state, selected: false, header_edit: false }
        }));
      }
    },
    get_selected_cells: () => get(state).ui_state.selected_cells,
    get_active_cell_menu: () => get(state).ui_state.active_cell_menu,
    get_active_button: () => get(state).ui_state.active_button,
    set_active_button: (button) => update_state((s) => ({
      ui_state: { ...s.ui_state, active_button: button }
    })),
    set_copy_flash: (value) => update_state((s) => ({ ui_state: { ...s.ui_state, copy_flash: value } })),
    handle_cell_click: (event, row, col) => {
      event.preventDefault();
      event.stopPropagation();
      const s = get(state);
      if (s.config.show_row_numbers && col === -1) return;
      let actual_row = row;
      if (s.current_search_query && context.data) {
        const filtered_indices = [];
        context.data.forEach((dataRow, idx) => {
          if (dataRow.some(
            (cell) => String(cell?.value).toLowerCase().includes(s.current_search_query?.toLowerCase() || "")
          )) {
            filtered_indices.push(idx);
          }
        });
        actual_row = filtered_indices[row] ?? row;
      }
      const cells = handle_selection(
        [actual_row, col],
        s.ui_state.selected_cells,
        event
      );
      update_state((s2) => ({
        ui_state: {
          ...s2.ui_state,
          active_cell_menu: null,
          active_header_menu: null,
          selected_header: false,
          header_edit: false,
          selected_cells: cells,
          selected: cells[0]
        }
      }));
      if (s.config.editable && cells.length === 1) {
        update_state((s2) => ({
          ui_state: { ...s2.ui_state, editing: [actual_row, col] }
        }));
        tick$1().then(
          () => context.els[context.data[actual_row][col].id]?.input?.focus()
        );
      } else {
        tick$1().then(() => {
          if (context.parent_element) {
            context.parent_element.focus();
          }
        });
      }
      context.dispatch?.("select", {
        index: [actual_row, col],
        col_value: context.get_column(col),
        row_value: context.get_row(actual_row),
        value: context.get_data_at(actual_row, col)
      });
    },
    toggle_cell_menu: (event, row, col) => {
      event.stopPropagation();
      const current_menu = get(state).ui_state.active_cell_menu;
      if (current_menu?.row === row && current_menu.col === col) {
        update_state((s) => ({
          ui_state: { ...s.ui_state, active_cell_menu: null }
        }));
      } else {
        const cell = event.target.closest("td");
        if (cell) {
          const rect = cell.getBoundingClientRect();
          update_state((s) => ({
            ui_state: {
              ...s.ui_state,
              active_cell_menu: { row, col, x: rect.right, y: rect.bottom }
            }
          }));
        }
      }
    },
    toggle_cell_button: (row, col) => {
      const current_button = get(state).ui_state.active_button;
      const new_button = current_button?.type === "cell" && current_button.row === row && current_button.col === col ? null : { type: "cell", row, col };
      update_state((s) => ({
        ui_state: { ...s.ui_state, active_button: new_button }
      }));
    },
    handle_select_column: (col) => {
      if (!context.data) return;
      const cells = context.data.map((_, row) => [row, col]);
      update_state((s) => ({
        ui_state: {
          ...s.ui_state,
          selected_cells: cells,
          selected: cells[0],
          editing: false
        }
      }));
      setTimeout(() => context.parent_element?.focus(), 0);
    },
    handle_select_row: (row) => {
      if (!context.data || !context.data[0]) return;
      const cells = context.data[0].map(
        (_, col) => [row, col]
      );
      update_state((s) => ({
        ui_state: {
          ...s.ui_state,
          selected_cells: cells,
          selected: cells[0],
          editing: false
        }
      }));
      setTimeout(() => context.parent_element?.focus(), 0);
    },
    get_next_cell_coordinates,
    get_range_selection,
    move_cursor
  };
}
function create_dataframe_context(config) {
  const state = writable$1({
    config,
    current_search_query: null,
    sort_state: { sort_columns: [], row_order: [], initial_data: null },
    filter_state: { filter_columns: [], initial_data: null },
    ui_state: {
      active_cell_menu: null,
      active_header_menu: null,
      selected_cells: [],
      selected: false,
      editing: false,
      header_edit: false,
      selected_header: false,
      active_button: null,
      copy_flash: false
    }
  });
  const context = { state, actions: null };
  context.actions = create_actions(state, context);
  const instance_id = /* @__PURE__ */ Symbol(
    `dataframe_${Math.random().toString(36).substring(2)}`
  );
  setContext$1(instance_id, context);
  setContext$1(DATAFRAME_KEY, { instance_id, context });
  return context;
}

var root$e = from_html(`<button><span><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="svelte-fit6p6"><path d="m16.707 13.293-4-4a1 1 0 0 0-1.414 0l-4 4A1 1 0 0 0 8 15h8a1 1 0 0 0 .707-1.707z"></path></svg></span></button>`);

function SelectionButtons($$anchor, $$props) {
	push($$props, false);

	const is_first_position = mutable_source();
	const direction = mutable_source();
	let position = prop($$props, 'position', 12);
	let coords = prop($$props, 'coords', 12);
	let on_click = prop($$props, 'on_click', 12, null);

	legacy_pre_effect(() => (deep_read_state(position()), deep_read_state(coords())), () => {
		set(is_first_position, position() === "column" ? coords()[0] === 0 : coords()[1] === 0);
	});

	legacy_pre_effect(() => (deep_read_state(position()), get$1(is_first_position)), () => {
		set(direction, position() === "column"
			? get$1(is_first_position) ? "down" : "up"
			: get$1(is_first_position) ? "right" : "left");
	});

	legacy_pre_effect_reset();

	var $$exports = {
		get position() {
			return position();
		},

		set position($$value) {
			position($$value);
			flushSync();
		},

		get coords() {
			return coords();
		},

		set coords($$value) {
			coords($$value);
			flushSync();
		},

		get on_click() {
			return on_click();
		},

		set on_click($$value) {
			on_click($$value);
			flushSync();
		}
	};

	init$1();

	var button = root$e();
	var span = child(button);
	var svg = child(span);
	var path = child(svg);

	reset(svg);
	reset(span);
	reset(button);

	template_effect(() => {
		set_class(button, 1, `selection-button selection-button-${position() ?? ''} ${get$1(is_first_position) ? `move-${get$1(direction)}` : ''}`, 'svelte-fit6p6');
		set_attribute(button, 'aria-label', `Select ${position()}`);
		set_class(span, 1, clsx(get$1(direction)), 'svelte-fit6p6');
		set_attribute(path, 'data-name', get$1(direction));
	});

	event('click', button, stopPropagation(() => on_click() && on_click()()));
	append$1($$anchor, button);

	return pop($$exports);
}

var root$d = from_html(`<div class="bool-cell svelte-1d51ufy" role="button" tabindex="-1"><!></div>`);

function BooleanCell($$anchor, $$props) {
	push($$props, false);

	let value = prop($$props, 'value', 12, false);
	let editable = prop($$props, 'editable', 12, true);
	let on_change = prop($$props, 'on_change', 12);

	function handle_change(event) {
		if (editable()) {
			on_change()(event.detail);
		}
	}

	var $$exports = {
		get value() {
			return value();
		},

		set value($$value) {
			value($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get on_change() {
			return on_change();
		},

		set on_change($$value) {
			on_change($$value);
			flushSync();
		}
	};

	init$1();

	var div = root$d();
	var node = child(div);

	Checkbox$1(node, {
		label: '',
		get interactive() {
			return editable();
		},

		get value() {
			return value();
		},

		set value($$value) {
			value($$value);
		},
		$$events: { change: handle_change },
		$$legacy: true
	});

	reset(div);
	append$1($$anchor, div);

	return pop($$exports);
}

var root_1$8 = from_html(`<textarea tabindex="-1"></textarea>`);
var root_3$3 = from_html(`<span tabindex="0" role="button" placeholder=" "><!></span>`);
var root_10$1 = from_html(`<!> <!>`, 1);
var root$c = from_html(`<!> <!> <!>`, 1);

function EditableCell($$anchor, $$props) {
	push($$props, false);

	const should_truncate = mutable_source();
	const display_content = mutable_source();
	const display_text = mutable_source();
	let edit = prop($$props, 'edit', 12);
	let value = prop($$props, 'value', 12, "");
	let display_value = prop($$props, 'display_value', 12, null);
	let styling = prop($$props, 'styling', 12, "");
	let header = prop($$props, 'header', 12, false);
	let datatype = prop($$props, 'datatype', 12, "str");
	let latex_delimiters = prop($$props, 'latex_delimiters', 12);
	let line_breaks = prop($$props, 'line_breaks', 12, true);
	let editable = prop($$props, 'editable', 12, true);
	let is_static = prop($$props, 'is_static', 12, false);
	let max_chars = prop($$props, 'max_chars', 12, null);
	let components = prop($$props, 'components', 28, () => ({}));
	let i18n = prop($$props, 'i18n', 12);
	let is_dragging = prop($$props, 'is_dragging', 12, false);
	let wrap_text = prop($$props, 'wrap_text', 12, false);
	let show_selection_buttons = prop($$props, 'show_selection_buttons', 12, false);
	let coords = prop($$props, 'coords', 12);
	let on_select_column = prop($$props, 'on_select_column', 12, null);
	let on_select_row = prop($$props, 'on_select_row', 12, null);
	let el = prop($$props, 'el', 12);
	const dispatch = createEventDispatcher$1();

	function truncate_text(text, max_length = null, is_image = false) {
		if (is_image) return String(text);

		const str = String(text);

		if (!max_length || max_length <= 0) return str;
		if (str.length <= max_length) return str;

		return str.slice(0, max_length) + "...";
	}

	function use_focus(node) {
		requestAnimationFrame(() => {
			node.focus();
		});

		return {};
	}

	function handle_blur(event) {
		dispatch("blur", { blur_event: event, coords: coords() });
	}

	function handle_keydown(event) {
		dispatch("keydown", event);
	}

	function commit_change(checked) {
		handle_blur({ target: { value: value() } });
	}

	legacy_pre_effect(() => (deep_read_state(edit()), deep_read_state(max_chars())), () => {
		set(should_truncate, !edit() && max_chars() !== null && max_chars() > 0);
	});

	legacy_pre_effect(
		() => (
			deep_read_state(editable()),
			deep_read_state(value()),
			deep_read_state(display_value())
		),
		() => {
			set(display_content, editable()
				? value()
				: display_value() !== null ? display_value() : value());
		}
	);

	legacy_pre_effect(
		() => (
			get$1(should_truncate),
			get$1(display_content),
			deep_read_state(max_chars()),
			deep_read_state(datatype())
		),
		() => {
			set(display_text, get$1(should_truncate)
				? truncate_text(get$1(display_content), max_chars(), datatype() === "image")
				: get$1(display_content));
		}
	);

	legacy_pre_effect(() => (deep_read_state(edit()), deep_read_state(value())), () => {
		if (!edit()) {
			// Shim blur on removal for Safari and Firefox
			handle_blur({ target: { value: value() } });
		}
	});

	legacy_pre_effect_reset();

	var $$exports = {
		get edit() {
			return edit();
		},

		set edit($$value) {
			edit($$value);
			flushSync();
		},

		get value() {
			return value();
		},

		set value($$value) {
			value($$value);
			flushSync();
		},

		get display_value() {
			return display_value();
		},

		set display_value($$value) {
			display_value($$value);
			flushSync();
		},

		get styling() {
			return styling();
		},

		set styling($$value) {
			styling($$value);
			flushSync();
		},

		get header() {
			return header();
		},

		set header($$value) {
			header($$value);
			flushSync();
		},

		get datatype() {
			return datatype();
		},

		set datatype($$value) {
			datatype($$value);
			flushSync();
		},

		get latex_delimiters() {
			return latex_delimiters();
		},

		set latex_delimiters($$value) {
			latex_delimiters($$value);
			flushSync();
		},

		get line_breaks() {
			return line_breaks();
		},

		set line_breaks($$value) {
			line_breaks($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get is_static() {
			return is_static();
		},

		set is_static($$value) {
			is_static($$value);
			flushSync();
		},

		get max_chars() {
			return max_chars();
		},

		set max_chars($$value) {
			max_chars($$value);
			flushSync();
		},

		get components() {
			return components();
		},

		set components($$value) {
			components($$value);
			flushSync();
		},

		get i18n() {
			return i18n();
		},

		set i18n($$value) {
			i18n($$value);
			flushSync();
		},

		get is_dragging() {
			return is_dragging();
		},

		set is_dragging($$value) {
			is_dragging($$value);
			flushSync();
		},

		get wrap_text() {
			return wrap_text();
		},

		set wrap_text($$value) {
			wrap_text($$value);
			flushSync();
		},

		get show_selection_buttons() {
			return show_selection_buttons();
		},

		set show_selection_buttons($$value) {
			show_selection_buttons($$value);
			flushSync();
		},

		get coords() {
			return coords();
		},

		set coords($$value) {
			coords($$value);
			flushSync();
		},

		get on_select_column() {
			return on_select_column();
		},

		set on_select_column($$value) {
			on_select_column($$value);
			flushSync();
		},

		get on_select_row() {
			return on_select_row();
		},

		set on_select_row($$value) {
			on_select_row($$value);
			flushSync();
		},

		get el() {
			return el();
		},

		set el($$value) {
			el($$value);
			flushSync();
		}
	};

	init$1();

	var fragment = root$c();
	var node_1 = first_child(fragment);

	{
		var consequent = ($$anchor) => {
			var textarea = root_1$8();

			remove_textarea_child(textarea);

			let classes;

			bind_this(textarea, ($$value) => el($$value), () => el());
			effect(() => bind_value(textarea, value));
			effect(() => event('blur', textarea, handle_blur));

			effect(() => event('mousedown', textarea, stopPropagation(function ($$arg) {
				bubble_event.call(this, $$props, $$arg);
			})));

			effect(() => event('click', textarea, stopPropagation(function ($$arg) {
				bubble_event.call(this, $$props, $$arg);
			})));

			action(textarea, ($$node) => use_focus?.($$node));
			effect(() => event('keydown', textarea, handle_keydown));

			template_effect(() => {
				textarea.readOnly = is_static();
				set_attribute(textarea, 'aria-readonly', is_static());
				set_attribute(textarea, 'aria-label', is_static() ? "Cell is read-only" : "Edit cell");
				classes = set_class(textarea, 1, 'svelte-odwpey', null, classes, { header: header() });
			});

			append$1($$anchor, textarea);
		};

		if_block(node_1, ($$render) => {
			if (edit() && datatype() !== "bool") $$render(consequent);
		});
	}

	var node_2 = sibling(node_1, 2);

	{
		var consequent_1 = ($$anchor) => {
			BooleanCell($$anchor, {
				get editable() {
					return editable();
				},
				on_change: commit_change,
				get value() {
					return value();
				},

				set value($$value) {
					value($$value);
				},
				$$legacy: true
			});
		};

		var alternate_3 = ($$anchor) => {
			var span = root_3$3();
			let classes_1;
			var node_3 = child(span);

			{
				var consequent_2 = ($$anchor) => {
					var fragment_2 = comment();
					var node_4 = first_child(fragment_2);

					{
						let $0 = derived_safe_equal(() => ({ url: get$1(display_text) }));

						component(node_4, () => components().image, ($$anchor, $$component) => {
							$$component($$anchor, {
								get value() {
									return get$1($0);
								},
								show_label: false,
								label: 'cell-image',
								show_download_button: false,
								get i18n() {
									return i18n();
								},
								gradio: { dispatch: () => {} }
							});
						});
					}

					append$1($$anchor, fragment_2);
				};

				var alternate_2 = ($$anchor) => {
					var fragment_3 = comment();
					var node_5 = first_child(fragment_3);

					{
						var consequent_3 = ($$anchor) => {
							var fragment_4 = comment();
							var node_6 = first_child(fragment_4);

							html$1(node_6, () => get$1(display_text));
							append$1($$anchor, fragment_4);
						};

						var alternate_1 = ($$anchor) => {
							var fragment_5 = comment();
							var node_7 = first_child(fragment_5);

							{
								var consequent_4 = ($$anchor) => {
									{
										let $0 = derived_safe_equal(() => (
											get$1(display_text),
											untrack(() => get$1(display_text).toLocaleString())
										));

										MarkdownCode$1($$anchor, {
											get message() {
												return get$1($0);
											},

											get latex_delimiters() {
												return latex_delimiters();
											},

											get line_breaks() {
												return line_breaks();
											},
											chatbot: false
										});
									}
								};

								var alternate = ($$anchor) => {
									var text_1 = text$1();

									template_effect(() => set_text(text_1, get$1(display_text)));
									append$1($$anchor, text_1);
								};

								if_block(
									node_7,
									($$render) => {
										if (datatype() === "markdown") $$render(consequent_4); else $$render(alternate, false);
									},
									true
								);
							}

							append$1($$anchor, fragment_5);
						};

						if_block(
							node_5,
							($$render) => {
								if (datatype() === "html") $$render(consequent_3); else $$render(alternate_1, false);
							},
							true
						);
					}

					append$1($$anchor, fragment_3);
				};

				if_block(node_3, ($$render) => {
					if ((
						deep_read_state(datatype()),
						deep_read_state(components()),
						untrack(() => datatype() === "image" && components().image)
					)) $$render(consequent_2); else $$render(alternate_2, false);
				});
			}

			reset(span);

			template_effect(() => {
				set_style$1(span, styling());
				set_attribute(span, 'data-editable', editable());
				set_attribute(span, 'data-max-chars', max_chars());
				set_attribute(span, 'data-expanded', edit());

				classes_1 = set_class(span, 1, 'svelte-odwpey', null, classes_1, {
					dragging: is_dragging(),
					edit: edit(),
					expanded: edit(),
					multiline: header(),
					text: datatype() === "str",
					wrap: wrap_text()
				});
			});

			event('keydown', span, handle_keydown);

			event('focus', span, preventDefault(function ($$arg) {
				bubble_event.call(this, $$props, $$arg);
			}));

			append$1($$anchor, span);
		};

		if_block(node_2, ($$render) => {
			if (datatype() === "bool" && typeof value() === "boolean") $$render(consequent_1); else $$render(alternate_3, false);
		});
	}

	var node_8 = sibling(node_2, 2);

	{
		var consequent_5 = ($$anchor) => {
			var fragment_8 = root_10$1();
			var node_9 = first_child(fragment_8);

			SelectionButtons(node_9, {
				position: 'column',
				get coords() {
					return coords();
				},
				on_click: () => on_select_column()(coords()[1])
			});

			var node_10 = sibling(node_9, 2);

			SelectionButtons(node_10, {
				position: 'row',
				get coords() {
					return coords();
				},
				on_click: () => on_select_row()(coords()[0])
			});

			append$1($$anchor, fragment_8);
		};

		if_block(node_8, ($$render) => {
			if (show_selection_buttons() && coords() && on_select_column() && on_select_row()) $$render(consequent_5);
		});
	}

	append$1($$anchor, fragment);

	return pop($$exports);
}

var root_1$7 = from_html(`<th tabindex="-1" class="row-number svelte-11p754p"><div class="cell-wrap"><div class="header-content"><div class="header-text"></div></div></div></th>`);
var root_2$5 = from_html(`<td class="row-number svelte-11p754p" tabindex="-1" data-col="row-number"> </td>`);

function RowNumber($$anchor, $$props) {
	push($$props, false);

	let index = prop($$props, 'index', 12, null);
	let is_header = prop($$props, 'is_header', 12, false);

	var $$exports = {
		get index() {
			return index();
		},

		set index($$value) {
			index($$value);
			flushSync();
		},

		get is_header() {
			return is_header();
		},

		set is_header($$value) {
			is_header($$value);
			flushSync();
		}
	};

	var fragment = comment();
	var node = first_child(fragment);

	{
		var consequent = ($$anchor) => {
			var th = root_1$7();

			append$1($$anchor, th);
		};

		var alternate = ($$anchor) => {
			var td = root_2$5();
			var text = child(td, true);

			reset(td);

			template_effect(() => {
				set_attribute(td, 'data-row', index());
				set_text(text, index() !== null ? index() + 1 : "");
			});

			append$1($$anchor, td);
		};

		if_block(node, ($$render) => {
			if (is_header()) $$render(consequent); else $$render(alternate, false);
		});
	}

	append$1($$anchor, fragment);

	return pop($$exports);
}

var root$b = from_html(`<button aria-label="Open cell menu" class="cell-menu-button svelte-j6wkfp" aria-haspopup="menu">&#8942;</button>`);

function CellMenuButton($$anchor, $$props) {
	push($$props, false);

	let on_click = prop($$props, 'on_click', 12);

	var $$exports = {
		get on_click() {
			return on_click();
		},

		set on_click($$value) {
			on_click($$value);
			flushSync();
		}
	};

	init$1();

	var button = root$b();

	event('click', button, function (...$$args) {
		on_click()?.apply(this, $$args);
	});

	event('touchstart', button, (event) => {
		event.preventDefault();

		const touch = event.touches[0];

		const mouseEvent = new MouseEvent("click", {
			clientX: touch.clientX,
			clientY: touch.clientY,
			bubbles: true,
			cancelable: true,
			view: window
		});

		on_click()(mouseEvent);
	});

	append$1($$anchor, button);

	return pop($$exports);
}

var root$a = from_html(`<div class="wrapper svelte-4dxgzr" aria-label="Static column"><svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg></div>`);

function Padlock($$anchor) {
	var div = root$a();

	append$1($$anchor, div);
}

var root$9 = from_svg(`<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 8L8 4L12 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8 4V12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>`);

function SortArrowUp($$anchor, $$props) {
	push($$props, false);

	let size = prop($$props, 'size', 12, 16);

	var $$exports = {
		get size() {
			return size();
		},

		set size($$value) {
			size($$value);
			flushSync();
		}
	};

	var svg = root$9();

	template_effect(() => {
		set_attribute(svg, 'width', size());
		set_attribute(svg, 'height', size());
	});

	append$1($$anchor, svg);

	return pop($$exports);
}

var root$8 = from_svg(`<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 8L8 12L12 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8 12V4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>`);

function SortArrowDown($$anchor, $$props) {
	push($$props, false);

	let size = prop($$props, 'size', 12, 16);

	var $$exports = {
		get size() {
			return size();
		},

		set size($$value) {
			size($$value);
			flushSync();
		}
	};

	var svg = root$8();

	template_effect(() => {
		set_attribute(svg, 'width', size());
		set_attribute(svg, 'height', size());
	});

	append$1($$anchor, svg);

	return pop($$exports);
}

var root_1$6 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="4" y="6" width="4" height="12" stroke="currentColor" stroke-width="2" fill="none"></rect><path d="M12 12H19M16 8L19 12L16 16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"></path></svg>`);
var root_3$2 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="16" y="6" width="4" height="12" stroke="currentColor" stroke-width="2" fill="none"></rect><path d="M12 12H5M8 8L5 12L8 16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"></path></svg>`);
var root_5$2 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="6" y="16" width="12" height="4" stroke="currentColor" stroke-width="2"></rect><path d="M12 12V5M8 8L12 5L16 8" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"></path></svg>`);
var root_7$1 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="6" y="4" width="12" height="4" stroke="currentColor" stroke-width="2"></rect><path d="M12 12V19M8 16L12 19L16 16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round"></path></svg>`);
var root_9$1 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="5" y="10" width="14" height="4" stroke="currentColor" stroke-width="2"></rect><path d="M8 7L16 17M16 7L8 17" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_11 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><rect x="10" y="5" width="4" height="14" stroke="currentColor" stroke-width="2"></rect><path d="M7 8L17 16M17 8L7 16" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_13$1 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 16L12 12L16 16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path><path d="M12 12V19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M5 7H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_15 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><path d="M8 12L12 16L16 12" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round"></path><path d="M12 16V9" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M5 5H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_17 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><path d="M5 5H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M5 9H15" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M5 13H11" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M5 17H7" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M17 17L21 21M21 17L17 21" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_19 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><path d="M5 5H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M8 9H16" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M11 13H13" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);
var root_21 = from_svg(`<svg viewBox="0 0 24 24" width="16" height="16"><path d="M5 5H19" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M8 9H16" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M11 13H13" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path><path d="M17 17L21 21M21 17L17 21" stroke="currentColor" stroke-width="2" stroke-linecap="round"></path></svg>`);

function CellMenuIcons($$anchor, $$props) {
	push($$props, false);

	let icon = prop($$props, 'icon', 12);

	var $$exports = {
		get icon() {
			return icon();
		},

		set icon($$value) {
			icon($$value);
			flushSync();
		}
	};

	var fragment = comment();
	var node = first_child(fragment);

	{
		var consequent = ($$anchor) => {
			var svg = root_1$6();

			append$1($$anchor, svg);
		};

		var alternate_9 = ($$anchor) => {
			var fragment_1 = comment();
			var node_1 = first_child(fragment_1);

			{
				var consequent_1 = ($$anchor) => {
					var svg_1 = root_3$2();

					append$1($$anchor, svg_1);
				};

				var alternate_8 = ($$anchor) => {
					var fragment_2 = comment();
					var node_2 = first_child(fragment_2);

					{
						var consequent_2 = ($$anchor) => {
							var svg_2 = root_5$2();

							append$1($$anchor, svg_2);
						};

						var alternate_7 = ($$anchor) => {
							var fragment_3 = comment();
							var node_3 = first_child(fragment_3);

							{
								var consequent_3 = ($$anchor) => {
									var svg_3 = root_7$1();

									append$1($$anchor, svg_3);
								};

								var alternate_6 = ($$anchor) => {
									var fragment_4 = comment();
									var node_4 = first_child(fragment_4);

									{
										var consequent_4 = ($$anchor) => {
											var svg_4 = root_9$1();

											append$1($$anchor, svg_4);
										};

										var alternate_5 = ($$anchor) => {
											var fragment_5 = comment();
											var node_5 = first_child(fragment_5);

											{
												var consequent_5 = ($$anchor) => {
													var svg_5 = root_11();

													append$1($$anchor, svg_5);
												};

												var alternate_4 = ($$anchor) => {
													var fragment_6 = comment();
													var node_6 = first_child(fragment_6);

													{
														var consequent_6 = ($$anchor) => {
															var svg_6 = root_13$1();

															append$1($$anchor, svg_6);
														};

														var alternate_3 = ($$anchor) => {
															var fragment_7 = comment();
															var node_7 = first_child(fragment_7);

															{
																var consequent_7 = ($$anchor) => {
																	var svg_7 = root_15();

																	append$1($$anchor, svg_7);
																};

																var alternate_2 = ($$anchor) => {
																	var fragment_8 = comment();
																	var node_8 = first_child(fragment_8);

																	{
																		var consequent_8 = ($$anchor) => {
																			var svg_8 = root_17();

																			append$1($$anchor, svg_8);
																		};

																		var alternate_1 = ($$anchor) => {
																			var fragment_9 = comment();
																			var node_9 = first_child(fragment_9);

																			{
																				var consequent_9 = ($$anchor) => {
																					var svg_9 = root_19();

																					append$1($$anchor, svg_9);
																				};

																				var alternate = ($$anchor) => {
																					var fragment_10 = comment();
																					var node_10 = first_child(fragment_10);

																					{
																						var consequent_10 = ($$anchor) => {
																							var svg_10 = root_21();

																							append$1($$anchor, svg_10);
																						};

																						if_block(
																							node_10,
																							($$render) => {
																								if (icon() == "clear-filter") $$render(consequent_10);
																							},
																							true
																						);
																					}

																					append$1($$anchor, fragment_10);
																				};

																				if_block(
																					node_9,
																					($$render) => {
																						if (icon() == "filter") $$render(consequent_9); else $$render(alternate, false);
																					},
																					true
																				);
																			}

																			append$1($$anchor, fragment_9);
																		};

																		if_block(
																			node_8,
																			($$render) => {
																				if (icon() == "clear-sort") $$render(consequent_8); else $$render(alternate_1, false);
																			},
																			true
																		);
																	}

																	append$1($$anchor, fragment_8);
																};

																if_block(
																	node_7,
																	($$render) => {
																		if (icon() == "sort-desc") $$render(consequent_7); else $$render(alternate_2, false);
																	},
																	true
																);
															}

															append$1($$anchor, fragment_7);
														};

														if_block(
															node_6,
															($$render) => {
																if (icon() == "sort-asc") $$render(consequent_6); else $$render(alternate_3, false);
															},
															true
														);
													}

													append$1($$anchor, fragment_6);
												};

												if_block(
													node_5,
													($$render) => {
														if (icon() == "delete-column") $$render(consequent_5); else $$render(alternate_4, false);
													},
													true
												);
											}

											append$1($$anchor, fragment_5);
										};

										if_block(
											node_4,
											($$render) => {
												if (icon() == "delete-row") $$render(consequent_4); else $$render(alternate_5, false);
											},
											true
										);
									}

									append$1($$anchor, fragment_4);
								};

								if_block(
									node_3,
									($$render) => {
										if (icon() == "add-row-below") $$render(consequent_3); else $$render(alternate_6, false);
									},
									true
								);
							}

							append$1($$anchor, fragment_3);
						};

						if_block(
							node_2,
							($$render) => {
								if (icon() == "add-row-above") $$render(consequent_2); else $$render(alternate_7, false);
							},
							true
						);
					}

					append$1($$anchor, fragment_2);
				};

				if_block(
					node_1,
					($$render) => {
						if (icon() == "add-column-left") $$render(consequent_1); else $$render(alternate_8, false);
					},
					true
				);
			}

			append$1($$anchor, fragment_1);
		};

		if_block(node, ($$render) => {
			if (icon() == "add-column-right") $$render(consequent); else $$render(alternate_9, false);
		});
	}

	append$1($$anchor, fragment);

	return pop($$exports);
}

var root_1$5 = from_html(`<div class="select-all-checkbox svelte-1yuystx" role="button" tabindex="0"><!></div>`);
var root_5$1 = from_html(`<span class="sort-priority svelte-1yuystx"> </span>`);
var root_2$4 = from_html(`<div class="sort-indicators svelte-1yuystx"><span class="sort-arrow svelte-1yuystx"><!></span> <!></div>`);
var root_6$1 = from_html(`<div class="filter-indicators svelte-1yuystx"><span class="filter-icon svelte-1yuystx"><!></span></div>`);
var root$7 = from_html(`<th><div class="cell-wrap svelte-1yuystx"><div class="header-content svelte-1yuystx"><!> <button class="header-button svelte-1yuystx"><!> <!> <!></button> <!></div> <!></div></th>`);

function TableHeader($$anchor, $$props) {
	push($$props, false);

	const can_add_columns = mutable_source();
	const is_bool_column = mutable_source();
	const select_all_state = mutable_source();
	const sort_index = mutable_source();
	const filter_index = mutable_source();
	const sort_priority = mutable_source();
	const current_direction = mutable_source();
	let value = prop($$props, 'value', 12);
	let i = prop($$props, 'i', 12);
	let datatype = prop($$props, 'datatype', 12, "str");
	let actual_pinned_columns = prop($$props, 'actual_pinned_columns', 12);
	let header_edit = prop($$props, 'header_edit', 12);
	let selected_header = prop($$props, 'selected_header', 12);
	let headers = prop($$props, 'headers', 12);
	let get_cell_width = prop($$props, 'get_cell_width', 12);
	let handle_header_click = prop($$props, 'handle_header_click', 12);
	let toggle_header_menu = prop($$props, 'toggle_header_menu', 12);
	let end_header_edit = prop($$props, 'end_header_edit', 12);
	let sort_columns = prop($$props, 'sort_columns', 28, () => []);
	let filter_columns = prop($$props, 'filter_columns', 28, () => []);
	let latex_delimiters = prop($$props, 'latex_delimiters', 12);
	let line_breaks = prop($$props, 'line_breaks', 12);
	let max_chars = prop($$props, 'max_chars', 12);
	let editable = prop($$props, 'editable', 12);
	let i18n = prop($$props, 'i18n', 12);
	let el = prop($$props, 'el', 12);
	let is_static = prop($$props, 'is_static', 12);
	let col_count = prop($$props, 'col_count', 12);
	let data = prop($$props, 'data', 28, () => []);
	let on_select_all = prop($$props, 'on_select_all', 12, undefined);

	function get_header_position(col_index) {
		if (col_index >= actual_pinned_columns()) {
			return "auto";
		}

		if (col_index === 0) {
			return "0";
		}

		const previous_widths = Array(col_index).fill(0).map((_, idx) => {
			return get_cell_width()(idx);
		}).join(" + ");

		return `calc(${previous_widths})`;
	}

	legacy_pre_effect(() => (deep_read_state(col_count())), () => {
		set(can_add_columns, col_count() && col_count()[1] === "dynamic");
	});

	legacy_pre_effect(() => (deep_read_state(datatype())), () => {
		set(is_bool_column, datatype() === "bool");
	});

	legacy_pre_effect(
		() => (
			get$1(is_bool_column),
			deep_read_state(data()),
			deep_read_state(i())
		),
		() => {
			set(select_all_state, (() => {
				if (!get$1(is_bool_column) || data().length === 0) return "unchecked";

				const true_count = data().filter((row) => row[i()]?.value === true || row[i()]?.value === "true").length;

				if (true_count === 0) return "unchecked";
				if (true_count === data().length) return "checked";

				return "indeterminate";
			})());
		}
	);

	legacy_pre_effect(() => (deep_read_state(sort_columns()), deep_read_state(i())), () => {
		set(sort_index, sort_columns().findIndex((item) => item.col === i()));
	});

	legacy_pre_effect(() => (deep_read_state(filter_columns()), deep_read_state(i())), () => {
		set(filter_index, filter_columns().findIndex((item) => item.col === i()));
	});

	legacy_pre_effect(() => (get$1(sort_index)), () => {
		set(sort_priority, get$1(sort_index) !== -1 ? get$1(sort_index) + 1 : null);
	});

	legacy_pre_effect(() => (get$1(sort_index), deep_read_state(sort_columns())), () => {
		set(current_direction, get$1(sort_index) !== -1 ? sort_columns()[get$1(sort_index)].direction : null);
	});

	legacy_pre_effect_reset();

	var $$exports = {
		get value() {
			return value();
		},

		set value($$value) {
			value($$value);
			flushSync();
		},

		get i() {
			return i();
		},

		set i($$value) {
			i($$value);
			flushSync();
		},

		get datatype() {
			return datatype();
		},

		set datatype($$value) {
			datatype($$value);
			flushSync();
		},

		get actual_pinned_columns() {
			return actual_pinned_columns();
		},

		set actual_pinned_columns($$value) {
			actual_pinned_columns($$value);
			flushSync();
		},

		get header_edit() {
			return header_edit();
		},

		set header_edit($$value) {
			header_edit($$value);
			flushSync();
		},

		get selected_header() {
			return selected_header();
		},

		set selected_header($$value) {
			selected_header($$value);
			flushSync();
		},

		get headers() {
			return headers();
		},

		set headers($$value) {
			headers($$value);
			flushSync();
		},

		get get_cell_width() {
			return get_cell_width();
		},

		set get_cell_width($$value) {
			get_cell_width($$value);
			flushSync();
		},

		get handle_header_click() {
			return handle_header_click();
		},

		set handle_header_click($$value) {
			handle_header_click($$value);
			flushSync();
		},

		get toggle_header_menu() {
			return toggle_header_menu();
		},

		set toggle_header_menu($$value) {
			toggle_header_menu($$value);
			flushSync();
		},

		get end_header_edit() {
			return end_header_edit();
		},

		set end_header_edit($$value) {
			end_header_edit($$value);
			flushSync();
		},

		get sort_columns() {
			return sort_columns();
		},

		set sort_columns($$value) {
			sort_columns($$value);
			flushSync();
		},

		get filter_columns() {
			return filter_columns();
		},

		set filter_columns($$value) {
			filter_columns($$value);
			flushSync();
		},

		get latex_delimiters() {
			return latex_delimiters();
		},

		set latex_delimiters($$value) {
			latex_delimiters($$value);
			flushSync();
		},

		get line_breaks() {
			return line_breaks();
		},

		set line_breaks($$value) {
			line_breaks($$value);
			flushSync();
		},

		get max_chars() {
			return max_chars();
		},

		set max_chars($$value) {
			max_chars($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get i18n() {
			return i18n();
		},

		set i18n($$value) {
			i18n($$value);
			flushSync();
		},

		get el() {
			return el();
		},

		set el($$value) {
			el($$value);
			flushSync();
		},

		get is_static() {
			return is_static();
		},

		set is_static($$value) {
			is_static($$value);
			flushSync();
		},

		get col_count() {
			return col_count();
		},

		set col_count($$value) {
			col_count($$value);
			flushSync();
		},

		get data() {
			return data();
		},

		set data($$value) {
			data($$value);
			flushSync();
		},

		get on_select_all() {
			return on_select_all();
		},

		set on_select_all($$value) {
			on_select_all($$value);
			flushSync();
		}
	};

	init$1();

	var th = root$7();
	let classes;
	var div = child(th);
	var div_1 = child(div);
	var node = child(div_1);

	{
		var consequent = ($$anchor) => {
			var div_2 = root_1$5();
			var node_1 = child(div_2);

			{
				let $0 = derived_safe_equal(() => get$1(select_all_state) === "checked");
				let $1 = derived_safe_equal(() => get$1(select_all_state) === "indeterminate");

				Checkbox$1(node_1, {
					get value() {
						return get$1($0);
					},

					get indeterminate() {
						return get$1($1);
					},
					label: '',
					interactive: true,
					$$events: {
						select: () => {
							if (on_select_all()) {
								const new_value = get$1(select_all_state) !== "checked";

								on_select_all()(i(), new_value);
							}
						}
					}
				});
			}

			reset(div_2);

			event('click', div_2, stopPropagation(function ($$arg) {
				bubble_event.call(this, $$props, $$arg);
			}));

			event('keydown', div_2, stopPropagation((e) => {
				if (e.key === "Enter" || e.key === " ") {
					e.preventDefault();
				}
			}));

			event('mousedown', div_2, stopPropagation(function ($$arg) {
				bubble_event.call(this, $$props, $$arg);
			}));

			append$1($$anchor, div_2);
		};

		if_block(node, ($$render) => {
			if (get$1(is_bool_column) && editable() && on_select_all()) $$render(consequent);
		});
	}

	var button = sibling(node, 2);
	var node_2 = child(button);

	{
		let $0 = derived_safe_equal(() => header_edit() === i());
		let $1 = derived_safe_equal(() => [i(), 0]);

		EditableCell(node_2, {
			get max_chars() {
				return max_chars();
			},

			get latex_delimiters() {
				return latex_delimiters();
			},

			get line_breaks() {
				return line_breaks();
			},

			get edit() {
				return get$1($0);
			},
			header: true,
			get editable() {
				return editable();
			},

			get is_static() {
				return is_static();
			},

			get i18n() {
				return i18n();
			},

			get coords() {
				return get$1($1);
			},

			get value() {
				return value();
			},

			set value($$value) {
				value($$value);
			},

			get el() {
				return el();
			},

			set el($$value) {
				el($$value);
			},

			$$events: {
				keydown: (event) => {
					if (event.detail.key === "Enter" || event.detail.key === "Escape" || event.detail.key === "Tab") {
						end_header_edit()(event);
					}
				}
			},
			$$legacy: true
		});
	}

	var node_3 = sibling(node_2, 2);

	{
		var consequent_3 = ($$anchor) => {
			var div_3 = root_2$4();
			var span = child(div_3);
			var node_4 = child(span);

			{
				var consequent_1 = ($$anchor) => {
					SortArrowUp($$anchor, { size: 12 });
				};

				var alternate = ($$anchor) => {
					SortArrowDown($$anchor, { size: 12 });
				};

				if_block(node_4, ($$render) => {
					if (get$1(current_direction) === "asc") $$render(consequent_1); else $$render(alternate, false);
				});
			}

			reset(span);

			var node_5 = sibling(span, 2);

			{
				var consequent_2 = ($$anchor) => {
					var span_1 = root_5$1();
					var text = child(span_1, true);

					reset(span_1);
					template_effect(() => set_text(text, get$1(sort_priority)));
					append$1($$anchor, span_1);
				};

				if_block(node_5, ($$render) => {
					if ((
						deep_read_state(sort_columns()),
						untrack(() => sort_columns().length > 1)
					)) $$render(consequent_2);
				});
			}

			reset(div_3);
			append$1($$anchor, div_3);
		};

		if_block(node_3, ($$render) => {
			if (get$1(sort_index) !== -1) $$render(consequent_3);
		});
	}

	var node_6 = sibling(node_3, 2);

	{
		var consequent_4 = ($$anchor) => {
			var div_4 = root_6$1();
			var span_2 = child(div_4);
			var node_7 = child(span_2);

			CellMenuIcons(node_7, { icon: 'filter' });
			reset(span_2);
			reset(div_4);
			append$1($$anchor, div_4);
		};

		if_block(node_6, ($$render) => {
			if (get$1(filter_index) !== -1) $$render(consequent_4);
		});
	}

	reset(button);

	var node_8 = sibling(button, 2);

	{
		var consequent_5 = ($$anchor) => {
			Padlock($$anchor);
		};

		if_block(node_8, ($$render) => {
			if (is_static()) $$render(consequent_5);
		});
	}

	reset(div_1);

	var node_9 = sibling(div_1, 2);

	{
		var consequent_6 = ($$anchor) => {
			CellMenuButton($$anchor, { on_click: (event) => toggle_header_menu()(event, i()) });
		};

		if_block(node_9, ($$render) => {
			if (get$1(can_add_columns)) $$render(consequent_6);
		});
	}

	reset(div);
	reset(th);

	template_effect(
		($0, $1, $2) => {
			set_attribute(th, 'aria-sort', $0);
			set_style$1(th, `width: ${$1 ?? ''}; left: ${$2 ?? ''};`);
			set_attribute(th, 'title', value());

			classes = set_class(th, 1, 'svelte-1yuystx', null, classes, {
				'pinned-column': i() < actual_pinned_columns(),
				'last-pinned': i() === actual_pinned_columns() - 1,
				focus: header_edit() === i() || selected_header() === i(),
				sorted: get$1(sort_index) !== -1,
				filtered: get$1(filter_index) !== -1
			});

			set_attribute(button, 'title', value());
		},
		[
			() => (
				deep_read_state(get_sort_status),
				deep_read_state(value()),
				deep_read_state(sort_columns()),
				deep_read_state(headers()),
				untrack(() => get_sort_status(value(), sort_columns(), headers()) === "none"
					? "none"
					: get_sort_status(value(), sort_columns(), headers()) === "asc" ? "ascending" : "descending")
			),

			() => (
				deep_read_state(get_cell_width()),
				deep_read_state(i()),
				untrack(() => get_cell_width()(i()))
			),

			() => (
				deep_read_state(i()),
				untrack(() => get_header_position(i()))
			)
		]
	);

	event('click', button, (event) => handle_header_click()(event, i()));

	event('mousedown', button, (event) => {
		event.preventDefault();
		event.stopPropagation();
	});

	event('click', th, (event) => handle_header_click()(event, i()));

	event('mousedown', th, (event) => {
		event.preventDefault();
		event.stopPropagation();
	});

	append$1($$anchor, th);

	return pop($$exports);
}

var root$6 = from_html(`<td><div class="cell-wrap svelte-18bs22a"><!> <!></div></td>`);

function TableCell($$anchor, $$props) {
	push($$props, false);

	const cell_classes = mutable_source();
	const is_in_selection = mutable_source();
	const has_no_top = mutable_source();
	const has_no_bottom = mutable_source();
	const has_no_left = mutable_source();
	const has_no_right = mutable_source();
	let value = prop($$props, 'value', 12);
	let index = prop($$props, 'index', 12);
	let j = prop($$props, 'j', 12);
	let actual_pinned_columns = prop($$props, 'actual_pinned_columns', 12);
	let get_cell_width = prop($$props, 'get_cell_width', 12);
	let handle_cell_click = prop($$props, 'handle_cell_click', 12);
	let handle_blur = prop($$props, 'handle_blur', 12);
	let toggle_cell_menu = prop($$props, 'toggle_cell_menu', 12);
	let is_cell_selected = prop($$props, 'is_cell_selected', 12);
	let should_show_cell_menu = prop($$props, 'should_show_cell_menu', 12);
	let selected_cells = prop($$props, 'selected_cells', 12);
	let copy_flash = prop($$props, 'copy_flash', 12);
	let active_cell_menu = prop($$props, 'active_cell_menu', 12);
	let styling = prop($$props, 'styling', 12);
	let latex_delimiters = prop($$props, 'latex_delimiters', 12);
	let line_breaks = prop($$props, 'line_breaks', 12);
	let datatype = prop($$props, 'datatype', 12);
	let editing = prop($$props, 'editing', 12);
	let max_chars = prop($$props, 'max_chars', 12);
	let editable = prop($$props, 'editable', 12);
	let is_static = prop($$props, 'is_static', 12, false);
	let i18n = prop($$props, 'i18n', 12);
	let components = prop($$props, 'components', 28, () => ({}));
	let el = prop($$props, 'el', 12);
	let handle_select_column = prop($$props, 'handle_select_column', 12);
	let handle_select_row = prop($$props, 'handle_select_row', 12);
	let is_dragging = prop($$props, 'is_dragging', 12);
	let display_value = prop($$props, 'display_value', 12);
	let wrap = prop($$props, 'wrap', 12, false);

	function get_cell_position(col_index) {
		if (col_index >= actual_pinned_columns()) {
			return "auto";
		}

		if (col_index === 0) {
			return "0";
		}

		const previous_widths = Array(col_index).fill(0).map((_, idx) => {
			return get_cell_width()(idx);
		}).join(" + ");

		return `calc(${previous_widths})`;
	}

	legacy_pre_effect(
		() => (
			deep_read_state(is_cell_selected()),
			deep_read_state(index()),
			deep_read_state(j()),
			deep_read_state(selected_cells())
		),
		() => {
			set(cell_classes, is_cell_selected()([index(), j()], selected_cells() || []));
		}
	);

	legacy_pre_effect(
		() => (
			deep_read_state(index()),
			deep_read_state(j()),
			deep_read_state(selected_cells())
		),
		() => {
			set(is_in_selection, is_cell_in_selection([index(), j()], selected_cells()));
		}
	);

	legacy_pre_effect(() => (get$1(cell_classes)), () => {
		set(has_no_top, get$1(cell_classes).includes("no-top"));
	});

	legacy_pre_effect(() => (get$1(cell_classes)), () => {
		set(has_no_bottom, get$1(cell_classes).includes("no-bottom"));
	});

	legacy_pre_effect(() => (get$1(cell_classes)), () => {
		set(has_no_left, get$1(cell_classes).includes("no-left"));
	});

	legacy_pre_effect(() => (get$1(cell_classes)), () => {
		set(has_no_right, get$1(cell_classes).includes("no-right"));
	});

	legacy_pre_effect_reset();

	var $$exports = {
		get value() {
			return value();
		},

		set value($$value) {
			value($$value);
			flushSync();
		},

		get index() {
			return index();
		},

		set index($$value) {
			index($$value);
			flushSync();
		},

		get j() {
			return j();
		},

		set j($$value) {
			j($$value);
			flushSync();
		},

		get actual_pinned_columns() {
			return actual_pinned_columns();
		},

		set actual_pinned_columns($$value) {
			actual_pinned_columns($$value);
			flushSync();
		},

		get get_cell_width() {
			return get_cell_width();
		},

		set get_cell_width($$value) {
			get_cell_width($$value);
			flushSync();
		},

		get handle_cell_click() {
			return handle_cell_click();
		},

		set handle_cell_click($$value) {
			handle_cell_click($$value);
			flushSync();
		},

		get handle_blur() {
			return handle_blur();
		},

		set handle_blur($$value) {
			handle_blur($$value);
			flushSync();
		},

		get toggle_cell_menu() {
			return toggle_cell_menu();
		},

		set toggle_cell_menu($$value) {
			toggle_cell_menu($$value);
			flushSync();
		},

		get is_cell_selected() {
			return is_cell_selected();
		},

		set is_cell_selected($$value) {
			is_cell_selected($$value);
			flushSync();
		},

		get should_show_cell_menu() {
			return should_show_cell_menu();
		},

		set should_show_cell_menu($$value) {
			should_show_cell_menu($$value);
			flushSync();
		},

		get selected_cells() {
			return selected_cells();
		},

		set selected_cells($$value) {
			selected_cells($$value);
			flushSync();
		},

		get copy_flash() {
			return copy_flash();
		},

		set copy_flash($$value) {
			copy_flash($$value);
			flushSync();
		},

		get active_cell_menu() {
			return active_cell_menu();
		},

		set active_cell_menu($$value) {
			active_cell_menu($$value);
			flushSync();
		},

		get styling() {
			return styling();
		},

		set styling($$value) {
			styling($$value);
			flushSync();
		},

		get latex_delimiters() {
			return latex_delimiters();
		},

		set latex_delimiters($$value) {
			latex_delimiters($$value);
			flushSync();
		},

		get line_breaks() {
			return line_breaks();
		},

		set line_breaks($$value) {
			line_breaks($$value);
			flushSync();
		},

		get datatype() {
			return datatype();
		},

		set datatype($$value) {
			datatype($$value);
			flushSync();
		},

		get editing() {
			return editing();
		},

		set editing($$value) {
			editing($$value);
			flushSync();
		},

		get max_chars() {
			return max_chars();
		},

		set max_chars($$value) {
			max_chars($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get is_static() {
			return is_static();
		},

		set is_static($$value) {
			is_static($$value);
			flushSync();
		},

		get i18n() {
			return i18n();
		},

		set i18n($$value) {
			i18n($$value);
			flushSync();
		},

		get components() {
			return components();
		},

		set components($$value) {
			components($$value);
			flushSync();
		},

		get el() {
			return el();
		},

		set el($$value) {
			el($$value);
			flushSync();
		},

		get handle_select_column() {
			return handle_select_column();
		},

		set handle_select_column($$value) {
			handle_select_column($$value);
			flushSync();
		},

		get handle_select_row() {
			return handle_select_row();
		},

		set handle_select_row($$value) {
			handle_select_row($$value);
			flushSync();
		},

		get is_dragging() {
			return is_dragging();
		},

		set is_dragging($$value) {
			is_dragging($$value);
			flushSync();
		},

		get display_value() {
			return display_value();
		},

		set display_value($$value) {
			display_value($$value);
			flushSync();
		},

		get wrap() {
			return wrap();
		},

		set wrap($$value) {
			wrap($$value);
			flushSync();
		}
	};

	init$1();

	var td = root$6();
	let classes;
	var div = child(td);
	var node = child(div);

	{
		let $0 = derived_safe_equal(() => (
			deep_read_state(display_value()),
			deep_read_state(value()),
			untrack(() => display_value() !== undefined ? display_value() : String(value()))
		));

		let $1 = derived_safe_equal(() => (
			deep_read_state(editing()),
			deep_read_state(index()),
			deep_read_state(j()),
			untrack(() => editing() && editing()[0] === index() && editing()[1] === j())
		));

		let $2 = derived_safe_equal(() => (
			deep_read_state(selected_cells()),
			deep_read_state(index()),
			deep_read_state(j()),
			untrack(() => selected_cells().length === 1 && selected_cells()[0][0] === index() && selected_cells()[0][1] === j())
		));

		let $3 = derived_safe_equal(() => [index(), j()]);

		EditableCell(node, {
			get display_value() {
				return get$1($0);
			},

			get latex_delimiters() {
				return latex_delimiters();
			},

			get line_breaks() {
				return line_breaks();
			},

			get editable() {
				return editable();
			},

			get is_static() {
				return is_static();
			},

			get edit() {
				return get$1($1);
			},

			get datatype() {
				return datatype();
			},

			get max_chars() {
				return max_chars();
			},

			get i18n() {
				return i18n();
			},

			get components() {
				return components();
			},

			get show_selection_buttons() {
				return get$1($2);
			},

			get coords() {
				return get$1($3);
			},

			get on_select_column() {
				return handle_select_column();
			},

			get on_select_row() {
				return handle_select_row();
			},

			get is_dragging() {
				return is_dragging();
			},

			get wrap_text() {
				return wrap();
			},

			get value() {
				return value();
			},

			set value($$value) {
				value($$value);
			},

			get el() {
				return el().input;
			},

			set el($$value) {
				el(el().input = $$value, true);
			},

			$$events: {
				focus: () => {
					const row = index();
					const col = j();

					if (!selected_cells().some(([r, c]) => r === row && c === col)) {
						selected_cells([[row, col]]);
					}
				},

				blur(...$$args) {
					handle_blur()?.apply(this, $$args);
				}
			},
			$$legacy: true
		});
	}

	var node_1 = sibling(node, 2);

	{
		var consequent = ($$anchor) => {
			CellMenuButton($$anchor, { on_click: (event) => toggle_cell_menu()(event, index(), j()) });
		};

		if_block(node_1, ($$render) => {
			if ((
				deep_read_state(editable()),
				deep_read_state(should_show_cell_menu()),
				deep_read_state(index()),
				deep_read_state(j()),
				deep_read_state(selected_cells()),
				untrack(() => editable() && should_show_cell_menu()([index(), j()], selected_cells(), editable()))
			)) $$render(consequent);
		});
	}

	reset(div);
	reset(td);
	bind_this(td, ($$value) => el(el().cell = $$value, true), () => el()?.cell);

	template_effect(
		($0, $1) => {
			set_attribute(td, 'tabindex', j() < actual_pinned_columns() ? -1 : 0);
			set_attribute(td, 'data-row', index());
			set_attribute(td, 'data-col', j());
			set_attribute(td, 'data-testid', `cell-${index()}-${j()}`);
			set_style$1(td, `width: ${$0 ?? ''}; left: ${$1 ?? ''}; ${(styling() || '') ?? ''}`);

			classes = set_class(td, 1, 'svelte-18bs22a', null, classes, {
				'pinned-column': j() < actual_pinned_columns(),
				'last-pinned': j() === actual_pinned_columns() - 1,
				flash: copy_flash() && get$1(is_in_selection),
				'cell-selected': get$1(is_in_selection),
				'no-top': get$1(has_no_top),
				'no-bottom': get$1(has_no_bottom),
				'no-left': get$1(has_no_left),
				'no-right': get$1(has_no_right),
				'menu-active': active_cell_menu() && active_cell_menu().row === index() && active_cell_menu().col === j(),
				dragging: is_dragging()
			});
		},
		[
			() => (
				deep_read_state(get_cell_width()),
				deep_read_state(j()),
				untrack(() => get_cell_width()(j()))
			),

			() => (
				deep_read_state(j()),
				untrack(() => get_cell_position(j()))
			)
		]
	);

	event('mousedown', td, (e) => handle_cell_click()(e, index(), j()));
	event('contextmenu', td, preventDefault((e) => toggle_cell_menu()(e, index(), j())));
	append$1($$anchor, td);

	return pop($$exports);
}

var root$5 = from_html(`<button class="add-row-button svelte-1at77md" aria-label="Add row">+</button>`);

function EmptyRowButton($$anchor, $$props) {
	push($$props, false);

	let on_click = prop($$props, 'on_click', 12);

	var $$exports = {
		get on_click() {
			return on_click();
		},

		set on_click($$value) {
			on_click($$value);
			flushSync();
		}
	};

	var button = root$5();

	event('click', button, function (...$$args) {
		on_click()?.apply(this, $$args);
	});

	append$1($$anchor, button);

	return pop($$exports);
}

var root_1$4 = from_html(`<caption class="sr-only"> </caption>`);
var root_4$2 = from_html(`<tr><td>Missing Table Row</td></tr>`);
var root$4 = from_html(`<svelte-virtual-table-viewport><div><table><!><thead class="thead svelte-fhd0lr"><!></thead><tbody class="tbody svelte-fhd0lr"><!></tbody><tfoot class="tfoot svelte-fhd0lr"><!></tfoot></table></div></svelte-virtual-table-viewport>`, 2);

function VirtualTable($$anchor, $$props) {
	push($$props, false);

	const sortedItems = mutable_source();
	let items = prop($$props, 'items', 28, () => []);
	let max_height = prop($$props, 'max_height', 12);
	let actual_height = prop($$props, 'actual_height', 12);
	let table_scrollbar_width = prop($$props, 'table_scrollbar_width', 12);
	let start = prop($$props, 'start', 12, 0);
	let end = prop($$props, 'end', 12, 20);
	let selected = prop($$props, 'selected', 12);
	let disable_scroll = prop($$props, 'disable_scroll', 12, false);
	let show_scroll_button = prop($$props, 'show_scroll_button', 12, false);
	let viewport = prop($$props, 'viewport', 12);
	let label = prop($$props, 'label', 12, null);
	createEventDispatcher$1();
	let average_height = mutable_source(30);
	let bottom = mutable_source(0);
	let contents = mutable_source();
	let head_height = mutable_source(0);
	let foot_height = mutable_source(0);
	let height_map = [];
	let mounted = mutable_source();
	let rows;
	let top = mutable_source(0);
	let viewport_height = mutable_source(200);
	let visible = mutable_source([]);
	let viewport_box = mutable_source();
	const is_browser = typeof window !== "undefined";
	const raf = is_browser ? window.requestAnimationFrame : (cb) => cb();

	async function refresh_height_map() {
		if (!viewport()) {
			return;
		}

		if (get$1(sortedItems).length < start()) {
			await scroll_to_index(get$1(sortedItems).length - 1, { behavior: "auto" });
		}

		const scrollTop = Math.max(0, viewport().scrollTop);

		show_scroll_button(scrollTop > 100);
		table_scrollbar_width(viewport().offsetWidth - viewport().clientWidth);

		// acquire height map for currently visible rows
		for (let v = 0; v < rows.length; v += 1) {
			height_map[start() + v] = rows[v].getBoundingClientRect().height;
		}

		let i = 0;
		let y = get$1(head_height);

		// loop items to find new start
		while (i < get$1(sortedItems).length) {
			const row_height = height_map[i] || get$1(average_height);

			// keep a page of rows buffered above
			if (y + row_height > scrollTop - max_height()) {
				start(i);
				set(top, y - get$1(head_height));

				break;
			}

			y += row_height;
			i += 1;
		}

		let content_height = get$1(head_height);

		while (i < get$1(sortedItems).length) {
			const row_height = height_map[i] || get$1(average_height);

			content_height += row_height;
			i += 1;

			// keep a page of rows buffered below
			if (content_height - get$1(head_height) > 3 * max_height()) {
				break;
			}
		}

		end(i);

		const remaining = get$1(sortedItems).length - end();
		const scrollbar_height = viewport().offsetHeight - viewport().clientHeight;

		if (scrollbar_height > 0) {
			content_height += scrollbar_height;
		}

		let filtered_height_map = height_map.filter((v) => typeof v === "number");

		set(average_height, filtered_height_map.reduce((a, b) => a + b, 0) / filtered_height_map.length || 30);
		set(bottom, remaining * get$1(average_height));

		if (!isFinite(get$1(bottom))) {
			set(bottom, 200000);
		}

		height_map.length = get$1(sortedItems).length;

		while (i < get$1(sortedItems).length) {
			i += 1;
			height_map[i] = get$1(average_height);
		}

		if (max_height() && content_height > max_height()) {
			actual_height(max_height());
		} else {
			actual_height(content_height);
		}
	}

	async function scroll_and_render(n) {
		raf(async () => {
			if (typeof n !== "number") return;

			const direction = typeof n !== "number" ? false : is_in_view(n);

			if (direction === true) {
				return;
			}

			if (direction === "back") {
				await scroll_to_index(n, { behavior: "instant" });
			}

			if (direction === "forwards") {
				await scroll_to_index(n, { behavior: "instant" }, true);
			}
		});
	}

	function is_in_view(n) {
		const current = rows && rows[n - start()];

		if (!current && n < start()) {
			return "back";
		}

		if (!current && n >= end() - 1) {
			return "forwards";
		}

		const { top: viewport_top } = viewport().getBoundingClientRect();
		const { top, bottom } = current.getBoundingClientRect();

		if (top - viewport_top < 37) {
			return "back";
		}

		if (bottom - viewport_top > get$1(viewport_height)) {
			return "forwards";
		}

		return true;
	}

	async function scroll_to_index(index, opts, align_end = false) {
		await tick$1();

		const _itemHeight = get$1(average_height);
		let distance = index * _itemHeight;

		if (align_end) {
			distance = distance - get$1(viewport_height) + _itemHeight + get$1(head_height);
		}

		const scrollbar_height = viewport().offsetHeight - viewport().clientHeight;

		if (scrollbar_height > 0) {
			distance += scrollbar_height;
		}

		const _opts = { top: distance, behavior: "smooth", ...opts };

		viewport().scrollTo(_opts);
	}

	onMount$1(() => {
		rows = get$1(contents).children;
		set(mounted, true);
	});

	legacy_pre_effect(() => (get$1(viewport_box)), () => {
		set(viewport_height, get$1(viewport_box)?.height || 200);
	});

	legacy_pre_effect(() => (deep_read_state(items())), () => {
		set(sortedItems, items());
	});

	legacy_pre_effect(
		() => (
			get$1(mounted),
			get$1(viewport_height),
			deep_read_state(viewport()),
			get$1(sortedItems)
		),
		() => {
			if (get$1(mounted) && get$1(viewport_height) && viewport().offsetParent) {
				(get$1(sortedItems), raf(refresh_height_map));
			}
		}
	);

	legacy_pre_effect(() => (deep_read_state(selected())), () => {
		scroll_and_render(selected());
	});

	legacy_pre_effect(
		() => (
			get$1(sortedItems),
			deep_read_state(start()),
			deep_read_state(end()),
			deep_read_state(max_height()),
			get$1(average_height)
		),
		() => {
			set(visible, is_browser
				? get$1(sortedItems).slice(start(), end()).map((data, i) => {
					return { index: i + start(), data };
				})
				: get$1(sortedItems).slice(0, max_height() / get$1(sortedItems).length * get$1(average_height) + 1).map((data, i) => {
					return { index: i + start(), data };
				}));
		}
	);

	legacy_pre_effect_reset();

	var $$exports = {
		scroll_to_index,
		get items() {
			return items();
		},

		set items($$value) {
			items($$value);
			flushSync();
		},

		get max_height() {
			return max_height();
		},

		set max_height($$value) {
			max_height($$value);
			flushSync();
		},

		get actual_height() {
			return actual_height();
		},

		set actual_height($$value) {
			actual_height($$value);
			flushSync();
		},

		get table_scrollbar_width() {
			return table_scrollbar_width();
		},

		set table_scrollbar_width($$value) {
			table_scrollbar_width($$value);
			flushSync();
		},

		get start() {
			return start();
		},

		set start($$value) {
			start($$value);
			flushSync();
		},

		get end() {
			return end();
		},

		set end($$value) {
			end($$value);
			flushSync();
		},

		get selected() {
			return selected();
		},

		set selected($$value) {
			selected($$value);
			flushSync();
		},

		get disable_scroll() {
			return disable_scroll();
		},

		set disable_scroll($$value) {
			disable_scroll($$value);
			flushSync();
		},

		get show_scroll_button() {
			return show_scroll_button();
		},

		set show_scroll_button($$value) {
			show_scroll_button($$value);
			flushSync();
		},

		get viewport() {
			return viewport();
		},

		set viewport($$value) {
			viewport($$value);
			flushSync();
		},

		get label() {
			return label();
		},

		set label($$value) {
			label($$value);
			flushSync();
		}
	};

	init$1();

	var svelte_virtual_table_viewport = root$4();
	var div = child(svelte_virtual_table_viewport);
	var table = child(div);
	let classes;
	var node = child(table);

	{
		var consequent = ($$anchor) => {
			var caption = root_1$4();
			var text = child(caption, true);

			reset(caption);
			template_effect(() => set_text(text, label()));
			append$1($$anchor, caption);
		};

		if_block(node, ($$render) => {
			if ((
				deep_read_state(label()),
				untrack(() => label() && label().length !== 0)
			)) $$render(consequent);
		});
	}

	var thead = sibling(node);
	var node_1 = child(thead);

	slot(node_1, $$props, 'thead', {}, null);
	reset(thead);

	var tbody = sibling(thead);
	var node_2 = child(tbody);

	{
		var consequent_1 = ($$anchor) => {
			var fragment = comment();
			var node_3 = first_child(fragment);

			each(node_3, 1, () => get$1(visible), (item) => item.data[0].id, ($$anchor, item) => {
				var fragment_1 = comment();
				var node_4 = first_child(fragment_1);

				slot(
					node_4,
					$$props,
					'tbody',
					{
						get item() {
							return (get$1(item), untrack(() => get$1(item).data));
						},

						get index() {
							return (get$1(item), untrack(() => get$1(item).index));
						}
					},
					($$anchor) => {
						var tr = root_4$2();

						append$1($$anchor, tr);
					}
				);

				append$1($$anchor, fragment_1);
			});

			append$1($$anchor, fragment);
		};

		if_block(node_2, ($$render) => {
			if ((
				get$1(visible),
				untrack(() => get$1(visible).length && get$1(visible)[0].data.length)
			)) $$render(consequent_1);
		});
	}

	reset(tbody);
	bind_this(tbody, ($$value) => set(contents, $$value), () => get$1(contents));

	var tfoot = sibling(tbody);
	var node_5 = child(tfoot);

	slot(node_5, $$props, 'tfoot', {}, null);
	reset(tfoot);
	reset(table);
	bind_this(table, ($$value) => viewport($$value), () => viewport());
	reset(div);
	reset(svelte_virtual_table_viewport);

	template_effect(() => {
		classes = set_class(table, 1, 'table svelte-fhd0lr', null, classes, { 'disable-scroll': disable_scroll() });
		set_style$1(table, `height: 100%; --bw-svt-p-top: ${get$1(top) ?? ''}px; --bw-svt-p-bottom: ${get$1(bottom) ?? ''}px; --bw-svt-head-height: ${get$1(head_height) ?? ''}px; --bw-svt-foot-height: ${get$1(foot_height) ?? ''}px; --bw-svt-avg-row-height: ${get$1(average_height) ?? ''}px; --max-height: ${max_height() ?? ''}px`);
	});

	bind_element_size(thead, 'offsetHeight', ($$value) => set(head_height, $$value));
	bind_element_size(tfoot, 'offsetHeight', ($$value) => set(foot_height, $$value));
	bind_resize_observer(table, 'contentRect', ($$value) => set(viewport_box, $$value));
	event('scroll', table, refresh_height_map);
	append$1($$anchor, svelte_virtual_table_viewport);
	bind_prop($$props, 'scroll_to_index', scroll_to_index);

	return pop($$exports);
}

var root_2$3 = from_html(`<button class="filter-option svelte-1y6dxc7"> </button>`);
var root_1$3 = from_html(`<div class="dropdown-filter-options svelte-1y6dxc7"></div>`);
var root$3 = from_html(`<div><div class="background svelte-1y6dxc7"></div> <div class="filter-menu svelte-1y6dxc7"><div class="filter-datatype-container svelte-1y6dxc7"><span class="svelte-1y6dxc7">Filter as</span> <button class="svelte-1y6dxc7"> </button></div> <div class="input-container svelte-1y6dxc7"><div class="filter-dropdown"><button class="svelte-1y6dxc7"> <!></button> <!></div> <input type="text" placeholder="Type a value" class="filter-input svelte-1y6dxc7"/></div> <button class="check-button svelte-1y6dxc7"><!></button></div></div>`);

function FilterMenu($$anchor, $$props) {
	push($$props, false);

	let on_filter = prop($$props, 'on_filter', 12, () => {});
	let menu_element = mutable_source();
	let datatype = mutable_source("string");
	let current_filter = mutable_source("Contains");
	let filter_dropdown_open = mutable_source(false);
	let filter_input_value = mutable_source("");

	const filter_options = {
		string: [
			"Contains",
			"Does not contain",
			"Starts with",
			"Ends with",
			"Is",
			"Is not",
			"Is empty",
			"Is not empty"
		],
		number: ["=", "≠", ">", "<", "≥", "≤", "Is empty", "Is not empty"]
	};

	onMount$1(() => {
		position_menu();
	});

	function position_menu() {
		if (!get$1(menu_element)) return;

		const viewport_width = window.innerWidth;
		const viewport_height = window.innerHeight;
		const menu_rect = get$1(menu_element).getBoundingClientRect();
		const x = (viewport_width - menu_rect.width) / 2;
		const y = (viewport_height - menu_rect.height) / 2;

		mutate(menu_element, get$1(menu_element).style.left = `${x}px`);
		mutate(menu_element, get$1(menu_element).style.top = `${y}px`);
	}

	function handle_filter_input(e) {
		const target = e.target;

		set(filter_input_value, target.value);
	}

	var $$exports = {
		get on_filter() {
			return on_filter();
		},

		set on_filter($$value) {
			on_filter($$value);
			flushSync();
		}
	};

	init$1();

	var div = root$3();
	var div_1 = sibling(child(div), 2);
	var div_2 = child(div_1);
	var button = sibling(child(div_2), 2);
	var text = child(button, true);

	reset(button);
	reset(div_2);

	var div_3 = sibling(div_2, 2);
	var div_4 = child(div_3);
	var button_1 = child(div_4);
	var text_1 = child(button_1);
	var node = sibling(text_1);

	DropdownArrow$1(node);
	reset(button_1);

	var node_1 = sibling(button_1, 2);

	{
		var consequent = ($$anchor) => {
			var div_5 = root_1$3();

			each(
				div_5,
				5,
				() => (
					get$1(datatype),
					untrack(() => filter_options[get$1(datatype)])
				),
				index,
				($$anchor, opt) => {
					var button_2 = root_2$3();
					var text_2 = child(button_2, true);

					reset(button_2);
					template_effect(() => set_text(text_2, get$1(opt)));

					event('click', button_2, stopPropagation(() => {
						set(current_filter, get$1(opt));
						set(filter_dropdown_open, !get$1(filter_dropdown_open));
					}));

					append$1($$anchor, button_2);
				}
			);

			reset(div_5);
			append$1($$anchor, div_5);
		};

		if_block(node_1, ($$render) => {
			if (get$1(filter_dropdown_open)) $$render(consequent);
		});
	}

	reset(div_4);

	var input = sibling(div_4, 2);

	remove_input_defaults(input);
	reset(div_3);

	var button_3 = sibling(div_3, 2);
	var node_2 = child(button_3);

	Check$1(node_2);
	reset(button_3);
	reset(div_1);
	bind_this(div_1, ($$value) => set(menu_element, $$value), () => get$1(menu_element));
	reset(div);

	template_effect(() => {
		set_attribute(button, 'aria-label', `Change filter type. Filtering ${get$1(datatype)}s`);
		set_text(text, get$1(datatype));
		set_attribute(button_1, 'aria-label', `Change filter. Using '${get$1(current_filter)}'`);
		set_text(text_1, `${get$1(current_filter) ?? ''} `);
		set_value(input, get$1(filter_input_value));
	});

	event('click', button, stopPropagation(() => {
		set(datatype, get$1(datatype) === "string" ? "number" : "string");
		set(current_filter, filter_options[get$1(datatype)][0]);
	}));

	event('click', button_1, stopPropagation(() => set(filter_dropdown_open, !get$1(filter_dropdown_open))));

	event('click', input, stopPropagation(function ($$arg) {
		bubble_event.call(this, $$props, $$arg);
	}));

	event('input', input, handle_filter_input);
	event('click', button_3, () => on_filter()(get$1(datatype), get$1(current_filter), get$1(filter_input_value)));
	append$1($$anchor, div);

	return pop($$exports);
}

var root_2$2 = from_html(`<span class="priority svelte-1v4jjjx"> </span>`);
var root_3$1 = from_html(`<span class="priority svelte-1v4jjjx"> </span>`);
var root_4$1 = from_html(`<span class="priority svelte-1v4jjjx">1</span>`);
var root_1$2 = from_html(`<button role="menuitem"><!> <!></button> <button role="menuitem"><!> <!></button> <button role="menuitem" class="svelte-1v4jjjx"><!> </button> <button role="menuitem"><!> <!></button> <button role="menuitem" class="svelte-1v4jjjx"><!> </button>`, 1);
var root_6 = from_html(`<button role="menuitem" class="delete svelte-1v4jjjx" aria-label="Delete row"><!> </button>`);
var root_5 = from_html(`<button role="menuitem" aria-label="Add row above" class="svelte-1v4jjjx"><!> </button> <button role="menuitem" aria-label="Add row below" class="svelte-1v4jjjx"><!> </button> <!>`, 1);
var root_8$1 = from_html(`<button role="menuitem" class="delete svelte-1v4jjjx" aria-label="Delete column"><!> </button>`);
var root_7 = from_html(`<button role="menuitem" aria-label="Add column to the left" class="svelte-1v4jjjx"><!> </button> <button role="menuitem" aria-label="Add column to the right" class="svelte-1v4jjjx"><!> </button> <!>`, 1);
var root$2 = from_html(`<div class="cell-menu svelte-1v4jjjx" role="menu"><!> <!> <!></div> <!>`, 1);

function CellMenu($$anchor, $$props) {
	push($$props, false);

	const is_header = mutable_source();
	const can_add_rows = mutable_source();
	const can_add_columns = mutable_source();
	let x = prop($$props, 'x', 12);
	let y = prop($$props, 'y', 12);
	let on_add_row_above = prop($$props, 'on_add_row_above', 12);
	let on_add_row_below = prop($$props, 'on_add_row_below', 12);
	let on_add_column_left = prop($$props, 'on_add_column_left', 12);
	let on_add_column_right = prop($$props, 'on_add_column_right', 12);
	let row = prop($$props, 'row', 12);
	let col_count = prop($$props, 'col_count', 12);
	let row_count = prop($$props, 'row_count', 12);
	let on_delete_row = prop($$props, 'on_delete_row', 12);
	let on_delete_col = prop($$props, 'on_delete_col', 12);
	let can_delete_rows = prop($$props, 'can_delete_rows', 12);
	let can_delete_cols = prop($$props, 'can_delete_cols', 12);
	let on_sort = prop($$props, 'on_sort', 12, () => {});
	let on_clear_sort = prop($$props, 'on_clear_sort', 12, () => {});
	let sort_direction = prop($$props, 'sort_direction', 12, null);
	let sort_priority = prop($$props, 'sort_priority', 12, null);
	let on_filter = prop($$props, 'on_filter', 12, () => {});
	let on_clear_filter = prop($$props, 'on_clear_filter', 12, () => {});
	let filter_active = prop($$props, 'filter_active', 12, null);
	let editable = prop($$props, 'editable', 12, true);
	let i18n = prop($$props, 'i18n', 12);
	let menu_element = mutable_source();
	let active_filter_menu = mutable_source(null);

	onMount$1(() => {
		position_menu();
	});

	function position_menu() {
		if (!get$1(menu_element)) return;

		const viewport_width = window.innerWidth;
		const viewport_height = window.innerHeight;
		const menu_rect = get$1(menu_element).getBoundingClientRect();
		let new_x = x() - 30;
		let new_y = y() - 20;

		if (new_x + menu_rect.width > viewport_width) {
			new_x = x() - menu_rect.width + 10;
		}

		if (new_y + menu_rect.height > viewport_height) {
			new_y = y() - menu_rect.height + 10;
		}

		mutate(menu_element, get$1(menu_element).style.left = `${new_x}px`);
		mutate(menu_element, get$1(menu_element).style.top = `${new_y}px`);
	}

	function toggle_filter_menu() {
		if (filter_active()) {
			on_filter()("string", "", "");

			return;
		}

		const menu_rect = get$1(menu_element).getBoundingClientRect();

		set(active_filter_menu, { x: menu_rect.right, y: menu_rect.top + menu_rect.height / 2 });
	}

	legacy_pre_effect(() => (deep_read_state(row())), () => {
		set(is_header, row() === -1);
	});

	legacy_pre_effect(
		() => (
			deep_read_state(editable()),
			deep_read_state(row_count())
		),
		() => {
			set(can_add_rows, editable() && row_count()[1] === "dynamic");
		}
	);

	legacy_pre_effect(
		() => (
			deep_read_state(editable()),
			deep_read_state(col_count())
		),
		() => {
			set(can_add_columns, editable() && col_count()[1] === "dynamic");
		}
	);

	legacy_pre_effect_reset();

	var $$exports = {
		get x() {
			return x();
		},

		set x($$value) {
			x($$value);
			flushSync();
		},

		get y() {
			return y();
		},

		set y($$value) {
			y($$value);
			flushSync();
		},

		get on_add_row_above() {
			return on_add_row_above();
		},

		set on_add_row_above($$value) {
			on_add_row_above($$value);
			flushSync();
		},

		get on_add_row_below() {
			return on_add_row_below();
		},

		set on_add_row_below($$value) {
			on_add_row_below($$value);
			flushSync();
		},

		get on_add_column_left() {
			return on_add_column_left();
		},

		set on_add_column_left($$value) {
			on_add_column_left($$value);
			flushSync();
		},

		get on_add_column_right() {
			return on_add_column_right();
		},

		set on_add_column_right($$value) {
			on_add_column_right($$value);
			flushSync();
		},

		get row() {
			return row();
		},

		set row($$value) {
			row($$value);
			flushSync();
		},

		get col_count() {
			return col_count();
		},

		set col_count($$value) {
			col_count($$value);
			flushSync();
		},

		get row_count() {
			return row_count();
		},

		set row_count($$value) {
			row_count($$value);
			flushSync();
		},

		get on_delete_row() {
			return on_delete_row();
		},

		set on_delete_row($$value) {
			on_delete_row($$value);
			flushSync();
		},

		get on_delete_col() {
			return on_delete_col();
		},

		set on_delete_col($$value) {
			on_delete_col($$value);
			flushSync();
		},

		get can_delete_rows() {
			return can_delete_rows();
		},

		set can_delete_rows($$value) {
			can_delete_rows($$value);
			flushSync();
		},

		get can_delete_cols() {
			return can_delete_cols();
		},

		set can_delete_cols($$value) {
			can_delete_cols($$value);
			flushSync();
		},

		get on_sort() {
			return on_sort();
		},

		set on_sort($$value) {
			on_sort($$value);
			flushSync();
		},

		get on_clear_sort() {
			return on_clear_sort();
		},

		set on_clear_sort($$value) {
			on_clear_sort($$value);
			flushSync();
		},

		get sort_direction() {
			return sort_direction();
		},

		set sort_direction($$value) {
			sort_direction($$value);
			flushSync();
		},

		get sort_priority() {
			return sort_priority();
		},

		set sort_priority($$value) {
			sort_priority($$value);
			flushSync();
		},

		get on_filter() {
			return on_filter();
		},

		set on_filter($$value) {
			on_filter($$value);
			flushSync();
		},

		get on_clear_filter() {
			return on_clear_filter();
		},

		set on_clear_filter($$value) {
			on_clear_filter($$value);
			flushSync();
		},

		get filter_active() {
			return filter_active();
		},

		set filter_active($$value) {
			filter_active($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get i18n() {
			return i18n();
		},

		set i18n($$value) {
			i18n($$value);
			flushSync();
		}
	};

	init$1();

	var fragment = root$2();
	var div = first_child(fragment);
	var node = child(div);

	{
		var consequent_3 = ($$anchor) => {
			var fragment_1 = root_1$2();
			var button = first_child(fragment_1);
			let classes;
			var node_1 = child(button);

			CellMenuIcons(node_1, { icon: 'sort-asc' });

			var text = sibling(node_1);
			var node_2 = sibling(text);

			{
				var consequent = ($$anchor) => {
					var span = root_2$2();
					var text_1 = child(span, true);

					reset(span);
					template_effect(() => set_text(text_1, sort_priority()));
					append$1($$anchor, span);
				};

				if_block(node_2, ($$render) => {
					if (sort_direction() === "asc" && sort_priority() !== null) $$render(consequent);
				});
			}

			reset(button);

			var button_1 = sibling(button, 2);
			let classes_1;
			var node_3 = child(button_1);

			CellMenuIcons(node_3, { icon: 'sort-desc' });

			var text_2 = sibling(node_3);
			var node_4 = sibling(text_2);

			{
				var consequent_1 = ($$anchor) => {
					var span_1 = root_3$1();
					var text_3 = child(span_1, true);

					reset(span_1);
					template_effect(() => set_text(text_3, sort_priority()));
					append$1($$anchor, span_1);
				};

				if_block(node_4, ($$render) => {
					if (sort_direction() === "desc" && sort_priority() !== null) $$render(consequent_1);
				});
			}

			reset(button_1);

			var button_2 = sibling(button_1, 2);
			var node_5 = child(button_2);

			CellMenuIcons(node_5, { icon: 'clear-sort' });

			var text_4 = sibling(node_5);

			reset(button_2);

			var button_3 = sibling(button_2, 2);
			let classes_2;
			var node_6 = child(button_3);

			CellMenuIcons(node_6, { icon: 'filter' });

			var text_5 = sibling(node_6);
			var node_7 = sibling(text_5);

			{
				var consequent_2 = ($$anchor) => {
					var span_2 = root_4$1();

					append$1($$anchor, span_2);
				};

				if_block(node_7, ($$render) => {
					if (filter_active()) $$render(consequent_2);
				});
			}

			reset(button_3);

			var button_4 = sibling(button_3, 2);
			var node_8 = child(button_4);

			CellMenuIcons(node_8, { icon: 'clear-filter' });

			var text_6 = sibling(node_8);

			reset(button_4);

			template_effect(
				($0, $1, $2, $3, $4) => {
					classes = set_class(button, 1, 'svelte-1v4jjjx', null, classes, { active: sort_direction() === "asc" });
					set_text(text, ` ${$0 ?? ''} `);
					classes_1 = set_class(button_1, 1, 'svelte-1v4jjjx', null, classes_1, { active: sort_direction() === "desc" });
					set_text(text_2, ` ${$1 ?? ''} `);
					set_text(text_4, ` ${$2 ?? ''}`);
					classes_2 = set_class(button_3, 1, 'svelte-1v4jjjx', null, classes_2, { active: filter_active() || get$1(active_filter_menu) });
					set_text(text_5, ` ${$3 ?? ''} `);
					set_text(text_6, ` ${$4 ?? ''}`);
				},
				[
					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.sort_ascending"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.sort_descending"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.clear_sort"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.filter"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.clear_filter"))
					)
				]
			);

			event('click', button, () => on_sort()("asc"));
			event('click', button_1, () => on_sort()("desc"));

			event('click', button_2, function (...$$args) {
				on_clear_sort()?.apply(this, $$args);
			});

			event('click', button_3, stopPropagation(toggle_filter_menu));

			event('click', button_4, function (...$$args) {
				on_clear_filter()?.apply(this, $$args);
			});

			append$1($$anchor, fragment_1);
		};

		if_block(node, ($$render) => {
			if (get$1(is_header)) $$render(consequent_3);
		});
	}

	var node_9 = sibling(node, 2);

	{
		var consequent_5 = ($$anchor) => {
			var fragment_2 = root_5();
			var button_5 = first_child(fragment_2);
			var node_10 = child(button_5);

			CellMenuIcons(node_10, { icon: 'add-row-above' });

			var text_7 = sibling(node_10);

			reset(button_5);

			var button_6 = sibling(button_5, 2);
			var node_11 = child(button_6);

			CellMenuIcons(node_11, { icon: 'add-row-below' });

			var text_8 = sibling(node_11);

			reset(button_6);

			var node_12 = sibling(button_6, 2);

			{
				var consequent_4 = ($$anchor) => {
					var button_7 = root_6();
					var node_13 = child(button_7);

					CellMenuIcons(node_13, { icon: 'delete-row' });

					var text_9 = sibling(node_13);

					reset(button_7);

					template_effect(($0) => set_text(text_9, ` ${$0 ?? ''}`), [
						() => (
							deep_read_state(i18n()),
							untrack(() => i18n()("dataframe.delete_row"))
						)
					]);

					event('click', button_7, function (...$$args) {
						on_delete_row()?.apply(this, $$args);
					});

					append$1($$anchor, button_7);
				};

				if_block(node_12, ($$render) => {
					if (can_delete_rows()) $$render(consequent_4);
				});
			}

			template_effect(
				($0, $1) => {
					set_text(text_7, ` ${$0 ?? ''}`);
					set_text(text_8, ` ${$1 ?? ''}`);
				},
				[
					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.add_row_above"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.add_row_below"))
					)
				]
			);

			event('click', button_5, () => on_add_row_above()());
			event('click', button_6, () => on_add_row_below()());
			append$1($$anchor, fragment_2);
		};

		if_block(node_9, ($$render) => {
			if (!get$1(is_header) && get$1(can_add_rows)) $$render(consequent_5);
		});
	}

	var node_14 = sibling(node_9, 2);

	{
		var consequent_7 = ($$anchor) => {
			var fragment_3 = root_7();
			var button_8 = first_child(fragment_3);
			var node_15 = child(button_8);

			CellMenuIcons(node_15, { icon: 'add-column-left' });

			var text_10 = sibling(node_15);

			reset(button_8);

			var button_9 = sibling(button_8, 2);
			var node_16 = child(button_9);

			CellMenuIcons(node_16, { icon: 'add-column-right' });

			var text_11 = sibling(node_16);

			reset(button_9);

			var node_17 = sibling(button_9, 2);

			{
				var consequent_6 = ($$anchor) => {
					var button_10 = root_8$1();
					var node_18 = child(button_10);

					CellMenuIcons(node_18, { icon: 'delete-column' });

					var text_12 = sibling(node_18);

					reset(button_10);

					template_effect(($0) => set_text(text_12, ` ${$0 ?? ''}`), [
						() => (
							deep_read_state(i18n()),
							untrack(() => i18n()("dataframe.delete_column"))
						)
					]);

					event('click', button_10, function (...$$args) {
						on_delete_col()?.apply(this, $$args);
					});

					append$1($$anchor, button_10);
				};

				if_block(node_17, ($$render) => {
					if (can_delete_cols()) $$render(consequent_6);
				});
			}

			template_effect(
				($0, $1) => {
					set_text(text_10, ` ${$0 ?? ''}`);
					set_text(text_11, ` ${$1 ?? ''}`);
				},
				[
					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.add_column_left"))
					),

					() => (
						deep_read_state(i18n()),
						untrack(() => i18n()("dataframe.add_column_right"))
					)
				]
			);

			event('click', button_8, () => on_add_column_left()());
			event('click', button_9, () => on_add_column_right()());
			append$1($$anchor, fragment_3);
		};

		if_block(node_14, ($$render) => {
			if (get$1(can_add_columns)) $$render(consequent_7);
		});
	}

	reset(div);
	bind_this(div, ($$value) => set(menu_element, $$value), () => get$1(menu_element));

	var node_19 = sibling(div, 2);

	{
		var consequent_8 = ($$anchor) => {
			FilterMenu($$anchor, {
				get on_filter() {
					return on_filter();
				}
			});
		};

		if_block(node_19, ($$render) => {
			if (get$1(active_filter_menu)) $$render(consequent_8);
		});
	}

	append$1($$anchor, fragment);

	return pop($$exports);
}

var root_2$1 = from_html(`<button class="toolbar-button check-button svelte-1rajnm3" aria-label="Apply filter and update dataframe values" title="Apply filter and update dataframe values"><!></button>`);
var root_1$1 = from_html(`<div class="search-container svelte-1rajnm3"><input type="text"/> <!></div>`);
var root$1 = from_html(`<div class="toolbar svelte-1rajnm3" role="toolbar" aria-label="Table actions"><div class="toolbar-buttons svelte-1rajnm3"><!> <!> <!></div></div>`);

function Toolbar($$anchor, $$props) {
	push($$props, false);

	let show_fullscreen_button = prop($$props, 'show_fullscreen_button', 12, false);
	let show_copy_button = prop($$props, 'show_copy_button', 12, false);
	let show_search = prop($$props, 'show_search', 12, "none");
	let fullscreen = prop($$props, 'fullscreen', 12, false);
	let on_copy = prop($$props, 'on_copy', 12);
	let on_commit_filter = prop($$props, 'on_commit_filter', 12);
	const dispatch = createEventDispatcher$1();
	let copied = mutable_source(false);
	let timer;
	let current_search_query = prop($$props, 'current_search_query', 12, null);
	let input_value = "";

	function handle_search_input(e) {
		const target = e.target;

		input_value = target.value;

		const new_query = input_value || null;

		if (current_search_query() !== new_query) {
			current_search_query(new_query);
			dispatch("search", current_search_query());
		}
	}

	function copy_feedback() {
		set(copied, true);

		if (timer) clearTimeout(timer);

		timer = setTimeout(
			() => {
				set(copied, false);
			},
			2000
		);
	}

	async function handle_copy() {
		await on_copy()();
		copy_feedback();
	}

	onDestroy$1(() => {
		if (timer) clearTimeout(timer);
	});

	var $$exports = {
		get show_fullscreen_button() {
			return show_fullscreen_button();
		},

		set show_fullscreen_button($$value) {
			show_fullscreen_button($$value);
			flushSync();
		},

		get show_copy_button() {
			return show_copy_button();
		},

		set show_copy_button($$value) {
			show_copy_button($$value);
			flushSync();
		},

		get show_search() {
			return show_search();
		},

		set show_search($$value) {
			show_search($$value);
			flushSync();
		},

		get fullscreen() {
			return fullscreen();
		},

		set fullscreen($$value) {
			fullscreen($$value);
			flushSync();
		},

		get on_copy() {
			return on_copy();
		},

		set on_copy($$value) {
			on_copy($$value);
			flushSync();
		},

		get on_commit_filter() {
			return on_commit_filter();
		},

		set on_commit_filter($$value) {
			on_commit_filter($$value);
			flushSync();
		},

		get current_search_query() {
			return current_search_query();
		},

		set current_search_query($$value) {
			current_search_query($$value);
			flushSync();
		}
	};

	init$1();

	var div = root$1();
	var div_1 = child(div);
	var node = child(div_1);

	{
		var consequent_1 = ($$anchor) => {
			var div_2 = root_1$1();
			var input = child(div_2);

			remove_input_defaults(input);

			let classes;
			var node_1 = sibling(input, 2);

			{
				var consequent = ($$anchor) => {
					var button = root_2$1();
					var node_2 = child(button);

					Check$1(node_2);
					reset(button);

					event('click', button, function (...$$args) {
						on_commit_filter()?.apply(this, $$args);
					});

					append$1($$anchor, button);
				};

				if_block(node_1, ($$render) => {
					if (current_search_query() && show_search() === "filter") $$render(consequent);
				});
			}

			reset(div_2);

			template_effect(() => {
				set_value(input, current_search_query() || "");
				set_attribute(input, 'placeholder', show_search() === "filter" ? "Filter..." : "Search...");
				classes = set_class(input, 1, 'search-input svelte-1rajnm3', null, classes, { 'filter-mode': show_search() === "filter" });
				set_attribute(input, 'title', `Enter text to ${show_search()} the table`);
			});

			event('input', input, handle_search_input);
			append$1($$anchor, div_2);
		};

		if_block(node, ($$render) => {
			if (show_search() !== "none") $$render(consequent_1);
		});
	}

	var node_3 = sibling(node, 2);

	{
		var consequent_2 = ($$anchor) => {
			{
				let $0 = derived_safe_equal(() => get$1(copied) ? Check$1 : Copy$1);
				let $1 = derived_safe_equal(() => get$1(copied) ? "Copied to clipboard" : "Copy table data");

				IconButton$1($$anchor, {
					get Icon() {
						return get$1($0);
					},

					get label() {
						return get$1($1);
					},
					onclick: handle_copy
				});
			}
		};

		if_block(node_3, ($$render) => {
			if (show_copy_button()) $$render(consequent_2);
		});
	}

	var node_4 = sibling(node_3, 2);

	{
		var consequent_3 = ($$anchor) => {
			FullscreenButton$1($$anchor, {
				get fullscreen() {
					return fullscreen();
				},

				$$events: {
					fullscreen($$arg) {
						bubble_event.call(this, $$props, $$arg);
					}
				}
			});
		};

		if_block(node_4, ($$render) => {
			if (show_fullscreen_button()) $$render(consequent_3);
		});
	}

	reset(div_1);
	reset(div);
	append$1($$anchor, div);

	return pop($$exports);
}

function cast_value_to_type(v, t) {
  if (v === null || v === void 0) {
    return v;
  }
  if (t === "number") {
    const n = Number(v);
    return isNaN(n) ? v : n;
  }
  if (t === "bool") {
    if (typeof v === "boolean") return v;
    if (typeof v === "number") return v !== 0;
    const s = String(v).toLowerCase();
    if (s === "true" || s === "1") return true;
    if (s === "false" || s === "0") return false;
    return v;
  }
  if (t === "date") {
    const d = new Date(v);
    return isNaN(d.getTime()) ? v : d.toISOString();
  }
  return v;
}

function make_headers(_head, col_count, els, make_id) {
  let _h = _head || [];
  if (col_count[1] === "fixed" && _h.length < col_count[0]) {
    const fill = Array(col_count[0] - _h.length).fill("").map((_, i) => `${i + _h.length}`);
    _h = _h.concat(fill);
  }
  if (!_h || _h.length === 0) {
    return Array(col_count[0]).fill(0).map((_, i) => {
      const _id = make_id();
      els[_id] = { cell: null, input: null };
      return { id: _id, value: JSON.stringify(i + 1) };
    });
  }
  return _h.map((h, i) => {
    const _id = make_id();
    els[_id] = { cell: null, input: null };
    return { id: _id, value: h ?? "" };
  });
}
function process_data(values, els, data_binding, make_id, display_value = null, datatype) {
  if (!values || values.length === 0) {
    return [];
  }
  const result = values.map((row, i) => {
    return row.map((value, j) => {
      const _id = make_id();
      els[_id] = { cell: null, input: null };
      data_binding[_id] = value;
      let display = display_value?.[i]?.[j];
      if (display === void 0) {
        display = String(value);
      }
      const dtype = Array.isArray(datatype) ? datatype[j] : datatype;
      return {
        id: _id,
        value: cast_value_to_type(value, dtype),
        display_value: display
      };
    });
  });
  return result;
}

async function save_cell_value(input_value, ctx, row, col) {
  if (!ctx.data || !ctx.data[row] || !ctx.data[row][col]) return;
  const old_value = ctx.data[row][col].value;
  ctx.data[row][col].value = input_value;
  if (ctx.data[row][col].display_value !== void 0) {
    ctx.data[row][col].display_value = input_value;
  }
  if (old_value !== input_value && ctx.dispatch) {
    ctx.dispatch("change", {
      data: ctx.data.map((row2) => row2.map((cell) => cell.value)),
      headers: ctx.headers?.map((h) => h.value) || [],
      metadata: null
    });
  }
  ctx.actions.set_selected([row, col]);
}
async function handle_cell_blur(event, ctx, coords) {
  if (!ctx.data || !ctx.headers || !ctx.els) return;
  const input_el = event.target;
  if (!input_el || input_el.value === void 0) return;
  await save_cell_value(input_el.value, ctx, coords[0], coords[1]);
}
function handle_header_navigation(event, ctx) {
  const state = get(ctx.state);
  const selected_header = state.ui_state.selected_header;
  const header_edit = state.ui_state.header_edit;
  const headers = ctx.headers || [];
  if (selected_header === false || header_edit !== false) return false;
  switch (event.key) {
    case "ArrowDown":
      ctx.actions.set_selected_header(false);
      ctx.actions.set_selected([0, selected_header]);
      ctx.actions.set_selected_cells([[0, selected_header]]);
      return true;
    case "ArrowLeft":
      ctx.actions.set_selected_header(
        selected_header > 0 ? selected_header - 1 : selected_header
      );
      return true;
    case "ArrowRight":
      ctx.actions.set_selected_header(
        selected_header < headers.length - 1 ? selected_header + 1 : selected_header
      );
      return true;
    case "Escape":
      event.preventDefault();
      ctx.actions.set_selected_header(false);
      return true;
    case "Enter":
      event.preventDefault();
      if (state.config.editable) {
        ctx.actions.set_header_edit(selected_header);
      }
      return true;
  }
  return false;
}
function handle_delete_operation(event, ctx) {
  if (!ctx.data || !ctx.headers || !ctx.els || !ctx.dispatch) return false;
  const state = get(ctx.state);
  if (!state.config.editable) return false;
  if (event.key !== "Delete" && event.key !== "Backspace") return false;
  const editing = state.ui_state.editing;
  const selected_cells = state.ui_state.selected_cells;
  const static_columns = state.config.static_columns || [];
  if (selected_cells.some(([_, col]) => static_columns.includes(col))) {
    return false;
  }
  if (editing) {
    const [row, col] = editing;
    const input_el = ctx.els[ctx.data[row][col].id]?.input;
    if (input_el && input_el.selectionStart !== input_el.selectionEnd) {
      return false;
    }
    if (event.key === "Delete" && input_el?.selectionStart !== input_el?.value.length) {
      return false;
    }
    if (event.key === "Backspace" && input_el?.selectionStart !== 0) {
      return false;
    }
  }
  event.preventDefault();
  if (selected_cells.length > 0) {
    const new_data = handle_delete_key(ctx.data, selected_cells);
    ctx.dispatch("change", {
      data: new_data.map((row) => row.map((cell) => cell.value)),
      headers: ctx.headers.map((h) => h.value),
      metadata: null
    });
  }
  return true;
}
function handle_arrow_keys(event, ctx, i, j) {
  const state = get(ctx.state);
  const editing = state.ui_state.editing;
  const selected_cells = state.ui_state.selected_cells;
  if (editing) return false;
  if (!ctx.data) return false;
  event.preventDefault();
  const next_coords = ctx.actions.move_cursor(event, [i, j], ctx.data);
  if (next_coords) {
    if (event.shiftKey) {
      ctx.actions.set_selected_cells(
        ctx.actions.get_range_selection(
          selected_cells.length > 0 ? selected_cells[0] : [i, j],
          next_coords
        )
      );
      ctx.actions.set_editing(false);
    } else {
      ctx.actions.set_selected_cells([next_coords]);
      ctx.actions.set_editing(false);
    }
    ctx.actions.set_selected(next_coords);
  } else if (next_coords === false && event.key === "ArrowUp" && i === 0) {
    ctx.actions.set_selected_header(j);
    ctx.actions.set_selected(false);
    ctx.actions.set_selected_cells([]);
    ctx.actions.set_editing(false);
  }
  return true;
}
async function handle_enter_key(event, ctx, i, j) {
  if (!ctx.data || !ctx.els) return false;
  const state = get(ctx.state);
  if (!state.config.editable) return false;
  const editing = state.ui_state.editing;
  if (editing && event.shiftKey) return false;
  event.preventDefault();
  if (editing && dequal$3(editing, [i, j])) {
    const cell_id = ctx.data[i][j].id;
    const input_el = ctx.els[cell_id]?.input;
    if (input_el) {
      await save_cell_value(input_el.value, ctx, i, j);
    }
    ctx.actions.set_editing(false);
    await tick$1();
    ctx.parent_element?.focus();
  } else {
    ctx.actions.set_editing([i, j]);
  }
  return true;
}
function handle_tab_key(event, ctx, i, j) {
  if (!ctx.data) return false;
  event.preventDefault();
  ctx.actions.set_editing(false);
  const next_cell = ctx.actions.get_next_cell_coordinates(
    [i, j],
    ctx.data,
    event.shiftKey
  );
  if (next_cell) {
    ctx.actions.set_selected_cells([next_cell]);
    ctx.actions.set_selected(next_cell);
    if (get(ctx.state).config.editable) {
      ctx.actions.set_editing(next_cell);
    }
  }
  return true;
}
function handle_default_key(event, ctx, i, j) {
  const state = get(ctx.state);
  if (!state.config.editable) return false;
  const editing = state.ui_state.editing;
  if (event.key.length === 1 && (!editing || !dequal$3(editing, [i, j]))) {
    ctx.actions.set_editing([i, j]);
    return true;
  }
  return false;
}
async function handle_cell_navigation(event, ctx) {
  if (!ctx.data) return false;
  const state = get(ctx.state);
  const selected = state.ui_state.selected;
  const selected_cells = state.ui_state.selected_cells;
  if (!selected) return false;
  if (event.key === "c" && (event.metaKey || event.ctrlKey)) {
    event.preventDefault();
    if (selected_cells.length > 0) {
      await copy_table_data(ctx.data, selected_cells);
    }
    ctx.actions.set_copy_flash(true);
    return true;
  }
  const [i, j] = selected;
  switch (event.key) {
    case "ArrowRight":
    case "ArrowLeft":
    case "ArrowDown":
    case "ArrowUp":
      return handle_arrow_keys(event, ctx, i, j);
    case "Escape":
      if (!state.config.editable) return false;
      event.preventDefault();
      ctx.actions.set_editing(false);
      tick$1().then(() => {
        if (ctx.parent_element) {
          ctx.parent_element.focus();
        }
      });
      return true;
    case "Enter":
      return await handle_enter_key(event, ctx, i, j);
    case "Tab":
      return handle_tab_key(event, ctx, i, j);
    case "Delete":
    case "Backspace":
      return handle_delete_operation(event, ctx);
    default:
      return handle_default_key(event, ctx, i, j);
  }
}
async function handle_keydown(event, context) {
  if (handle_header_navigation(event, context)) return;
  if (handle_delete_operation(event, context)) return;
  await handle_cell_navigation(event, context);
}

function create_drag_handlers(state, set_is_dragging, set_selected_cells, set_selected, handle_cell_click, show_row_numbers, parent_element) {
  const start_drag = (event, row, col) => {
    const target = event.target;
    const is_checkbox_click = target.type === "checkbox" || target.closest('input[type="checkbox"]') || target.closest(".bool-cell");
    if (event.target instanceof HTMLAnchorElement || show_row_numbers && col === -1 || is_checkbox_click)
      return;
    event.preventDefault();
    event.stopPropagation();
    state.mouse_down_pos = { x: event.clientX, y: event.clientY };
    state.drag_start = [row, col];
    if (!event.shiftKey && !event.metaKey && !event.ctrlKey) {
      set_selected_cells([[row, col]]);
      set_selected([row, col]);
      handle_cell_click(event, row, col);
    }
  };
  const update_selection = (event) => {
    const cell = event.target.closest("td");
    if (!cell) return;
    const row = parseInt(cell.getAttribute("data-row") || "0");
    const col = parseInt(cell.getAttribute("data-col") || "0");
    if (isNaN(row) || isNaN(col)) return;
    const selection_range = get_range_selection(state.drag_start, [row, col]);
    set_selected_cells(selection_range);
    set_selected([row, col]);
  };
  const end_drag = (event) => {
    if (!state.is_dragging && state.drag_start) {
      handle_cell_click(event, state.drag_start[0], state.drag_start[1]);
    } else if (state.is_dragging && parent_element) {
      parent_element.focus();
    }
    state.is_dragging = false;
    set_is_dragging(false);
    state.drag_start = null;
    state.mouse_down_pos = null;
  };
  return {
    handle_mouse_down: start_drag,
    handle_mouse_move(event) {
      if (!state.drag_start || !state.mouse_down_pos) return;
      if (!(event.buttons & 1)) {
        end_drag(event);
        return;
      }
      const dx = Math.abs(event.clientX - state.mouse_down_pos.x);
      const dy = Math.abs(event.clientY - state.mouse_down_pos.y);
      if (!state.is_dragging && (dx > 3 || dy > 3)) {
        state.is_dragging = true;
        set_is_dragging(true);
      }
      if (state.is_dragging) {
        update_selection(event);
      }
    },
    handle_mouse_up: end_drag
  };
}

var root_3 = from_html(`<div class="label svelte-2balj6"><p class="svelte-2balj6"> </p></div>`);
var root_2 = from_html(`<div class="header-row svelte-2balj6"><!> <!></div>`);
var root_4 = from_html(`<caption class="sr-only svelte-2balj6"> </caption>`);
var root_8 = from_html(`<td tabindex="-1" class="svelte-2balj6"><div class="cell-wrap svelte-2balj6"><!></div></td>`);
var root_10 = from_html(`<tr slot="thead" class="svelte-2balj6"><!><!></tr>`);
var root_13 = from_html(`<tr slot="tbody"><!><!></tr>`);
var root_9 = from_html(`<div class="table-wrap svelte-2balj6"><!></div>`);
var root_16 = from_html(`<button class="scroll-top-button svelte-2balj6">&uarr;</button>`);
var root_1 = from_html(`<div class="table-container svelte-2balj6"><!> <div role="grid" tabindex="0"><table aria-hidden="true" class="svelte-2balj6"><!><thead class="svelte-2balj6"><tr class="svelte-2balj6"><!><!></tr></thead><tbody class="svelte-2balj6"><tr class="svelte-2balj6"><!><!></tr></tbody></table> <!> <!></div></div> <!> <!>`, 1);

function Table($$anchor, $$props) {
	push($$props, false);

	const $df_state = () => store_get(df_state, '$df_state', $$stores);
	const [$$stores, $$cleanup] = setup_stores();
	const selected_cells = mutable_source();
	const selected = mutable_source();
	const editing = mutable_source();
	const header_edit = mutable_source();
	const selected_header = mutable_source();
	const active_cell_menu = mutable_source();
	const active_header_menu = mutable_source();
	const copy_flash = mutable_source();
	const actual_pinned_columns = mutable_source();
	const max = mutable_source();
	const selected_index = mutable_source();
	const handle_mouse_down = mutable_source();
	const handle_mouse_move = mutable_source();
	const handle_mouse_up = mutable_source();
	let datatype = prop($$props, 'datatype', 12);
	let label = prop($$props, 'label', 12, null);
	let show_label = prop($$props, 'show_label', 12, true);
	let headers = prop($$props, 'headers', 28, () => []);
	let values = prop($$props, 'values', 28, () => []);
	let col_count = prop($$props, 'col_count', 12);
	let row_count = prop($$props, 'row_count', 12);
	let latex_delimiters = prop($$props, 'latex_delimiters', 12);
	let components = prop($$props, 'components', 28, () => ({}));
	let editable = prop($$props, 'editable', 12, true);
	let wrap = prop($$props, 'wrap', 12, false);
	let root = prop($$props, 'root', 12);
	let i18n = prop($$props, 'i18n', 12);
	let max_height = prop($$props, 'max_height', 12, 500);
	let line_breaks = prop($$props, 'line_breaks', 12, true);
	let column_widths = prop($$props, 'column_widths', 28, () => []);
	let show_row_numbers = prop($$props, 'show_row_numbers', 12, false);
	let upload = prop($$props, 'upload', 12);
	let stream_handler = prop($$props, 'stream_handler', 12);
	let buttons = prop($$props, 'buttons', 12, null);
	let value_is_output = prop($$props, 'value_is_output', 12, false);
	let max_chars = prop($$props, 'max_chars', 12, undefined);
	let show_search = prop($$props, 'show_search', 12, "none");
	let pinned_columns = prop($$props, 'pinned_columns', 12, 0);
	let static_columns = prop($$props, 'static_columns', 28, () => []);
	let fullscreen = prop($$props, 'fullscreen', 12, false);

	const df_ctx = mutable_source(create_dataframe_context({
		show_fullscreen_button: buttons() === null ? true : buttons().includes("fullscreen"),
		show_copy_button: buttons() === null ? true : buttons().includes("copy"),
		show_search: show_search(),
		show_row_numbers: show_row_numbers(),
		editable: editable(),
		pinned_columns: pinned_columns(),
		show_label: show_label(),
		line_breaks: line_breaks(),
		wrap: wrap(),
		max_height: max_height(),
		column_widths: column_widths(),
		max_chars: max_chars(),
		static_columns: static_columns()
	}));

	const { state: df_state, actions: df_actions } = get$1(df_ctx);

	onMount$1(() => {
		mutate(df_ctx, get$1(df_ctx).parent_element = get$1(parent));
		mutate(df_ctx, get$1(df_ctx).get_data_at = get_data_at);
		mutate(df_ctx, get$1(df_ctx).get_column = get_column);
		mutate(df_ctx, get$1(df_ctx).get_row = get_row);
		mutate(df_ctx, get$1(df_ctx).dispatch = dispatch);
		init_drag_handlers();

		const observer = new IntersectionObserver((entries) => {
			entries.forEach((entry) => {
				if (entry.isIntersecting && !is_visible) {
					set(width_calculated, false);
				}

				is_visible = entry.isIntersecting;
			});
		});

		observer.observe(get$1(parent));
		document.addEventListener("click", handle_click_outside$1);
		window.addEventListener("resize", handle_resize);

		const global_mouse_up = (event) => {
			if (get$1(is_dragging) || get$1(drag_start)) {
				get$1(handle_mouse_up)(event);
			}
		};

		document.addEventListener("mouseup", global_mouse_up);

		return () => {
			observer.disconnect();
			document.removeEventListener("click", handle_click_outside$1);
			window.removeEventListener("resize", handle_resize);
			document.removeEventListener("mouseup", global_mouse_up);
		};
	});

	const dispatch = createEventDispatcher$1();
	let els = mutable_source({});
	let data_binding = {};
	let _headers = mutable_source(make_headers(headers(), col_count(), get$1(els), make_id));
	let old_headers = mutable_source(headers());
	let data = mutable_source([[]]);
	let old_val = mutable_source(undefined);
	let search_results = mutable_source([[]]);
	let dragging = mutable_source(false);
	let color_accent_copied;
	let filtered_to_original_map = mutable_source([]);

	onMount$1(() => {
		const color = getComputedStyle(document.documentElement).getPropertyValue("--color-accent").trim();

		color_accent_copied = color + "40"; // 80 is 50% opacity in hex
		document.documentElement.style.setProperty("--color-accent-copied", color_accent_copied);
	});

	const get_data_at = (row, col) => get$1(data)?.[row]?.[col]?.value;
	const get_column = (col) => get$1(data)?.map((row) => row[col]?.value) ?? [];
	const get_row = (row) => get$1(data)?.[row]?.map((cell) => cell.value) ?? [];

	function make_id() {
		return Math.random().toString(36).substring(2, 15);
	}

	let display_value = prop($$props, 'display_value', 12, null);
	let styling = prop($$props, 'styling', 12, null);

	// only clear column widths when the data structure changes
	// only reset sort state when values are changed
	let previous_headers = mutable_source(get$1(_headers).map((h) => h.value));

	let previous_data = mutable_source(get$1(data).map((row) => row.map((cell) => cell.value)));

	function handle_sort(col, direction) {
		df_actions.handle_sort(col, direction);
		sort_data(get$1(data), display_value(), styling());
	}

	function clear_sort() {
		df_actions.reset_sort_state();
		sort_data(get$1(data), display_value(), styling());
	}

	function handle_filter(col, datatype, filter, value) {
		df_actions.handle_filter(col, datatype, filter, value);
		filter_data(get$1(data), display_value(), styling());
	}

	function clear_filter() {
		df_actions.reset_filter_state();
		filter_data(get$1(data), display_value(), styling());
	}

	async function edit_header(i, _select = false) {
		if (!editable() || get$1(header_edit) === i || col_count()[1] !== "dynamic") return;

		df_actions.set_header_edit(i);
	}

	function handle_header_click(event, col) {
		if (event.target instanceof HTMLAnchorElement) {
			return;
		}

		event.preventDefault();
		event.stopPropagation();

		if (!editable()) return;

		df_actions.set_editing(false);
		df_actions.handle_header_click(col, editable());
		get$1(parent).focus();
	}

	function end_header_edit(event) {
		if (!editable()) return;

		df_actions.end_header_edit(event.detail.key);
		get$1(parent).focus();
	}

	async function add_row(index) {
		get$1(parent).focus();

		if (row_count()[1] !== "dynamic") return;

		const new_row = Array(get$1(data)[0]?.length || headers().length).fill(0).map((_, i) => {
			const _id = make_id();

			mutate(els, get$1(els)[_id] = { cell: null, input: null });

			return { id: _id, value: "" };
		});

		if (get$1(data).length === 0) {
			set(data, [new_row]);
		} else if (index !== undefined && index >= 0 && index <= get$1(data).length) {
			get$1(data).splice(index, 0, new_row);
		} else {
			get$1(data).push(new_row);
		}

		set(selected, [index !== undefined ? index : get$1(data).length - 1, 0]);
	}

	async function add_col(index) {
		get$1(parent).focus();

		if (col_count()[1] !== "dynamic") return;

		const result = df_actions.add_col(get$1(data), headers(), make_id, index);

		result.data.forEach((row) => {
			row.forEach((cell) => {
				if (!get$1(els)[cell.id]) {
					mutate(els, get$1(els)[cell.id] = { cell: null, input: null });
				}
			});
		});

		set(data, result.data);
		headers(result.headers);
		await tick$1();

		requestAnimationFrame(() => {
			edit_header(index !== undefined ? index : get$1(data)[0].length - 1, true);

			const new_w = get$1(parent).querySelectorAll("tbody")[1].offsetWidth;

			get$1(parent).querySelectorAll("table")[1].scrollTo({ left: new_w });
		});
	}

	function handle_click_outside$1(event) {
		if (handle_click_outside(event, get$1(parent))) {
			df_actions.clear_ui_state();
			set(header_edit, false);
			set(selected_header, false);
		}
	}

	let width_calc_timeout = mutable_source();
	let width_calculated = mutable_source(false);
	let cells = mutable_source([]);
	let parent = mutable_source();
	let table = mutable_source();
	let last_width_data_length = mutable_source(0);
	let last_width_column_count = mutable_source(0);

	function set_cell_widths() {
		const column_count = get$1(data)[0]?.length || 0;

		if ($df_state().filter_state.filter_columns.length > 0) {
			return;
		}

		if (get$1(last_width_data_length) === get$1(data).length && get$1(last_width_column_count) === column_count && $df_state().sort_state.sort_columns.length > 0) {
			return;
		}

		if (!get$1(parent)) {
			return;
		}

		set(last_width_data_length, get$1(data).length);
		set(last_width_column_count, column_count);

		const widths = get$1(cells).map((el) => el?.clientWidth || 0);

		if (widths.length === 0) return;

		if (show_row_numbers()) {
			get$1(parent).style.setProperty(`--cell-width-row-number`, `${widths[0]}px`);
		}

		for (let i = 0; i < 50; i++) {
			if (!column_widths()[i]) {
				get$1(parent).style.removeProperty(`--cell-width-${i}`);
			} else if (column_widths()[i].endsWith("%")) {
				const percentage = parseFloat(column_widths()[i]);
				const pixel_width = Math.floor(percentage / 100 * get$1(parent).clientWidth);

				get$1(parent).style.setProperty(`--cell-width-${i}`, `${pixel_width}px`);
			} else {
				get$1(parent).style.setProperty(`--cell-width-${i}`, column_widths()[i]);
			}
		}

		widths.forEach((width, i) => {
			if (!column_widths()[i]) {
				const calculated_width = `${Math.max(width, 45)}px`;

				get$1(parent).style.setProperty(`--cell-width-${i}`, calculated_width);
			}
		});
	}

	function get_cell_width(index) {
		return `var(--cell-width-${index})`;
	}

	let table_height = mutable_source(values().slice(0, max_height() / values().length * 37).length * 37 + 37);
	let scrollbar_width = mutable_source(0);

	function sort_data(_data, _display_value, _styling) {
		const result = sort_data_and_preserve_selection(_data, _display_value, _styling, $df_state().sort_state.sort_columns, get$1(selected), get_current_indices);

		set(data, result.data);
		set(selected, result.selected);
	}

	function filter_data(_data, _display_value, _styling) {
		const result = filter_data_and_preserve_selection(_data, _display_value, _styling, $df_state().filter_state.filter_columns, get$1(selected), get_current_indices, $df_state().filter_state.initial_data?.data, $df_state().filter_state.initial_data?.display_value, $df_state().filter_state.initial_data?.styling);

		set(data, result.data);
		set(selected, result.selected);
	}

	let is_visible = false;

	const set_copy_flash = (value) => {
		df_actions.set_copy_flash(value);
	};

	let previous_selected_cells = mutable_source([]);

	function handle_blur(event) {
		const { blur_event, coords } = event.detail;

		handle_cell_blur(blur_event, get$1(df_ctx), coords);
	}

	function toggle_header_menu(event, col) {
		event.stopPropagation();

		if (get$1(active_header_menu) && get$1(active_header_menu).col === col) {
			df_actions.set_active_header_menu(null);
		} else {
			const header = event.target.closest("th");

			if (header) {
				const rect = header.getBoundingClientRect();

				df_actions.set_active_header_menu({ col, x: rect.right, y: rect.bottom });
			}
		}
	}

	afterUpdate$1(() => {
		value_is_output(false);
	});

	function delete_col_at(index) {
		if (col_count()[1] !== "dynamic") return;
		if (get$1(data)[0].length <= 1) return;

		const result = df_actions.delete_col_at(get$1(data), headers(), index);

		set(data, result.data);
		headers(result.headers);
		set(_headers, make_headers(headers(), col_count(), get$1(els), make_id));
		df_actions.set_active_cell_menu(null);
		df_actions.set_active_header_menu(null);
		df_actions.set_selected(false);
		df_actions.set_selected_cells([]);
		df_actions.set_editing(false);
	}

	function delete_row_at(index) {
		set(data, df_actions.delete_row_at(get$1(data), index));
		df_actions.set_active_cell_menu(null);
		df_actions.set_active_header_menu(null);
	}

	let selected_cell_coords = mutable_source();

	function commit_filter() {
		if ($df_state().current_search_query && show_search() === "filter") {
			const filtered_data = [];
			const filtered_display_values = [];
			const filtered_styling = [];

			get$1(search_results).forEach((row) => {
				const data_row = [];
				const display_row = [];
				const styling_row = [];

				row.forEach((cell) => {
					data_row.push(cell.value);
					display_row.push(cell.display_value !== undefined ? cell.display_value : String(cell.value));
					styling_row.push(cell.styling || "");
				});

				filtered_data.push(data_row);
				filtered_display_values.push(display_row);
				filtered_styling.push(styling_row);
			});

			const change_payload = {
				data: filtered_data,
				headers: get$1(_headers).map((h) => h.value),
				metadata: {
					display_value: filtered_display_values,
					styling: filtered_styling
				}
			};

			dispatch("change", change_payload);

			if (!value_is_output()) {
				dispatch("input");
			}

			df_actions.handle_search(null);
		}
	}

	let viewport = mutable_source();
	let show_scroll_button = mutable_source(false);

	function scroll_to_top() {
		get$1(viewport).scrollTo({ top: 0 });
	}

	function handle_resize() {
		df_actions.set_active_cell_menu(null);
		df_actions.set_active_header_menu(null);
		set(selected_cells, []);
		set(selected, false);
		set(editing, false);
		set(width_calculated, false);
		set_cell_widths();
	}

	function add_row_at(index, position) {
		const row_index = position === "above" ? index : index + 1;

		add_row(row_index);
		set(active_cell_menu, null);
		set(active_header_menu, null);
	}

	function add_col_at(index, position) {
		const col_index = position === "left" ? index : index + 1;

		add_col(col_index);
		set(active_cell_menu, null);
		set(active_header_menu, null);
	}

	function reset_sort_state() {
		df_actions.reset_sort_state();
	}

	function handle_select_all(col, checked) {
		set(data, get$1(data).map((row) => {
			const new_row = [...row];

			if (new_row[col]) {
				new_row[col] = { ...new_row[col], value: checked };
			}

			return new_row;
		}));
	}

	let is_dragging = mutable_source(false);
	let drag_start = mutable_source(null);
	let mouse_down_pos = mutable_source(null);

	const drag_state = {
		is_dragging: get$1(is_dragging),
		drag_start: get$1(drag_start),
		mouse_down_pos: get$1(mouse_down_pos)
	};

	let drag_handlers = mutable_source();

	function init_drag_handlers() {
		set(drag_handlers, create_drag_handlers(drag_state, (value) => set(is_dragging, value), (cells) => df_actions.set_selected_cells(cells), (cell) => df_actions.set_selected(cell), (event, row, col) => df_actions.handle_cell_click(event, row, col), show_row_numbers(), get$1(parent)));
	}

	function get_cell_display_value(row, col) {
		const is_search_active = $df_state().current_search_query !== undefined;

		if (is_search_active && get$1(search_results)?.[row]?.[col]) {
			return get$1(search_results)[row][col].display_value !== undefined
				? get$1(search_results)[row][col].display_value
				: String(get$1(search_results)[row][col].value);
		}

		if (get$1(data)?.[row]?.[col]) {
			return get$1(data)[row][col].display_value !== undefined
				? get$1(data)[row][col].display_value
				: String(get$1(data)[row][col].value);
		}

		return "";
	}

	legacy_pre_effect(() => ($df_state()), () => {
		set(selected_cells, $df_state().ui_state.selected_cells);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(selected, $df_state().ui_state.selected);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(editing, $df_state().ui_state.editing);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(header_edit, $df_state().ui_state.header_edit);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(selected_header, $df_state().ui_state.selected_header);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(active_cell_menu, $df_state().ui_state.active_cell_menu);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(active_header_menu, $df_state().ui_state.active_header_menu);
	});

	legacy_pre_effect(() => ($df_state()), () => {
		set(copy_flash, $df_state().ui_state.copy_flash);
	});

	legacy_pre_effect(
		() => (
			deep_read_state(values()),
			get$1(old_val),
			get$1(parent),
			get$1(data),
			get$1(els),
			deep_read_state(display_value()),
			deep_read_state(datatype()),
			$df_state(),
			deep_read_state(styling()),
			get$1(cells)
		),
		() => {
			if (!dequal$3(values(), get$1(old_val))) {
				if (get$1(parent)) {
					// only clear column widths when the data structure changes
					const is_reset = values().length === 0 || values().length === 1 && values()[0].length === 0;

					const is_different_structure = get$1(old_val) !== undefined && (values().length !== get$1(old_val).length || values()[0] && get$1(old_val)[0] && values()[0].length !== get$1(old_val)[0].length);

					if (is_reset || is_different_structure) {
						for (let i = 0; i < 50; i++) {
							get$1(parent).style.removeProperty(`--cell-width-${i}`);
						}

						set(last_width_data_length, 0);
						set(last_width_column_count, 0);
						set(width_calculated, false);
					}
				}

				// only reset sort state when values are changed
				const is_reset = values().length === 0 || values().length === 1 && values()[0].length === 0;

				const is_different_structure = get$1(old_val) !== undefined && (values().length !== get$1(old_val).length || values()[0] && get$1(old_val)[0] && values()[0].length !== get$1(old_val)[0].length);

				set(data, process_data(values(), get$1(els), data_binding, make_id, display_value(), datatype()));
				set(old_val, JSON.parse(JSON.stringify(values())));

				if (is_reset || is_different_structure) {
					df_actions.reset_sort_state();
				} else if ($df_state().sort_state.sort_columns.length > 0) {
					sort_data(get$1(data), display_value(), styling());
				} else {
					df_actions.handle_sort(-1, "asc");
					df_actions.reset_sort_state();
				}

				if ($df_state().filter_state.filter_columns.length > 0) {
					filter_data(get$1(data), display_value(), styling());
				} else {
					df_actions.reset_filter_state();
				}

				if ($df_state().current_search_query) {
					df_actions.handle_search(null);
				}

				if (get$1(parent) && get$1(cells).length > 0 && (is_reset || is_different_structure)) {
					set(width_calculated, false);
				}
			}
		}
	);

	legacy_pre_effect(() => (deep_read_state(pinned_columns()), get$1(data)), () => {
		set(actual_pinned_columns, pinned_columns() && get$1(data)?.[0]?.length ? Math.min(pinned_columns(), get$1(data)[0].length) : 0);
	});

	legacy_pre_effect(
		() => (
			deep_read_state(headers()),
			get$1(old_headers),
			deep_read_state(col_count()),
			get$1(els)
		),
		() => {
			if (!dequal$3(headers(), get$1(old_headers))) {
				set(_headers, make_headers(headers(), col_count(), get$1(els), make_id));
				set(old_headers, JSON.parse(JSON.stringify(headers())));
			}
		}
	);

	legacy_pre_effect(
		() => (
			get$1(data),
			get$1(_headers),
			get$1(els),
			deep_read_state(display_value()),
			deep_read_state(styling())
		),
		() => {
			if (get$1(data) || get$1(_headers) || get$1(els)) {
				mutate(df_ctx, get$1(df_ctx).data = get$1(data));
				mutate(df_ctx, get$1(df_ctx).headers = get$1(_headers));
				mutate(df_ctx, get$1(df_ctx).els = get$1(els));
				mutate(df_ctx, get$1(df_ctx).display_value = display_value());
				mutate(df_ctx, get$1(df_ctx).styling = styling());
			}
		}
	);

	legacy_pre_effect(
		() => (
			$df_state(),
			get$1(filtered_to_original_map),
			get$1(data),
			deep_read_state(styling())
		),
		() => {
			if ($df_state().current_search_query !== undefined) {
				const cell_map = new Map();

				set(filtered_to_original_map, []);

				get$1(data).forEach((row, row_idx) => {
					if (row.some((cell) => String(cell?.value).toLowerCase().includes($df_state().current_search_query?.toLowerCase() || ""))) {
						get$1(filtered_to_original_map).push(row_idx);
					}

					row.forEach((cell, col_idx) => {
						cell_map.set(cell.id, {
							value: cell.value,
							display_value: cell.display_value !== undefined ? cell.display_value : String(cell.value),
							styling: styling()?.[row_idx]?.[col_idx] || ""
						});
					});
				});

				const filtered = df_actions.filter_data(get$1(data));

				set(search_results, filtered.map((row) => row.map((cell) => {
					const original = cell_map.get(cell.id);

					return {
						...cell,
						display_value: original?.display_value !== undefined ? original.display_value : String(cell.value),
						styling: original?.styling || ""
					};
				})));
			} else {
				set(filtered_to_original_map, []);
			}
		}
	);

	legacy_pre_effect(
		() => (
			get$1(data),
			get$1(_headers),
			get$1(previous_data),
			get$1(previous_headers),
			deep_read_state(value_is_output())
		),
		() => {
			if (get$1(data) || get$1(_headers)) {
				df_actions.trigger_change(get$1(data), get$1(_headers), get$1(previous_data), get$1(previous_headers), value_is_output(), dispatch);
				set(previous_data, get$1(data).map((row) => row.map((cell) => cell.value)));
				set(previous_headers, get$1(_headers).map((h) => h.value));
			}
		}
	);

	legacy_pre_effect(
		() => (
			$df_state(),
			get$1(data),
			deep_read_state(display_value()),
			deep_read_state(styling())
		),
		() => {
			if ($df_state().filter_state.filter_columns.length > 0) {
				filter_data(get$1(data), display_value(), styling());
			}

			if ($df_state().sort_state.sort_columns.length > 0) {
				sort_data(get$1(data), display_value(), styling());
				df_actions.update_row_order(get$1(data));
			}
		}
	);

	legacy_pre_effect(() => (get$1(data)), () => {
		set(max, get_max(get$1(data)));
	});

	legacy_pre_effect(() => (get$1(cells), get$1(width_calc_timeout)), () => {
		if (get$1(cells)[0] && get$1(cells)[0]?.clientWidth) {
			clearTimeout(get$1(width_calc_timeout));
			set(width_calc_timeout, setTimeout(() => set_cell_widths(), 100));
		}
	});

	legacy_pre_effect(() => (get$1(cells), get$1(width_calculated)), () => {
		if (get$1(cells)[0] && !get$1(width_calculated)) {
			set_cell_widths();
			set(width_calculated, true);
		}
	});

	legacy_pre_effect(() => (get$1(selected)), () => {
		set(selected_index, !!get$1(selected) && get$1(selected)[0]);
	});

	legacy_pre_effect(
		() => (
			get$1(copy_flash),
			get$1(selected_cells),
			get$1(previous_selected_cells)
		),
		() => {
			if (get$1(copy_flash) && !dequal$3(get$1(selected_cells), get$1(previous_selected_cells))) {
				set_copy_flash(false);
			}

			set(previous_selected_cells, get$1(selected_cells));
		}
	);

	legacy_pre_effect(() => (get$1(selected)), () => {
		if (get$1(selected) !== false) set(selected_cell_coords, get$1(selected));
	});

	legacy_pre_effect(
		() => (
			get$1(selected),
			get$1(data),
			get$1(els),
			get$1(parent),
			get$1(table)
		),
		() => {
			if (get$1(selected) !== false) {
				const positions = calculate_selection_positions(get$1(selected), get$1(data), get$1(els), get$1(parent), get$1(table));

				document.documentElement.style.setProperty("--selected-col-pos", positions.col_pos);
				document.documentElement.style.setProperty("--selected-row-pos", positions.row_pos || "0px");
			}
		}
	);

	legacy_pre_effect(() => {}, () => {
		set(is_dragging, drag_state.is_dragging);
		set(drag_start, drag_state.drag_start);
		set(mouse_down_pos, drag_state.mouse_down_pos);
	});

	legacy_pre_effect(() => (get$1(parent)), () => {
		if (get$1(parent)) init_drag_handlers();
	});

	legacy_pre_effect(() => (get$1(drag_handlers)), () => {
		set(handle_mouse_down, get$1(drag_handlers)?.handle_mouse_down || (() => {}));
	});

	legacy_pre_effect(() => (get$1(drag_handlers)), () => {
		set(handle_mouse_move, get$1(drag_handlers)?.handle_mouse_move || (() => {}));
	});

	legacy_pre_effect(() => (get$1(drag_handlers)), () => {
		set(handle_mouse_up, get$1(drag_handlers)?.handle_mouse_up || (() => {}));
	});

	legacy_pre_effect_reset();

	var $$exports = {
		reset_sort_state,
		get datatype() {
			return datatype();
		},

		set datatype($$value) {
			datatype($$value);
			flushSync();
		},

		get label() {
			return label();
		},

		set label($$value) {
			label($$value);
			flushSync();
		},

		get show_label() {
			return show_label();
		},

		set show_label($$value) {
			show_label($$value);
			flushSync();
		},

		get headers() {
			return headers();
		},

		set headers($$value) {
			headers($$value);
			flushSync();
		},

		get values() {
			return values();
		},

		set values($$value) {
			values($$value);
			flushSync();
		},

		get col_count() {
			return col_count();
		},

		set col_count($$value) {
			col_count($$value);
			flushSync();
		},

		get row_count() {
			return row_count();
		},

		set row_count($$value) {
			row_count($$value);
			flushSync();
		},

		get latex_delimiters() {
			return latex_delimiters();
		},

		set latex_delimiters($$value) {
			latex_delimiters($$value);
			flushSync();
		},

		get components() {
			return components();
		},

		set components($$value) {
			components($$value);
			flushSync();
		},

		get editable() {
			return editable();
		},

		set editable($$value) {
			editable($$value);
			flushSync();
		},

		get wrap() {
			return wrap();
		},

		set wrap($$value) {
			wrap($$value);
			flushSync();
		},

		get root() {
			return root();
		},

		set root($$value) {
			root($$value);
			flushSync();
		},

		get i18n() {
			return i18n();
		},

		set i18n($$value) {
			i18n($$value);
			flushSync();
		},

		get max_height() {
			return max_height();
		},

		set max_height($$value) {
			max_height($$value);
			flushSync();
		},

		get line_breaks() {
			return line_breaks();
		},

		set line_breaks($$value) {
			line_breaks($$value);
			flushSync();
		},

		get column_widths() {
			return column_widths();
		},

		set column_widths($$value) {
			column_widths($$value);
			flushSync();
		},

		get show_row_numbers() {
			return show_row_numbers();
		},

		set show_row_numbers($$value) {
			show_row_numbers($$value);
			flushSync();
		},

		get upload() {
			return upload();
		},

		set upload($$value) {
			upload($$value);
			flushSync();
		},

		get stream_handler() {
			return stream_handler();
		},

		set stream_handler($$value) {
			stream_handler($$value);
			flushSync();
		},

		get buttons() {
			return buttons();
		},

		set buttons($$value) {
			buttons($$value);
			flushSync();
		},

		get value_is_output() {
			return value_is_output();
		},

		set value_is_output($$value) {
			value_is_output($$value);
			flushSync();
		},

		get max_chars() {
			return max_chars();
		},

		set max_chars($$value) {
			max_chars($$value);
			flushSync();
		},

		get show_search() {
			return show_search();
		},

		set show_search($$value) {
			show_search($$value);
			flushSync();
		},

		get pinned_columns() {
			return pinned_columns();
		},

		set pinned_columns($$value) {
			pinned_columns($$value);
			flushSync();
		},

		get static_columns() {
			return static_columns();
		},

		set static_columns($$value) {
			static_columns($$value);
			flushSync();
		},

		get fullscreen() {
			return fullscreen();
		},

		set fullscreen($$value) {
			fullscreen($$value);
			flushSync();
		},

		get display_value() {
			return display_value();
		},

		set display_value($$value) {
			display_value($$value);
			flushSync();
		},

		get styling() {
			return styling();
		},

		set styling($$value) {
			styling($$value);
			flushSync();
		}
	};

	init$1();

	var fragment = root_1();

	event('resize', $window, () => set_cell_widths());

	var div = first_child(fragment);
	var node = child(div);

	{
		var consequent_1 = ($$anchor) => {
			var div_1 = root_2();
			var node_1 = child(div_1);

			{
				var consequent = ($$anchor) => {
					var div_2 = root_3();
					var p = child(div_2);
					var text = child(p, true);

					reset(p);
					reset(div_2);
					template_effect(() => set_text(text, label()));
					append$1($$anchor, div_2);
				};

				if_block(node_1, ($$render) => {
					if ((
						deep_read_state(label()),
						deep_read_state(show_label()),
						untrack(() => label() && label().length !== 0 && show_label())
					)) $$render(consequent);
				});
			}

			var node_2 = sibling(node_1, 2);

			{
				let $0 = derived_safe_equal(() => (
					deep_read_state(buttons()),
					untrack(() => buttons() === null ? true : buttons().includes("fullscreen"))
				));

				let $1 = derived_safe_equal(() => (
					deep_read_state(buttons()),
					untrack(() => buttons() === null ? true : buttons().includes("copy"))
				));

				Toolbar(node_2, {
					get show_fullscreen_button() {
						return get$1($0);
					},

					get fullscreen() {
						return fullscreen();
					},
					on_copy: async () => await copy_table_data(get$1(data), null),
					get show_copy_button() {
						return get$1($1);
					},

					get show_search() {
						return show_search();
					},
					on_commit_filter: commit_filter,
					get current_search_query() {
						return (
							$df_state(),
							untrack(() => $df_state().current_search_query)
						);
					},

					$$events: {
						search: (e) => df_actions.handle_search(e.detail),
						fullscreen($$arg) {
							bubble_event.call(this, $$props, $$arg);
						}
					}
				});
			}

			reset(div_1);
			append$1($$anchor, div_1);
		};

		if_block(node, ($$render) => {
			if ((
				deep_read_state(label()),
				deep_read_state(show_label()),
				deep_read_state(buttons()),
				deep_read_state(show_search()),
				untrack(() => label() && label().length !== 0 && show_label() || (buttons() === null ? true : buttons().includes("fullscreen")) || (buttons() === null ? true : buttons().includes("copy")) || show_search() !== "none")
			)) $$render(consequent_1);
		});
	}

	var div_3 = sibling(node, 2);
	let classes;
	var table_1 = child(div_3);
	var node_3 = child(table_1);

	{
		var consequent_2 = ($$anchor) => {
			var caption = root_4();
			var text_1 = child(caption, true);

			reset(caption);
			template_effect(() => set_text(text_1, label()));
			append$1($$anchor, caption);
		};

		if_block(node_3, ($$render) => {
			if ((
				deep_read_state(label()),
				untrack(() => label() && label().length !== 0)
			)) $$render(consequent_2);
		});
	}

	var thead = sibling(node_3);
	var tr = child(thead);
	var node_4 = child(tr);

	{
		var consequent_3 = ($$anchor) => {
			RowNumber($$anchor, { is_header: true });
		};

		if_block(node_4, ($$render) => {
			if (show_row_numbers()) $$render(consequent_3);
		});
	}

	var node_5 = sibling(node_4);

	each(node_5, 3, () => get$1(_headers), ({ value, id }) => id, ($$anchor, $$item, i) => {
		let id = () => get$1($$item).id;

		{
			let $0 = derived_safe_equal(() => (
				deep_read_state(static_columns()),
				deep_read_state(get$1(i)),
				untrack(() => static_columns().includes(get$1(i)))
			));

			let $1 = derived_safe_equal(() => (
				deep_read_state(datatype()),
				deep_read_state(get$1(i)),
				untrack(() => Array.isArray(datatype()) ? datatype()[get$1(i)] : datatype())
			));

			TableHeader($$anchor, {
				get i() {
					return get$1(i);
				},

				get actual_pinned_columns() {
					return get$1(actual_pinned_columns);
				},

				get header_edit() {
					return get$1(header_edit);
				},

				get selected_header() {
					return get$1(selected_header);
				},

				get headers() {
					return headers();
				},
				get_cell_width,
				handle_header_click,
				toggle_header_menu,
				end_header_edit,
				get sort_columns() {
					return (
						$df_state(),
						untrack(() => $df_state().sort_state.sort_columns)
					);
				},

				get filter_columns() {
					return (
						$df_state(),
						untrack(() => $df_state().filter_state.filter_columns)
					);
				},

				get latex_delimiters() {
					return latex_delimiters();
				},

				get line_breaks() {
					return line_breaks();
				},

				get max_chars() {
					return max_chars();
				},

				get editable() {
					return editable();
				},

				get is_static() {
					return get$1($0);
				},

				get i18n() {
					return i18n();
				},

				get col_count() {
					return col_count();
				},

				get datatype() {
					return get$1($1);
				},

				get data() {
					return get$1(data);
				},
				on_select_all: handle_select_all,
				get value() {
					return get$1(_headers)[get$1(i)].value;
				},

				set value($$value) {
					mutate(_headers, get$1(_headers)[get$1(i)].value = $$value);
				},

				get el() {
					return get$1(els)[id()].input;
				},

				set el($$value) {
					mutate(els, get$1(els)[id()].input = $$value);
				},
				$$legacy: true
			});
		}
	});

	reset(tr);
	reset(thead);

	var tbody = sibling(thead);
	var tr_1 = child(tbody);
	var node_6 = child(tr_1);

	{
		var consequent_4 = ($$anchor) => {
			RowNumber($$anchor, { index: 0 });
		};

		if_block(node_6, ($$render) => {
			if (show_row_numbers()) $$render(consequent_4);
		});
	}

	var node_7 = sibling(node_6);

	each(node_7, 3, () => get$1(max), ({ value, id }) => id, ($$anchor, $$item, j) => {
		let value = () => get$1($$item).value;
		var td = root_8();
		var div_4 = child(td);
		var node_8 = child(div_4);

		{
			let $0 = derived_safe_equal(() => (
				deep_read_state(datatype()),
				deep_read_state(get$1(j)),
				untrack(() => Array.isArray(datatype()) ? datatype()[get$1(j)] : datatype())
			));

			let $1 = derived_safe_equal(() => (
				get$1(selected_cells),
				deep_read_state(get$1(j)),
				untrack(() => get$1(selected_cells).length === 1 && get$1(selected_cells)[0][0] === 0 && get$1(selected_cells)[0][1] === get$1(j))
			));

			EditableCell(node_8, {
				get value() {
					return value();
				},

				get latex_delimiters() {
					return latex_delimiters();
				},

				get line_breaks() {
					return line_breaks();
				},

				get datatype() {
					return get$1($0);
				},
				edit: false,
				el: null,
				get editable() {
					return editable();
				},

				get i18n() {
					return i18n();
				},

				get show_selection_buttons() {
					return get$1($1);
				},

				get coords() {
					return get$1(selected_cell_coords);
				},

				get on_select_column() {
					return (untrack(() => df_actions.handle_select_column));
				},

				get on_select_row() {
					return (untrack(() => df_actions.handle_select_row));
				},

				get is_dragging() {
					return get$1(is_dragging);
				},
				$$events: { blur: handle_blur }
			});
		}

		reset(div_4);
		reset(td);
		bind_this(td, ($$value, j) => mutate(cells, get$1(cells)[j] = $$value), (j) => get$1(cells)?.[j], () => [get$1(j)]);
		append$1($$anchor, td);
	});

	reset(tr_1);
	reset(tbody);
	reset(table_1);
	bind_this(table_1, ($$value) => set(table, $$value), () => get$1(table));

	var node_9 = sibling(table_1, 2);

	{
		let $0 = derived_safe_equal(() => (
			deep_read_state(i18n()),
			untrack(() => i18n()("dataframe.drop_to_upload"))
		));

		Upload(node_9, {
			get upload() {
				return upload();
			},

			get stream_handler() {
				return stream_handler();
			},
			flex: false,
			center: false,
			boundedheight: false,
			disable_click: true,
			get root() {
				return root();
			},

			get aria_label() {
				return get$1($0);
			},

			get dragging() {
				return get$1(dragging);
			},

			set dragging($$value) {
				set(dragging, $$value);
			},

			$$events: {
				load: ({ detail }) => handle_file_upload(
					detail.data,
					(head) => {
						set(_headers, make_headers(head.map((h) => h ?? ""), col_count(), get$1(els), make_id));

						return get$1(_headers);
					},
					(vals) => {
						values(vals);
					}
				)
			},

			children: ($$anchor, $$slotProps) => {
				var div_5 = root_9();
				var node_10 = child(div_5);

				{
					let $0 = derived_safe_equal(() => get$1(active_cell_menu) !== null || get$1(active_header_menu) !== null);

					VirtualTable(node_10, {
						get max_height() {
							return max_height();
						},

						get selected() {
							return get$1(selected_index);
						},

						get disable_scroll() {
							return get$1($0);
						},

						get label() {
							return label();
						},

						get items() {
							return get$1(search_results);
						},

						set items($$value) {
							set(search_results, $$value);
						},

						get actual_height() {
							return get$1(table_height);
						},

						set actual_height($$value) {
							set(table_height, $$value);
						},

						get table_scrollbar_width() {
							return get$1(scrollbar_width);
						},

						set table_scrollbar_width($$value) {
							set(scrollbar_width, $$value);
						},

						get viewport() {
							return get$1(viewport);
						},

						set viewport($$value) {
							set(viewport, $$value);
						},

						get show_scroll_button() {
							return get$1(show_scroll_button);
						},

						set show_scroll_button($$value) {
							set(show_scroll_button, $$value);
						},
						$$events: { scroll_top: (_) => {} },
						$$slots: {
							thead: ($$anchor, $$slotProps) => {
								var tr_2 = root_10();
								var node_11 = child(tr_2);

								{
									var consequent_5 = ($$anchor) => {
										RowNumber($$anchor, { is_header: true });
									};

									if_block(node_11, ($$render) => {
										if (show_row_numbers()) $$render(consequent_5);
									});
								}

								var node_12 = sibling(node_11);

								each(node_12, 3, () => get$1(_headers), ({ value, id }) => id, ($$anchor, $$item, i) => {
									let id = () => get$1($$item).id;

									{
										let $0 = derived_safe_equal(() => (
											deep_read_state(static_columns()),
											deep_read_state(get$1(i)),
											untrack(() => static_columns().includes(get$1(i)))
										));

										let $1 = derived_safe_equal(() => (
											deep_read_state(datatype()),
											deep_read_state(get$1(i)),
											untrack(() => Array.isArray(datatype()) ? datatype()[get$1(i)] : datatype())
										));

										TableHeader($$anchor, {
											get i() {
												return get$1(i);
											},

											get actual_pinned_columns() {
												return get$1(actual_pinned_columns);
											},

											get header_edit() {
												return get$1(header_edit);
											},

											get selected_header() {
												return get$1(selected_header);
											},

											get headers() {
												return headers();
											},
											get_cell_width,
											handle_header_click,
											toggle_header_menu,
											end_header_edit,
											get sort_columns() {
												return (
													$df_state(),
													untrack(() => $df_state().sort_state.sort_columns)
												);
											},

											get filter_columns() {
												return (
													$df_state(),
													untrack(() => $df_state().filter_state.filter_columns)
												);
											},

											get latex_delimiters() {
												return latex_delimiters();
											},

											get line_breaks() {
												return line_breaks();
											},

											get max_chars() {
												return max_chars();
											},

											get editable() {
												return editable();
											},

											get is_static() {
												return get$1($0);
											},

											get i18n() {
												return i18n();
											},

											get col_count() {
												return col_count();
											},

											get datatype() {
												return get$1($1);
											},

											get data() {
												return get$1(data);
											},
											on_select_all: handle_select_all,
											get value() {
												return get$1(_headers)[get$1(i)].value;
											},

											set value($$value) {
												mutate(_headers, get$1(_headers)[get$1(i)].value = $$value);
											},

											get el() {
												return get$1(els)[id()].input;
											},

											set el($$value) {
												mutate(els, get$1(els)[id()].input = $$value);
											},
											$$legacy: true
										});
									}
								});

								reset(tr_2);
								append$1($$anchor, tr_2);
							},

							tbody: ($$anchor, $$slotProps) => {
								var tr_3 = root_13();
								const item = derived_safe_equal(() => $$slotProps.item);
								const index = derived_safe_equal(() => $$slotProps.index);
								let classes_1;
								var node_13 = child(tr_3);

								{
									var consequent_6 = ($$anchor) => {
										RowNumber($$anchor, {
											get index() {
												return get$1(index);
											}
										});
									};

									if_block(node_13, ($$render) => {
										if (show_row_numbers()) $$render(consequent_6);
									});
								}

								var node_14 = sibling(node_13);

								each(node_14, 3, () => get$1(item), ({ value, id }) => id, ($$anchor, $$item, j) => {
									let id = () => get$1($$item).id;

									{
										let $0 = derived_safe_equal(() => (
											deep_read_state(get$1(index)),
											deep_read_state(get$1(j)),
											untrack(() => get_cell_display_value(get$1(index), get$1(j)))
										));

										let $1 = derived_safe_equal(() => (
											$df_state(),
											get$1(filtered_to_original_map),
											deep_read_state(get$1(index)),
											untrack(() => $df_state().current_search_query !== undefined && get$1(filtered_to_original_map)[get$1(index)] !== undefined
												? get$1(filtered_to_original_map)[get$1(index)]
												: get$1(index))
										));

										let $2 = derived_safe_equal(() => (
											deep_read_state(datatype()),
											deep_read_state(get$1(j)),
											untrack(() => Array.isArray(datatype()) ? datatype()[get$1(j)] : datatype())
										));

										let $3 = derived_safe_equal(() => (
											deep_read_state(static_columns()),
											deep_read_state(get$1(j)),
											untrack(() => static_columns().includes(get$1(j)))
										));

										TableCell($$anchor, {
											get display_value() {
												return get$1($0);
											},

											get index() {
												return get$1($1);
											},

											get j() {
												return get$1(j);
											},

											get actual_pinned_columns() {
												return get$1(actual_pinned_columns);
											},
											get_cell_width,
											handle_cell_click: (e, r, c) => get$1(handle_mouse_down)(e, r, c),
											handle_blur,
											get toggle_cell_menu() {
												return (untrack(() => df_actions.toggle_cell_menu));
											},

											get is_cell_selected() {
												return is_cell_selected;
											},

											get should_show_cell_menu() {
												return should_show_cell_menu;
											},

											get selected_cells() {
												return get$1(selected_cells);
											},

											get copy_flash() {
												return get$1(copy_flash);
											},

											get active_cell_menu() {
												return get$1(active_cell_menu);
											},

											get styling() {
												return (
													get$1(search_results),
													deep_read_state(get$1(index)),
													deep_read_state(get$1(j)),
													untrack(() => get$1(search_results)[get$1(index)][get$1(j)].styling)
												);
											},

											get latex_delimiters() {
												return latex_delimiters();
											},

											get line_breaks() {
												return line_breaks();
											},

											get datatype() {
												return get$1($2);
											},

											get editing() {
												return get$1(editing);
											},

											get max_chars() {
												return max_chars();
											},

											get editable() {
												return editable();
											},

											get is_static() {
												return get$1($3);
											},

											get i18n() {
												return i18n();
											},

											get components() {
												return components();
											},

											get handle_select_column() {
												return (untrack(() => df_actions.handle_select_column));
											},

											get handle_select_row() {
												return (untrack(() => df_actions.handle_select_row));
											},

											get is_dragging() {
												return get$1(is_dragging);
											},

											get wrap() {
												return wrap();
											},

											get value() {
												return get$1(search_results)[get$1(index)][get$1(j)].value;
											},

											set value($$value) {
												mutate(search_results, get$1(search_results)[get$1(index)][get$1(j)].value = $$value);
											},

											get el() {
												return get$1(els)[id()];
											},

											set el($$value) {
												mutate(els, get$1(els)[id()] = $$value);
											},
											$$legacy: true
										});
									}
								});

								reset(tr_3);
								template_effect(() => classes_1 = set_class(tr_3, 1, 'svelte-2balj6', null, classes_1, { 'row-odd': get$1(index) % 2 === 0 }));
								append$1($$anchor, tr_3);
							}
						},
						$$legacy: true
					});
				}

				reset(div_5);
				append$1($$anchor, div_5);
			},
			$$slots: { default: true },
			$$legacy: true
		});
	}

	var node_15 = sibling(node_9, 2);

	{
		var consequent_7 = ($$anchor) => {
			var button = root_16();

			event('click', button, scroll_to_top);
			append$1($$anchor, button);
		};

		if_block(node_15, ($$render) => {
			if (get$1(show_scroll_button)) $$render(consequent_7);
		});
	}

	reset(div_3);
	bind_this(div_3, ($$value) => set(parent, $$value), () => get$1(parent));
	reset(div);

	var node_16 = sibling(div, 2);

	{
		var consequent_8 = ($$anchor) => {
			EmptyRowButton($$anchor, { on_click: () => add_row() });
		};

		if_block(node_16, ($$render) => {
			if ((
				get$1(data),
				deep_read_state(editable()),
				deep_read_state(row_count()),
				untrack(() => get$1(data).length === 0 && editable() && row_count()[1] === "dynamic")
			)) $$render(consequent_8);
		});
	}

	var node_17 = sibling(node_16, 2);

	{
		var consequent_9 = ($$anchor) => {
			{
				let $0 = derived_safe_equal(() => (
					get$1(active_cell_menu),
					get$1(active_header_menu),
					untrack(() => get$1(active_cell_menu)?.x ?? get$1(active_header_menu)?.x ?? 0)
				));

				let $1 = derived_safe_equal(() => (
					get$1(active_cell_menu),
					get$1(active_header_menu),
					untrack(() => get$1(active_cell_menu)?.y ?? get$1(active_header_menu)?.y ?? 0)
				));

				let $2 = derived_safe_equal(() => (
					get$1(active_header_menu),
					get$1(active_cell_menu),
					untrack(() => get$1(active_header_menu) ? -1 : get$1(active_cell_menu)?.row ?? 0)
				));

				let $3 = derived_safe_equal(() => (
					get$1(active_header_menu),
					get$1(data),
					deep_read_state(editable()),
					untrack(() => !get$1(active_header_menu) && get$1(data).length > 1 && editable())
				));

				let $4 = derived_safe_equal(() => (
					get$1(data),
					deep_read_state(editable()),
					untrack(() => get$1(data).length > 0 && get$1(data)[0]?.length > 1 && editable())
				));

				let $5 = derived_safe_equal(() => get$1(active_header_menu)
					? (direction) => {
						if (get$1(active_header_menu)) {
							handle_sort(get$1(active_header_menu).col, direction);
							df_actions.set_active_header_menu(null);
						}
					}
					: undefined);

				let $6 = derived_safe_equal(() => get$1(active_header_menu)
					? () => {
						clear_sort();
						df_actions.set_active_header_menu(null);
					}
					: undefined);

				let $7 = derived_safe_equal(() => (
					get$1(active_header_menu),
					$df_state(),
					untrack(() => get$1(active_header_menu)
						? $df_state().sort_state.sort_columns.find((item) => item.col === (get$1(active_header_menu)?.col ?? -1))?.direction ?? null
						: null)
				));

				let $8 = derived_safe_equal(() => (
					get$1(active_header_menu),
					$df_state(),
					untrack(() => get$1(active_header_menu)
						? $df_state().sort_state.sort_columns.findIndex((item) => item.col === (get$1(active_header_menu)?.col ?? -1)) + 1 || null
						: null)
				));

				let $9 = derived_safe_equal(() => get$1(active_header_menu)
					? (datatype, filter, value) => {
						if (get$1(active_header_menu)) {
							handle_filter(get$1(active_header_menu).col, datatype, filter, value);
							df_actions.set_active_header_menu(null);
						}
					}
					: undefined);

				let $10 = derived_safe_equal(() => get$1(active_header_menu)
					? () => {
						clear_filter();
						df_actions.set_active_header_menu(null);
					}
					: undefined);

				let $11 = derived_safe_equal(() => (
					get$1(active_header_menu),
					$df_state(),
					untrack(() => get$1(active_header_menu)
						? $df_state().filter_state.filter_columns.some((c) => c.col === (get$1(active_header_menu)?.col ?? -1))
						: null)
				));

				CellMenu($$anchor, {
					get x() {
						return get$1($0);
					},

					get y() {
						return get$1($1);
					},

					get row() {
						return get$1($2);
					},

					get col_count() {
						return col_count();
					},

					get row_count() {
						return row_count();
					},
					on_add_row_above: () => add_row_at(get$1(active_cell_menu)?.row ?? -1, "above"),
					on_add_row_below: () => add_row_at(get$1(active_cell_menu)?.row ?? -1, "below"),
					on_add_column_left: () => add_col_at(get$1(active_cell_menu)?.col ?? get$1(active_header_menu)?.col ?? -1, "left"),
					on_add_column_right: () => add_col_at(get$1(active_cell_menu)?.col ?? get$1(active_header_menu)?.col ?? -1, "right"),
					on_delete_row: () => delete_row_at(get$1(active_cell_menu)?.row ?? -1),
					on_delete_col: () => delete_col_at(get$1(active_cell_menu)?.col ?? get$1(active_header_menu)?.col ?? -1),
					get editable() {
						return editable();
					},

					get can_delete_rows() {
						return get$1($3);
					},

					get can_delete_cols() {
						return get$1($4);
					},

					get i18n() {
						return i18n();
					},

					get on_sort() {
						return get$1($5);
					},

					get on_clear_sort() {
						return get$1($6);
					},

					get sort_direction() {
						return get$1($7);
					},

					get sort_priority() {
						return get$1($8);
					},

					get on_filter() {
						return get$1($9);
					},

					get on_clear_filter() {
						return get$1($10);
					},

					get filter_active() {
						return get$1($11);
					}
				});
			}
		};

		if_block(node_17, ($$render) => {
			if (get$1(active_cell_menu) || get$1(active_header_menu)) $$render(consequent_9);
		});
	}

	template_effect(() => classes = set_class(div_3, 1, 'table-wrap svelte-2balj6', null, classes, {
		dragging: get$1(is_dragging),
		'no-wrap': !wrap(),
		'menu-open': get$1(active_cell_menu) || get$1(active_header_menu)
	}));

	event('keydown', div_3, (e) => handle_keydown(e, get$1(df_ctx)));

	event('mousemove', div_3, function (...$$args) {
		get$1(handle_mouse_move)?.apply(this, $$args);
	});

	event('mouseup', div_3, function (...$$args) {
		get$1(handle_mouse_up)?.apply(this, $$args);
	});

	event('mouseleave', div_3, function (...$$args) {
		get$1(handle_mouse_up)?.apply(this, $$args);
	});

	append$1($$anchor, fragment);
	bind_prop($$props, 'reset_sort_state', reset_sort_state);

	var $$pop = pop($$exports);

	$$cleanup();

	return $$pop;
}

var root = from_html(`<div></div>`);

function Index($$anchor, $$props) {
	push($$props, true);

	let prev_data = null;
	let changed = false;

	class DataframeGradio extends Gradio {
		async set_data(data) {
			if (data.value) {
				changed = true;
			}

			super.set_data(data);

			if (data.value && dequal$2(data.value, JSON.parse(prev_data)) === false) {
				// this.dispatch("change");
				prev_data = JSON.stringify(data.value);
			}
		}
	}

	let props = rest_props($$props, ['$$slots', '$$events', '$$legacy']);
	let gradio = new DataframeGradio(props);
	let el;
	let Component = null;

	onMount$1(() => {
		Component = new Index3({
			target: el,
			props: {
				elem_id: gradio.shared.elem_id,
				elem_classes: gradio.shared.elem_classes,
				visible: gradio.shared.visible,
				value: gradio.props.value,
				col_count: gradio.props.col_count,
				row_count: gradio.props.row_count,
				label: gradio.shared.label,
				show_label: gradio.shared.show_label,
				wrap: gradio.props.wrap,
				datatype: gradio.props.datatype,
				scale: gradio.shared.scale,
				min_width: gradio.shared.min_width,
				root: gradio.shared.root,
				line_breaks: gradio.props.line_breaks,
				column_widths: gradio.props.column_widths,
				gradio: compat_gradio,
				latex_delimiters: gradio.props.latex_delimiters,
				max_height: gradio.props.max_height,
				loading_status: gradio.shared.loading_status,
				interactive: gradio.shared.interactive,
				buttons: gradio.props.buttons,
				max_chars: gradio.props.max_chars,
				show_row_numbers: gradio.props.show_row_numbers,
				show_search: gradio.props.show_search,
				pinned_columns: gradio.props.pinned_columns,
				static_columns: gradio.props.static_columns,
				fullscreen: gradio.props.fullscreen,
				show_copy_button: gradio.props.buttons && gradio.props.buttons.includes("copy"),
				show_fullscreen_button: gradio.props.buttons && gradio.props.buttons.includes("fullscreen")
			}
		});
	});

	const compat_gradio = {
		i18n: gradio.i18n,
		client: gradio.shared.client,
		dispatch(name, detail) {
			if (name === "input" && changed) {
				changed = false;

				return;
			}

			gradio.dispatch(name, detail);
		},
		autoscroll: gradio.shared.autoscroll
	};

	user_effect(() => {
		if (Component) {
			Component.$set({
				elem_id: gradio.shared.elem_id,
				elem_classes: gradio.shared.elem_classes,
				visible: gradio.shared.visible,
				value: gradio.props.value,
				col_count: gradio.props.col_count,
				row_count: gradio.props.row_count,
				label: gradio.shared.label,
				show_label: gradio.shared.show_label,
				wrap: gradio.props.wrap,
				datatype: gradio.props.datatype,
				scale: gradio.shared.scale,
				min_width: gradio.shared.min_width,
				root: gradio.shared.root,
				line_breaks: gradio.props.line_breaks,
				column_widths: gradio.props.column_widths,
				gradio: compat_gradio,
				latex_delimiters: gradio.props.latex_delimiters,
				max_height: gradio.props.max_height,
				loading_status: gradio.shared.loading_status,
				interactive: gradio.shared.interactive,
				buttons: gradio.props.buttons,
				max_chars: gradio.props.max_chars,
				show_row_numbers: gradio.props.show_row_numbers,
				show_search: gradio.props.show_search,
				pinned_columns: gradio.props.pinned_columns,
				static_columns: gradio.props.static_columns,
				fullscreen: gradio.props.fullscreen
			});
		}
	});

	var div = root();

	bind_this(div, ($$value) => el = $$value, () => el);
	append$1($$anchor, div);
	pop();
}

const Index$1 = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  BaseDataFrame: Table,
  BaseExample: Example,
  default: Index
}, Symbol.toStringTag, { value: 'Module' }));

export { Index$1 as I, commonjsGlobal as c, getDefaultExportFromCjs as g };
//# sourceMappingURL=Index-BOG-LPoW.js.map
