import {
  $document,
  $window,
  Amount,
  Balance,
  DEFAULT_INTERVAL,
  DatalessRoute,
  DateColumn,
  HAVE_EXCEL,
  INTERVALS,
  InternMap,
  Inventory,
  LineChart,
  Note,
  NumberColumn,
  ParsedHierarchyChart,
  ParsedLineChart,
  Position,
  Posting,
  ReportLoadError,
  Route,
  ScatterPlot,
  Sorter,
  StringColumn,
  Tooltip,
  Transaction,
  UnsortedColumn,
  _,
  account_details,
  account_hierarchy_validator,
  accounts,
  accounts_internal,
  accounts_set,
  ancestors,
  append,
  arc_default,
  area_default,
  array,
  attach,
  auto_reload,
  await_block,
  balance_with_percentage,
  bind_checked,
  bind_element_size,
  bind_files,
  bind_group,
  bind_property,
  bind_select_value,
  bind_this,
  bind_value,
  bisect_default,
  boolean,
  charts_validator,
  child,
  clsx,
  collapse_pattern,
  comment,
  compare_strings,
  constants,
  conversion,
  conversion_currencies,
  createContext,
  css_props,
  currencies,
  currencies_sorted,
  currency_column,
  currency_name,
  date,
  dateFormat,
  day,
  delegate,
  delegated,
  delete_document,
  delete_source_slice,
  derived,
  derived_array,
  domHelpers,
  each,
  err,
  errors,
  event,
  extensions,
  extent,
  false_default,
  fetch_text,
  first_child,
  format,
  format2,
  formatPrefix,
  formatSpecifier,
  formatter_context,
  fragment_from_string,
  from_html,
  from_svg,
  get,
  get2,
  getContext,
  get_account_report,
  get_balance_sheet,
  get_changed,
  get_commodities,
  get_context,
  get_direction,
  get_documents,
  get_el,
  get_errors,
  get_events,
  get_extract,
  get_help,
  get_imports,
  get_income_statement,
  get_interval,
  get_journal_page,
  get_ledger_data,
  get_narration_transaction,
  get_narrations,
  get_options,
  get_payee_accounts,
  get_payee_transaction,
  get_query,
  get_script_tag_value,
  get_source,
  get_source_slice,
  get_statistics,
  get_trial_balance,
  get_url_path,
  group,
  has_changes,
  hash,
  html,
  if_block,
  import_config,
  incognito,
  increment,
  indent,
  index,
  insert_entry,
  intersection,
  interval,
  interval_label,
  invert_gains_losses_colors,
  invert_income_liabilities_equity,
  is_descendant,
  is_descendant_or_equal,
  is_editable,
  is_empty,
  is_loading,
  is_non_empty,
  label,
  leaf,
  least,
  ledgerDataValidator,
  ledger_data,
  ledger_mtime,
  line_default,
  links,
  loading_state,
  local_storage_synced_store,
  locale,
  locale_formatter,
  log_error,
  max,
  min,
  mount,
  move,
  move_document,
  next,
  noop,
  notify,
  notify_err,
  ok,
  onMount,
  page_title,
  parent,
  partition_default,
  pathname,
  payees,
  pop,
  precisionFixed_default,
  precisionPrefix_default,
  precisionRound_default,
  precisions,
  prop,
  props_id,
  proxy,
  push,
  put_add_document,
  put_attach_document,
  put_source,
  put_source_slice,
  put_upload_import_file,
  query_table_validator,
  range,
  read_mtime,
  remove_input_defaults,
  remove_textarea_child,
  replaceNumbers,
  reset,
  router,
  save_entries,
  search_params,
  second,
  set,
  setContext,
  set_attribute,
  set_checked,
  set_class,
  set_custom_element_data,
  set_query_param,
  set_style,
  set_text,
  set_value,
  setup_stores,
  shallow_equal,
  show_accounts_with_zero_balance,
  show_accounts_with_zero_transactions,
  show_charts,
  show_closed_accounts,
  sibling,
  snippet,
  some,
  sort_elements,
  source,
  state,
  stepAfter,
  store_get,
  store_set,
  string,
  sum,
  tag,
  tags,
  template_effect,
  text,
  tickIncrement,
  tickStep,
  ticks,
  timeDay,
  timeFilterDateFormat,
  to_array,
  today_as_string,
  treemap_default,
  tuple,
  unmount,
  untrack,
  update_version,
  uptodate_indicator_grey_lookback_days,
  url_for,
  url_for_account,
  url_for_raw,
  url_for_source,
  user_derived,
  user_effect,
  user_pre_effect,
  utcDay,
  utcFormat,
  utcHour,
  utcMinute,
  utcMonth,
  utcSunday,
  utcTickInterval,
  utcTicks,
  utcYear,
  writable,
  years
} from "./chunk-TVG7KHLA.js";

// node_modules/@ungap/custom-elements/index.js
(function() {
  "use strict";
  var attributesObserver = (function(whenDefined2, MutationObserver2) {
    var attributeChanged = function attributeChanged2(records) {
      for (var i = 0, length = records.length; i < length; i++) dispatch(records[i]);
    };
    var dispatch = function dispatch2(_ref2) {
      var target = _ref2.target, attributeName = _ref2.attributeName, oldValue = _ref2.oldValue;
      target.attributeChangedCallback(attributeName, oldValue, target.getAttribute(attributeName));
    };
    return function(target, is2) {
      var attributeFilter = target.constructor.observedAttributes;
      if (attributeFilter) {
        whenDefined2(is2).then(function() {
          new MutationObserver2(attributeChanged).observe(target, {
            attributes: true,
            attributeOldValue: true,
            attributeFilter
          });
          for (var i = 0, length = attributeFilter.length; i < length; i++) {
            if (target.hasAttribute(attributeFilter[i])) dispatch({
              target,
              attributeName: attributeFilter[i],
              oldValue: null
            });
          }
        });
      }
      return target;
    };
  });
  function _unsupportedIterableToArray(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _arrayLikeToArray(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(o);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  }
  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
    return arr2;
  }
  function _createForOfIteratorHelper(o, allowArrayLike) {
    var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
    if (!it) {
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it) o = it;
        var i = 0;
        var F = function() {
        };
        return {
          s: F,
          n: function() {
            if (i >= o.length) return {
              done: true
            };
            return {
              done: false,
              value: o[i++]
            };
          },
          e: function(e) {
            throw e;
          },
          f: F
        };
      }
      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    var normalCompletion = true, didErr = false, err2;
    return {
      s: function() {
        it = it.call(o);
      },
      n: function() {
        var step = it.next();
        normalCompletion = step.done;
        return step;
      },
      e: function(e) {
        didErr = true;
        err2 = e;
      },
      f: function() {
        try {
          if (!normalCompletion && it.return != null) it.return();
        } finally {
          if (didErr) throw err2;
        }
      }
    };
  }
  var TRUE = true, FALSE = false, QSA$1 = "querySelectorAll";
  var notify2 = function notify3(callback) {
    var root93 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : document;
    var MO = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : MutationObserver;
    var query3 = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ["*"];
    var loop = function loop2(nodes, selectors, added, removed, connected, pass) {
      var _iterator = _createForOfIteratorHelper(nodes), _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done; ) {
          var node = _step.value;
          if (pass || QSA$1 in node) {
            if (connected) {
              if (!added.has(node)) {
                added.add(node);
                removed["delete"](node);
                callback(node, connected);
              }
            } else if (!removed.has(node)) {
              removed.add(node);
              added["delete"](node);
              callback(node, connected);
            }
            if (!pass) loop2(node[QSA$1](selectors), selectors, added, removed, connected, TRUE);
          }
        }
      } catch (err2) {
        _iterator.e(err2);
      } finally {
        _iterator.f();
      }
    };
    var mo = new MO(function(records) {
      if (query3.length) {
        var selectors = query3.join(",");
        var added = /* @__PURE__ */ new Set(), removed = /* @__PURE__ */ new Set();
        var _iterator2 = _createForOfIteratorHelper(records), _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done; ) {
            var _step2$value = _step2.value, addedNodes = _step2$value.addedNodes, removedNodes = _step2$value.removedNodes;
            loop(removedNodes, selectors, added, removed, FALSE, FALSE);
            loop(addedNodes, selectors, added, removed, TRUE, FALSE);
          }
        } catch (err2) {
          _iterator2.e(err2);
        } finally {
          _iterator2.f();
        }
      }
    });
    var observe = mo.observe;
    (mo.observe = function(node) {
      return observe.call(mo, node, {
        subtree: TRUE,
        childList: TRUE
      });
    })(root93);
    return mo;
  };
  var QSA = "querySelectorAll";
  var _self$1 = self, document$2 = _self$1.document, Element$1 = _self$1.Element, MutationObserver$2 = _self$1.MutationObserver, Set$2 = _self$1.Set, WeakMap$1 = _self$1.WeakMap;
  var elements = function elements2(element) {
    return QSA in element;
  };
  var filter2 = [].filter;
  var qsaObserver = (function(options3) {
    var live = new WeakMap$1();
    var drop = function drop2(elements2) {
      for (var i = 0, length = elements2.length; i < length; i++) live["delete"](elements2[i]);
    };
    var flush = function flush2() {
      var records = observer.takeRecords();
      for (var i = 0, length = records.length; i < length; i++) {
        parse2(filter2.call(records[i].removedNodes, elements), false);
        parse2(filter2.call(records[i].addedNodes, elements), true);
      }
    };
    var matches = function matches2(element) {
      return element.matches || element.webkitMatchesSelector || element.msMatchesSelector;
    };
    var notifier = function notifier2(element, connected) {
      var selectors;
      if (connected) {
        for (var q, m = matches(element), i = 0, length = query3.length; i < length; i++) {
          if (m.call(element, q = query3[i])) {
            if (!live.has(element)) live.set(element, new Set$2());
            selectors = live.get(element);
            if (!selectors.has(q)) {
              selectors.add(q);
              options3.handle(element, connected, q);
            }
          }
        }
      } else if (live.has(element)) {
        selectors = live.get(element);
        live["delete"](element);
        selectors.forEach(function(q2) {
          options3.handle(element, connected, q2);
        });
      }
    };
    var parse2 = function parse3(elements2) {
      var connected = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
      for (var i = 0, length = elements2.length; i < length; i++) notifier(elements2[i], connected);
    };
    var query3 = options3.query;
    var root93 = options3.root || document$2;
    var observer = notify2(notifier, root93, MutationObserver$2, query3);
    var attachShadow2 = Element$1.prototype.attachShadow;
    if (attachShadow2) Element$1.prototype.attachShadow = function(init2) {
      var shadowRoot = attachShadow2.call(this, init2);
      observer.observe(shadowRoot);
      return shadowRoot;
    };
    if (query3.length) parse2(root93[QSA](query3));
    return {
      drop,
      flush,
      observer,
      parse: parse2
    };
  });
  var _self = self, document$1 = _self.document, Map2 = _self.Map, MutationObserver$1 = _self.MutationObserver, Object$1 = _self.Object, Set$1 = _self.Set, WeakMap = _self.WeakMap, Element2 = _self.Element, HTMLElement2 = _self.HTMLElement, Node = _self.Node, Error2 = _self.Error, TypeError$1 = _self.TypeError, Reflect = _self.Reflect;
  var defineProperty = Object$1.defineProperty, keys = Object$1.keys, getOwnPropertyNames = Object$1.getOwnPropertyNames, setPrototypeOf = Object$1.setPrototypeOf;
  var legacy = !self.customElements;
  var expando = function expando2(element) {
    var key2 = keys(element);
    var value = [];
    var ignore = new Set$1();
    var length = key2.length;
    for (var i = 0; i < length; i++) {
      value[i] = element[key2[i]];
      try {
        delete element[key2[i]];
      } catch (SafariTP) {
        ignore.add(i);
      }
    }
    return function() {
      for (var _i = 0; _i < length; _i++) ignore.has(_i) || (element[key2[_i]] = value[_i]);
    };
  };
  if (legacy) {
    var HTMLBuiltIn = function HTMLBuiltIn2() {
      var constructor = this.constructor;
      if (!classes.has(constructor)) throw new TypeError$1("Illegal constructor");
      var is2 = classes.get(constructor);
      if (override) return augment(override, is2);
      var element = createElement.call(document$1, is2);
      return augment(setPrototypeOf(element, constructor.prototype), is2);
    };
    var createElement = document$1.createElement;
    var classes = new Map2();
    var defined = new Map2();
    var prototypes = new Map2();
    var registry = new Map2();
    var query2 = [];
    var handle = function handle2(element, connected, selector) {
      var proto = prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element)) {
        var redefine = expando(element);
        override = setPrototypeOf(element, proto);
        try {
          new proto.constructor();
        } finally {
          override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto) element[method]();
    };
    var _qsaObserver = qsaObserver({
      query: query2,
      handle
    }), parse = _qsaObserver.parse;
    var override = null;
    var whenDefined = function whenDefined2(name) {
      if (!defined.has(name)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        defined.set(name, {
          $,
          _: _2
        });
      }
      return defined.get(name).$;
    };
    var augment = attributesObserver(whenDefined, MutationObserver$1);
    self.customElements = {
      define: function define2(is2, Class) {
        if (registry.has(is2)) throw new Error2('the name "'.concat(is2, '" has already been used with this registry'));
        classes.set(Class, is2);
        prototypes.set(is2, Class.prototype);
        registry.set(is2, Class);
        query2.push(is2);
        whenDefined(is2).then(function() {
          parse(document$1.querySelectorAll(is2));
        });
        defined.get(is2)._(Class);
      },
      get: function get4(is2) {
        return registry.get(is2);
      },
      whenDefined
    };
    defineProperty(HTMLBuiltIn.prototype = HTMLElement2.prototype, "constructor", {
      value: HTMLBuiltIn
    });
    self.HTMLElement = HTMLBuiltIn;
    document$1.createElement = function(name, options3) {
      var is2 = options3 && options3.is;
      var Class = is2 ? registry.get(is2) : registry.get(name);
      return Class ? new Class() : createElement.call(document$1, name);
    };
    if (!("isConnected" in Node.prototype)) defineProperty(Node.prototype, "isConnected", {
      configurable: true,
      get: function get4() {
        return !(this.ownerDocument.compareDocumentPosition(this) & this.DOCUMENT_POSITION_DISCONNECTED);
      }
    });
  } else {
    legacy = !self.customElements.get("extends-br");
    if (legacy) {
      try {
        var BR = function BR2() {
          return self.Reflect.construct(HTMLBRElement, [], BR2);
        };
        BR.prototype = HTMLLIElement.prototype;
        var is = "extends-br";
        self.customElements.define("extends-br", BR, {
          "extends": "br"
        });
        legacy = document$1.createElement("br", {
          is
        }).outerHTML.indexOf(is) < 0;
        var _self$customElements = self.customElements, get3 = _self$customElements.get, _whenDefined = _self$customElements.whenDefined;
        self.customElements.whenDefined = function(is2) {
          var _this = this;
          return _whenDefined.call(this, is2).then(function(Class) {
            return Class || get3.call(_this, is2);
          });
        };
      } catch (o_O) {
      }
    }
  }
  if (legacy) {
    var _parseShadow = function _parseShadow2(element) {
      var root93 = shadowRoots.get(element);
      _parse(root93.querySelectorAll(this), element.isConnected);
    };
    var customElements2 = self.customElements;
    var _createElement = document$1.createElement;
    var define = customElements2.define, _get = customElements2.get, upgrade = customElements2.upgrade;
    var _ref = Reflect || {
      construct: function construct2(HTMLElement3) {
        return HTMLElement3.call(this);
      }
    }, construct = _ref.construct;
    var shadowRoots = new WeakMap();
    var shadows = new Set$1();
    var _classes = new Map2();
    var _defined = new Map2();
    var _prototypes = new Map2();
    var _registry = new Map2();
    var shadowed = [];
    var _query = [];
    var getCE = function getCE2(is2) {
      return _registry.get(is2) || _get.call(customElements2, is2);
    };
    var _handle = function _handle2(element, connected, selector) {
      var proto = _prototypes.get(selector);
      if (connected && !proto.isPrototypeOf(element)) {
        var redefine = expando(element);
        _override = setPrototypeOf(element, proto);
        try {
          new proto.constructor();
        } finally {
          _override = null;
          redefine();
        }
      }
      var method = "".concat(connected ? "" : "dis", "connectedCallback");
      if (method in proto) element[method]();
    };
    var _qsaObserver2 = qsaObserver({
      query: _query,
      handle: _handle
    }), _parse = _qsaObserver2.parse;
    var _qsaObserver3 = qsaObserver({
      query: shadowed,
      handle: function handle2(element, connected) {
        if (shadowRoots.has(element)) {
          if (connected) shadows.add(element);
          else shadows["delete"](element);
          if (_query.length) _parseShadow.call(_query, element);
        }
      }
    }), parseShadowed = _qsaObserver3.parse;
    var attachShadow = Element2.prototype.attachShadow;
    if (attachShadow) Element2.prototype.attachShadow = function(init2) {
      var root93 = attachShadow.call(this, init2);
      shadowRoots.set(this, root93);
      return root93;
    };
    var _whenDefined2 = function _whenDefined22(name) {
      if (!_defined.has(name)) {
        var _2, $ = new Promise(function($2) {
          _2 = $2;
        });
        _defined.set(name, {
          $,
          _: _2
        });
      }
      return _defined.get(name).$;
    };
    var _augment = attributesObserver(_whenDefined2, MutationObserver$1);
    var _override = null;
    getOwnPropertyNames(self).filter(function(k) {
      return /^HTML.*Element$/.test(k);
    }).forEach(function(k) {
      var HTMLElement3 = self[k];
      function HTMLBuiltIn2() {
        var constructor = this.constructor;
        if (!_classes.has(constructor)) throw new TypeError$1("Illegal constructor");
        var _classes$get = _classes.get(constructor), is2 = _classes$get.is, tag2 = _classes$get.tag;
        if (is2) {
          if (_override) return _augment(_override, is2);
          var element = _createElement.call(document$1, tag2);
          element.setAttribute("is", is2);
          return _augment(setPrototypeOf(element, constructor.prototype), is2);
        } else return construct.call(this, HTMLElement3, [], constructor);
      }
      defineProperty(HTMLBuiltIn2.prototype = HTMLElement3.prototype, "constructor", {
        value: HTMLBuiltIn2
      });
      defineProperty(self, k, {
        value: HTMLBuiltIn2
      });
    });
    document$1.createElement = function(name, options3) {
      var is2 = options3 && options3.is;
      if (is2) {
        var Class = _registry.get(is2);
        if (Class && _classes.get(Class).tag === name) return new Class();
      }
      var element = _createElement.call(document$1, name);
      if (is2) element.setAttribute("is", is2);
      return element;
    };
    customElements2.get = getCE;
    customElements2.whenDefined = _whenDefined2;
    customElements2.upgrade = function(element) {
      var is2 = element.getAttribute("is");
      if (is2) {
        var _constructor = _registry.get(is2);
        if (_constructor) {
          _augment(setPrototypeOf(element, _constructor.prototype), is2);
          return;
        }
      }
      upgrade.call(customElements2, element);
    };
    customElements2.define = function(is2, Class, options3) {
      if (getCE(is2)) throw new Error2("'".concat(is2, "' has already been defined as a custom element"));
      var selector;
      var tag2 = options3 && options3["extends"];
      _classes.set(Class, tag2 ? {
        is: is2,
        tag: tag2
      } : {
        is: "",
        tag: is2
      });
      if (tag2) {
        selector = "".concat(tag2, '[is="').concat(is2, '"]');
        _prototypes.set(selector, Class.prototype);
        _registry.set(is2, Class);
        _query.push(selector);
      } else {
        define.apply(customElements2, arguments);
        shadowed.push(selector = is2);
      }
      _whenDefined2(is2).then(function() {
        if (tag2) {
          _parse(document$1.querySelectorAll(selector));
          shadows.forEach(_parseShadow, [selector]);
        } else parseShadowed(document$1.querySelectorAll(selector));
      });
      _defined.get(is2)._(Class);
    };
  }
})();

// src/clipboard.ts
var CopyableText = class extends HTMLElement {
  constructor() {
    super();
    this.addEventListener("click", (event2) => {
      const text2 = this.getAttribute("data-clipboard-text");
      if (text2 != null) {
        navigator.clipboard.writeText(text2).catch(log_error);
      }
      event2.stopPropagation();
    });
  }
};

// src/codemirror/dom.ts
var BeancountTextarea = class extends HTMLTextAreaElement {
  constructor() {
    super();
    import("./beancount-OG2DLLWG.js").then(({ init_textarea }) => {
      init_textarea(this);
    }).catch(log_error);
  }
};
function attach_editor(editor2) {
  return (el) => {
    el.appendChild(editor2.dom);
    return () => {
      el.removeChild(editor2.dom);
    };
  };
}

// src/keyboard-shortcuts.ts
function is_editable_element(element) {
  return element instanceof HTMLElement && (element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement || element.isContentEditable);
}
var keyboardShortcuts = /* @__PURE__ */ new Map();
var lastChar = "";
function normalise_key(event2) {
  let key2 = event2.key;
  if (event2.metaKey) {
    key2 = `Meta+${key2}`;
  }
  if (event2.altKey) {
    key2 = `Alt+${key2}`;
  }
  if (event2.ctrlKey) {
    key2 = `Control+${key2}`;
  }
  return key2;
}
function keydown(event2) {
  if (is_editable_element(event2.target)) {
    return;
  }
  const eventKey = normalise_key(event2);
  const lastTwoKeys = `${lastChar} ${eventKey}`;
  const handler = keyboardShortcuts.get(lastTwoKeys) ?? keyboardShortcuts.get(eventKey);
  if (handler) {
    if (handler instanceof HTMLInputElement) {
      event2.preventDefault();
      handler.focus();
    } else if (handler instanceof HTMLElement) {
      event2.preventDefault();
      handler.click();
    } else {
      handler(event2);
    }
  }
  if (event2.key !== "Alt" && event2.key !== "Control" && event2.key !== "Shift") {
    lastChar = eventKey;
  }
}
var isMac = (
  // This still seems to be the least bad way to check whether we are running on macOS or iOS
  navigator.platform.startsWith("Mac") || navigator.platform === "iPhone"
);
var modKey = isMac ? "Cmd" : "Ctrl";
function get_key_spec_key(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  return isMac ? spec.mac ?? spec.key : spec.key;
}
function get_key_spec_description(spec) {
  if (typeof spec === "string") {
    return spec;
  }
  const key2 = isMac ? spec.mac ?? spec.key : spec.key;
  return spec.note != null ? `${key2} - ${spec.note}` : key2;
}
function bind_key(spec, handler) {
  const key2 = get_key_spec_key(spec);
  const sequence = key2.split(" ");
  if (sequence.length > 2) {
    console.error("Only key sequences of length <=2 are supported: ", key2);
  }
  if (keyboardShortcuts.has(key2)) {
    console.warn("Duplicate keyboard shortcut: ", key2, handler);
  }
  keyboardShortcuts.set(key2, handler);
  return () => {
    keyboardShortcuts.delete(key2);
  };
}
var keyboardShortcut = (spec) => {
  if (spec == null) {
    return null;
  }
  return (node) => {
    node.setAttribute("data-key", get_key_spec_description(spec));
    const unbind = bind_key(spec, node);
    return () => {
      unbind();
      node.removeAttribute("data-key");
    };
  };
};
function show_keyboard_shortcuts() {
  const controller = new AbortController();
  const { signal } = controller;
  const tooltips = [];
  document.querySelectorAll("[data-key]").forEach((target) => {
    const key2 = target.getAttribute("data-key");
    if (target instanceof HTMLElement && key2 != null) {
      const target_was_hidden = target.hidden !== false;
      if (target_was_hidden) {
        target.hidden = false;
      }
      const tooltip = document.createElement("div");
      tooltip.className = "keyboard-tooltip";
      tooltip.textContent = key2;
      document.body.appendChild(tooltip);
      tooltips.push({ target, tooltip, target_was_hidden });
    }
  });
  tooltips.map(({ target, tooltip }) => {
    const rect = target.getBoundingClientRect();
    const left2 = rect.left + Math.min((target.offsetWidth - tooltip.offsetWidth) / 2, 10) + window.scrollX;
    const top2 = rect.top + (target.offsetHeight - tooltip.offsetHeight) / 2 + window.scrollY;
    return { left: left2, top: top2, tooltip };
  }).forEach(({ left: left2, top: top2, tooltip }) => {
    tooltip.style.left = `${left2.toString()}px`;
    tooltip.style.top = `${top2.toString()}px`;
  });
  const clear_tooltips = () => {
    tooltips.forEach(({ tooltip, target, target_was_hidden }) => {
      if (target_was_hidden) {
        target.hidden = true;
      }
      tooltip.remove();
    });
    controller.abort();
  };
  document.addEventListener("mousedown", clear_tooltips, { signal });
  document.addEventListener("keydown", clear_tooltips, { signal });
  document.addEventListener("scroll", clear_tooltips, {
    capture: true,
    signal
  });
  window.addEventListener("resize", clear_tooltips, { signal });
}
function init_global_keyboard_shortcuts() {
  document.addEventListener("keydown", keydown);
}

// src/stores/filters.ts
var time_filter = derived(
  search_params,
  ($search_params) => $search_params.get("time") ?? ""
);
var account_filter = derived(
  search_params,
  ($search_params) => $search_params.get("account") ?? ""
);
var fql_filter = derived(
  search_params,
  ($search_params) => $search_params.get("filter") ?? ""
);
var filter_params = derived(
  [time_filter, account_filter, fql_filter],
  ([$time_filter, $account_filter, $fql_filter]) => ({
    time: $time_filter,
    account: $account_filter,
    filter: $fql_filter
  })
);
function get_url_filters(url) {
  return {
    account: url.searchParams.get("account") ?? "",
    filter: url.searchParams.get("filter") ?? "",
    time: url.searchParams.get("time") ?? "",
    conversion: url.searchParams.get("conversion") ?? "",
    interval: url.searchParams.get("interval") ?? ""
  };
}

// src/lib/iso4217.ts
var iso4217_default = /* @__PURE__ */ new Set([
  "AED",
  "AFN",
  "ALL",
  "AMD",
  "ANG",
  "AOA",
  "ARS",
  "AUD",
  "AWG",
  "AZN",
  "BAM",
  "BBD",
  "BDT",
  "BGN",
  "BHD",
  "BIF",
  "BMD",
  "BND",
  "BOB",
  "BOV",
  "BRL",
  "BSD",
  "BTN",
  "BWP",
  "BYN",
  "BZD",
  "CAD",
  "CDF",
  "CHE",
  "CHF",
  "CHW",
  "CLF",
  "CLP",
  "CNY",
  "COP",
  "COU",
  "CRC",
  "CUC",
  "CUP",
  "CVE",
  "CZK",
  "DJF",
  "DKK",
  "DOP",
  "DZD",
  "EGP",
  "ERN",
  "ETB",
  "EUR",
  "FJD",
  "FKP",
  "GBP",
  "GEL",
  "GHS",
  "GIP",
  "GMD",
  "GNF",
  "GTQ",
  "GYD",
  "HKD",
  "HNL",
  "HRK",
  "HTG",
  "HUF",
  "IDR",
  "ILS",
  "INR",
  "IQD",
  "IRR",
  "ISK",
  "JMD",
  "JOD",
  "JPY",
  "KES",
  "KGS",
  "KHR",
  "KMF",
  "KPW",
  "KRW",
  "KWD",
  "KYD",
  "KZT",
  "LAK",
  "LBP",
  "LKR",
  "LRD",
  "LSL",
  "LYD",
  "MAD",
  "MDL",
  "MGA",
  "MKD",
  "MMK",
  "MNT",
  "MOP",
  "MRU",
  "MUR",
  "MVR",
  "MWK",
  "MXN",
  "MXV",
  "MYR",
  "MZN",
  "NAD",
  "NGN",
  "NIO",
  "NOK",
  "NPR",
  "NZD",
  "OMR",
  "PAB",
  "PEN",
  "PGK",
  "PHP",
  "PKR",
  "PLN",
  "PYG",
  "QAR",
  "RON",
  "RSD",
  "RUB",
  "RWF",
  "SAR",
  "SBD",
  "SCR",
  "SDG",
  "SEK",
  "SGD",
  "SHP",
  "SLL",
  "SOS",
  "SRD",
  "SSP",
  "STN",
  "SVC",
  "SYP",
  "SZL",
  "THB",
  "TJS",
  "TMT",
  "TND",
  "TOP",
  "TRY",
  "TTD",
  "TWD",
  "TZS",
  "UAH",
  "UGX",
  "USD",
  "USN",
  "UYI",
  "UYU",
  "UYW",
  "UZS",
  "VES",
  "VND",
  "VUV",
  "WST",
  "XAF",
  "XAG",
  "XAU",
  "XBA",
  "XBB",
  "XBC",
  "XBD",
  "XCD",
  "XDR",
  "XOF",
  "XPD",
  "XPF",
  "XPT",
  "XSU",
  "XTS",
  "XUA",
  "XXX",
  "YER",
  "ZAR",
  "ZMW",
  "ZWL"
]);

// src/stores/options.ts
var options = derived(ledger_data, (v) => v.options);
var ledger_title = derived(options, ($options) => $options.title);
var operating_currency = derived_array(
  options,
  ($options) => $options.operating_currency.toSorted(compare_strings)
);
var filename = derived(options, ($options) => $options.filename);
var include = derived_array(options, ($options) => $options.include);
var sources = derived(
  [filename, include],
  ([$filename, $include]) => /* @__PURE__ */ new Set([$filename, ...$include])
);
var documents = derived_array(
  options,
  ($options) => $options.documents
);
var name_assets = derived(options, ($options) => $options.name_assets);
var name_equity = derived(options, ($options) => $options.name_equity);
var name_income = derived(options, ($options) => $options.name_income);
var name_liabilities = derived(
  options,
  ($options) => $options.name_liabilities
);

// src/stores/chart.ts
var last_active_chart_name = writable(null);
var hierarchy_chart_mode_validator = constants(
  "treemap",
  "sunburst",
  "icicle"
);
var hierarchy_chart_mode = local_storage_synced_store(
  "hierarchy-chart-mode",
  hierarchy_chart_mode_validator,
  () => "treemap",
  () => [
    ["treemap", _("Treemap")],
    ["sunburst", _("Sunburst")],
    ["icicle", _("Icicle")]
  ]
);
var line_chart_mode_validator = constants("line", "area");
var line_chart_mode = local_storage_synced_store(
  "line-chart-mode",
  line_chart_mode_validator,
  () => "line",
  () => [
    ["line", _("Line chart")],
    ["area", _("Area chart")]
  ]
);
var bar_chart_mode_validator = constants("stacked", "single");
var bar_chart_mode = local_storage_synced_store(
  "bar-chart-mode",
  bar_chart_mode_validator,
  () => "stacked",
  () => [
    ["stacked", _("Stacked Bars")],
    ["single", _("Single Bars")]
  ]
);
var chart_toggled_currencies = local_storage_synced_store(
  "chart-toggled-currencies",
  array(string),
  () => []
);
var currency_suggestions = derived(
  [operating_currency, currencies_sorted, conversion_currencies],
  ([$operating_currency, $currencies_sorted, $conversion_currencies]) => $conversion_currencies.length > 0 ? $conversion_currencies : /* @__PURE__ */ new Set([
    ...$operating_currency,
    ...$currencies_sorted.filter((c) => iso4217_default.has(c))
  ])
);
var conversions = derived(
  currency_suggestions,
  ($currency_suggestions) => [
    "at_cost",
    "at_value",
    "units",
    ...$currency_suggestions
  ]
);

// node_modules/d3-axis/src/identity.js
function identity_default(x) {
  return x;
}

// node_modules/d3-axis/src/axis.js
var top = 1;
var right = 2;
var bottom = 3;
var left = 4;
var epsilon = 1e-6;
function translateX(x) {
  return "translate(" + x + ",0)";
}
function translateY(y) {
  return "translate(0," + y + ")";
}
function number(scale) {
  return (d) => +scale(d);
}
function center(scale, offset) {
  offset = Math.max(0, scale.bandwidth() - offset * 2) / 2;
  if (scale.round()) offset = Math.round(offset);
  return (d) => +scale(d) + offset;
}
function entering() {
  return !this.__axis;
}
function axis(orient, scale) {
  var tickArguments = [], tickValues = null, tickFormat2 = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, offset = typeof window !== "undefined" && window.devicePixelRatio > 1 ? 0 : 0.5, k = orient === top || orient === left ? -1 : 1, x = orient === left || orient === right ? "x" : "y", transform = orient === top || orient === bottom ? translateX : translateY;
  function axis2(context) {
    var values = tickValues == null ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format3 = tickFormat2 == null ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity_default : tickFormat2, spacing = Math.max(tickSizeInner, 0) + tickPadding, range2 = scale.range(), range0 = +range2[0] + offset, range1 = +range2[range2.length - 1] + offset, position = (scale.bandwidth ? center : number)(scale.copy(), offset), selection2 = context.selection ? context.selection() : context, path = selection2.selectAll(".domain").data([null]), tick = selection2.selectAll(".tick").data(values, scale).order(), tickExit = tick.exit(), tickEnter = tick.enter().append("g").attr("class", "tick"), line = tick.select("line"), text2 = tick.select("text");
    path = path.merge(path.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor"));
    tick = tick.merge(tickEnter);
    line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x + "2", k * tickSizeInner));
    text2 = text2.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x, k * spacing).attr("dy", orient === top ? "0em" : orient === bottom ? "0.71em" : "0.32em"));
    if (context !== selection2) {
      path = path.transition(context);
      tick = tick.transition(context);
      line = line.transition(context);
      text2 = text2.transition(context);
      tickExit = tickExit.transition(context).attr("opacity", epsilon).attr("transform", function(d) {
        return isFinite(d = position(d)) ? transform(d + offset) : this.getAttribute("transform");
      });
      tickEnter.attr("opacity", epsilon).attr("transform", function(d) {
        var p = this.parentNode.__axis;
        return transform((p && isFinite(p = p(d)) ? p : position(d)) + offset);
      });
    }
    tickExit.remove();
    path.attr("d", orient === left || orient === right ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H" + offset + "V" + range1 + "H" + k * tickSizeOuter : "M" + offset + "," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V" + offset + "H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + "," + offset + "H" + range1);
    tick.attr("opacity", 1).attr("transform", function(d) {
      return transform(position(d) + offset);
    });
    line.attr(x + "2", k * tickSizeInner);
    text2.attr(x, k * spacing).text(format3);
    selection2.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", orient === right ? "start" : orient === left ? "end" : "middle");
    selection2.each(function() {
      this.__axis = position;
    });
  }
  axis2.scale = function(_2) {
    return arguments.length ? (scale = _2, axis2) : scale;
  };
  axis2.ticks = function() {
    return tickArguments = Array.from(arguments), axis2;
  };
  axis2.tickArguments = function(_2) {
    return arguments.length ? (tickArguments = _2 == null ? [] : Array.from(_2), axis2) : tickArguments.slice();
  };
  axis2.tickValues = function(_2) {
    return arguments.length ? (tickValues = _2 == null ? null : Array.from(_2), axis2) : tickValues && tickValues.slice();
  };
  axis2.tickFormat = function(_2) {
    return arguments.length ? (tickFormat2 = _2, axis2) : tickFormat2;
  };
  axis2.tickSize = function(_2) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeInner = function(_2) {
    return arguments.length ? (tickSizeInner = +_2, axis2) : tickSizeInner;
  };
  axis2.tickSizeOuter = function(_2) {
    return arguments.length ? (tickSizeOuter = +_2, axis2) : tickSizeOuter;
  };
  axis2.tickPadding = function(_2) {
    return arguments.length ? (tickPadding = +_2, axis2) : tickPadding;
  };
  axis2.offset = function(_2) {
    return arguments.length ? (offset = +_2, axis2) : offset;
  };
  return axis2;
}
function axisBottom(scale) {
  return axis(bottom, scale);
}
function axisLeft(scale) {
  return axis(left, scale);
}

// node_modules/d3-scale/src/init.js
function initRange(domain, range2) {
  switch (arguments.length) {
    case 0:
      break;
    case 1:
      this.range(domain);
      break;
    default:
      this.range(range2).domain(domain);
      break;
  }
  return this;
}

// node_modules/d3-scale/src/ordinal.js
var implicit = /* @__PURE__ */ Symbol("implicit");
function ordinal() {
  var index2 = new InternMap(), domain = [], range2 = [], unknown = implicit;
  function scale(d) {
    let i = index2.get(d);
    if (i === void 0) {
      if (unknown !== implicit) return unknown;
      index2.set(d, i = domain.push(d) - 1);
    }
    return range2[i % range2.length];
  }
  scale.domain = function(_2) {
    if (!arguments.length) return domain.slice();
    domain = [], index2 = new InternMap();
    for (const value of _2) {
      if (index2.has(value)) continue;
      index2.set(value, domain.push(value) - 1);
    }
    return scale;
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), scale) : range2.slice();
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown = _2, scale) : unknown;
  };
  scale.copy = function() {
    return ordinal(domain, range2).unknown(unknown);
  };
  initRange.apply(scale, arguments);
  return scale;
}

// node_modules/d3-scale/src/band.js
function band() {
  var scale = ordinal().unknown(void 0), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5;
  delete scale.unknown;
  function rescale() {
    var n = domain().length, reverse = r1 < r0, start = reverse ? r1 : r0, stop = reverse ? r0 : r1;
    step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);
    if (round) step = Math.floor(step);
    start += (stop - start - step * (n - paddingInner)) * align;
    bandwidth = step * (1 - paddingInner);
    if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);
    var values = range(n).map(function(i) {
      return start + step * i;
    });
    return ordinalRange(reverse ? values.reverse() : values);
  }
  scale.domain = function(_2) {
    return arguments.length ? (domain(_2), rescale()) : domain();
  };
  scale.range = function(_2) {
    return arguments.length ? ([r0, r1] = _2, r0 = +r0, r1 = +r1, rescale()) : [r0, r1];
  };
  scale.rangeRound = function(_2) {
    return [r0, r1] = _2, r0 = +r0, r1 = +r1, round = true, rescale();
  };
  scale.bandwidth = function() {
    return bandwidth;
  };
  scale.step = function() {
    return step;
  };
  scale.round = function(_2) {
    return arguments.length ? (round = !!_2, rescale()) : round;
  };
  scale.padding = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_2), rescale()) : paddingInner;
  };
  scale.paddingInner = function(_2) {
    return arguments.length ? (paddingInner = Math.min(1, _2), rescale()) : paddingInner;
  };
  scale.paddingOuter = function(_2) {
    return arguments.length ? (paddingOuter = +_2, rescale()) : paddingOuter;
  };
  scale.align = function(_2) {
    return arguments.length ? (align = Math.max(0, Math.min(1, _2)), rescale()) : align;
  };
  scale.copy = function() {
    return band(domain(), [r0, r1]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
  };
  return initRange.apply(rescale(), arguments);
}
function pointish(scale) {
  var copy2 = scale.copy;
  scale.padding = scale.paddingOuter;
  delete scale.paddingInner;
  delete scale.paddingOuter;
  scale.copy = function() {
    return pointish(copy2());
  };
  return scale;
}
function point() {
  return pointish(band.apply(null, arguments).paddingInner(1));
}

// node_modules/d3-color/src/define.js
function define_default(constructor, factory, prototype) {
  constructor.prototype = factory.prototype = prototype;
  prototype.constructor = constructor;
}
function extend(parent2, definition) {
  var prototype = Object.create(parent2.prototype);
  for (var key2 in definition) prototype[key2] = definition[key2];
  return prototype;
}

// node_modules/d3-color/src/color.js
function Color() {
}
var darker = 0.7;
var brighter = 1 / darker;
var reI = "\\s*([+-]?\\d+)\\s*";
var reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*";
var reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*";
var reHex = /^#([0-9a-f]{3,8})$/;
var reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`);
var reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`);
var reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`);
var reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`);
var reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`);
var reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`);
var named = {
  aliceblue: 15792383,
  antiquewhite: 16444375,
  aqua: 65535,
  aquamarine: 8388564,
  azure: 15794175,
  beige: 16119260,
  bisque: 16770244,
  black: 0,
  blanchedalmond: 16772045,
  blue: 255,
  blueviolet: 9055202,
  brown: 10824234,
  burlywood: 14596231,
  cadetblue: 6266528,
  chartreuse: 8388352,
  chocolate: 13789470,
  coral: 16744272,
  cornflowerblue: 6591981,
  cornsilk: 16775388,
  crimson: 14423100,
  cyan: 65535,
  darkblue: 139,
  darkcyan: 35723,
  darkgoldenrod: 12092939,
  darkgray: 11119017,
  darkgreen: 25600,
  darkgrey: 11119017,
  darkkhaki: 12433259,
  darkmagenta: 9109643,
  darkolivegreen: 5597999,
  darkorange: 16747520,
  darkorchid: 10040012,
  darkred: 9109504,
  darksalmon: 15308410,
  darkseagreen: 9419919,
  darkslateblue: 4734347,
  darkslategray: 3100495,
  darkslategrey: 3100495,
  darkturquoise: 52945,
  darkviolet: 9699539,
  deeppink: 16716947,
  deepskyblue: 49151,
  dimgray: 6908265,
  dimgrey: 6908265,
  dodgerblue: 2003199,
  firebrick: 11674146,
  floralwhite: 16775920,
  forestgreen: 2263842,
  fuchsia: 16711935,
  gainsboro: 14474460,
  ghostwhite: 16316671,
  gold: 16766720,
  goldenrod: 14329120,
  gray: 8421504,
  green: 32768,
  greenyellow: 11403055,
  grey: 8421504,
  honeydew: 15794160,
  hotpink: 16738740,
  indianred: 13458524,
  indigo: 4915330,
  ivory: 16777200,
  khaki: 15787660,
  lavender: 15132410,
  lavenderblush: 16773365,
  lawngreen: 8190976,
  lemonchiffon: 16775885,
  lightblue: 11393254,
  lightcoral: 15761536,
  lightcyan: 14745599,
  lightgoldenrodyellow: 16448210,
  lightgray: 13882323,
  lightgreen: 9498256,
  lightgrey: 13882323,
  lightpink: 16758465,
  lightsalmon: 16752762,
  lightseagreen: 2142890,
  lightskyblue: 8900346,
  lightslategray: 7833753,
  lightslategrey: 7833753,
  lightsteelblue: 11584734,
  lightyellow: 16777184,
  lime: 65280,
  limegreen: 3329330,
  linen: 16445670,
  magenta: 16711935,
  maroon: 8388608,
  mediumaquamarine: 6737322,
  mediumblue: 205,
  mediumorchid: 12211667,
  mediumpurple: 9662683,
  mediumseagreen: 3978097,
  mediumslateblue: 8087790,
  mediumspringgreen: 64154,
  mediumturquoise: 4772300,
  mediumvioletred: 13047173,
  midnightblue: 1644912,
  mintcream: 16121850,
  mistyrose: 16770273,
  moccasin: 16770229,
  navajowhite: 16768685,
  navy: 128,
  oldlace: 16643558,
  olive: 8421376,
  olivedrab: 7048739,
  orange: 16753920,
  orangered: 16729344,
  orchid: 14315734,
  palegoldenrod: 15657130,
  palegreen: 10025880,
  paleturquoise: 11529966,
  palevioletred: 14381203,
  papayawhip: 16773077,
  peachpuff: 16767673,
  peru: 13468991,
  pink: 16761035,
  plum: 14524637,
  powderblue: 11591910,
  purple: 8388736,
  rebeccapurple: 6697881,
  red: 16711680,
  rosybrown: 12357519,
  royalblue: 4286945,
  saddlebrown: 9127187,
  salmon: 16416882,
  sandybrown: 16032864,
  seagreen: 3050327,
  seashell: 16774638,
  sienna: 10506797,
  silver: 12632256,
  skyblue: 8900331,
  slateblue: 6970061,
  slategray: 7372944,
  slategrey: 7372944,
  snow: 16775930,
  springgreen: 65407,
  steelblue: 4620980,
  tan: 13808780,
  teal: 32896,
  thistle: 14204888,
  tomato: 16737095,
  turquoise: 4251856,
  violet: 15631086,
  wheat: 16113331,
  white: 16777215,
  whitesmoke: 16119285,
  yellow: 16776960,
  yellowgreen: 10145074
};
define_default(Color, color, {
  copy(channels) {
    return Object.assign(new this.constructor(), this, channels);
  },
  displayable() {
    return this.rgb().displayable();
  },
  hex: color_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: color_formatHex,
  formatHex8: color_formatHex8,
  formatHsl: color_formatHsl,
  formatRgb: color_formatRgb,
  toString: color_formatRgb
});
function color_formatHex() {
  return this.rgb().formatHex();
}
function color_formatHex8() {
  return this.rgb().formatHex8();
}
function color_formatHsl() {
  return hslConvert(this).formatHsl();
}
function color_formatRgb() {
  return this.rgb().formatRgb();
}
function color(format3) {
  var m, l;
  format3 = (format3 + "").trim().toLowerCase();
  return (m = reHex.exec(format3)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format3)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format3)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format3)) ? rgba(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format3)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format3)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format3)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format3) ? rgbn(named[format3]) : format3 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
  return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1);
}
function rgba(r, g, b, a) {
  if (a <= 0) r = g = b = NaN;
  return new Rgb(r, g, b, a);
}
function rgbConvert(o) {
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Rgb();
  o = o.rgb();
  return new Rgb(o.r, o.g, o.b, o.opacity);
}
function rgb(r, g, b, opacity) {
  return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
  this.r = +r;
  this.g = +g;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Rgb, rgb, extend(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  },
  rgb() {
    return this;
  },
  clamp() {
    return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity));
  },
  displayable() {
    return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1);
  },
  hex: rgb_formatHex,
  // Deprecated! Use color.formatHex.
  formatHex: rgb_formatHex,
  formatHex8: rgb_formatHex8,
  formatRgb: rgb_formatRgb,
  toString: rgb_formatRgb
}));
function rgb_formatHex() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`;
}
function rgb_formatHex8() {
  return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`;
}
function rgb_formatRgb() {
  const a = clampa(this.opacity);
  return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`;
}
function clampa(opacity) {
  return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity));
}
function clampi(value) {
  return Math.max(0, Math.min(255, Math.round(value) || 0));
}
function hex(value) {
  value = clampi(value);
  return (value < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s, l, a) {
  if (a <= 0) h = s = l = NaN;
  else if (l <= 0 || l >= 1) h = s = NaN;
  else if (s <= 0) h = NaN;
  return new Hsl(h, s, l, a);
}
function hslConvert(o) {
  if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  if (!(o instanceof Color)) o = color(o);
  if (!o) return new Hsl();
  if (o instanceof Hsl) return o;
  o = o.rgb();
  var r = o.r / 255, g = o.g / 255, b = o.b / 255, min2 = Math.min(r, g, b), max2 = Math.max(r, g, b), h = NaN, s = max2 - min2, l = (max2 + min2) / 2;
  if (s) {
    if (r === max2) h = (g - b) / s + (g < b) * 6;
    else if (g === max2) h = (b - r) / s + 2;
    else h = (r - g) / s + 4;
    s /= l < 0.5 ? max2 + min2 : 2 - max2 - min2;
    h *= 60;
  } else {
    s = l > 0 && l < 1 ? 0 : h;
  }
  return new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
  return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
  this.h = +h;
  this.s = +s;
  this.l = +l;
  this.opacity = +opacity;
}
define_default(Hsl, hsl, extend(Color, {
  brighter(k) {
    k = k == null ? brighter : Math.pow(brighter, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  darker(k) {
    k = k == null ? darker : Math.pow(darker, k);
    return new Hsl(this.h, this.s, this.l * k, this.opacity);
  },
  rgb() {
    var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
    return new Rgb(
      hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
      hsl2rgb(h, m1, m2),
      hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
      this.opacity
    );
  },
  clamp() {
    return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity));
  },
  displayable() {
    return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1);
  },
  formatHsl() {
    const a = clampa(this.opacity);
    return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`;
  }
}));
function clamph(value) {
  value = (value || 0) % 360;
  return value < 0 ? value + 360 : value;
}
function clampt(value) {
  return Math.max(0, Math.min(1, value || 0));
}
function hsl2rgb(h, m1, m2) {
  return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}

// node_modules/d3-color/src/math.js
var radians = Math.PI / 180;
var degrees = 180 / Math.PI;

// node_modules/d3-color/src/lab.js
var K = 18;
var Xn = 0.96422;
var Yn = 1;
var Zn = 0.82521;
var t0 = 4 / 29;
var t1 = 6 / 29;
var t2 = 3 * t1 * t1;
var t3 = t1 * t1 * t1;
function labConvert(o) {
  if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
  if (o instanceof Hcl) return hcl2lab(o);
  if (!(o instanceof Rgb)) o = rgbConvert(o);
  var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;
  if (r === g && g === b) x = z = y;
  else {
    x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);
    z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);
  }
  return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}
function lab(l, a, b, opacity) {
  return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
  this.l = +l;
  this.a = +a;
  this.b = +b;
  this.opacity = +opacity;
}
define_default(Lab, lab, extend(Color, {
  brighter(k) {
    return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  darker(k) {
    return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);
  },
  rgb() {
    var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200;
    x = Xn * lab2xyz(x);
    y = Yn * lab2xyz(y);
    z = Zn * lab2xyz(z);
    return new Rgb(
      lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z),
      lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.033454 * z),
      lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z),
      this.opacity
    );
  }
}));
function xyz2lab(t) {
  return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
  return t > t1 ? t * t * t : t2 * (t - t0);
}
function lrgb2rgb(x) {
  return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x) {
  return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
  if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
  if (!(o instanceof Lab)) o = labConvert(o);
  if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
  var h = Math.atan2(o.b, o.a) * degrees;
  return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c, l, opacity) {
  return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
  this.h = +h;
  this.c = +c;
  this.l = +l;
  this.opacity = +opacity;
}
function hcl2lab(o) {
  if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
  var h = o.h * radians;
  return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define_default(Hcl, hcl, extend(Color, {
  brighter(k) {
    return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);
  },
  darker(k) {
    return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);
  },
  rgb() {
    return hcl2lab(this).rgb();
  }
}));

// node_modules/d3-interpolate/src/basis.js
function basis(t12, v0, v1, v2, v3) {
  var t22 = t12 * t12, t32 = t22 * t12;
  return ((1 - 3 * t12 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t12 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6;
}
function basis_default(values) {
  var n = values.length - 1;
  return function(t) {
    var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/basisClosed.js
function basisClosed_default(values) {
  var n = values.length;
  return function(t) {
    var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
    return basis((t - i / n) * n, v0, v1, v2, v3);
  };
}

// node_modules/d3-interpolate/src/constant.js
var constant_default = (x) => () => x;

// node_modules/d3-interpolate/src/color.js
function linear(a, d) {
  return function(t) {
    return a + t * d;
  };
}
function exponential(a, b, y) {
  return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {
    return Math.pow(a + t * b, y);
  };
}
function gamma(y) {
  return (y = +y) === 1 ? nogamma : function(a, b) {
    return b - a ? exponential(a, b, y) : constant_default(isNaN(a) ? b : a);
  };
}
function nogamma(a, b) {
  var d = b - a;
  return d ? linear(a, d) : constant_default(isNaN(a) ? b : a);
}

// node_modules/d3-interpolate/src/rgb.js
var rgb_default = (function rgbGamma(y) {
  var color2 = gamma(y);
  function rgb2(start, end) {
    var r = color2((start = rgb(start)).r, (end = rgb(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
    return function(t) {
      start.r = r(t);
      start.g = g(t);
      start.b = b(t);
      start.opacity = opacity(t);
      return start + "";
    };
  }
  rgb2.gamma = rgbGamma;
  return rgb2;
})(1);
function rgbSpline(spline) {
  return function(colors) {
    var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2;
    for (i = 0; i < n; ++i) {
      color2 = rgb(colors[i]);
      r[i] = color2.r || 0;
      g[i] = color2.g || 0;
      b[i] = color2.b || 0;
    }
    r = spline(r);
    g = spline(g);
    b = spline(b);
    color2.opacity = 1;
    return function(t) {
      color2.r = r(t);
      color2.g = g(t);
      color2.b = b(t);
      return color2 + "";
    };
  };
}
var rgbBasis = rgbSpline(basis_default);
var rgbBasisClosed = rgbSpline(basisClosed_default);

// node_modules/d3-interpolate/src/numberArray.js
function numberArray_default(a, b) {
  if (!b) b = [];
  var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i;
  return function(t) {
    for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;
    return c;
  };
}
function isNumberArray(x) {
  return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

// node_modules/d3-interpolate/src/array.js
function genericArray(a, b) {
  var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i;
  for (i = 0; i < na; ++i) x[i] = value_default(a[i], b[i]);
  for (; i < nb; ++i) c[i] = b[i];
  return function(t) {
    for (i = 0; i < na; ++i) c[i] = x[i](t);
    return c;
  };
}

// node_modules/d3-interpolate/src/date.js
function date_default(a, b) {
  var d = /* @__PURE__ */ new Date();
  return a = +a, b = +b, function(t) {
    return d.setTime(a * (1 - t) + b * t), d;
  };
}

// node_modules/d3-interpolate/src/number.js
function number_default(a, b) {
  return a = +a, b = +b, function(t) {
    return a * (1 - t) + b * t;
  };
}

// node_modules/d3-interpolate/src/object.js
function object_default(a, b) {
  var i = {}, c = {}, k;
  if (a === null || typeof a !== "object") a = {};
  if (b === null || typeof b !== "object") b = {};
  for (k in b) {
    if (k in a) {
      i[k] = value_default(a[k], b[k]);
    } else {
      c[k] = b[k];
    }
  }
  return function(t) {
    for (k in i) c[k] = i[k](t);
    return c;
  };
}

// node_modules/d3-interpolate/src/string.js
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g;
var reB = new RegExp(reA.source, "g");
function zero(b) {
  return function() {
    return b;
  };
}
function one(b) {
  return function(t) {
    return b(t) + "";
  };
}
function string_default(a, b) {
  var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
  a = a + "", b = b + "";
  while ((am = reA.exec(a)) && (bm = reB.exec(b))) {
    if ((bs = bm.index) > bi) {
      bs = b.slice(bi, bs);
      if (s[i]) s[i] += bs;
      else s[++i] = bs;
    }
    if ((am = am[0]) === (bm = bm[0])) {
      if (s[i]) s[i] += bm;
      else s[++i] = bm;
    } else {
      s[++i] = null;
      q.push({ i, x: number_default(am, bm) });
    }
    bi = reB.lastIndex;
  }
  if (bi < b.length) {
    bs = b.slice(bi);
    if (s[i]) s[i] += bs;
    else s[++i] = bs;
  }
  return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) {
    for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t);
    return s.join("");
  });
}

// node_modules/d3-interpolate/src/value.js
function value_default(a, b) {
  var t = typeof b, c;
  return b == null || t === "boolean" ? constant_default(b) : (t === "number" ? number_default : t === "string" ? (c = color(b)) ? (b = c, rgb_default) : string_default : b instanceof color ? rgb_default : b instanceof Date ? date_default : isNumberArray(b) ? numberArray_default : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object_default : number_default)(a, b);
}

// node_modules/d3-interpolate/src/round.js
function round_default(a, b) {
  return a = +a, b = +b, function(t) {
    return Math.round(a * (1 - t) + b * t);
  };
}

// node_modules/d3-scale/src/constant.js
function constants2(x) {
  return function() {
    return x;
  };
}

// node_modules/d3-scale/src/number.js
function number2(x) {
  return +x;
}

// node_modules/d3-scale/src/continuous.js
var unit = [0, 1];
function identity(x) {
  return x;
}
function normalize(a, b) {
  return (b -= a = +a) ? function(x) {
    return (x - a) / b;
  } : constants2(isNaN(b) ? NaN : 0.5);
}
function clamper(a, b) {
  var t;
  if (a > b) t = a, a = b, b = t;
  return function(x) {
    return Math.max(a, Math.min(b, x));
  };
}
function bimap(domain, range2, interpolate) {
  var d0 = domain[0], d1 = domain[1], r0 = range2[0], r1 = range2[1];
  if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);
  else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);
  return function(x) {
    return r0(d0(x));
  };
}
function polymap(domain, range2, interpolate) {
  var j = Math.min(domain.length, range2.length) - 1, d = new Array(j), r = new Array(j), i = -1;
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range2 = range2.slice().reverse();
  }
  while (++i < j) {
    d[i] = normalize(domain[i], domain[i + 1]);
    r[i] = interpolate(range2[i], range2[i + 1]);
  }
  return function(x) {
    var i2 = bisect_default(domain, x, 1, j) - 1;
    return r[i2](d[i2](x));
  };
}
function copy(source2, target) {
  return target.domain(source2.domain()).range(source2.range()).interpolate(source2.interpolate()).clamp(source2.clamp()).unknown(source2.unknown());
}
function transformer() {
  var domain = unit, range2 = unit, interpolate = value_default, transform, untransform, unknown, clamp = identity, piecewise, output, input;
  function rescale() {
    var n = Math.min(domain.length, range2.length);
    if (clamp !== identity) clamp = clamper(domain[0], domain[n - 1]);
    piecewise = n > 2 ? polymap : bimap;
    output = input = null;
    return scale;
  }
  function scale(x) {
    return x == null || isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range2, interpolate)))(transform(clamp(x)));
  }
  scale.invert = function(y) {
    return clamp(untransform((input || (input = piecewise(range2, domain.map(transform), number_default)))(y)));
  };
  scale.domain = function(_2) {
    return arguments.length ? (domain = Array.from(_2, number2), rescale()) : domain.slice();
  };
  scale.range = function(_2) {
    return arguments.length ? (range2 = Array.from(_2), rescale()) : range2.slice();
  };
  scale.rangeRound = function(_2) {
    return range2 = Array.from(_2), interpolate = round_default, rescale();
  };
  scale.clamp = function(_2) {
    return arguments.length ? (clamp = _2 ? true : identity, rescale()) : clamp !== identity;
  };
  scale.interpolate = function(_2) {
    return arguments.length ? (interpolate = _2, rescale()) : interpolate;
  };
  scale.unknown = function(_2) {
    return arguments.length ? (unknown = _2, scale) : unknown;
  };
  return function(t, u) {
    transform = t, untransform = u;
    return rescale();
  };
}
function continuous() {
  return transformer()(identity, identity);
}

// node_modules/d3-scale/src/tickFormat.js
function tickFormat(start, stop, count, specifier) {
  var step = tickStep(start, stop, count), precision;
  specifier = formatSpecifier(specifier == null ? ",f" : specifier);
  switch (specifier.type) {
    case "s": {
      var value = Math.max(Math.abs(start), Math.abs(stop));
      if (specifier.precision == null && !isNaN(precision = precisionPrefix_default(step, value))) specifier.precision = precision;
      return formatPrefix(specifier, value);
    }
    case "":
    case "e":
    case "g":
    case "p":
    case "r": {
      if (specifier.precision == null && !isNaN(precision = precisionRound_default(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e");
      break;
    }
    case "f":
    case "%": {
      if (specifier.precision == null && !isNaN(precision = precisionFixed_default(step))) specifier.precision = precision - (specifier.type === "%") * 2;
      break;
    }
  }
  return format(specifier);
}

// node_modules/d3-scale/src/linear.js
function linearish(scale) {
  var domain = scale.domain;
  scale.ticks = function(count) {
    var d = domain();
    return ticks(d[0], d[d.length - 1], count == null ? 10 : count);
  };
  scale.tickFormat = function(count, specifier) {
    var d = domain();
    return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);
  };
  scale.nice = function(count) {
    if (count == null) count = 10;
    var d = domain();
    var i0 = 0;
    var i1 = d.length - 1;
    var start = d[i0];
    var stop = d[i1];
    var prestep;
    var step;
    var maxIter = 10;
    if (stop < start) {
      step = start, start = stop, stop = step;
      step = i0, i0 = i1, i1 = step;
    }
    while (maxIter-- > 0) {
      step = tickIncrement(start, stop, count);
      if (step === prestep) {
        d[i0] = start;
        d[i1] = stop;
        return domain(d);
      } else if (step > 0) {
        start = Math.floor(start / step) * step;
        stop = Math.ceil(stop / step) * step;
      } else if (step < 0) {
        start = Math.ceil(start * step) / step;
        stop = Math.floor(stop * step) / step;
      } else {
        break;
      }
      prestep = step;
    }
    return scale;
  };
  return scale;
}
function linear2() {
  var scale = continuous();
  scale.copy = function() {
    return copy(scale, linear2());
  };
  initRange.apply(scale, arguments);
  return linearish(scale);
}

// node_modules/d3-scale/src/nice.js
function nice(domain, interval2) {
  domain = domain.slice();
  var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t;
  if (x1 < x0) {
    t = i0, i0 = i1, i1 = t;
    t = x0, x0 = x1, x1 = t;
  }
  domain[i0] = interval2.floor(x0);
  domain[i1] = interval2.ceil(x1);
  return domain;
}

// node_modules/d3-scale/src/pow.js
function transformPow(exponent) {
  return function(x) {
    return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
  };
}
function transformSqrt(x) {
  return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
}
function transformSquare(x) {
  return x < 0 ? -x * x : x * x;
}
function powish(transform) {
  var scale = transform(identity, identity), exponent = 1;
  function rescale() {
    return exponent === 1 ? transform(identity, identity) : exponent === 0.5 ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent));
  }
  scale.exponent = function(_2) {
    return arguments.length ? (exponent = +_2, rescale()) : exponent;
  };
  return linearish(scale);
}
function pow() {
  var scale = powish(transformer());
  scale.copy = function() {
    return copy(scale, pow()).exponent(scale.exponent());
  };
  initRange.apply(scale, arguments);
  return scale;
}
function sqrt() {
  return pow.apply(null, arguments).exponent(0.5);
}

// node_modules/d3-scale/src/time.js
function date2(t) {
  return new Date(t);
}
function number3(t) {
  return t instanceof Date ? +t : +/* @__PURE__ */ new Date(+t);
}
function calendar(ticks2, tickInterval, year, month, week, day2, hour, minute, second2, format3) {
  var scale = continuous(), invert = scale.invert, domain = scale.domain;
  var formatMillisecond = format3(".%L"), formatSecond = format3(":%S"), formatMinute = format3("%I:%M"), formatHour = format3("%I %p"), formatDay = format3("%a %d"), formatWeek = format3("%b %d"), formatMonth = format3("%B"), formatYear = format3("%Y");
  function tickFormat2(date3) {
    return (second2(date3) < date3 ? formatMillisecond : minute(date3) < date3 ? formatSecond : hour(date3) < date3 ? formatMinute : day2(date3) < date3 ? formatHour : month(date3) < date3 ? week(date3) < date3 ? formatDay : formatWeek : year(date3) < date3 ? formatMonth : formatYear)(date3);
  }
  scale.invert = function(y) {
    return new Date(invert(y));
  };
  scale.domain = function(_2) {
    return arguments.length ? domain(Array.from(_2, number3)) : domain().map(date2);
  };
  scale.ticks = function(interval2) {
    var d = domain();
    return ticks2(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
  };
  scale.tickFormat = function(count, specifier) {
    return specifier == null ? tickFormat2 : format3(specifier);
  };
  scale.nice = function(interval2) {
    var d = domain();
    if (!interval2 || typeof interval2.range !== "function") interval2 = tickInterval(d[0], d[d.length - 1], interval2 == null ? 10 : interval2);
    return interval2 ? domain(nice(d, interval2)) : scale;
  };
  scale.copy = function() {
    return copy(scale, calendar(ticks2, tickInterval, year, month, week, day2, hour, minute, second2, format3));
  };
  return scale;
}

// node_modules/d3-scale/src/utcTime.js
function utcTime() {
  return initRange.apply(calendar(utcTicks, utcTickInterval, utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, utcFormat).domain([Date.UTC(2e3, 0, 1), Date.UTC(2e3, 0, 2)]), arguments);
}

// src/stores/format.ts
var short_format = format(".3s");
var short = derived(
  incognito,
  ($incognito) => $incognito ? (n) => replaceNumbers(short_format(n)) : short_format
);
var num = derived(locale, ($locale) => locale_formatter($locale));
var ctx = derived(
  [incognito, locale, precisions],
  ([$incognito, $locale, $precisions]) => formatter_context($incognito, $locale, $precisions)
);
var current_date_format = derived(interval, (val) => dateFormat[val]);
var current_time_filter_date_format = derived(
  interval,
  (val) => timeFilterDateFormat[val]
);

// node_modules/d3-selection/src/namespaces.js
var xhtml = "http://www.w3.org/1999/xhtml";
var namespaces_default = {
  svg: "http://www.w3.org/2000/svg",
  xhtml,
  xlink: "http://www.w3.org/1999/xlink",
  xml: "http://www.w3.org/XML/1998/namespace",
  xmlns: "http://www.w3.org/2000/xmlns/"
};

// node_modules/d3-selection/src/namespace.js
function namespace_default(name) {
  var prefix = name += "", i = prefix.indexOf(":");
  if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
  return namespaces_default.hasOwnProperty(prefix) ? { space: namespaces_default[prefix], local: name } : name;
}

// node_modules/d3-selection/src/creator.js
function creatorInherit(name) {
  return function() {
    var document2 = this.ownerDocument, uri = this.namespaceURI;
    return uri === xhtml && document2.documentElement.namespaceURI === xhtml ? document2.createElement(name) : document2.createElementNS(uri, name);
  };
}
function creatorFixed(fullname) {
  return function() {
    return this.ownerDocument.createElementNS(fullname.space, fullname.local);
  };
}
function creator_default(name) {
  var fullname = namespace_default(name);
  return (fullname.local ? creatorFixed : creatorInherit)(fullname);
}

// node_modules/d3-selection/src/selector.js
function none() {
}
function selector_default(selector) {
  return selector == null ? none : function() {
    return this.querySelector(selector);
  };
}

// node_modules/d3-selection/src/selection/select.js
function select_default(select) {
  if (typeof select !== "function") select = selector_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups[j], n = group2.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {
      if ((node = group2[i]) && (subnode = select.call(node, node.__data__, i, group2))) {
        if ("__data__" in node) subnode.__data__ = node.__data__;
        subgroup[i] = subnode;
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/array.js
function array2(x) {
  return x == null ? [] : Array.isArray(x) ? x : Array.from(x);
}

// node_modules/d3-selection/src/selectorAll.js
function empty() {
  return [];
}
function selectorAll_default(selector) {
  return selector == null ? empty : function() {
    return this.querySelectorAll(selector);
  };
}

// node_modules/d3-selection/src/selection/selectAll.js
function arrayAll(select) {
  return function() {
    return array2(select.apply(this, arguments));
  };
}
function selectAll_default(select) {
  if (typeof select === "function") select = arrayAll(select);
  else select = selectorAll_default(select);
  for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {
    for (var group2 = groups[j], n = group2.length, node, i = 0; i < n; ++i) {
      if (node = group2[i]) {
        subgroups.push(select.call(node, node.__data__, i, group2));
        parents.push(node);
      }
    }
  }
  return new Selection(subgroups, parents);
}

// node_modules/d3-selection/src/matcher.js
function matcher_default(selector) {
  return function() {
    return this.matches(selector);
  };
}
function childMatcher(selector) {
  return function(node) {
    return node.matches(selector);
  };
}

// node_modules/d3-selection/src/selection/selectChild.js
var find = Array.prototype.find;
function childFind(match) {
  return function() {
    return find.call(this.children, match);
  };
}
function childFirst() {
  return this.firstElementChild;
}
function selectChild_default(match) {
  return this.select(match == null ? childFirst : childFind(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/selectChildren.js
var filter = Array.prototype.filter;
function children() {
  return Array.from(this.children);
}
function childrenFilter(match) {
  return function() {
    return filter.call(this.children, match);
  };
}
function selectChildren_default(match) {
  return this.selectAll(match == null ? children : childrenFilter(typeof match === "function" ? match : childMatcher(match)));
}

// node_modules/d3-selection/src/selection/filter.js
function filter_default(match) {
  if (typeof match !== "function") match = matcher_default(match);
  for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups[j], n = group2.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {
      if ((node = group2[i]) && match.call(node, node.__data__, i, group2)) {
        subgroup.push(node);
      }
    }
  }
  return new Selection(subgroups, this._parents);
}

// node_modules/d3-selection/src/selection/sparse.js
function sparse_default(update2) {
  return new Array(update2.length);
}

// node_modules/d3-selection/src/selection/enter.js
function enter_default() {
  return new Selection(this._enter || this._groups.map(sparse_default), this._parents);
}
function EnterNode(parent2, datum2) {
  this.ownerDocument = parent2.ownerDocument;
  this.namespaceURI = parent2.namespaceURI;
  this._next = null;
  this._parent = parent2;
  this.__data__ = datum2;
}
EnterNode.prototype = {
  constructor: EnterNode,
  appendChild: function(child2) {
    return this._parent.insertBefore(child2, this._next);
  },
  insertBefore: function(child2, next2) {
    return this._parent.insertBefore(child2, next2);
  },
  querySelector: function(selector) {
    return this._parent.querySelector(selector);
  },
  querySelectorAll: function(selector) {
    return this._parent.querySelectorAll(selector);
  }
};

// node_modules/d3-selection/src/constant.js
function constant_default2(x) {
  return function() {
    return x;
  };
}

// node_modules/d3-selection/src/selection/data.js
function bindIndex(parent2, group2, enter, update2, exit, data) {
  var i = 0, node, groupLength = group2.length, dataLength = data.length;
  for (; i < dataLength; ++i) {
    if (node = group2[i]) {
      node.__data__ = data[i];
      update2[i] = node;
    } else {
      enter[i] = new EnterNode(parent2, data[i]);
    }
  }
  for (; i < groupLength; ++i) {
    if (node = group2[i]) {
      exit[i] = node;
    }
  }
}
function bindKey(parent2, group2, enter, update2, exit, data, key2) {
  var i, node, nodeByKeyValue = /* @__PURE__ */ new Map(), groupLength = group2.length, dataLength = data.length, keyValues = new Array(groupLength), keyValue;
  for (i = 0; i < groupLength; ++i) {
    if (node = group2[i]) {
      keyValues[i] = keyValue = key2.call(node, node.__data__, i, group2) + "";
      if (nodeByKeyValue.has(keyValue)) {
        exit[i] = node;
      } else {
        nodeByKeyValue.set(keyValue, node);
      }
    }
  }
  for (i = 0; i < dataLength; ++i) {
    keyValue = key2.call(parent2, data[i], i, data) + "";
    if (node = nodeByKeyValue.get(keyValue)) {
      update2[i] = node;
      node.__data__ = data[i];
      nodeByKeyValue.delete(keyValue);
    } else {
      enter[i] = new EnterNode(parent2, data[i]);
    }
  }
  for (i = 0; i < groupLength; ++i) {
    if ((node = group2[i]) && nodeByKeyValue.get(keyValues[i]) === node) {
      exit[i] = node;
    }
  }
}
function datum(node) {
  return node.__data__;
}
function data_default(value, key2) {
  if (!arguments.length) return Array.from(this, datum);
  var bind = key2 ? bindKey : bindIndex, parents = this._parents, groups = this._groups;
  if (typeof value !== "function") value = constant_default2(value);
  for (var m = groups.length, update2 = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {
    var parent2 = parents[j], group2 = groups[j], groupLength = group2.length, data = arraylike(value.call(parent2, parent2 && parent2.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = new Array(dataLength), updateGroup = update2[j] = new Array(dataLength), exitGroup = exit[j] = new Array(groupLength);
    bind(parent2, group2, enterGroup, updateGroup, exitGroup, data, key2);
    for (var i0 = 0, i1 = 0, previous, next2; i0 < dataLength; ++i0) {
      if (previous = enterGroup[i0]) {
        if (i0 >= i1) i1 = i0 + 1;
        while (!(next2 = updateGroup[i1]) && ++i1 < dataLength) ;
        previous._next = next2 || null;
      }
    }
  }
  update2 = new Selection(update2, parents);
  update2._enter = enter;
  update2._exit = exit;
  return update2;
}
function arraylike(data) {
  return typeof data === "object" && "length" in data ? data : Array.from(data);
}

// node_modules/d3-selection/src/selection/exit.js
function exit_default() {
  return new Selection(this._exit || this._groups.map(sparse_default), this._parents);
}

// node_modules/d3-selection/src/selection/join.js
function join_default(onenter, onupdate, onexit) {
  var enter = this.enter(), update2 = this, exit = this.exit();
  if (typeof onenter === "function") {
    enter = onenter(enter);
    if (enter) enter = enter.selection();
  } else {
    enter = enter.append(onenter + "");
  }
  if (onupdate != null) {
    update2 = onupdate(update2);
    if (update2) update2 = update2.selection();
  }
  if (onexit == null) exit.remove();
  else onexit(exit);
  return enter && update2 ? enter.merge(update2).order() : update2;
}

// node_modules/d3-selection/src/selection/merge.js
function merge_default(context) {
  var selection2 = context.selection ? context.selection() : context;
  for (var groups0 = this._groups, groups1 = selection2._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {
    for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group0[i] || group1[i]) {
        merge[i] = node;
      }
    }
  }
  for (; j < m0; ++j) {
    merges[j] = groups0[j];
  }
  return new Selection(merges, this._parents);
}

// node_modules/d3-selection/src/selection/order.js
function order_default() {
  for (var groups = this._groups, j = -1, m = groups.length; ++j < m; ) {
    for (var group2 = groups[j], i = group2.length - 1, next2 = group2[i], node; --i >= 0; ) {
      if (node = group2[i]) {
        if (next2 && node.compareDocumentPosition(next2) ^ 4) next2.parentNode.insertBefore(node, next2);
        next2 = node;
      }
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/sort.js
function sort_default(compare) {
  if (!compare) compare = ascending;
  function compareNode(a, b) {
    return a && b ? compare(a.__data__, b.__data__) : !a - !b;
  }
  for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {
    for (var group2 = groups[j], n = group2.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {
      if (node = group2[i]) {
        sortgroup[i] = node;
      }
    }
    sortgroup.sort(compareNode);
  }
  return new Selection(sortgroups, this._parents).order();
}
function ascending(a, b) {
  return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}

// node_modules/d3-selection/src/selection/call.js
function call_default() {
  var callback = arguments[0];
  arguments[0] = this;
  callback.apply(null, arguments);
  return this;
}

// node_modules/d3-selection/src/selection/nodes.js
function nodes_default() {
  return Array.from(this);
}

// node_modules/d3-selection/src/selection/node.js
function node_default() {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group2 = groups[j], i = 0, n = group2.length; i < n; ++i) {
      var node = group2[i];
      if (node) return node;
    }
  }
  return null;
}

// node_modules/d3-selection/src/selection/size.js
function size_default() {
  let size = 0;
  for (const node of this) ++size;
  return size;
}

// node_modules/d3-selection/src/selection/empty.js
function empty_default() {
  return !this.node();
}

// node_modules/d3-selection/src/selection/each.js
function each_default(callback) {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group2 = groups[j], i = 0, n = group2.length, node; i < n; ++i) {
      if (node = group2[i]) callback.call(node, node.__data__, i, group2);
    }
  }
  return this;
}

// node_modules/d3-selection/src/selection/attr.js
function attrRemove(name) {
  return function() {
    this.removeAttribute(name);
  };
}
function attrRemoveNS(fullname) {
  return function() {
    this.removeAttributeNS(fullname.space, fullname.local);
  };
}
function attrConstant(name, value) {
  return function() {
    this.setAttribute(name, value);
  };
}
function attrConstantNS(fullname, value) {
  return function() {
    this.setAttributeNS(fullname.space, fullname.local, value);
  };
}
function attrFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttribute(name);
    else this.setAttribute(name, v);
  };
}
function attrFunctionNS(fullname, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.removeAttributeNS(fullname.space, fullname.local);
    else this.setAttributeNS(fullname.space, fullname.local, v);
  };
}
function attr_default(name, value) {
  var fullname = namespace_default(name);
  if (arguments.length < 2) {
    var node = this.node();
    return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
  }
  return this.each((value == null ? fullname.local ? attrRemoveNS : attrRemove : typeof value === "function" ? fullname.local ? attrFunctionNS : attrFunction : fullname.local ? attrConstantNS : attrConstant)(fullname, value));
}

// node_modules/d3-selection/src/window.js
function window_default(node) {
  return node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView;
}

// node_modules/d3-selection/src/selection/style.js
function styleRemove(name) {
  return function() {
    this.style.removeProperty(name);
  };
}
function styleConstant(name, value, priority) {
  return function() {
    this.style.setProperty(name, value, priority);
  };
}
function styleFunction(name, value, priority) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) this.style.removeProperty(name);
    else this.style.setProperty(name, v, priority);
  };
}
function style_default(name, value, priority) {
  return arguments.length > 1 ? this.each((value == null ? styleRemove : typeof value === "function" ? styleFunction : styleConstant)(name, value, priority == null ? "" : priority)) : styleValue(this.node(), name);
}
function styleValue(node, name) {
  return node.style.getPropertyValue(name) || window_default(node).getComputedStyle(node, null).getPropertyValue(name);
}

// node_modules/d3-selection/src/selection/property.js
function propertyRemove(name) {
  return function() {
    delete this[name];
  };
}
function propertyConstant(name, value) {
  return function() {
    this[name] = value;
  };
}
function propertyFunction(name, value) {
  return function() {
    var v = value.apply(this, arguments);
    if (v == null) delete this[name];
    else this[name] = v;
  };
}
function property_default(name, value) {
  return arguments.length > 1 ? this.each((value == null ? propertyRemove : typeof value === "function" ? propertyFunction : propertyConstant)(name, value)) : this.node()[name];
}

// node_modules/d3-selection/src/selection/classed.js
function classArray(string2) {
  return string2.trim().split(/^|\s+/);
}
function classList(node) {
  return node.classList || new ClassList(node);
}
function ClassList(node) {
  this._node = node;
  this._names = classArray(node.getAttribute("class") || "");
}
ClassList.prototype = {
  add: function(name) {
    var i = this._names.indexOf(name);
    if (i < 0) {
      this._names.push(name);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  remove: function(name) {
    var i = this._names.indexOf(name);
    if (i >= 0) {
      this._names.splice(i, 1);
      this._node.setAttribute("class", this._names.join(" "));
    }
  },
  contains: function(name) {
    return this._names.indexOf(name) >= 0;
  }
};
function classedAdd(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.add(names[i]);
}
function classedRemove(node, names) {
  var list = classList(node), i = -1, n = names.length;
  while (++i < n) list.remove(names[i]);
}
function classedTrue(names) {
  return function() {
    classedAdd(this, names);
  };
}
function classedFalse(names) {
  return function() {
    classedRemove(this, names);
  };
}
function classedFunction(names, value) {
  return function() {
    (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
  };
}
function classed_default(name, value) {
  var names = classArray(name + "");
  if (arguments.length < 2) {
    var list = classList(this.node()), i = -1, n = names.length;
    while (++i < n) if (!list.contains(names[i])) return false;
    return true;
  }
  return this.each((typeof value === "function" ? classedFunction : value ? classedTrue : classedFalse)(names, value));
}

// node_modules/d3-selection/src/selection/text.js
function textRemove() {
  this.textContent = "";
}
function textConstant(value) {
  return function() {
    this.textContent = value;
  };
}
function textFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.textContent = v == null ? "" : v;
  };
}
function text_default(value) {
  return arguments.length ? this.each(value == null ? textRemove : (typeof value === "function" ? textFunction : textConstant)(value)) : this.node().textContent;
}

// node_modules/d3-selection/src/selection/html.js
function htmlRemove() {
  this.innerHTML = "";
}
function htmlConstant(value) {
  return function() {
    this.innerHTML = value;
  };
}
function htmlFunction(value) {
  return function() {
    var v = value.apply(this, arguments);
    this.innerHTML = v == null ? "" : v;
  };
}
function html_default(value) {
  return arguments.length ? this.each(value == null ? htmlRemove : (typeof value === "function" ? htmlFunction : htmlConstant)(value)) : this.node().innerHTML;
}

// node_modules/d3-selection/src/selection/raise.js
function raise() {
  if (this.nextSibling) this.parentNode.appendChild(this);
}
function raise_default() {
  return this.each(raise);
}

// node_modules/d3-selection/src/selection/lower.js
function lower() {
  if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function lower_default() {
  return this.each(lower);
}

// node_modules/d3-selection/src/selection/append.js
function append_default(name) {
  var create = typeof name === "function" ? name : creator_default(name);
  return this.select(function() {
    return this.appendChild(create.apply(this, arguments));
  });
}

// node_modules/d3-selection/src/selection/insert.js
function constantNull() {
  return null;
}
function insert_default(name, before) {
  var create = typeof name === "function" ? name : creator_default(name), select = before == null ? constantNull : typeof before === "function" ? before : selector_default(before);
  return this.select(function() {
    return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
  });
}

// node_modules/d3-selection/src/selection/remove.js
function remove() {
  var parent2 = this.parentNode;
  if (parent2) parent2.removeChild(this);
}
function remove_default() {
  return this.each(remove);
}

// node_modules/d3-selection/src/selection/clone.js
function selection_cloneShallow() {
  var clone = this.cloneNode(false), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function selection_cloneDeep() {
  var clone = this.cloneNode(true), parent2 = this.parentNode;
  return parent2 ? parent2.insertBefore(clone, this.nextSibling) : clone;
}
function clone_default(deep) {
  return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
}

// node_modules/d3-selection/src/selection/datum.js
function datum_default(value) {
  return arguments.length ? this.property("__data__", value) : this.node().__data__;
}

// node_modules/d3-selection/src/selection/on.js
function contextListener(listener) {
  return function(event2) {
    listener.call(this, event2, this.__data__);
  };
}
function parseTypenames(typenames) {
  return typenames.trim().split(/^|\s+/).map(function(t) {
    var name = "", i = t.indexOf(".");
    if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);
    return { type: t, name };
  });
}
function onRemove(typename) {
  return function() {
    var on2 = this.__on;
    if (!on2) return;
    for (var j = 0, i = -1, m = on2.length, o; j < m; ++j) {
      if (o = on2[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
      } else {
        on2[++i] = o;
      }
    }
    if (++i) on2.length = i;
    else delete this.__on;
  };
}
function onAdd(typename, value, options3) {
  return function() {
    var on2 = this.__on, o, listener = contextListener(value);
    if (on2) for (var j = 0, m = on2.length; j < m; ++j) {
      if ((o = on2[j]).type === typename.type && o.name === typename.name) {
        this.removeEventListener(o.type, o.listener, o.options);
        this.addEventListener(o.type, o.listener = listener, o.options = options3);
        o.value = value;
        return;
      }
    }
    this.addEventListener(typename.type, listener, options3);
    o = { type: typename.type, name: typename.name, value, listener, options: options3 };
    if (!on2) this.__on = [o];
    else on2.push(o);
  };
}
function on_default(typename, value, options3) {
  var typenames = parseTypenames(typename + ""), i, n = typenames.length, t;
  if (arguments.length < 2) {
    var on2 = this.node().__on;
    if (on2) for (var j = 0, m = on2.length, o; j < m; ++j) {
      for (i = 0, o = on2[j]; i < n; ++i) {
        if ((t = typenames[i]).type === o.type && t.name === o.name) {
          return o.value;
        }
      }
    }
    return;
  }
  on2 = value ? onAdd : onRemove;
  for (i = 0; i < n; ++i) this.each(on2(typenames[i], value, options3));
  return this;
}

// node_modules/d3-selection/src/selection/dispatch.js
function dispatchEvent(node, type, params) {
  var window2 = window_default(node), event2 = window2.CustomEvent;
  if (typeof event2 === "function") {
    event2 = new event2(type, params);
  } else {
    event2 = window2.document.createEvent("Event");
    if (params) event2.initEvent(type, params.bubbles, params.cancelable), event2.detail = params.detail;
    else event2.initEvent(type, false, false);
  }
  node.dispatchEvent(event2);
}
function dispatchConstant(type, params) {
  return function() {
    return dispatchEvent(this, type, params);
  };
}
function dispatchFunction(type, params) {
  return function() {
    return dispatchEvent(this, type, params.apply(this, arguments));
  };
}
function dispatch_default(type, params) {
  return this.each((typeof params === "function" ? dispatchFunction : dispatchConstant)(type, params));
}

// node_modules/d3-selection/src/selection/iterator.js
function* iterator_default() {
  for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {
    for (var group2 = groups[j], i = 0, n = group2.length, node; i < n; ++i) {
      if (node = group2[i]) yield node;
    }
  }
}

// node_modules/d3-selection/src/selection/index.js
var root = [null];
function Selection(groups, parents) {
  this._groups = groups;
  this._parents = parents;
}
function selection() {
  return new Selection([[document.documentElement]], root);
}
function selection_selection() {
  return this;
}
Selection.prototype = selection.prototype = {
  constructor: Selection,
  select: select_default,
  selectAll: selectAll_default,
  selectChild: selectChild_default,
  selectChildren: selectChildren_default,
  filter: filter_default,
  data: data_default,
  enter: enter_default,
  exit: exit_default,
  join: join_default,
  merge: merge_default,
  selection: selection_selection,
  order: order_default,
  sort: sort_default,
  call: call_default,
  nodes: nodes_default,
  node: node_default,
  size: size_default,
  empty: empty_default,
  each: each_default,
  attr: attr_default,
  style: style_default,
  property: property_default,
  classed: classed_default,
  text: text_default,
  html: html_default,
  raise: raise_default,
  lower: lower_default,
  append: append_default,
  insert: insert_default,
  remove: remove_default,
  clone: clone_default,
  datum: datum_default,
  on: on_default,
  dispatch: dispatch_default,
  [Symbol.iterator]: iterator_default
};

// node_modules/d3-selection/src/select.js
function select_default2(selector) {
  return typeof selector === "string" ? new Selection([[document.querySelector(selector)]], [document.documentElement]) : new Selection([[selector]], root);
}

// node_modules/d3-selection/src/sourceEvent.js
function sourceEvent_default(event2) {
  let sourceEvent;
  while (sourceEvent = event2.sourceEvent) event2 = sourceEvent;
  return event2;
}

// node_modules/d3-selection/src/pointer.js
function pointer_default(event2, node) {
  event2 = sourceEvent_default(event2);
  if (node === void 0) node = event2.currentTarget;
  if (node) {
    var svg = node.ownerSVGElement || node;
    if (svg.createSVGPoint) {
      var point2 = svg.createSVGPoint();
      point2.x = event2.clientX, point2.y = event2.clientY;
      point2 = point2.matrixTransform(node.getScreenCTM().inverse());
      return [point2.x, point2.y];
    }
    if (node.getBoundingClientRect) {
      var rect = node.getBoundingClientRect();
      return [event2.clientX - rect.left - node.clientLeft, event2.clientY - rect.top - node.clientTop];
    }
  }
  return [event2.pageX, event2.pageY];
}

// src/charts/Axis.svelte
var root2 = from_svg(`<g class="zero svelte-1hrei6e"><line class="svelte-1hrei6e"></line></g>`);
var root_1 = from_svg(`<g><!></g>`);
function Axis($$anchor, $$props) {
  push($$props, true);
  let x = prop($$props, "x", 3, false), y = prop($$props, "y", 3, false), inner_height = prop($$props, "inner_height", 3, 0);
  let transform = user_derived(() => x() ? `translate(0,${inner_height().toString()})` : void 0);
  var g = root_1();
  let classes;
  var node_1 = child(g);
  {
    var consequent = ($$anchor2) => {
      var g_1 = root2();
      var line = child(g_1);
      reset(g_1);
      template_effect(
        ($0, $1) => {
          set_attribute(g_1, "transform", $0);
          set_attribute(line, "x2", $1);
        },
        [
          () => `translate(0,${$$props.line_at_zero.toString()})`,
          () => -$$props.axis.tickSizeInner()
        ]
      );
      append($$anchor2, g_1);
    };
    if_block(node_1, ($$render) => {
      if (y() && $$props.line_at_zero != null) $$render(consequent);
    });
  }
  reset(g);
  attach(g, () => (node) => {
    const selection2 = select_default2(node);
    user_effect(() => {
      $$props.axis(selection2);
    });
  });
  template_effect(() => {
    set_attribute(g, "transform", get2(transform));
    classes = set_class(g, 0, "svelte-1hrei6e", null, classes, { y: y() });
  });
  append($$anchor, g);
  pop();
}

// src/charts/context.ts
var operating_currencies_with_conversion = derived(
  [operating_currency, currencies, conversion],
  ([$operating_currency, $currencies, $conversion]) => $currencies.includes($conversion) && !$operating_currency.includes($conversion) ? [...$operating_currency, $conversion] : $operating_currency
);
var [get_chart_tooltip, set_chart_tooltip] = createContext();
var chart_context = derived(
  [operating_currencies_with_conversion, current_date_format],
  ([
    $operating_currencies_with_conversion,
    $current_date_format
  ]) => ({
    currencies: $operating_currencies_with_conversion,
    dateFormat: $current_date_format
  })
);

// src/charts/Brush.svelte
var root3 = from_svg(`<rect y="0" class="svelte-17ogpyx"></rect>`);
var root_12 = from_svg(`<g role="application"><!><!></g>`);
function Brush($$anchor, $$props) {
  push($$props, true);
  const $current_time_filter_date_format = () => store_get(current_time_filter_date_format, "$current_time_filter_date_format", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const DRAG_THRESHOLD = 5;
  const tooltip = get_chart_tooltip();
  let x_start = state(0);
  let x_current = state(0);
  let active_pointer_id = state(void 0);
  let active = user_derived(() => get2(active_pointer_id) != null && Math.abs(get2(x_current) - get2(x_start)) > DRAG_THRESHOLD);
  function onpointerdown(event2) {
    if (get2(active_pointer_id) != null || event2.button !== 0 || event2.ctrlKey || event2.metaKey || event2.shiftKey) {
      return;
    }
    (($$value) => {
      var $$array = to_array($$value, 1);
      set(x_start, $$array[0], true);
    })(pointer_default(event2));
    set(x_current, get2(x_start), true);
    set(active_pointer_id, event2.pointerId, true);
    event2.preventDefault();
  }
  const onpointermove = (event2) => {
    const [x_pointer, y_pointer] = pointer_default(event2);
    if ($$props.find != null) {
      const res = $$props.find(x_pointer, y_pointer);
      const matrix = event2.currentTarget.getCTM();
      if (res && matrix) {
        const [x, y, content] = res;
        const point2 = new DOMPoint(x, y).matrixTransform(matrix);
        tooltip.content(content);
        tooltip.position(point2.x, point2.y);
      } else {
        tooltip.hide();
      }
    }
    if (event2.pointerId !== get2(active_pointer_id)) {
      return;
    }
    set(x_current, x_pointer, true);
  };
  function onpointerup(event2) {
    if (event2.pointerId !== get2(active_pointer_id)) {
      return;
    }
    if (get2(active)) {
      const [x_end] = pointer_default(event2);
      const start_date = $$props.invert(Math.min(get2(x_start), x_end));
      const end_date = $$props.invert(Math.max(get2(x_start), x_end));
      const start = $current_time_filter_date_format()(start_date);
      const end = $current_time_filter_date_format()(end_date);
      const time_filter2 = start === end ? start : `${start} - ${end}`;
      router.set_search_param("time", time_filter2);
    }
    set(active_pointer_id, void 0);
  }
  function onpointerleave() {
    set(active_pointer_id, void 0);
    tooltip.hide();
  }
  var g = root_12();
  var node = child(g);
  snippet(node, () => $$props.children);
  var node_1 = sibling(node);
  {
    var consequent = ($$anchor2) => {
      var rect = root3();
      template_effect(
        ($0, $1) => {
          set_attribute(rect, "x", $0);
          set_attribute(rect, "height", $$props.height);
          set_attribute(rect, "width", $1);
        },
        [
          () => Math.min(get2(x_start), get2(x_current)),
          () => Math.abs(get2(x_current) - get2(x_start))
        ]
      );
      append($$anchor2, rect);
    };
    if_block(node_1, ($$render) => {
      if (get2(active)) $$render(consequent);
    });
  }
  reset(g);
  template_effect(() => {
    set_class(g, 0, clsx({ active: get2(active) }), "svelte-17ogpyx");
    set_attribute(g, "transform", $$props.transform);
  });
  delegated("pointerdown", g, onpointerdown);
  delegated("pointermove", g, onpointermove);
  event("pointerleave", g, onpointerleave);
  delegated("pointerup", g, onpointerup);
  append($$anchor, g);
  pop();
  $$cleanup();
}
delegate(["pointerdown", "pointermove", "pointerup"]);

// src/charts/helpers.ts
function url_for_time_filter(date3) {
  const url = new URL(window.location.href);
  url.searchParams.set(
    "time",
    get(current_time_filter_date_format)(date3)
  );
  return url.toString();
}
function include_zero([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  return [Math.min(0, from), Math.max(0, to)];
}
function pad_extent([from, to]) {
  if (from === void 0) {
    return [0, 1];
  }
  const diff = to - from;
  return [from - diff * 0.03, to + diff * 0.03];
}
function filter_ticks(domain, count) {
  if (domain.length <= count) {
    return domain;
  }
  const showIndices = Math.ceil(domain.length / count);
  return domain.filter((_d, i) => i % showIndices === 0);
}
function hcl_color_range(count, chroma = 45, luminance = 70) {
  const offset = 270;
  const delta = 360 / count;
  const colors = [...Array(count).keys()].map((index2) => {
    const hue = (index2 * delta + offset) % 360;
    return hcl(hue, chroma, luminance);
  });
  return colors.map((c) => c.toString());
}
var colors10 = hcl_color_range(10);
var colors15 = hcl_color_range(15, 30, 80);
var scatterplotScale = ordinal(colors10);
var treemap_scale = derived(
  accounts,
  ($accounts) => ordinal(colors15).domain($accounts)
);
var sunburst_scale = derived(
  accounts,
  ($accounts) => ordinal(colors10).domain($accounts)
);
var currencies_scale = derived(
  [operating_currency, currencies_sorted],
  ([$operating_currency, $currencies_sorted]) => ordinal(colors10).domain([
    ...$operating_currency,
    ...$currencies_sorted
  ])
);

// src/charts/BarChart.svelte
var root4 = from_svg(`<rect></rect><rect class="budget svelte-149r2zk"></rect>`, 1);
var root_13 = from_svg(`<g><rect class="group-box svelte-149r2zk"></rect><a><rect class="axis-group-box svelte-149r2zk"></rect></a><!></g>`);
var root_2 = from_svg(`<rect></rect>`);
var root_3 = from_svg(`<a class="svelte-149r2zk"></a>`);
var root_4 = from_svg(`<g class="stacks svelte-149r2zk"></g>`);
var root_5 = from_svg(`<!><!><!><!>`, 1);
var root_6 = from_svg(`<svg><!></svg>`);
function BarChart($$anchor, $$props) {
  push($$props, true);
  const $chart_toggled_currencies = () => store_get(chart_toggled_currencies, "$chart_toggled_currencies", $$stores);
  const $bar_chart_mode = () => store_get(bar_chart_mode, "$bar_chart_mode", $$stores);
  const $short = () => store_get(short, "$short", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $current_time_filter_date_format = () => store_get(current_time_filter_date_format, "$current_time_filter_date_format", $$stores);
  const $currencies_scale = () => store_get(currencies_scale, "$currencies_scale", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const today = /* @__PURE__ */ new Date();
  const tooltip = get_chart_tooltip();
  const max_column_width = 100;
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const height = 250;
  const inner_height = height - margin.top - margin.bottom;
  let accounts2 = user_derived(() => $$props.chart.accounts);
  let $$d = user_derived(() => $$props.chart.filter($chart_toggled_currencies())), currencies2 = user_derived(() => get2($$d).currencies), bar_groups = user_derived(() => get2($$d).bar_groups), stacks = user_derived(() => get2($$d).stacks);
  let max_width = user_derived(() => get2(bar_groups).length * max_column_width);
  let offset = user_derived(() => margin.left + Math.max(0, $$props.width - get2(max_width)) / 2);
  let inner_width = user_derived(() => Math.min($$props.width - margin.left - margin.right, get2(max_width)));
  let show_stacked_bars = user_derived(() => $bar_chart_mode() === "stacked" && $$props.chart.hasStackedData);
  let x0 = user_derived(() => band([0, get2(inner_width)]).domain(get2(bar_groups).map((d) => d.label)).padding(0.1));
  let x1 = user_derived(() => band([0, get2(x0).bandwidth()]).domain(get2(currencies2)));
  let y_extent = user_derived(() => get2(show_stacked_bars) ? extent(get2(stacks).flatMap(([, s]) => s.flat(2))) : extent(get2(bar_groups).flatMap((d) => d.values), (d) => d.value));
  let y = user_derived(() => linear2([inner_height, 0]).domain(pad_extent(include_zero(get2(y_extent)))));
  let account_color_scale = user_derived(() => ordinal(hcl_color_range(get2(accounts2).length)).domain(get2(accounts2)));
  let x_axis = user_derived(() => axisBottom(get2(x0)).tickSizeOuter(0).tickValues(filter_ticks(get2(x0).domain(), get2(inner_width) / 70)));
  let y_axis = user_derived(() => axisLeft(get2(y)).tickPadding(6).tickSize(-get2(inner_width)).tickFormat($short()));
  function invert(px) {
    const half = get2(x0).bandwidth() / 2;
    const closest = least(get2(bar_groups), ({ label: label2 }) => Math.abs(px - (get2(x0)(label2) ?? 0) - half));
    return closest?.date ?? /* @__PURE__ */ new Date();
  }
  var svg = root_6();
  var node = child(svg);
  {
    let $0 = user_derived(() => `translate(${get2(offset).toString()},${margin.top.toString()})`);
    Brush(node, {
      invert,
      get height() {
        return inner_height;
      },
      get transform() {
        return get2($0);
      },
      children: ($$anchor2, $$slotProps) => {
        var fragment = root_5();
        var node_1 = first_child(fragment);
        Axis(node_1, {
          x: true,
          get axis() {
            return get2(x_axis);
          },
          get inner_height() {
            return inner_height;
          }
        });
        var node_2 = sibling(node_1);
        {
          let $02 = user_derived(() => get2(y)(0));
          Axis(node_2, {
            y: true,
            get axis() {
              return get2(y_axis);
            },
            get line_at_zero() {
              return get2($02);
            }
          });
        }
        var node_3 = sibling(node_2);
        each(node_3, 17, () => get2(bar_groups), (group2) => group2.date, ($$anchor3, group2) => {
          var g = root_13();
          var rect = child(g);
          var a = sibling(rect);
          var rect_1 = child(a);
          reset(a);
          var node_4 = sibling(a);
          {
            var consequent = ($$anchor4) => {
              var fragment_1 = comment();
              var node_5 = first_child(fragment_1);
              each(node_5, 17, () => get2(group2).values, ({ currency, value, budget }) => currency, ($$anchor5, $$item) => {
                let currency = () => get2($$item).currency;
                let value = () => get2($$item).value;
                let budget = () => get2($$item).budget;
                var fragment_2 = root4();
                var rect_2 = first_child(fragment_2);
                var rect_3 = sibling(rect_2);
                template_effect(
                  ($02, $1, $2, $3, $4, $5, $6, $7, $8) => {
                    set_attribute(rect_2, "fill", $02);
                    set_attribute(rect_2, "width", $1);
                    set_attribute(rect_2, "x", $2);
                    set_attribute(rect_2, "y", $3);
                    set_attribute(rect_2, "height", $4);
                    set_attribute(rect_3, "width", $5);
                    set_attribute(rect_3, "x", $6);
                    set_attribute(rect_3, "y", $7);
                    set_attribute(rect_3, "height", $8);
                  },
                  [
                    () => $currencies_scale()(currency()),
                    () => get2(x1).bandwidth(),
                    () => get2(x1)(currency()),
                    () => get2(y)(Math.max(0, value())),
                    () => Math.abs(get2(y)(value()) - get2(y)(0)),
                    () => get2(x1).bandwidth(),
                    () => get2(x1)(currency()),
                    () => get2(y)(Math.max(0, budget())),
                    () => Math.abs(get2(y)(budget()) - get2(y)(0))
                  ]
                );
                append($$anchor5, fragment_2);
              });
              append($$anchor4, fragment_1);
            };
            if_block(node_4, ($$render) => {
              if (!get2(show_stacked_bars)) $$render(consequent);
            });
          }
          reset(g);
          attach(g, () => tooltip.following(() => $$props.chart.tooltip_text($ctx(), get2(group2))));
          template_effect(
            ($02, $1, $2, $3, $4, $5) => {
              set_class(g, 0, clsx(["group", get2(group2).date > today && "desaturate"]), "svelte-149r2zk");
              set_attribute(g, "transform", $02);
              set_attribute(rect, "x", $1);
              set_attribute(rect, "width", $2);
              set_attribute(rect, "height", inner_height);
              set_attribute(a, "href", $3);
              set_attribute(a, "aria-label", $4);
              set_attribute(rect_1, "y", inner_height);
              set_attribute(rect_1, "width", $5);
              set_attribute(rect_1, "height", margin.bottom);
            },
            [
              () => `translate(${(get2(x0)(get2(group2).label) ?? 0).toString()},0)`,
              () => (get2(x0).bandwidth() - get2(x0).step()) / 2,
              () => get2(x0).step(),
              () => url_for_time_filter(get2(group2).date),
              () => $current_time_filter_date_format()(get2(group2).date),
              () => get2(x0).bandwidth()
            ]
          );
          append($$anchor3, g);
        });
        var node_6 = sibling(node_3);
        {
          var consequent_1 = ($$anchor3) => {
            var g_1 = root_4();
            each(g_1, 21, () => get2(stacks), ([currency, account_stacks]) => currency, ($$anchor4, $$item) => {
              var $$array = user_derived(() => to_array(get2($$item), 2));
              let currency = () => get2($$array)[0];
              let account_stacks = () => get2($$array)[1];
              var fragment_3 = comment();
              var node_7 = first_child(fragment_3);
              each(node_7, 17, account_stacks, (stack) => stack.key, ($$anchor5, stack) => {
                const account = user_derived(() => get2(stack).key);
                var a_1 = root_3();
                each(a_1, 21, () => get2(stack), (bar) => bar.data.date, ($$anchor6, bar) => {
                  var rect_4 = root_2();
                  attach(rect_4, () => tooltip.following(() => $$props.chart.tooltip_text_account($ctx(), get2(bar).data, get2(account), $chart_toggled_currencies())));
                  template_effect(
                    ($02, $1, $2, $3, $4) => {
                      set_class(rect_4, 0, clsx([get2(bar).data.date > today && "desaturate"]), "svelte-149r2zk");
                      set_attribute(rect_4, "width", $02);
                      set_attribute(rect_4, "x", $1);
                      set_attribute(rect_4, "y", $2);
                      set_attribute(rect_4, "height", $3);
                      set_attribute(rect_4, "fill", $4);
                    },
                    [
                      () => get2(x1).bandwidth(),
                      () => (get2(x0)(get2(bar).data.label) ?? 0) + (get2(x1)(currency()) ?? 0),
                      () => get2(y)(Math.max(get2(bar)[0], get2(bar)[1])),
                      () => Math.abs(get2(y)(get2(bar)[1]) - get2(y)(get2(bar)[0])),
                      () => get2(account_color_scale)(get2(account))
                    ]
                  );
                  append($$anchor6, rect_4);
                });
                reset(a_1);
                template_effect(($02) => set_attribute(a_1, "href", $02), [() => $url_for_account()(get2(account))]);
                append($$anchor5, a_1);
              });
              append($$anchor4, fragment_3);
            });
            reset(g_1);
            append($$anchor3, g_1);
          };
          if_block(node_6, ($$render) => {
            if (get2(show_stacked_bars)) $$render(consequent_1);
          });
        }
        append($$anchor2, fragment);
      },
      $$slots: { default: true }
    });
  }
  reset(svg);
  template_effect(($0) => set_attribute(svg, "viewBox", $0), [() => `0 0 ${$$props.width.toString()} ${height.toString()}`]);
  append($$anchor, svg);
  pop();
  $$cleanup();
}

// src/charts/ChartLegend.svelte
var root5 = from_html(`<button type="button"><i class="svelte-2a4xq8"></i> <span class="svelte-2a4xq8"> </span></button>`);
var root_14 = from_html(`<div></div>`);
function ChartLegend($$anchor, $$props) {
  push($$props, true);
  const $active = () => store_get($$props.active, "$active", $$stores);
  const $toggled = () => store_get($$props.toggled, "$toggled", $$stores);
  const $currencies_scale = () => store_get(currencies_scale, "$currencies_scale", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var div = root_14();
  each(div, 20, () => $$props.legend, (item) => item, ($$anchor2, item) => {
    var button = root5();
    let classes;
    var i_1 = child(button);
    var span = sibling(i_1, 2);
    var text2 = child(span, true);
    reset(span);
    reset(button);
    template_effect(
      ($0, $1) => {
        classes = set_class(button, 1, "svelte-2a4xq8", null, classes, $0);
        set_style(i_1, `background-color: ${$1 ?? ""}`);
        set_text(text2, item);
      },
      [
        () => ({
          inactive: $$props.active ? item !== $active() : $toggled()?.includes(item)
        }),
        () => $$props.color ? $currencies_scale()(item) : "#bbb"
      ]
    );
    delegated("click", button, () => {
      if ($$props.active) {
        $$props.active.set(item);
      } else if ($$props.toggled) {
        $$props.toggled.update((v) => v.includes(item) ? v.filter((i) => i !== item) : [...v, item]);
      }
    });
    append($$anchor2, button);
  });
  reset(div);
  append($$anchor, div);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/charts/Icicle.svelte
var root_15 = from_svg(`<g><a><rect fill-rule="evenodd" role="img"></rect><text dy=".5em" text-anchor="middle" class="svelte-p3l8ik"> </text></a></g>`);
var root_22 = from_svg(`<g role="img" class="svelte-p3l8ik"></g>`);
function Icicle($$anchor, $$props) {
  push($$props, true);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const $sunburst_scale = () => store_get(sunburst_scale, "$sunburst_scale", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const tooltip = get_chart_tooltip();
  let root93 = user_derived(() => partition_default()($$props.data));
  let nodes = user_derived(() => get2(root93).descendants().filter((d) => !d.data.dummy));
  let current = state(void 0);
  var g = root_22();
  each(g, 21, () => get2(nodes), (d) => d.data.account, ($$anchor2, d) => {
    const account = user_derived(() => get2(d).data.account);
    var g_1 = root_15();
    let classes;
    var a = child(g_1);
    var rect = child(a);
    var text2 = sibling(rect);
    var text_1 = child(text2, true);
    reset(text2);
    reset(a);
    reset(g_1);
    attach(g_1, () => tooltip.following(() => [
      balance_with_percentage($ctx(), get2(d), $$props.currency),
      domHelpers.em(get2(account))
    ]));
    template_effect(
      ($0, $1, $2, $3) => {
        classes = set_class(g_1, 0, "svelte-p3l8ik", null, classes, $0);
        set_attribute(a, "href", $1);
        set_attribute(a, "aria-label", get2(account));
        set_attribute(rect, "fill", $2);
        set_attribute(rect, "width", $$props.width * (get2(d).y1 - get2(d).y0));
        set_attribute(rect, "height", $$props.height * (get2(d).x1 - get2(d).x0));
        set_attribute(rect, "x", $$props.width * get2(d).y0);
        set_attribute(rect, "y", $$props.height * get2(d).x0);
        set_attribute(text2, "x", $$props.width * (get2(d).y1 + get2(d).y0) / 2);
        set_attribute(text2, "y", $$props.height * (get2(d).x1 + get2(d).x0) / 2);
        set_attribute(text2, "visibility", $$props.height * (get2(d).x1 - get2(d).x0) > 14 ? "visible" : "hidden");
        set_text(text_1, $3);
      },
      [
        () => ({
          current: get2(current) != null ? get2(current).startsWith(get2(account)) : false
        }),
        () => $url_for_account()(get2(account)),
        () => $sunburst_scale()(get2(account)),
        () => leaf(get2(account))
      ]
    );
    delegated("mouseover", a, () => {
      set(current, get2(account), true);
    });
    event("focus", a, () => {
      set(current, get2(account), true);
    });
    append($$anchor2, g_1);
  });
  reset(g);
  template_effect(() => {
    set_attribute(g, "width", $$props.width);
    set_attribute(g, "height", $$props.height);
  });
  event("mouseleave", g, () => {
    set(current, void 0);
  });
  append($$anchor, g);
  pop();
  $$cleanup();
}
delegate(["mouseover"]);

// src/charts/Sunburst.svelte
var root_16 = from_svg(`<a><path fill-rule="evenodd" role="img"></path></a>`);
var root_23 = from_svg(`<g role="img"><circle class="svelte-wb1b3x"></circle><text class="account svelte-wb1b3x" text-anchor="middle"> </text><text class="balance svelte-wb1b3x" dy="1.2em" text-anchor="middle"> </text><!></g>`);
function Sunburst($$anchor, $$props) {
  push($$props, true);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const $sunburst_scale = () => store_get(sunburst_scale, "$sunburst_scale", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let radius = user_derived(() => Math.min($$props.width, $$props.height) / 2);
  let root93 = user_derived(() => partition_default()($$props.data));
  let nodes = user_derived(() => get2(root93).descendants().filter((d) => !d.data.dummy && d.depth > 0));
  let current = state(void 0);
  user_pre_effect(() => {
    void $$props.data;
    untrack(() => {
      set(current, void 0);
    });
  });
  const x = linear2([0, 2 * Math.PI]);
  let y = user_derived(() => sqrt([0, get2(radius)]));
  let arcShape = user_derived(() => arc_default().startAngle((d) => x(d.x0)).endAngle((d) => x(d.x1)).innerRadius((d) => get2(y)(d.y0)).outerRadius((d) => get2(y)(d.y1)));
  var g = root_23();
  var circle = child(g);
  var text2 = sibling(circle);
  var text_1 = child(text2, true);
  reset(text2);
  var text_2 = sibling(text2);
  var text_3 = child(text_2, true);
  reset(text_2);
  var node = sibling(text_2);
  each(node, 17, () => get2(nodes), (d) => d.data.account, ($$anchor2, d) => {
    var a = root_16();
    var path = child(a);
    let classes;
    reset(a);
    template_effect(
      ($0, $1, $2, $3) => {
        set_attribute(a, "href", $0);
        set_attribute(a, "aria-label", get2(d).data.account);
        set_attribute(path, "fill", $1);
        set_attribute(path, "d", $2);
        classes = set_class(path, 0, "svelte-wb1b3x", null, classes, $3);
      },
      [
        () => $url_for_account()(get2(d).data.account),
        () => $sunburst_scale()(get2(d).data.account),
        () => get2(arcShape)(get2(d)),
        () => ({
          half: get2(current) && !get2(current).data.account.startsWith(get2(d).data.account)
        })
      ]
    );
    delegated("mouseover", path, () => {
      set(current, get2(d), true);
    });
    event("focus", path, () => {
      set(current, get2(d), true);
    });
    append($$anchor2, a);
  });
  reset(g);
  template_effect(
    ($0, $1) => {
      set_attribute(g, "width", $$props.width);
      set_attribute(g, "height", $$props.height);
      set_attribute(g, "transform", $0);
      set_attribute(circle, "r", get2(radius));
      set_text(text_1, (get2(current) ?? get2(root93)).data.account);
      set_text(text_3, $1);
    },
    [
      () => `translate(${($$props.width / 2).toString()},${($$props.height / 2).toString()})`,
      () => balance_with_percentage($ctx(), get2(current) ?? get2(root93), $$props.currency)
    ]
  );
  event("mouseleave", g, () => {
    set(current, void 0);
  });
  append($$anchor, g);
  pop();
  $$cleanup();
}
delegate(["mouseover"]);

// src/charts/Treemap.svelte
var root_17 = from_svg(`<g><rect></rect><a><text dy=".5em" text-anchor="middle" class="svelte-1cyp5vn"> </text></a></g>`);
var root_24 = from_svg(`<svg class="svelte-1cyp5vn"></svg>`);
function Treemap($$anchor, $$props) {
  push($$props, true);
  const $treemap_scale = () => store_get(treemap_scale, "$treemap_scale", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const tooltip = get_chart_tooltip();
  const tree = treemap_default().paddingInner(2).round(true);
  let root93 = user_derived(() => tree.size([$$props.width, $$props.height])($$props.data.copy()));
  let leaves = user_derived(() => get2(root93).leaves().filter((d) => d.value != null && d.value !== 0));
  function fill(d) {
    const node = d.data.dummy && d.parent ? d.parent : d;
    return $treemap_scale()(node.depth === 1 || !node.parent ? node.data.account : node.parent.data.account);
  }
  var svg = root_24();
  each(svg, 21, () => get2(leaves), (d) => d.data.account, ($$anchor2, d) => {
    const account = user_derived(() => get2(d).data.account);
    var g = root_17();
    var rect = child(g);
    var a = sibling(rect);
    var text2 = child(a);
    var text_1 = child(text2, true);
    reset(text2);
    attach(text2, () => (node) => {
      const length = node.getComputedTextLength();
      node.style.visibility = get2(d).x1 - get2(d).x0 > length + 4 && get2(d).y1 - get2(d).y0 > 14 ? "visible" : "hidden";
    });
    reset(a);
    reset(g);
    attach(g, () => tooltip.following(() => [
      balance_with_percentage($ctx(), get2(d), $$props.currency),
      domHelpers.em(get2(account))
    ]));
    template_effect(
      ($0, $1, $2, $3) => {
        set_attribute(g, "transform", $0);
        set_attribute(rect, "fill", $1);
        set_attribute(rect, "width", get2(d).x1 - get2(d).x0);
        set_attribute(rect, "height", get2(d).y1 - get2(d).y0);
        set_attribute(a, "href", $2);
        set_attribute(text2, "x", (get2(d).x1 - get2(d).x0) / 2);
        set_attribute(text2, "y", (get2(d).y1 - get2(d).y0) / 2);
        set_text(text_1, $3);
      },
      [
        () => `translate(${get2(d).x0.toString()},${get2(d).y0.toString()})`,
        () => fill(get2(d)),
        () => $url_for_account()(get2(account)),
        () => leaf(get2(account))
      ]
    );
    append($$anchor2, g);
  });
  reset(svg);
  template_effect(($0) => set_attribute(svg, "viewBox", $0), [
    () => `0 0 ${$$props.width.toString()} ${$$props.height.toString()}`
  ]);
  append($$anchor, svg);
  pop();
  $$cleanup();
}

// src/charts/HierarchyContainer.svelte
var root6 = from_svg(`<svg><text text-anchor="middle"> </text></svg>`);
var root_18 = from_svg(`<g><!></g>`);
var root_25 = from_svg(`<svg></svg>`);
function HierarchyContainer($$anchor, $$props) {
  push($$props, true);
  const $hierarchy_chart_mode = () => store_get(hierarchy_chart_mode, "$hierarchy_chart_mode", $$stores);
  const $treemap_currency = () => store_get(get2(treemap_currency), "$treemap_currency", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let data = user_derived(() => $$props.chart.data);
  let currencies2 = user_derived(() => $$props.chart.currencies);
  let treemap_currency = user_derived(() => $$props.chart.treemap_currency);
  let mode = user_derived($hierarchy_chart_mode);
  let treemap = user_derived(() => get2(mode) === "treemap" ? get2(data).get($treemap_currency() ?? "") : void 0);
  let treemap_height = user_derived(() => Math.min($$props.width / 2.5, 400));
  let sunburst_height = 500;
  let icicle_height = user_derived(() => Math.min($$props.width / 2.5, 400));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var svg = root6();
      var text2 = child(svg);
      set_attribute(text2, "y", 80);
      var text_1 = child(text2, true);
      reset(text2);
      reset(svg);
      template_effect(
        ($0, $1) => {
          set_attribute(svg, "viewBox", $0);
          set_attribute(text2, "x", $$props.width / 2);
          set_text(text_1, $1);
        },
        [
          () => `0 0 ${$$props.width.toString()} 160`,
          () => _("Chart is empty.")
        ]
      );
      append($$anchor2, svg);
    };
    var consequent_1 = ($$anchor2) => {
      Treemap($$anchor2, {
        get data() {
          return get2(treemap);
        },
        get currency() {
          return $treemap_currency();
        },
        get width() {
          return $$props.width;
        },
        get height() {
          return get2(treemap_height);
        }
      });
    };
    var consequent_2 = ($$anchor2) => {
      const single_width = user_derived(() => $$props.width / get2(currencies2).length);
      var svg_1 = root_25();
      each(svg_1, 23, () => [...get2(data)], ([chart_currency, d]) => chart_currency, ($$anchor3, $$item, i) => {
        var $$array = user_derived(() => to_array(get2($$item), 2));
        let chart_currency = () => get2($$array)[0];
        let d = () => get2($$array)[1];
        var g = root_18();
        var node_1 = child(g);
        Sunburst(node_1, {
          get data() {
            return d();
          },
          get currency() {
            return chart_currency();
          },
          get width() {
            return get2(single_width);
          },
          height: sunburst_height
        });
        reset(g);
        template_effect(($0) => set_attribute(g, "transform", $0), [
          () => `translate(${(get2(single_width) * get2(i)).toString()},0)`
        ]);
        append($$anchor3, g);
      });
      reset(svg_1);
      template_effect(($0) => set_attribute(svg_1, "viewBox", $0), [
        () => `0 0 ${$$props.width.toString()} ${sunburst_height.toString()}`
      ]);
      append($$anchor2, svg_1);
    };
    var consequent_3 = ($$anchor2) => {
      const single_width = user_derived(() => $$props.width / get2(currencies2).length);
      var svg_2 = root_25();
      each(svg_2, 23, () => [...get2(data)], ([chart_currency, d]) => chart_currency, ($$anchor3, $$item, i) => {
        var $$array_1 = user_derived(() => to_array(get2($$item), 2));
        let chart_currency = () => get2($$array_1)[0];
        let d = () => get2($$array_1)[1];
        var g_1 = root_18();
        var node_2 = child(g_1);
        Icicle(node_2, {
          get data() {
            return d();
          },
          get currency() {
            return chart_currency();
          },
          get width() {
            return get2(single_width);
          },
          get height() {
            return get2(icicle_height);
          }
        });
        reset(g_1);
        template_effect(($0) => set_attribute(g_1, "transform", $0), [
          () => `translate(${(get2(single_width) * get2(i)).toString()},0)`
        ]);
        append($$anchor3, g_1);
      });
      reset(svg_2);
      template_effect(($0) => set_attribute(svg_2, "viewBox", $0), [
        () => `0 0 ${$$props.width.toString()} ${get2(icicle_height).toString()}`
      ]);
      append($$anchor2, svg_2);
    };
    if_block(node, ($$render) => {
      if (get2(currencies2).length === 0) $$render(consequent);
      else if (get2(treemap) && $treemap_currency()) $$render(consequent_1, 1);
      else if (get2(mode) === "sunburst") $$render(consequent_2, 2);
      else if (get2(mode) === "icicle") $$render(consequent_3, 3);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// node_modules/d3-quadtree/src/add.js
function add_default(d) {
  const x = +this._x.call(null, d), y = +this._y.call(null, d);
  return add(this.cover(x, y), x, y, d);
}
function add(tree, x, y, d) {
  if (isNaN(x) || isNaN(y)) return tree;
  var parent2, node = tree._root, leaf2 = { data: d }, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right2, bottom2, i, j;
  if (!node) return tree._root = leaf2, tree;
  while (node.length) {
    if (right2 = x >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
    if (parent2 = node, !(node = node[i = bottom2 << 1 | right2])) return parent2[i] = leaf2, tree;
  }
  xp = +tree._x.call(null, node.data);
  yp = +tree._y.call(null, node.data);
  if (x === xp && y === yp) return leaf2.next = node, parent2 ? parent2[i] = leaf2 : tree._root = leaf2, tree;
  do {
    parent2 = parent2 ? parent2[i] = new Array(4) : tree._root = new Array(4);
    if (right2 = x >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
  } while ((i = bottom2 << 1 | right2) === (j = (yp >= ym) << 1 | xp >= xm));
  return parent2[j] = node, parent2[i] = leaf2, tree;
}
function addAll(data) {
  var d, i, n = data.length, x, y, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
  for (i = 0; i < n; ++i) {
    if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;
    xz[i] = x;
    yz[i] = y;
    if (x < x0) x0 = x;
    if (x > x1) x1 = x;
    if (y < y0) y0 = y;
    if (y > y1) y1 = y;
  }
  if (x0 > x1 || y0 > y1) return this;
  this.cover(x0, y0).cover(x1, y1);
  for (i = 0; i < n; ++i) {
    add(this, xz[i], yz[i], data[i]);
  }
  return this;
}

// node_modules/d3-quadtree/src/cover.js
function cover_default(x, y) {
  if (isNaN(x = +x) || isNaN(y = +y)) return this;
  var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
  if (isNaN(x0)) {
    x1 = (x0 = Math.floor(x)) + 1;
    y1 = (y0 = Math.floor(y)) + 1;
  } else {
    var z = x1 - x0 || 1, node = this._root, parent2, i;
    while (x0 > x || x >= x1 || y0 > y || y >= y1) {
      i = (y < y0) << 1 | x < x0;
      parent2 = new Array(4), parent2[i] = node, node = parent2, z *= 2;
      switch (i) {
        case 0:
          x1 = x0 + z, y1 = y0 + z;
          break;
        case 1:
          x0 = x1 - z, y1 = y0 + z;
          break;
        case 2:
          x1 = x0 + z, y0 = y1 - z;
          break;
        case 3:
          x0 = x1 - z, y0 = y1 - z;
          break;
      }
    }
    if (this._root && this._root.length) this._root = node;
  }
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  return this;
}

// node_modules/d3-quadtree/src/data.js
function data_default2() {
  var data = [];
  this.visit(function(node) {
    if (!node.length) do
      data.push(node.data);
    while (node = node.next);
  });
  return data;
}

// node_modules/d3-quadtree/src/extent.js
function extent_default(_2) {
  return arguments.length ? this.cover(+_2[0][0], +_2[0][1]).cover(+_2[1][0], +_2[1][1]) : isNaN(this._x0) ? void 0 : [[this._x0, this._y0], [this._x1, this._y1]];
}

// node_modules/d3-quadtree/src/quad.js
function quad_default(node, x0, y0, x1, y1) {
  this.node = node;
  this.x0 = x0;
  this.y0 = y0;
  this.x1 = x1;
  this.y1 = y1;
}

// node_modules/d3-quadtree/src/find.js
function find_default(x, y, radius) {
  var data, x0 = this._x0, y0 = this._y0, x1, y1, x2, y2, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i;
  if (node) quads.push(new quad_default(node, x0, y0, x3, y3));
  if (radius == null) radius = Infinity;
  else {
    x0 = x - radius, y0 = y - radius;
    x3 = x + radius, y3 = y + radius;
    radius *= radius;
  }
  while (q = quads.pop()) {
    if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x2 = q.x1) < x0 || (y2 = q.y1) < y0) continue;
    if (node.length) {
      var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2;
      quads.push(
        new quad_default(node[3], xm, ym, x2, y2),
        new quad_default(node[2], x1, ym, xm, y2),
        new quad_default(node[1], xm, y1, x2, ym),
        new quad_default(node[0], x1, y1, xm, ym)
      );
      if (i = (y >= ym) << 1 | x >= xm) {
        q = quads[quads.length - 1];
        quads[quads.length - 1] = quads[quads.length - 1 - i];
        quads[quads.length - 1 - i] = q;
      }
    } else {
      var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
      if (d2 < radius) {
        var d = Math.sqrt(radius = d2);
        x0 = x - d, y0 = y - d;
        x3 = x + d, y3 = y + d;
        data = node.data;
      }
    }
  }
  return data;
}

// node_modules/d3-quadtree/src/remove.js
function remove_default2(d) {
  if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this;
  var parent2, node = this._root, retainer, previous, next2, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x, y, xm, ym, right2, bottom2, i, j;
  if (!node) return this;
  if (node.length) while (true) {
    if (right2 = x >= (xm = (x0 + x1) / 2)) x0 = xm;
    else x1 = xm;
    if (bottom2 = y >= (ym = (y0 + y1) / 2)) y0 = ym;
    else y1 = ym;
    if (!(parent2 = node, node = node[i = bottom2 << 1 | right2])) return this;
    if (!node.length) break;
    if (parent2[i + 1 & 3] || parent2[i + 2 & 3] || parent2[i + 3 & 3]) retainer = parent2, j = i;
  }
  while (node.data !== d) if (!(previous = node, node = node.next)) return this;
  if (next2 = node.next) delete node.next;
  if (previous) return next2 ? previous.next = next2 : delete previous.next, this;
  if (!parent2) return this._root = next2, this;
  next2 ? parent2[i] = next2 : delete parent2[i];
  if ((node = parent2[0] || parent2[1] || parent2[2] || parent2[3]) && node === (parent2[3] || parent2[2] || parent2[1] || parent2[0]) && !node.length) {
    if (retainer) retainer[j] = node;
    else this._root = node;
  }
  return this;
}
function removeAll(data) {
  for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);
  return this;
}

// node_modules/d3-quadtree/src/root.js
function root_default() {
  return this._root;
}

// node_modules/d3-quadtree/src/size.js
function size_default2() {
  var size = 0;
  this.visit(function(node) {
    if (!node.length) do
      ++size;
    while (node = node.next);
  });
  return size;
}

// node_modules/d3-quadtree/src/visit.js
function visit_default(callback) {
  var quads = [], q, node = this._root, child2, x0, y0, x1, y1;
  if (node) quads.push(new quad_default(node, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
      var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child2 = node[3]) quads.push(new quad_default(child2, xm, ym, x1, y1));
      if (child2 = node[2]) quads.push(new quad_default(child2, x0, ym, xm, y1));
      if (child2 = node[1]) quads.push(new quad_default(child2, xm, y0, x1, ym));
      if (child2 = node[0]) quads.push(new quad_default(child2, x0, y0, xm, ym));
    }
  }
  return this;
}

// node_modules/d3-quadtree/src/visitAfter.js
function visitAfter_default(callback) {
  var quads = [], next2 = [], q;
  if (this._root) quads.push(new quad_default(this._root, this._x0, this._y0, this._x1, this._y1));
  while (q = quads.pop()) {
    var node = q.node;
    if (node.length) {
      var child2, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
      if (child2 = node[0]) quads.push(new quad_default(child2, x0, y0, xm, ym));
      if (child2 = node[1]) quads.push(new quad_default(child2, xm, y0, x1, ym));
      if (child2 = node[2]) quads.push(new quad_default(child2, x0, ym, xm, y1));
      if (child2 = node[3]) quads.push(new quad_default(child2, xm, ym, x1, y1));
    }
    next2.push(q);
  }
  while (q = next2.pop()) {
    callback(q.node, q.x0, q.y0, q.x1, q.y1);
  }
  return this;
}

// node_modules/d3-quadtree/src/x.js
function defaultX(d) {
  return d[0];
}
function x_default(_2) {
  return arguments.length ? (this._x = _2, this) : this._x;
}

// node_modules/d3-quadtree/src/y.js
function defaultY(d) {
  return d[1];
}
function y_default(_2) {
  return arguments.length ? (this._y = _2, this) : this._y;
}

// node_modules/d3-quadtree/src/quadtree.js
function quadtree(nodes, x, y) {
  var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);
  return nodes == null ? tree : tree.addAll(nodes);
}
function Quadtree(x, y, x0, y0, x1, y1) {
  this._x = x;
  this._y = y;
  this._x0 = x0;
  this._y0 = y0;
  this._x1 = x1;
  this._y1 = y1;
  this._root = void 0;
}
function leaf_copy(leaf2) {
  var copy2 = { data: leaf2.data }, next2 = copy2;
  while (leaf2 = leaf2.next) next2 = next2.next = { data: leaf2.data };
  return copy2;
}
var treeProto = quadtree.prototype = Quadtree.prototype;
treeProto.copy = function() {
  var copy2 = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child2;
  if (!node) return copy2;
  if (!node.length) return copy2._root = leaf_copy(node), copy2;
  nodes = [{ source: node, target: copy2._root = new Array(4) }];
  while (node = nodes.pop()) {
    for (var i = 0; i < 4; ++i) {
      if (child2 = node.source[i]) {
        if (child2.length) nodes.push({ source: child2, target: node.target[i] = new Array(4) });
        else node.target[i] = leaf_copy(child2);
      }
    }
  }
  return copy2;
};
treeProto.add = add_default;
treeProto.addAll = addAll;
treeProto.cover = cover_default;
treeProto.data = data_default2;
treeProto.extent = extent_default;
treeProto.find = find_default;
treeProto.remove = remove_default2;
treeProto.removeAll = removeAll;
treeProto.root = root_default;
treeProto.size = size_default2;
treeProto.visit = visit_default;
treeProto.visitAfter = visitAfter_default;
treeProto.x = x_default;
treeProto.y = y_default;

// src/charts/LineChart.svelte
var root7 = from_svg(`<path class="svelte-1ri0k4j"></path>`);
var root_19 = from_svg(`<g class="area svelte-1ri0k4j"></g>`);
var root_26 = from_svg(`<circle r="2"></circle>`);
var root_32 = from_svg(`<g></g>`);
var root_42 = from_svg(`<!><!><!><g class="lines svelte-1ri0k4j"></g><!>`, 1);
var root_52 = from_svg(`<svg><defs><filter><feColorMatrix type="saturate" values="0.5"></feColorMatrix><feBlend in2="SourceGraphic"></feBlend></filter></defs><!></svg>`);
function LineChart2($$anchor, $$props) {
  const uid = props_id();
  push($$props, true);
  const $chart_toggled_currencies = () => store_get(chart_toggled_currencies, "$chart_toggled_currencies", $$stores);
  const $line_chart_mode = () => store_get(line_chart_mode, "$line_chart_mode", $$stores);
  const $short = () => store_get(short, "$short", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $currencies_scale = () => store_get(currencies_scale, "$currencies_scale", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 40 };
  const height = 250;
  const inner_height = height - margin.top - margin.bottom;
  let inner_width = user_derived(() => $$props.width - margin.left - margin.right);
  let data = user_derived(() => $$props.chart.filter($chart_toggled_currencies()));
  let all_values = user_derived(() => get2(data).flatMap((d) => d.values));
  let x_extent = user_derived(() => [
    min(get2(data), (s) => s.values[0]?.date) ?? today,
    max(get2(data), (s) => s.values[s.values.length - 1]?.date) ?? today
  ]);
  let x = user_derived(() => utcTime([0, get2(inner_width)]).domain(get2(x_extent)));
  let value_extent = user_derived(() => extent(get2(all_values), (v) => v.value));
  let y_extent = user_derived(() => $line_chart_mode() === "area" ? include_zero(get2(value_extent)) : get2(value_extent));
  let y = user_derived(() => linear2([inner_height, 0]).domain(pad_extent(get2(y_extent))));
  let quad = user_derived(() => quadtree(get2(all_values), (d) => get2(x)(d.date), (d) => get2(y)(d.value)));
  let line_shape = user_derived(() => line_default().x((d) => get2(x)(d.date)).y((d) => get2(y)(d.value)).curve(stepAfter));
  let area_shape = user_derived(() => area_default().x((d) => get2(x)(d.date)).y1((d) => get2(y)(d.value)).y0(Math.min(inner_height, get2(y)(0))).curve(stepAfter));
  let x_axis = user_derived(() => axisBottom(get2(x)).tickSizeOuter(0));
  let y_axis = user_derived(() => axisLeft(get2(y)).tickPadding(6).tickSize(-get2(inner_width)).tickFormat($short()));
  const tooltip_find = (x_pointer, y_pointer) => {
    const d = get2(quad).find(x_pointer, y_pointer);
    return d && [
      get2(x)(d.date),
      get2(y)(d.value),
      $$props.chart.tooltip_text($ctx(), d)
    ];
  };
  let desaturate_filter_id = user_derived(() => `desaturate-future-${uid}`);
  let desaturate_future_filter = user_derived(() => get2(x_extent)[1] > today ? `url(#${get2(desaturate_filter_id)})` : void 0);
  var svg = root_52();
  var defs = child(svg);
  var filter2 = child(defs);
  var feColorMatrix = child(filter2);
  next();
  reset(filter2);
  reset(defs);
  var node = sibling(defs);
  {
    let $0 = user_derived(() => get2(x).invert.bind(get2(x)));
    let $1 = user_derived(() => `translate(${margin.left.toString()},${margin.top.toString()})`);
    Brush(node, {
      get invert() {
        return get2($0);
      },
      get height() {
        return inner_height;
      },
      find: tooltip_find,
      get transform() {
        return get2($1);
      },
      children: ($$anchor2, $$slotProps) => {
        var fragment = root_42();
        var node_1 = first_child(fragment);
        Axis(node_1, {
          x: true,
          get axis() {
            return get2(x_axis);
          },
          get inner_height() {
            return inner_height;
          }
        });
        var node_2 = sibling(node_1);
        Axis(node_2, {
          y: true,
          get axis() {
            return get2(y_axis);
          }
        });
        var node_3 = sibling(node_2);
        {
          var consequent = ($$anchor3) => {
            var g = root_19();
            each(g, 21, () => get2(data), (d) => d.name, ($$anchor4, d) => {
              var path = root7();
              template_effect(
                ($02, $12) => {
                  set_attribute(path, "d", $02);
                  set_attribute(path, "fill", $12);
                },
                [
                  () => get2(area_shape)(get2(d).values),
                  () => $currencies_scale()(get2(d).name)
                ]
              );
              append($$anchor4, path);
            });
            reset(g);
            template_effect(() => set_attribute(g, "filter", get2(desaturate_future_filter)));
            append($$anchor3, g);
          };
          if_block(node_3, ($$render) => {
            if ($line_chart_mode() === "area") $$render(consequent);
          });
        }
        var g_1 = sibling(node_3);
        each(g_1, 21, () => get2(data), (d) => d.name, ($$anchor3, d) => {
          var path_1 = root7();
          template_effect(
            ($02, $12) => {
              set_attribute(path_1, "d", $02);
              set_attribute(path_1, "stroke", $12);
            },
            [
              () => get2(line_shape)(get2(d).values),
              () => $currencies_scale()(get2(d).name)
            ]
          );
          append($$anchor3, path_1);
        });
        reset(g_1);
        var node_4 = sibling(g_1);
        {
          var consequent_1 = ($$anchor3) => {
            var g_2 = root_32();
            each(g_2, 21, () => get2(data), (d) => d.name, ($$anchor4, d) => {
              var g_3 = root_32();
              each(g_3, 21, () => get2(d).values, (v) => v.date, ($$anchor5, v) => {
                var circle = root_26();
                let classes;
                template_effect(
                  ($02, $12) => {
                    set_attribute(circle, "cx", $02);
                    set_attribute(circle, "cy", $12);
                    classes = set_class(circle, 0, "svelte-1ri0k4j", null, classes, { desaturate: get2(v).date > today });
                  },
                  [
                    () => get2(x)(get2(v).date),
                    () => get2(y)(get2(v).value)
                  ]
                );
                append($$anchor5, circle);
              });
              reset(g_3);
              template_effect(($02) => set_attribute(g_3, "fill", $02), [() => $currencies_scale()(get2(d).name)]);
              append($$anchor4, g_3);
            });
            reset(g_2);
            append($$anchor3, g_2);
          };
          if_block(node_4, ($$render) => {
            if ($line_chart_mode() === "line") $$render(consequent_1);
          });
        }
        template_effect(() => set_attribute(g_1, "filter", get2(desaturate_future_filter)));
        append($$anchor2, fragment);
      },
      $$slots: { default: true }
    });
  }
  reset(svg);
  template_effect(
    ($0, $1) => {
      set_attribute(svg, "viewBox", $0);
      set_attribute(filter2, "id", get2(desaturate_filter_id));
      set_attribute(feColorMatrix, "x", $1);
    },
    [
      () => `0 0 ${$$props.width.toString()} ${height.toString()}`,
      () => get2(x)(today)
    ]
  );
  append($$anchor, svg);
  pop();
  $$cleanup();
}

// src/charts/ModeSwitch.svelte
var root8 = from_html(`<label><input type="radio" class="svelte-jgdjh0"/> </label>`);
var root_110 = from_html(`<span></span>`);
function ModeSwitch($$anchor, $$props) {
  push($$props, true);
  const $store = () => store_get($$props.store, "$store", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const binding_group = [];
  var span = root_110();
  each(span, 21, () => $$props.store.values(), ([option, name]) => option, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let option = () => get2($$array)[0];
    let name = () => get2($$array)[1];
    var label2 = root8();
    let classes;
    var input = child(label2);
    remove_input_defaults(input);
    var input_value;
    var text2 = sibling(input);
    reset(label2);
    template_effect(() => {
      classes = set_class(label2, 1, "button svelte-jgdjh0", null, classes, { muted: $store() !== option() });
      if (input_value !== (input_value = option())) {
        input.value = (input.__value = option()) ?? "";
      }
      set_text(text2, ` ${name() ?? ""}`);
    });
    bind_group(
      binding_group,
      [],
      input,
      () => {
        option();
        return $store();
      },
      ($$value) => store_set($$props.store, $$value)
    );
    append($$anchor2, label2);
  });
  reset(span);
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/charts/ScatterPlot.svelte
var root9 = from_svg(`<circle r="5"></circle>`);
var root_111 = from_svg(`<!><!><g></g>`, 1);
var root_27 = from_svg(`<svg><!></svg>`);
function ScatterPlot2($$anchor, $$props) {
  push($$props, true);
  const today = /* @__PURE__ */ new Date();
  const margin = { top: 10, right: 10, bottom: 30, left: 70 };
  const height = 250;
  const inner_height = height - margin.top - margin.bottom;
  let inner_width = user_derived(() => $$props.width - margin.left - margin.right);
  let date_extent = user_derived(() => extent($$props.chart.data, (d) => d.date));
  let x = user_derived(() => utcTime([0, get2(inner_width)]).domain(get2(date_extent)[0] ? get2(date_extent) : [0, 1]));
  let y = user_derived(() => point([inner_height, 0]).domain($$props.chart.data.map((d) => d.type)).padding(1));
  let x_axis = user_derived(() => axisBottom(get2(x)).tickSizeOuter(0));
  let y_axis = user_derived(() => axisLeft(get2(y)).tickPadding(6).tickSize(-get2(inner_width)).tickFormat((d) => d));
  let quad = user_derived(() => quadtree([...$$props.chart.data], (d) => get2(x)(d.date), (d) => get2(y)(d.type) ?? 0));
  function tooltip_text(d) {
    return [d.description, domHelpers.em(day(d.date))];
  }
  const tooltip_find = (x_pointer, y_pointer) => {
    const d = get2(quad).find(x_pointer, y_pointer);
    return d && [get2(x)(d.date), get2(y)(d.type) ?? 0, tooltip_text(d)];
  };
  var svg = root_27();
  var node = child(svg);
  {
    let $0 = user_derived(() => get2(x).invert.bind(get2(x)));
    let $1 = user_derived(() => `translate(${margin.left.toString()},${margin.top.toString()})`);
    Brush(node, {
      get invert() {
        return get2($0);
      },
      get height() {
        return inner_height;
      },
      find: tooltip_find,
      get transform() {
        return get2($1);
      },
      children: ($$anchor2, $$slotProps) => {
        var fragment = root_111();
        var node_1 = first_child(fragment);
        Axis(node_1, {
          x: true,
          get axis() {
            return get2(x_axis);
          },
          get inner_height() {
            return inner_height;
          }
        });
        var node_2 = sibling(node_1);
        Axis(node_2, {
          y: true,
          get axis() {
            return get2(y_axis);
          }
        });
        var g = sibling(node_2);
        each(g, 21, () => $$props.chart.data, (dot) => `${dot.date.toString()}-${dot.type}`, ($$anchor3, dot) => {
          var circle = root9();
          let classes;
          template_effect(
            ($02, $12, $2) => {
              set_attribute(circle, "fill", $02);
              set_attribute(circle, "cx", $12);
              set_attribute(circle, "cy", $2);
              classes = set_class(circle, 0, "svelte-xm85bw", null, classes, { desaturate: get2(dot).date > today });
            },
            [
              () => scatterplotScale(get2(dot).type),
              () => get2(x)(get2(dot).date),
              () => get2(y)(get2(dot).type)
            ]
          );
          append($$anchor3, circle);
        });
        reset(g);
        append($$anchor2, fragment);
      },
      $$slots: { default: true }
    });
  }
  reset(svg);
  template_effect(($0) => set_attribute(svg, "viewBox", $0), [() => `0 0 ${$$props.width.toString()} ${height.toString()}`]);
  append($$anchor, svg);
  pop();
}

// src/charts/Chart.svelte
var root10 = from_html(`<!> <!> <!> <span class="spacer"></span> <!>`, 1);
var root_112 = from_html(`<span class="spacer"></span>`);
var root_28 = from_html(`<div class="flex-row svelte-u18gp1"><!> <!> <button type="button" class="show-charts svelte-u18gp1"> </button></div> <div class="chart-wrapper svelte-u18gp1"><!></div>`, 1);
function Chart($$anchor, $$props) {
  push($$props, true);
  const $show_charts = () => store_get(show_charts, "$show_charts", $$stores);
  const $bar_chart_mode = () => store_get(bar_chart_mode, "$bar_chart_mode", $$stores);
  const $hierarchy_chart_mode = () => store_get(hierarchy_chart_mode, "$hierarchy_chart_mode", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const tooltip = new Tooltip();
  set_chart_tooltip(tooltip);
  let width = state(void 0);
  var fragment = root_28();
  var div = first_child(fragment);
  var node = child(div);
  {
    var consequent_6 = ($$anchor2) => {
      var fragment_1 = root10();
      var node_1 = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          {
            let $0 = user_derived(() => !($bar_chart_mode() === "stacked" && $$props.chart.hasStackedData));
            ChartLegend($$anchor3, {
              get legend() {
                return $$props.chart.currencies;
              },
              get color() {
                return get2($0);
              },
              get toggled() {
                return chart_toggled_currencies;
              }
            });
          }
        };
        if_block(node_1, ($$render) => {
          if ($$props.chart.type === "barchart") $$render(consequent);
        });
      }
      var node_2 = sibling(node_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          ChartLegend($$anchor3, {
            get legend() {
              return $$props.chart.series_names;
            },
            color: true,
            get toggled() {
              return chart_toggled_currencies;
            }
          });
        };
        if_block(node_2, ($$render) => {
          if ($$props.chart.type === "linechart") $$render(consequent_1);
        });
      }
      var node_3 = sibling(node_2, 2);
      {
        var consequent_2 = ($$anchor3) => {
          ChartLegend($$anchor3, {
            get legend() {
              return $$props.chart.currencies;
            },
            color: false,
            get active() {
              return $$props.chart.treemap_currency;
            }
          });
        };
        if_block(node_3, ($$render) => {
          if ($$props.chart.type === "hierarchy" && $hierarchy_chart_mode() === "treemap" && $$props.chart.treemap_currency) $$render(consequent_2);
        });
      }
      var node_4 = sibling(node_3, 4);
      {
        var consequent_3 = ($$anchor3) => {
          ModeSwitch($$anchor3, {
            get store() {
              return hierarchy_chart_mode;
            }
          });
        };
        var consequent_4 = ($$anchor3) => {
          ModeSwitch($$anchor3, {
            get store() {
              return line_chart_mode;
            }
          });
        };
        var consequent_5 = ($$anchor3) => {
          ModeSwitch($$anchor3, {
            get store() {
              return bar_chart_mode;
            }
          });
        };
        if_block(node_4, ($$render) => {
          if ($$props.chart.type === "hierarchy") $$render(consequent_3);
          else if ($$props.chart.type === "linechart") $$render(consequent_4, 1);
          else if ($$props.chart.type === "barchart" && $$props.chart.hasStackedData) $$render(consequent_5, 2);
        });
      }
      append($$anchor2, fragment_1);
    };
    var alternate = ($$anchor2) => {
      var span = root_112();
      append($$anchor2, span);
    };
    if_block(node, ($$render) => {
      if ($show_charts()) $$render(consequent_6);
      else $$render(alternate, -1);
    });
  }
  var node_5 = sibling(node, 2);
  snippet(node_5, () => $$props.children ?? noop);
  var button = sibling(node_5, 2);
  var text2 = child(button, true);
  reset(button);
  reset(div);
  var div_1 = sibling(div, 2);
  var node_6 = child(div_1);
  {
    var consequent_11 = ($$anchor2) => {
      var fragment_8 = comment();
      var node_7 = first_child(fragment_8);
      {
        var consequent_7 = ($$anchor3) => {
          BarChart($$anchor3, {
            get chart() {
              return $$props.chart;
            },
            get width() {
              return get2(width);
            }
          });
        };
        var consequent_8 = ($$anchor3) => {
          HierarchyContainer($$anchor3, {
            get chart() {
              return $$props.chart;
            },
            get width() {
              return get2(width);
            }
          });
        };
        var consequent_9 = ($$anchor3) => {
          LineChart2($$anchor3, {
            get chart() {
              return $$props.chart;
            },
            get width() {
              return get2(width);
            }
          });
        };
        var consequent_10 = ($$anchor3) => {
          ScatterPlot2($$anchor3, {
            get chart() {
              return $$props.chart;
            },
            get width() {
              return get2(width);
            }
          });
        };
        if_block(node_7, ($$render) => {
          if ($$props.chart.type === "barchart") $$render(consequent_7);
          else if ($$props.chart.type === "hierarchy") $$render(consequent_8, 1);
          else if ($$props.chart.type === "linechart") $$render(consequent_9, 2);
          else if ($$props.chart.type === "scatterplot") $$render(consequent_10, 3);
        });
      }
      append($$anchor2, fragment_8);
    };
    if_block(node_6, ($$render) => {
      if (get2(width)) $$render(consequent_11);
    });
  }
  reset(div_1);
  attach(div_1, () => tooltip.init.bind(tooltip));
  template_effect(() => {
    set_text(text2, $show_charts() ? "\u25BC" : "\u25C0");
    set_attribute(div_1, "hidden", !$show_charts());
  });
  delegated("click", button, () => {
    router.set_search_param("charts", $show_charts() ? "false" : "");
  });
  bind_element_size(div_1, "clientWidth", ($$value) => set(width, $$value));
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/components/SelectCombobox.svelte
var root11 = from_html(`<li role="option"> </li>`);
var root_113 = from_html(`<span class="svelte-1pxj9t1"><button type="button" role="combobox" class="muted"> </button> <ul role="listbox" class="svelte-1pxj9t1"></ul></span>`);
function SelectCombobox($$anchor, $$props) {
  const uid = props_id();
  push($$props, true);
  let value = prop($$props, "value", 15);
  let hidden = state(true);
  let index2 = state(proxy($$props.options.indexOf(value())));
  let ul = state(void 0);
  const listbox_id = `combobox-listbox-${uid}`;
  const SEPARATOR = ",";
  let values = user_derived(() => value() === "" ? [] : value().split(SEPARATOR));
  let active_id = user_derived(() => !get2(hidden) && get2(index2) > -1 ? `${listbox_id}-${get2(index2).toString()}` : void 0);
  user_effect(() => {
    if (!get2(hidden) && get2(index2) > -1) {
      get2(ul)?.children[get2(index2)]?.scrollIntoView({ block: "nearest", inline: "nearest" });
    }
  });
  const actions = {
    /** Close the popup list. */
    close: () => {
      set(hidden, true);
    },
    /** Find the first element matching the typed letter and focus it. */
    find_letter: (key2, event2) => {
      const lower_key = key2.toLowerCase();
      const match = $$props.options.findIndex((o) => o.toLowerCase().startsWith(lower_key));
      if (match > -1) {
        event2.stopPropagation();
        set(index2, match, true);
        set(hidden, false);
      }
    },
    /** Focus the first element and open if not open yet. */
    first: () => {
      set(index2, 0);
      set(hidden, false);
    },
    /** Focus the last element and open if not open yet. */
    last: () => {
      set(index2, $$props.options.length - 1);
      set(hidden, false);
    },
    /** Focus the next element in the popup. */
    next: () => {
      set(index2, get2(index2) === $$props.options.length - 1 ? 0 : get2(index2) + 1, true);
    },
    /** Open the popup list. */
    open: () => {
      set(hidden, false);
    },
    /** Focus the previous element in the popup. */
    previous: () => {
      set(index2, get2(index2) === 0 ? $$props.options.length - 1 : get2(index2) - 1, true);
    },
    /** Select the given or the focused element in the options list. */
    select: (o) => {
      const option = o ?? $$props.options[get2(index2)];
      if (option != null) {
        if ($$props.multiple_select != null && $$props.multiple_select(option) && get2(values).every($$props.multiple_select)) {
          value(get2(values).includes(option) ? get2(values).filter((v) => v !== option).join(SEPARATOR) : [...get2(values), option].join(SEPARATOR));
        } else {
          value(option);
        }
        set(index2, $$props.options.indexOf(option), true);
        set(hidden, true);
      }
    },
    /** Toggle the popup list. */
    toggle: () => {
      set(hidden, !get2(hidden));
    }
  };
  function key_action(event2) {
    const { key: key2 } = event2;
    const modifier = event2.altKey || event2.ctrlKey || event2.metaKey;
    if (/^[\w]$/.exec(key2) && !modifier) {
      return actions.find_letter.bind(null, key2, event2);
    }
    if (key2 === "Home") {
      return actions.first;
    }
    if (key2 === "End") {
      return actions.last;
    }
    if ((key2 === "Enter" || key2 === " ") && !get2(hidden)) {
      return actions.select;
    }
    if (key2 === "Escape" && !get2(hidden)) {
      return actions.close;
    }
    if (key2 === "ArrowUp") {
      return get2(hidden) ? actions.open : actions.previous;
    }
    if (key2 === "ArrowDown") {
      return get2(hidden) ? actions.open : actions.next;
    }
    return null;
  }
  var span = root_113();
  var button = child(span);
  var text2 = child(button, true);
  reset(button);
  var ul_1 = sibling(button, 2);
  each(ul_1, 22, () => $$props.options, (option) => option, ($$anchor2, option, i) => {
    var li = root11();
    let classes;
    var text_1 = child(li, true);
    reset(li);
    template_effect(
      ($0, $1, $2) => {
        set_attribute(li, "id", $0);
        set_attribute(li, "aria-selected", $1);
        classes = set_class(li, 1, "svelte-1pxj9t1", null, classes, { current: get2(i) === get2(index2) });
        set_text(text_1, $2);
      },
      [
        () => `${listbox_id}-${get2(i).toString()}`,
        () => get2(values).includes(option),
        () => $$props.description(option)
      ]
    );
    delegated("mousedown", li, (ev) => {
      if (ev.button === 0) {
        actions.select(option);
      }
    });
    append($$anchor2, li);
  });
  reset(ul_1);
  bind_this(ul_1, ($$value) => set(ul, $$value), () => get2(ul));
  reset(span);
  template_effect(
    ($0) => {
      set_attribute(button, "aria-expanded", !get2(hidden));
      set_attribute(button, "aria-controls", listbox_id);
      set_attribute(button, "aria-activedescendant", get2(active_id));
      set_text(text2, $0);
      set_attribute(ul_1, "hidden", get2(hidden));
      set_attribute(ul_1, "id", listbox_id);
    },
    [() => $$props.description(value())]
  );
  delegated("click", button, function(...$$args) {
    actions.toggle?.apply(this, $$args);
  });
  event("blur", button, function(...$$args) {
    actions.close?.apply(this, $$args);
  });
  delegated("keydown", button, (event2) => {
    const action = key_action(event2);
    if (action) {
      event2.preventDefault();
      event2.stopPropagation();
      action();
    }
  });
  append($$anchor, span);
  pop();
}
delegate(["click", "keydown", "mousedown"]);

// src/charts/ConversionAndInterval.svelte
var root12 = from_html(`<!> <!>`, 1);
function ConversionAndInterval($$anchor, $$props) {
  push($$props, true);
  const $conversion = () => store_get(conversion, "$conversion", $$stores);
  const $conversions = () => store_get(conversions, "$conversions", $$stores);
  const $interval = () => store_get(interval, "$interval", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const conversion_description = (option) => {
    switch (option) {
      case "at_cost":
        return _("At Cost");
      case "at_value":
        return _("At Market Value");
      case "units":
        return _("Units");
      default:
        return format2(_("Converted to %(currency)s"), { currency: option });
    }
  };
  const is_currency_conversion = (option) => !["at_cost", "at_value", "units"].includes(option);
  var fragment = root12();
  var node = first_child(fragment);
  var bind_get = () => $conversion();
  var bind_set = (value) => {
    router.set_search_param("conversion", value === "at_cost" ? "" : value);
  };
  SelectCombobox(node, {
    get value() {
      return bind_get();
    },
    set value($$value) {
      bind_set($$value);
    },
    get options() {
      return $conversions();
    },
    description: conversion_description,
    multiple_select: is_currency_conversion
  });
  var node_1 = sibling(node, 2);
  var bind_get_1 = () => $interval();
  var bind_set_1 = (value) => {
    router.set_search_param("interval", value === DEFAULT_INTERVAL ? "" : value);
  };
  SelectCombobox(node_1, {
    get value() {
      return bind_get_1();
    },
    set value($$value) {
      bind_set_1($$value);
    },
    get options() {
      return INTERVALS;
    },
    description: (o) => interval_label(get_interval(o))
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/charts/ChartSwitcher.svelte
var root13 = from_html(`<button type="button"> </button>`);
var root_114 = from_html(`<!> <div class="svelte-4vmeqm"></div>`, 1);
function ChartSwitcher($$anchor, $$props) {
  push($$props, true);
  const $last_active_chart_name = () => store_get(last_active_chart_name, "$last_active_chart_name", $$stores);
  const $chart_context = () => store_get(chart_context, "$chart_context", $$stores);
  const $show_charts = () => store_get(show_charts, "$show_charts", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let active_chart = user_derived(() => $$props.charts.find((c) => c.label === $last_active_chart_name()) ?? $$props.charts[0]);
  let shortcutPrevious = user_derived(() => (index2) => {
    const current = get2(active_chart) ? $$props.charts.indexOf(get2(active_chart)) : -1;
    return index2 === (current - 1 + $$props.charts.length) % $$props.charts.length ? { key: "C", note: _("Previous") } : void 0;
  });
  let shortcutNext = user_derived(() => (index2) => {
    const current = get2(active_chart) ? $$props.charts.indexOf(get2(active_chart)) : -1;
    return index2 === (current + 1 + $$props.charts.length) % $$props.charts.length ? { key: "c", note: _("Next") } : void 0;
  });
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var fragment_1 = root_114();
      var node_1 = first_child(fragment_1);
      {
        let $0 = user_derived(() => get2(active_chart).with_context($chart_context()));
        Chart(node_1, {
          get chart() {
            return get2($0);
          },
          children: ($$anchor3, $$slotProps) => {
            ConversionAndInterval($$anchor3, {});
          },
          $$slots: { default: true }
        });
      }
      var div = sibling(node_1, 2);
      each(div, 23, () => $$props.charts, (chart) => chart.label, ($$anchor3, chart, index2) => {
        var button = root13();
        let classes;
        var text2 = child(button, true);
        reset(button);
        attach(button, () => keyboardShortcut(get2(shortcutPrevious)(get2(index2))));
        attach(button, () => keyboardShortcut(get2(shortcutNext)(get2(index2))));
        template_effect(() => {
          classes = set_class(button, 1, "unset svelte-4vmeqm", null, classes, { selected: get2(chart) === get2(active_chart) });
          set_text(text2, get2(chart).label);
        });
        delegated("click", button, () => {
          store_set(last_active_chart_name, get2(chart).label);
        });
        append($$anchor3, button);
      });
      reset(div);
      template_effect(() => set_attribute(div, "hidden", !$show_charts()));
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (get2(active_chart)) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/stores/accounts.ts
var collapsed_accounts = derived(
  [collapse_pattern, accounts_internal],
  ([$collapse_pattern, $accounts_internal]) => {
    const matchers = $collapse_pattern.map((pattern) => new RegExp(pattern));
    return $accounts_internal.filter(
      (account) => matchers.some((matcher) => matcher.test(account))
    );
  }
);
var explicitly_toggled = writable(/* @__PURE__ */ new Map());
var toggled_accounts = derived(
  [collapsed_accounts, explicitly_toggled],
  ([$collapsed_accounts, $explicitly_toggled]) => {
    const toggled = new Set($collapsed_accounts);
    for (const [account, is_toggled] of $explicitly_toggled) {
      if (is_toggled) {
        toggled.add(account);
      } else {
        toggled.delete(account);
      }
    }
    return toggled;
  }
);
function toggle_account(account, event2) {
  const $toggled_accounts = get(toggled_accounts);
  const $accounts_internal = get(accounts_internal);
  const is_opening = $toggled_accounts.has(account);
  explicitly_toggled.update(($explicitly_toggled) => {
    const new_explicitly_toggled = new Map($explicitly_toggled);
    new_explicitly_toggled.set(account, !is_opening);
    if (is_opening) {
      if (event2.shiftKey) {
        $accounts_internal.filter(is_descendant(account)).forEach((child2) => {
          new_explicitly_toggled.set(child2, false);
        });
      } else if (event2.ctrlKey || event2.metaKey) {
        $accounts_internal.filter((a) => parent(a) === account).forEach((child2) => {
          new_explicitly_toggled.set(child2, true);
        });
      }
    }
    return new_explicitly_toggled;
  });
}
function expand_all(account) {
  const $toggled_accounts = get(toggled_accounts);
  explicitly_toggled.update(($explicitly_toggled) => {
    const new_explicitly_toggled = new Map($explicitly_toggled);
    [...$toggled_accounts].filter(is_descendant_or_equal(account)).forEach((descendant) => {
      new_explicitly_toggled.set(descendant, false);
    });
    return new_explicitly_toggled;
  });
}
var invert_account = derived(
  [
    invert_income_liabilities_equity,
    name_income,
    name_liabilities,
    name_equity
  ],
  ([
    $invert_income_liabilities_equity,
    $name_income,
    $name_liabilities,
    $name_equity
  ]) => $invert_income_liabilities_equity ? (name) => name.startsWith($name_income) || name.startsWith($name_liabilities) || name.startsWith($name_equity) || name === _("Net Profit") : () => false
);
var is_closed_account = derived(
  [account_details],
  ([$account_details]) => (name, date3) => {
    const close_date = $account_details[name]?.close_date;
    if (!close_date) {
      return false;
    }
    return date3 == null ? true : close_date < date3;
  }
);

// src/tree-table/AccountCellHeader.svelte
var root14 = from_html(`<button type="button" class="link svelte-1qitpob"> </button>`);
var root_115 = from_html(`<span class="svelte-1qitpob"><!></span>`);
function AccountCellHeader($$anchor, $$props) {
  push($$props, true);
  const $toggled_accounts = () => store_get(toggled_accounts, "$toggled_accounts", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const toggled_children = user_derived(() => some($toggled_accounts(), is_descendant_or_equal($$props.account)));
  const help_title = _("Hold Shift while clicking to expand all children.\nHold Ctrl or Cmd while clicking to expand one level.");
  var span = root_115();
  var node = child(span);
  {
    var consequent = ($$anchor2) => {
      var button = root14();
      var text2 = child(button, true);
      reset(button);
      template_effect(
        ($0, $1) => {
          set_attribute(button, "title", $0);
          set_text(text2, $1);
        },
        [() => _("Expand all accounts"), () => _("Expand all")]
      );
      delegated("click", button, () => {
        expand_all($$props.account);
      });
      append($$anchor2, button);
    };
    if_block(node, ($$render) => {
      if (get2(toggled_children)) $$render(consequent);
    });
  }
  reset(span);
  template_effect(() => set_attribute(span, "title", help_title));
  append($$anchor, span);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/tree-table/helpers.ts
var key = /* @__PURE__ */ Symbol("tree-table");
var setTreeTableNotShownContext = (ctx2) => setContext(key, ctx2);
var getTreeTableNotShownContext = () => getContext(key);
var get_not_shown = derived(
  [
    show_accounts_with_zero_balance,
    show_accounts_with_zero_transactions,
    show_closed_accounts,
    accounts_set,
    is_closed_account
  ],
  ([
    $show_accounts_with_zero_balance,
    $show_accounts_with_zero_transactions,
    $show_closed_accounts,
    $accounts_set,
    $is_closed_account
  ]) => (node, end) => {
    const not_shown = /* @__PURE__ */ new Set();
    const should_show_recursive = (n) => {
      if (
        // We need to evaluate this for all descendants recursively
        // the .map().some() ensures it does not short-circuit
        n.children.map(should_show_recursive).some((b) => b) || !is_empty(n.balance_children)
      ) {
        return true;
      }
      if (!$accounts_set.has(n.account) || !$show_closed_accounts && $is_closed_account(n.account, end) || !$show_accounts_with_zero_balance && is_empty(n.balance) || !$show_accounts_with_zero_transactions && !n.has_txns) {
        not_shown.add(n.account);
        return false;
      }
      return true;
    };
    should_show_recursive(node);
    return not_shown;
  }
);

// src/sidebar/AccountIndicator.svelte
var root15 = from_html(`<span title="The last entry is a passing balance check."></span>`);
var root_116 = from_html(`<copyable-text></copyable-text>`, 2);
var root_29 = from_html(`<span></span>`);
var root_33 = from_html(`<!> <!>`, 1);
function AccountIndicator($$anchor, $$props) {
  push($$props, true);
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $uptodate_indicator_grey_lookback_days = () => store_get(uptodate_indicator_grey_lookback_days, "$uptodate_indicator_grey_lookback_days", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let small = prop($$props, "small", 3, false);
  let details = user_derived(() => $account_details()[$$props.account]);
  let status = user_derived(() => get2(details)?.uptodate_status);
  let balance = user_derived(() => get2(details)?.balance_string ?? "");
  let last_entry = user_derived(() => get2(details)?.last_entry);
  let last_account_activity = user_derived(() => get2(last_entry) ? timeDay.count(get2(last_entry).date, /* @__PURE__ */ new Date()) : 0);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var fragment_1 = root_33();
      var node_1 = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          var span = root15();
          let classes;
          template_effect(() => classes = set_class(span, 1, "status-indicator status-green svelte-1qv6o8a", null, classes, { small: small() }));
          append($$anchor3, span);
        };
        var alternate = ($$anchor3) => {
          var copyable_text = root_116();
          let classes_1;
          template_effect(() => set_custom_element_data(copyable_text, "title", `${get2(status) === "yellow" ? "The last entry is not a balance check." : "The last entry is a failing balance check."}

Click to copy the balance directives to the clipboard:

${get2(balance)}`));
          template_effect(() => set_custom_element_data(copyable_text, "data-clipboard-text", get2(balance)));
          template_effect(() => classes_1 = set_class(copyable_text, 1, `status-indicator status-${get2(status) ?? ""}`, "svelte-1qv6o8a", classes_1, { small: small() }));
          append($$anchor3, copyable_text);
        };
        if_block(node_1, ($$render) => {
          if (get2(status) === "green") $$render(consequent);
          else $$render(alternate, -1);
        });
      }
      var node_2 = sibling(node_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var span_1 = root_29();
          let classes_2;
          template_effect(() => {
            classes_2 = set_class(span_1, 1, "status-indicator status-gray svelte-1qv6o8a", null, classes_2, { small: small() });
            set_attribute(span_1, "title", `This account has not been updated in a while. (${get2(last_account_activity) ?? ""} days ago)`);
          });
          append($$anchor3, span_1);
        };
        if_block(node_2, ($$render) => {
          if (get2(last_account_activity) > $uptodate_indicator_grey_lookback_days()) $$render(consequent_1);
        });
      }
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if (get2(status)) $$render(consequent_2);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/tree-table/AccountCell.svelte
var root16 = from_html(`<button type="button" class="unset svelte-1t9i0uq"> </button>`);
var root_117 = from_html(`<span class="droptarget svelte-1t9i0uq"><!> <a class="account svelte-1t9i0uq"> </a> <!></span>`);
function AccountCell($$anchor, $$props) {
  push($$props, true);
  const $toggled_accounts = () => store_get(toggled_accounts, "$toggled_accounts", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let account = user_derived(() => $$props.node.account), children2 = user_derived(() => $$props.node.children);
  let is_toggled = user_derived(() => $toggled_accounts().has(get2(account)));
  var span = root_117();
  var node_1 = child(span);
  {
    var consequent = ($$anchor2) => {
      var button = root16();
      var text2 = child(button, true);
      reset(button);
      template_effect(() => set_text(text2, get2(is_toggled) ? "\u25B8" : "\u25BE"));
      delegated("click", button, (event2) => {
        toggle_account(get2(account), event2);
      });
      append($$anchor2, button);
    };
    if_block(node_1, ($$render) => {
      if (get2(children2).length > 0) $$render(consequent);
    });
  }
  var a = sibling(node_1, 2);
  var text_1 = child(a, true);
  reset(a);
  var node_2 = sibling(a, 2);
  AccountIndicator(node_2, {
    get account() {
      return get2(account);
    },
    small: true
  });
  reset(span);
  template_effect(
    ($0, $1) => {
      set_attribute(span, "data-account-name", get2(account));
      set_attribute(a, "href", $0);
      set_text(text_1, $1);
    },
    [
      () => $url_for_account()(get2(account)),
      () => leaf(get2(account))
    ]
  );
  append($$anchor, span);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/tree-table/Diff.svelte
var root17 = from_html(`<br/> <span> </span>`, 1);
function Diff($$anchor, $$props) {
  push($$props, true);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let positive = user_derived(() => $$props.diff > 0);
  var fragment = root17();
  var span = sibling(first_child(fragment), 2);
  let classes;
  var text2 = child(span);
  reset(span);
  template_effect(
    ($0, $1) => {
      set_attribute(span, "title", $0);
      classes = set_class(span, 1, "svelte-1wiuwio", null, classes, { positive: get2(positive) });
      set_text(text2, `(${get2(positive) ? "+" : "-"}${$1 ?? ""})`);
    },
    [
      () => $ctx().amount($$props.num, $$props.currency),
      () => $ctx().num(Math.abs($$props.diff), $$props.currency)
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/tree-table/IntervalTreeTableNode.svelte
var root18 = from_html(`<span> </span> <!> <br/>`, 1);
var root_118 = from_html(`<span><!> <!></span>`);
var root_210 = from_html(`<ol></ol>`);
var root_34 = from_html(`<li><p><!> <!></p> <!></li>`);
function IntervalTreeTableNode_1($$anchor, $$props) {
  push($$props, true);
  const $toggled_accounts = () => store_get(toggled_accounts, "$toggled_accounts", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const not_shown = getTreeTableNotShownContext();
  let $$array = user_derived(() => to_array($$props.nodes, 1)), node = user_derived(() => get2($$array)[0]);
  let account = user_derived(() => get2(node).account), children2 = user_derived(() => get2(node).children);
  let account_budgets = user_derived(() => $$props.budgets[get2(account)]);
  let is_toggled = user_derived(() => $toggled_accounts().has(get2(account)));
  var li = root_34();
  var p = child(li);
  var node_1 = child(p);
  AccountCell(node_1, {
    get node() {
      return get2(node);
    }
  });
  var node_2 = sibling(node_1, 2);
  each(node_2, 17, () => $$props.nodes, index, ($$anchor2, n, index2) => {
    const account_budget = user_derived(() => get2(account_budgets)?.[index2]);
    const has_balance = user_derived(() => !is_empty(get2(n).balance) || get2(account_budget) != null && !is_empty(get2(account_budget).budget));
    const show_balance = user_derived(() => !get2(is_toggled) && get2(has_balance));
    const shown_balance = user_derived(() => get2(show_balance) ? get2(n).balance : get2(n).balance_children);
    const shown_budget = user_derived(() => get2(show_balance) ? get2(account_budget)?.budget : get2(account_budget)?.budget_children);
    var span = root_118();
    let classes;
    var node_3 = child(span);
    each(node_3, 17, () => Object.entries(get2(shown_balance)), ([currency, number4]) => currency, ($$anchor3, $$item) => {
      var $$array_1 = user_derived(() => to_array(get2($$item), 2));
      let currency = () => get2($$array_1)[0];
      let number4 = () => get2($$array_1)[1];
      const budget = user_derived(() => get2(shown_budget)?.[currency()]);
      var fragment = root18();
      var span_1 = first_child(fragment);
      var text2 = child(span_1, true);
      reset(span_1);
      var node_4 = sibling(span_1, 2);
      {
        var consequent = ($$anchor4) => {
          {
            let $0 = user_derived(() => get2(budget) - number4());
            Diff($$anchor4, {
              get diff() {
                return get2($0);
              },
              get num() {
                return get2(budget);
              },
              get currency() {
                return currency();
              }
            });
          }
        };
        if_block(node_4, ($$render) => {
          if (get2(budget)) $$render(consequent);
        });
      }
      next(2);
      template_effect(
        ($0, $1) => {
          set_attribute(span_1, "title", $0);
          set_text(text2, $1);
        },
        [
          () => $currency_name()(currency()),
          () => $ctx().amount(number4(), currency())
        ]
      );
      append($$anchor3, fragment);
    });
    var node_5 = sibling(node_3, 2);
    {
      var consequent_1 = ($$anchor3) => {
        var fragment_2 = comment();
        var node_6 = first_child(fragment_2);
        each(node_6, 17, () => Object.entries(get2(shown_budget)).filter(([c]) => !(get2(shown_balance)[c] ?? 0)), ([currency, budget]) => currency, ($$anchor4, $$item) => {
          var $$array_2 = user_derived(() => to_array(get2($$item), 2));
          let currency = () => get2($$array_2)[0];
          let budget = () => get2($$array_2)[1];
          var fragment_3 = root18();
          var span_2 = first_child(fragment_3);
          var text_1 = child(span_2, true);
          reset(span_2);
          var node_7 = sibling(span_2, 2);
          Diff(node_7, {
            get diff() {
              return budget();
            },
            get num() {
              return budget();
            },
            get currency() {
              return currency();
            }
          });
          next(2);
          template_effect(
            ($0, $1) => {
              set_attribute(span_2, "title", $0);
              set_text(text_1, $1);
            },
            [
              () => $currency_name()(currency()),
              () => $ctx().amount(0, currency())
            ]
          );
          append($$anchor4, fragment_3);
        });
        append($$anchor3, fragment_2);
      };
      if_block(node_5, ($$render) => {
        if (get2(shown_budget)) $$render(consequent_1);
      });
    }
    reset(span);
    template_effect(() => classes = set_class(span, 1, "num other", null, classes, { dimmed: !get2(is_toggled) && !get2(has_balance) }));
    append($$anchor2, span);
  });
  reset(p);
  var node_8 = sibling(p, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ol = root_210();
      each(ol, 23, () => get2(children2), (child2) => child2.account, ($$anchor3, child2, index2) => {
        var fragment_4 = comment();
        var node_9 = first_child(fragment_4);
        {
          var consequent_2 = ($$anchor4) => {
            {
              let $0 = user_derived(() => $$props.nodes.map((n) => n.children[get2(index2)]));
              IntervalTreeTableNode_1($$anchor4, {
                get nodes() {
                  return get2($0);
                },
                get budgets() {
                  return $$props.budgets;
                }
              });
            }
          };
          var d = user_derived(() => !$not_shown().has(get2(child2).account));
          if_block(node_9, ($$render) => {
            if (get2(d)) $$render(consequent_2);
          });
        }
        append($$anchor3, fragment_4);
      });
      reset(ol);
      append($$anchor2, ol);
    };
    var d_1 = user_derived(() => !get2(is_toggled) && get2(children2).some((n) => !$not_shown().has(n.account)));
    if_block(node_8, ($$render) => {
      if (get2(d_1)) $$render(consequent_3);
    });
  }
  reset(li);
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/tree-table/IntervalTreeTable.svelte
var root19 = from_html(`<span class="num other"><a> </a></span>`);
var root_119 = from_html(`<ol class="flex-table tree-table-new svelte-4xc05i"><li class="head"><p><!> <!></p></li> <!></ol>`);
function IntervalTreeTable($$anchor, $$props) {
  push($$props, true);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const $get_not_shown = () => store_get(get_not_shown, "$get_not_shown", $$stores);
  const $current_time_filter_date_format = () => store_get(current_time_filter_date_format, "$current_time_filter_date_format", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const not_shown = writable(/* @__PURE__ */ new Set());
  setTreeTableNotShownContext(not_shown);
  user_effect(() => {
    store_set(not_shown, intersection(...$$props.trees.map((n, index2) => $get_not_shown()(n, $$props.dates[index2]?.end ?? null))));
  });
  let account = user_derived(() => $$props.trees[0].account);
  let start_date = user_derived(() => $$props.accumulate ? min($$props.dates, (d) => d.begin) : void 0);
  let start_date_filter = user_derived(() => get2(start_date) ? $current_time_filter_date_format()(get2(start_date)) : void 0);
  let time_filters = user_derived(() => $$props.dates.map((date_range) => {
    const title = $current_time_filter_date_format()(date_range.begin);
    return get2(start_date_filter) != null ? [title, `${get2(start_date_filter)}-${title}`] : [title, title];
  }));
  var ol = root_119();
  var li = child(ol);
  var p = child(li);
  var node = child(p);
  AccountCellHeader(node, {
    get account() {
      return get2(account);
    }
  });
  var node_1 = sibling(node, 2);
  each(node_1, 17, () => get2(time_filters), ([title, time]) => time, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let title = () => get2($$array)[0];
    let time = () => get2($$array)[1];
    var span = root19();
    var a = child(span);
    var text2 = child(a, true);
    reset(a);
    reset(span);
    template_effect(
      ($0) => {
        set_attribute(a, "href", $0);
        set_text(text2, title());
      },
      [() => $url_for_account()(get2(account), { time: time() })]
    );
    append($$anchor2, span);
  });
  reset(p);
  reset(li);
  var node_2 = sibling(li, 2);
  IntervalTreeTableNode_1(node_2, {
    get nodes() {
      return $$props.trees;
    },
    get budgets() {
      return $$props.budgets;
    }
  });
  reset(ol);
  append($$anchor, ol);
  pop();
  $$cleanup();
}

// src/modals/document-upload.ts
function is_supported_datatransfer(dataTransfer) {
  return dataTransfer != null && (dataTransfer.types.includes("Files") || dataTransfer.types.includes("text/uri-list") && new URL(dataTransfer.getData("URL")).searchParams.has("filename"));
}

// src/stores/journal.ts
var default_journal_show = [
  "balance",
  "budget",
  "cleared",
  "custom",
  "discovered",
  "document",
  "note",
  "pending",
  "query",
  "statement",
  "transaction"
];
var journal_show = local_storage_synced_store(
  "journal-show",
  array(string),
  () => default_journal_show
);
var default_journal_sort = ["date", "desc"];
var journal_sort = local_storage_synced_store(
  "journal-sort-order",
  tuple(
    constants("date", "flag", "narration", "change"),
    constants("asc", "desc")
  ),
  () => default_journal_sort
);

// src/lib/regex.ts
function escape_for_regex(value) {
  return value.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
}

// src/reports/journal/click_handler.ts
function add_filter(value) {
  const $fql_filter = get(fql_filter);
  router.set_search_param(
    "filter",
    $fql_filter ? `${$fql_filter} ${value}` : value
  );
}
function handle_journal_click({ target }) {
  if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement) {
    return;
  }
  if (target.matches(".tag, .link")) {
    add_filter(target.innerText);
  } else if (target.matches(".payee")) {
    add_filter(`payee:"^${escape_for_regex(target.innerText)}$"`);
  } else if (target.tagName === "DT") {
    const expr = `${target.innerText}""`;
    add_filter(target.closest(".postings") ? `any(${expr})` : expr);
  } else if (target.tagName === "DD") {
    const key2 = target.previousElementSibling.innerText;
    const value = `"^${escape_for_regex(target.innerText)}$"`;
    const expr = `${key2}${value}`;
    add_filter(target.closest(".postings") ? `any(${expr})` : expr);
  } else if (target.closest(".indicators")) {
    target.closest(".journal > li")?.classList.toggle("show-full-entry");
  }
}

// src/lib/set.ts
function toggle(set3, element) {
  if (set3.has(element)) {
    set3.delete(element);
  } else {
    set3.add(element);
  }
  return set3;
}

// src/reports/journal/JournalFilters.svelte
var toggleText = _("Toggle %(type)s entries");
var buttons = [
  ["open", "Open", null, "s o"],
  ["close", "Close", null, "s c"],
  ["transaction", "Transaction", null, "s t"],
  [
    "cleared",
    "*",
    _("Cleared transactions"),
    "t c",
    "transaction"
  ],
  [
    "pending",
    "!",
    _("Pending transactions"),
    "t p",
    "transaction"
  ],
  ["other", "x", _("Other transactions"), "t o", "transaction"],
  ["balance", "Balance", null, "s b"],
  ["note", "Note", null, "s n"],
  ["document", "Document", null, "s d"],
  [
    "discovered",
    "D",
    _("Documents with a #discovered tag"),
    "d d",
    "document"
  ],
  [
    "linked",
    "L",
    _("Documents with a #linked tag"),
    "d l",
    "document"
  ],
  ["pad", "Pad", null, "s p"],
  ["query", "Query", null, "s q"],
  ["custom", "Custom", null, "s C"],
  ["budget", "B", _("Budget entries"), "s B", "custom"],
  ["metadata", _("Metadata"), _("Toggle metadata"), "m"],
  ["postings", _("Postings"), _("Toggle postings"), "p"]
];
var root20 = from_html(`<button type="button"> </button>`);
var root_120 = from_html(`<form class="flex-row svelte-v5wnk9"></form>`);
function JournalFilters($$anchor, $$props) {
  push($$props, true);
  const $journal_show = () => store_get(journal_show, "$journal_show", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let shownSet = user_derived(() => new Set($journal_show()));
  function toggle_type(type) {
    journal_show.update((show) => {
      const set3 = new Set(show);
      toggle(set3, type);
      buttons.filter((b) => b[4] === type).forEach((b) => {
        toggle(set3, b[0]);
      });
      return [...set3].sort();
    });
  }
  let active = user_derived(() => (type, supertype) => supertype != null ? get2(shownSet).has(type) && get2(shownSet).has(supertype) : get2(shownSet).has(type));
  var form = root_120();
  each(form, 21, () => buttons, ([type, button_text, title, shortcut, supertype]) => type, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 5));
    let type = () => get2($$array)[0];
    let button_text = () => get2($$array)[1];
    let title = () => get2($$array)[2];
    let shortcut = () => get2($$array)[3];
    let supertype = () => get2($$array)[4];
    var button = root20();
    let classes;
    var text2 = child(button, true);
    reset(button);
    attach(button, () => keyboardShortcut(shortcut()));
    template_effect(
      ($0, $1) => {
        set_attribute(button, "title", $0);
        classes = set_class(button, 1, "", null, classes, $1);
        set_text(text2, button_text());
      },
      [
        () => title() ?? format2(toggleText, { type: button_text() }),
        () => ({ inactive: !get2(active)(type(), supertype()) })
      ]
    );
    delegated("click", button, () => {
      toggle_type(type());
    });
    append($$anchor2, button);
  });
  reset(form);
  append($$anchor, form);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/journal/JournalHeaders.svelte
var root21 = from_html(`<button type="button" class="num unset svelte-6nb29s"> </button> <span class="num"> </span>`, 1);
var root_121 = from_html(`<span class="num"> </span> <span class="num"> </span>`, 1);
var root_211 = from_html(`<ol class="flex-table journal svelte-6nb29s"><li class="head"><p><button type="button" class="datecell unset svelte-6nb29s"> </button> <button type="button" class="flag unset svelte-6nb29s"> </button> <button type="button" class="description unset svelte-6nb29s"> </button> <span class="num"> </span> <!></p></li></ol>`);
function JournalHeaders($$anchor, $$props) {
  push($$props, true);
  const $journal_sort = () => store_get(journal_sort, "$journal_sort", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let $$array = user_derived(() => to_array($journal_sort(), 2)), name = user_derived(() => get2($$array)[0]), order = user_derived(() => get2($$array)[1]);
  var ol = root_211();
  var li = child(ol);
  var p = child(li);
  var button = child(p);
  var text2 = child(button, true);
  reset(button);
  var button_1 = sibling(button, 2);
  var text_1 = child(button_1, true);
  reset(button_1);
  var button_2 = sibling(button_1, 2);
  var text_2 = child(button_2);
  reset(button_2);
  var span = sibling(button_2, 2);
  var text_3 = child(span, true);
  reset(span);
  var node = sibling(span, 2);
  {
    var consequent = ($$anchor2) => {
      var fragment = root21();
      var button_3 = first_child(fragment);
      var text_4 = child(button_3);
      reset(button_3);
      var span_1 = sibling(button_3, 2);
      var text_5 = child(span_1);
      reset(span_1);
      template_effect(
        ($0, $1, $2, $3) => {
          set_attribute(button_3, "data-order", get2(name) === "change" ? get2(order) : void 0);
          button_3.disabled = $$props.disabled;
          set_text(text_4, `${$0 ?? ""} / ${$1 ?? ""}`);
          set_text(text_5, `${$2 ?? ""} / ${$3 ?? ""}`);
        },
        [
          () => _("Cost"),
          () => _("Change"),
          () => _("Price"),
          () => _("Balance")
        ]
      );
      delegated("click", button_3, () => {
        $$props.set_sort_column("change");
      });
      append($$anchor2, fragment);
    };
    var alternate = ($$anchor2) => {
      var fragment_1 = root_121();
      var span_2 = first_child(fragment_1);
      var text_6 = child(span_2, true);
      reset(span_2);
      var span_3 = sibling(span_2, 2);
      var text_7 = child(span_3, true);
      reset(span_3);
      template_effect(
        ($0, $1) => {
          set_text(text_6, $0);
          set_text(text_7, $1);
        },
        [() => _("Cost"), () => _("Price")]
      );
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if ($$props.show_change_and_balance) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  reset(p);
  reset(li);
  reset(ol);
  template_effect(
    ($0, $1, $2, $3, $4) => {
      set_attribute(button, "data-order", get2(name) === "date" ? get2(order) : void 0);
      button.disabled = $$props.disabled;
      set_text(text2, $0);
      set_attribute(button_1, "data-order", get2(name) === "flag" ? get2(order) : void 0);
      button_1.disabled = $$props.disabled;
      set_text(text_1, $1);
      set_attribute(button_2, "data-order", get2(name) === "narration" ? get2(order) : void 0);
      button_2.disabled = $$props.disabled;
      set_text(text_2, `${$2 ?? ""}/${$3 ?? ""}`);
      set_text(text_3, $4);
    },
    [
      () => _("Date"),
      () => _("F"),
      () => _("Payee"),
      () => _("Narration"),
      () => _("Units")
    ]
  );
  delegated("click", button, () => {
    $$props.set_sort_column("date");
  });
  delegated("click", button_1, () => {
    $$props.set_sort_column("flag");
  });
  delegated("click", button_2, () => {
    $$props.set_sort_column("narration");
  });
  append($$anchor, ol);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/journal/sort.ts
var journal_column_types = {
  date: "num",
  flag: "string",
  narration: "string",
  change: "num"
};
var journal_column_selectors = {
  date: ".datecell",
  flag: ".flag",
  narration: ".description",
  change: ".change"
};
function sort_journal(ol, sort) {
  const [column, order] = sort;
  const type = journal_column_types[column];
  const selector = journal_column_selectors[column];
  sort_elements(
    ol,
    [].slice.call(ol.children),
    (li) => li.querySelector(selector),
    get_direction(order),
    type
  );
}

// src/reports/journal/JournalTable.svelte
var root22 = from_html(`<!> <!>  <ol></ol>`, 1);
function JournalTable($$anchor, $$props) {
  push($$props, true);
  const $is_loading = () => store_get(is_loading, "$is_loading", $$stores);
  const $journal_sort = () => store_get(journal_sort, "$journal_sort", $$stores);
  const $journal_show = () => store_get(journal_show, "$journal_show", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let all_pages = prop($$props, "all_pages", 19, () => []);
  let ol = state(void 0);
  function ondragenter(event2) {
    const closest_element = get_el(event2.target);
    const description = closest_element?.closest(".description");
    const li = description?.closest("li");
    if (description instanceof Element && li && is_supported_datatransfer(event2.dataTransfer)) {
      const account = [...li.querySelectorAll("a")].map((a) => new URL(a.href)).map(get_account_from_url).find((res) => res.is_ok)?.value;
      if (account != null) {
        description.setAttribute("data-account-name", account);
        description.classList.add("dragover");
        event2.preventDefault();
        const date_link = description.closest(".journal > li")?.querySelector(".datecell")?.querySelector("a");
        if (date_link != null) {
          const entry_date = date_link.innerText;
          const hash2 = new URL(date_link.href).hash;
          if (hash2.startsWith("#context-")) {
            const entry_hash = hash2.slice(9);
            description.setAttribute("data-entry-date", entry_date);
            description.setAttribute("data-entry-hash", entry_hash);
          }
        }
      }
    }
  }
  var fragment_1 = root22();
  var node_1 = first_child(fragment_1);
  JournalFilters(node_1, {});
  var node_2 = sibling(node_1, 2);
  JournalHeaders(node_2, {
    get disabled() {
      return $is_loading();
    },
    get show_change_and_balance() {
      return $$props.show_change_and_balance;
    },
    set_sort_column: (column) => {
      const sort = [
        column,
        shallow_equal($journal_sort(), [column, "asc"]) ? "desc" : "asc"
      ];
      if (get2(ol)) {
        sort_journal(get2(ol), sort);
        store_set(journal_sort, sort);
      }
    }
  });
  var ol_1 = sibling(node_2, 2);
  bind_this(ol_1, ($$value) => set(ol, $$value), () => get2(ol));
  attach(ol_1, () => (node) => {
    void $$props.journal;
    untrack(() => {
      const sort = $journal_sort();
      node.innerHTML = "";
      node.append($$props.journal);
      const needs_sorting = !shallow_equal(sort, $$props.initial_sort);
      if (needs_sorting) {
        sort_journal(node, sort);
      }
      if (all_pages().length > 0) {
        loading_state.run(async () => {
          for (const page of all_pages()) {
            const fragment = await page;
            if (fragment) {
              node.append(fragment);
            }
          }
          if (needs_sorting) {
            sort_journal(node, sort);
          }
        }).catch(log_error);
      }
    });
  });
  template_effect(($0) => set_class(ol_1, 1, $0), [
    () => clsx([
      "flex-table",
      "journal",
      ...$journal_show().map((s) => `show-${s}`)
    ])
  ]);
  delegated("click", ol_1, function(...$$args) {
    handle_journal_click?.apply(this, $$args);
  });
  event("dragenter", ol_1, ondragenter);
  append($$anchor, fragment_1);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/accounts/AccountReport.svelte
var root23 = from_html(`<a> </a>`);
var root_122 = from_html(`<!> <div class="droptarget"><div class="headerline"><h3><!></h3> <h3><!></h3> <h3><!></h3></div> <!></div>`, 1);
function AccountReport($$anchor, $$props) {
  push($$props, true);
  const $interval = () => store_get(interval, "$interval", $$stores);
  const $current_time_filter_date_format = () => store_get(current_time_filter_date_format, "$current_time_filter_date_format", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let accumulate = user_derived(() => $$props.report_type === "balances");
  let interval_label_lower = user_derived(() => interval_label($interval()).toLowerCase());
  let all_charts = user_derived(() => $$props.interval_balances && $$props.dates ? [
    ...$$props.charts,
    ...$$props.interval_balances.slice(0, 3).map((node, index2) => new ParsedHierarchyChart($current_time_filter_date_format()($$props.dates[index2]?.begin ?? /* @__PURE__ */ new Date()), node))
  ] : $$props.charts);
  var fragment = root_122();
  var node_1 = first_child(fragment);
  ChartSwitcher(node_1, {
    get charts() {
      return get2(all_charts);
    }
  });
  var div = sibling(node_1, 2);
  var div_1 = child(div);
  var h3 = child(div_1);
  var node_2 = child(h3);
  {
    var consequent = ($$anchor2) => {
      var a = root23();
      var text2 = child(a, true);
      reset(a);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a, "href", $0);
          set_attribute(a, "title", $1);
          set_text(text2, $2);
        },
        [
          () => $url_for_account()($$props.account),
          () => _("Journal of all entries for this Account and Sub-Accounts"),
          () => _("Account Journal")
        ]
      );
      append($$anchor2, a);
    };
    var alternate = ($$anchor2) => {
      var text_1 = text();
      template_effect(($0) => set_text(text_1, $0), [() => _("Account Journal")]);
      append($$anchor2, text_1);
    };
    if_block(node_2, ($$render) => {
      if ($$props.report_type !== "journal") $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  reset(h3);
  var h3_1 = sibling(h3, 2);
  var node_3 = child(h3_1);
  {
    var consequent_1 = ($$anchor2) => {
      var a_1 = root23();
      var text_2 = child(a_1);
      reset(a_1);
      template_effect(
        ($0, $1) => {
          set_attribute(a_1, "href", $0);
          set_text(text_2, `${$1 ?? ""} (${get2(interval_label_lower) ?? ""})`);
        },
        [
          () => $url_for_account()($$props.account, { r: "changes" }),
          () => _("Changes")
        ]
      );
      append($$anchor2, a_1);
    };
    var alternate_1 = ($$anchor2) => {
      var text_3 = text();
      template_effect(($0) => set_text(text_3, `${$0 ?? ""} (${get2(interval_label_lower) ?? ""})`), [() => _("Changes")]);
      append($$anchor2, text_3);
    };
    if_block(node_3, ($$render) => {
      if ($$props.report_type !== "changes") $$render(consequent_1);
      else $$render(alternate_1, -1);
    });
  }
  reset(h3_1);
  var h3_2 = sibling(h3_1, 2);
  var node_4 = child(h3_2);
  {
    var consequent_2 = ($$anchor2) => {
      var a_2 = root23();
      var text_4 = child(a_2);
      reset(a_2);
      template_effect(
        ($0, $1) => {
          set_attribute(a_2, "href", $0);
          set_text(text_4, `${$1 ?? ""} (${get2(interval_label_lower) ?? ""})`);
        },
        [
          () => $url_for_account()($$props.account, { r: "balances" }),
          () => _("Balances")
        ]
      );
      append($$anchor2, a_2);
    };
    var alternate_2 = ($$anchor2) => {
      var text_5 = text();
      template_effect(($0) => set_text(text_5, `${$0 ?? ""} (${get2(interval_label_lower) ?? ""})`), [() => _("Balances")]);
      append($$anchor2, text_5);
    };
    if_block(node_4, ($$render) => {
      if ($$props.report_type !== "balances") $$render(consequent_2);
      else $$render(alternate_2, -1);
    });
  }
  reset(h3_2);
  reset(div_1);
  var node_5 = sibling(div_1, 2);
  {
    var consequent_3 = ($$anchor2) => {
      JournalTable($$anchor2, {
        get journal() {
          return $$props.journal;
        },
        initial_sort: ["date", "desc"],
        show_change_and_balance: true
      });
    };
    var consequent_4 = ($$anchor2) => {
      IntervalTreeTable($$anchor2, {
        get trees() {
          return $$props.interval_balances;
        },
        get dates() {
          return $$props.dates;
        },
        get budgets() {
          return $$props.budgets;
        },
        get accumulate() {
          return get2(accumulate);
        }
      });
    };
    var d = user_derived(() => $$props.interval_balances && is_non_empty($$props.interval_balances) && $$props.budgets && $$props.dates);
    if_block(node_5, ($$render) => {
      if ($$props.report_type === "journal" && $$props.journal != null) $$render(consequent_3);
      else if (get2(d)) $$render(consequent_4, 1);
    });
  }
  reset(div);
  template_effect(() => set_attribute(div, "data-account-name", $$props.account));
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/accounts/index.ts
var to_report_type = (s) => s === "balances" || s === "changes" ? s : "journal";
var NotAnAccountUrlError = class extends Error {
  constructor(pathname2) {
    super(`Path '${pathname2}' is not a path for the account report.`);
  }
};
function get_account_from_url(url) {
  return get_url_path(url).and_then((relative_path) => {
    const [base, account] = relative_path.split("/");
    if (base === "account" && account != null) {
      return ok(account);
    }
    return err(new NotAnAccountUrlError(relative_path));
  });
}
var account_report = new Route(
  "account",
  AccountReport,
  async (url) => {
    const account = get_account_from_url(url).unwrap();
    const report_type = to_report_type(url.searchParams.get("r"));
    const { charts, journal: journal2, interval_balances, dates, budgets } = await get_account_report({
      ...get_url_filters(url),
      a: account,
      r: report_type
    });
    return {
      charts,
      journal: journal2 != null ? fragment_from_string(journal2) : null,
      interval_balances,
      dates,
      budgets,
      account,
      report_type
    };
  },
  ({ account }) => `account:${account}`
);

// src/sort/SortHeader.svelte
var root24 = from_html(`<th data-sort=""> </th>`);
var root_123 = from_html(`<th> </th>`);
function SortHeader($$anchor, $$props) {
  push($$props, true);
  let sorter = prop($$props, "sorter", 15);
  let is_sortable = user_derived(() => !($$props.column instanceof UnsortedColumn));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var th = root24();
      var text2 = child(th, true);
      reset(th);
      template_effect(() => {
        set_attribute(th, "data-order", $$props.column === sorter().column ? sorter().order : void 0);
        set_text(text2, $$props.column.name);
      });
      delegated("click", th, () => {
        sorter(sorter().switch_column($$props.column));
      });
      append($$anchor2, th);
    };
    var alternate = ($$anchor2) => {
      var th_1 = root_123();
      var text_1 = child(th_1, true);
      reset(th_1);
      template_effect(() => set_text(text_1, $$props.column.name));
      append($$anchor2, th_1);
    };
    if_block(node, ($$render) => {
      if (get2(is_sortable)) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["click"]);

// src/reports/commodities/CommodityTable.svelte
var root25 = from_html(`<tr><td> </td><td class="num"> </td></tr>`);
var root_124 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function CommodityTable($$anchor, $$props) {
  push($$props, true);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const columns = [
    new NumberColumn(_("Date"), (d) => d[0].valueOf()),
    new NumberColumn(_("Price"), (d) => d[1])
  ];
  let sorter = state(proxy(new Sorter(columns[0], "desc")));
  let sorted_prices = user_derived(() => get2(sorter).sort($$props.prices));
  let quote_name = user_derived(() => $currency_name()($$props.quote));
  var table = root_124();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_prices), ([date3, value]) => date3, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let date3 = () => get2($$array)[0];
    let value = () => get2($$array)[1];
    var tr_1 = root25();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(
      ($0, $1) => {
        set_text(text2, $0);
        set_attribute(td_1, "title", get2(quote_name));
        set_text(text_1, $1);
      },
      [
        () => day(date3()),
        () => $ctx().amount(value(), $$props.quote)
      ]
    );
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
  $$cleanup();
}

// src/reports/commodities/Commodities.svelte
var root26 = from_html(`<div class="left"><h3><span> </span> / <span> </span></h3> <!></div>`);
var root_125 = from_html(`<!> <!>`, 1);
function Commodities($$anchor, $$props) {
  push($$props, true);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var fragment = root_125();
  var node = first_child(fragment);
  ChartSwitcher(node, {
    get charts() {
      return $$props.charts;
    }
  });
  var node_1 = sibling(node, 2);
  each(node_1, 17, () => $$props.commodities, ({ base, quote, prices }) => `${base}-${quote}`, ($$anchor2, $$item) => {
    let base = () => get2($$item).base;
    let quote = () => get2($$item).quote;
    let prices = () => get2($$item).prices;
    var div = root26();
    var h3 = child(div);
    var span = child(h3);
    var text2 = child(span, true);
    reset(span);
    var span_1 = sibling(span, 2);
    var text_1 = child(span_1, true);
    reset(span_1);
    reset(h3);
    var node_2 = sibling(h3, 2);
    CommodityTable(node_2, {
      get prices() {
        return prices();
      },
      get quote() {
        return quote();
      }
    });
    reset(div);
    template_effect(
      ($0, $1) => {
        set_attribute(span, "title", $0);
        set_text(text2, base());
        set_attribute(span_1, "title", $1);
        set_text(text_1, quote());
      },
      [
        () => $currency_name()(base()),
        () => $currency_name()(quote())
      ]
    );
    append($$anchor2, div);
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/commodities/index.ts
var commodities = new Route(
  "commodities",
  Commodities,
  async (url) => get_commodities(get_url_filters(url)).then((cs) => {
    const charts = cs.map(({ base, quote, prices }) => {
      const name = `${base} / ${quote}`;
      const values = prices.map((d) => ({ name, date: d[0], value: d[1] }));
      return new LineChart(name, [{ name, values }], (c, d) => [
        `1 ${base} = ${c.amount(d.value, quote)}`,
        domHelpers.em(day(d.date))
      ]);
    });
    return { commodities: cs, charts };
  }),
  () => _("Commodities")
);

// src/lib/fuzzy.ts
function fuzzytest(pattern, text2) {
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    return pattern.length ** 2;
  }
  let score = 0;
  let localScore = 0;
  let pindex = 0;
  for (const char of text2) {
    const search = pattern[pindex];
    if (char === search || char.toLowerCase() === search) {
      pindex += 1;
      localScore += 1;
    } else {
      localScore = 0;
    }
    score += localScore;
  }
  return pindex === pattern.length ? score : 0;
}
function fuzzyfilter(pattern, suggestions) {
  if (!pattern) {
    return suggestions;
  }
  return suggestions.map((s) => [s, fuzzytest(pattern, s)]).filter(([, score]) => score > 0).sort((a, b) => b[1] - a[1]).map(([s]) => s);
}
function fuzzywrap(pattern, text2) {
  if (!pattern) {
    return [["text", text2]];
  }
  const casesensitive = pattern === pattern.toLowerCase();
  const exact = casesensitive ? text2.toLowerCase().indexOf(pattern) : text2.indexOf(pattern);
  if (exact > -1) {
    const before = text2.slice(0, exact);
    const match2 = text2.slice(exact, exact + pattern.length);
    const after = text2.slice(exact + pattern.length);
    const result2 = [];
    if (before) {
      result2.push(["text", before]);
    }
    result2.push(["match", match2]);
    if (after) {
      result2.push(["text", after]);
    }
    return result2;
  }
  let pindex = 0;
  let plain = null;
  let match = null;
  const result = [];
  for (const char of text2) {
    const search = pattern[pindex];
    if (char === search || char.toLowerCase() === search) {
      match = match != null ? match + char : char;
      if (plain != null) {
        result.push(["text", plain]);
        plain = null;
      }
      pindex += 1;
    } else {
      plain = plain != null ? plain + char : char;
      if (match != null) {
        result.push(["match", match]);
        match = null;
      }
    }
  }
  if (pindex < pattern.length) {
    return [["text", text2]];
  }
  if (plain != null) {
    result.push(["text", plain]);
  }
  if (match != null) {
    result.push(["match", match]);
  }
  return result;
}

// src/components/AutocompleteInput.svelte
var root27 = from_html(`<button type="button" class="muted round svelte-1kd9pqk">\xD7</button>`);
var root_126 = from_html(`<span class="svelte-1kd9pqk"> </span>`);
var root_212 = from_html(`<li role="option" class="svelte-1kd9pqk"></li>`);
var root_35 = from_html(`<ul role="listbox" class="svelte-1kd9pqk"></ul>`);
var root_43 = from_html(`<span class="svelte-1kd9pqk"><input type="text" autocomplete="off" role="combobox" aria-autocomplete="list"/> <!> <!></span>`);
function AutocompleteInput($$anchor, $$props) {
  const uid = props_id();
  push($$props, true);
  let value = prop($$props, "value", 15), suggestions = prop($$props, "suggestions", 19, () => []), automatic_selection = prop($$props, "automatic_selection", 3, false), set_size = prop($$props, "set_size", 3, false), clear_button = prop($$props, "clear_button", 3, false);
  const autocomplete_id = `combobox-autocomplete-${uid}`;
  let hidden = state(true);
  let index2 = state(-1);
  let input = state(void 0);
  let tab_pressed = false;
  let extracted_value = user_derived(() => get2(input) && $$props.value_extractor ? $$props.value_extractor(value(), get2(input)) : value());
  let filtered_suggestions = user_derived(() => {
    const filtered = fuzzyfilter(get2(extracted_value), suggestions()).slice(0, 30);
    return filtered.length === 1 && filtered[0] === get2(extracted_value) ? [] : filtered;
  });
  user_effect(() => {
    const msg = $$props.check_validity ? $$props.check_validity(value()) : "";
    get2(input)?.setCustomValidity(msg);
  });
  user_pre_effect(() => {
    const last = get2(filtered_suggestions).length - 1;
    const first = automatic_selection() && last > -1 ? 0 : -1;
    set(index2, Math.min(Math.max(get2(index2), first), last));
  });
  function blur() {
    get2(input)?.blur();
  }
  function select(suggestion) {
    value(get2(input) && $$props.value_selector ? $$props.value_selector(suggestion, get2(input)) : suggestion);
    $$props.onchange?.(value());
    $$props.onselect?.();
    set(hidden, true);
  }
  let expanded = user_derived(() => !get2(hidden) && get2(filtered_suggestions).length > 0);
  let active_suggestion = user_derived(() => get2(expanded) && get2(index2) > -1 ? get2(filtered_suggestions)[get2(index2)] : void 0);
  let active_id = user_derived(() => get2(expanded) && get2(index2) > -1 ? `${autocomplete_id}-${get2(index2).toString()}` : void 0);
  function onkeydown(event2) {
    const key2 = normalise_key(event2);
    tab_pressed = key2 === "Tab";
    if (key2 === "Enter") {
      if (get2(active_suggestion) != null) {
        select(get2(active_suggestion));
      } else {
        $$props.onchange?.(value());
        $$props.onenter?.();
        return;
      }
    } else if (key2 === "Escape") {
      if (get2(expanded)) {
        set(index2, -1);
        set(hidden, true);
      } else if (value()) {
        value("");
      } else {
        return;
      }
    } else if (key2 === "ArrowUp") {
      if (get2(expanded)) {
        set(index2, get2(index2) <= 0 ? get2(filtered_suggestions).length - 1 : get2(index2) - 1);
      }
    } else if (key2 === "ArrowDown") {
      if (get2(expanded)) {
        set(index2, get2(index2) === get2(filtered_suggestions).length - 1 ? 0 : get2(index2) + 1);
      } else {
        set(hidden, false);
      }
    } else if (key2 === "Alt+ArrowDown") {
      set(hidden, false);
    } else if (key2 === "Alt+ArrowUp") {
      set(hidden, true);
    } else {
      return;
    }
    event2.preventDefault();
    event2.stopPropagation();
  }
  var $$exports = { blur };
  var span = root_43();
  var input_1 = child(span);
  remove_input_defaults(input_1);
  bind_this(input_1, ($$value) => set(input, $$value), () => get2(input));
  attach(input_1, () => keyboardShortcut($$props.key));
  var node = sibling(input_1, 2);
  {
    var consequent = ($$anchor2) => {
      var button = root27();
      set_attribute(button, "tabindex", -1);
      delegated("click", button, () => {
        value("");
        $$props.onchange?.(value());
      });
      append($$anchor2, button);
    };
    if_block(node, ($$render) => {
      if (clear_button() && value()) $$render(consequent);
    });
  }
  var node_1 = sibling(node, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var ul = root_35();
      each(ul, 22, () => get2(filtered_suggestions), (suggestion) => suggestion, ($$anchor3, suggestion, i) => {
        var li = root_212();
        each(li, 21, () => fuzzywrap(get2(extracted_value), suggestion), index, ($$anchor4, $$item, i2, $$array) => {
          var $$array_1 = user_derived(() => to_array(get2($$item), 2));
          let type = () => get2($$array_1)[0];
          let text2 = () => get2($$array_1)[1];
          var fragment = comment();
          var node_2 = first_child(fragment);
          {
            var consequent_1 = ($$anchor5) => {
              var text_1 = text();
              template_effect(() => set_text(text_1, text2()));
              append($$anchor5, text_1);
            };
            var alternate = ($$anchor5) => {
              var span_1 = root_126();
              var text_2 = child(span_1, true);
              reset(span_1);
              template_effect(() => set_text(text_2, text2()));
              append($$anchor5, span_1);
            };
            if_block(node_2, ($$render) => {
              if (type() === "text") $$render(consequent_1);
              else $$render(alternate, -1);
            });
          }
          append($$anchor4, fragment);
        });
        reset(li);
        template_effect(
          ($0) => {
            set_attribute(li, "id", $0);
            set_attribute(li, "aria-selected", get2(i) === get2(index2));
          },
          [() => `${autocomplete_id}-${get2(i).toString()}`]
        );
        delegated("mousedown", li, (event2) => {
          if (event2.button === 0) {
            select(suggestion);
          }
        });
        append($$anchor3, li);
      });
      reset(ul);
      template_effect(() => set_attribute(ul, "id", autocomplete_id));
      append($$anchor2, ul);
    };
    if_block(node_1, ($$render) => {
      if (get2(expanded)) $$render(consequent_2);
    });
  }
  reset(span);
  template_effect(() => {
    set_class(input_1, 1, clsx({ "content-sized": set_size() }), "svelte-1kd9pqk");
    set_attribute(input_1, "aria-expanded", get2(expanded));
    set_attribute(input_1, "aria-controls", autocomplete_id);
    set_attribute(input_1, "aria-activedescendant", get2(active_id));
    set_attribute(input_1, "placeholder", $$props.placeholder);
    input_1.required = $$props.required;
  });
  event("blur", input_1, () => {
    if (automatic_selection() && tab_pressed && get2(active_suggestion) != null) {
      select(get2(active_suggestion));
    } else {
      $$props.onchange?.(value());
      set(hidden, true);
    }
    tab_pressed = false;
  });
  event("focus", input_1, () => {
    set(hidden, false);
  });
  delegated("input", input_1, () => {
    set(hidden, false);
    set(index2, -1);
  });
  delegated("keydown", input_1, onkeydown);
  bind_value(input_1, value);
  append($$anchor, span);
  return pop($$exports);
}
delegate(["input", "keydown", "click", "mousedown"]);

// src/entry-forms/AccountInput.svelte
function AccountInput($$anchor, $$props) {
  push($$props, true);
  const $accounts_set = () => store_get(accounts_set, "$accounts_set", $$stores);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const $is_closed_account = () => store_get(is_closed_account, "$is_closed_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let value = prop($$props, "value", 15);
  let check_validity = user_derived(() => (val) => !$accounts_set().size || $accounts_set().has(val) || $$props.required !== true && !val ? "" : _("Should be one of the declared accounts"));
  let parsed_date = user_derived(() => date($$props.date).unwrap_or(null));
  let account_suggestions = user_derived(() => $$props.suggestions ?? $accounts());
  let filtered_suggestions = user_derived(() => get2(parsed_date) ? get2(account_suggestions).filter((account) => !$is_closed_account()(account, get2(parsed_date))) : get2(account_suggestions));
  {
    let $0 = user_derived(() => _("Account"));
    AutocompleteInput($$anchor, {
      get placeholder() {
        return get2($0);
      },
      get check_validity() {
        return get2(check_validity);
      },
      automatic_selection: true,
      get required() {
        return $$props.required;
      },
      get suggestions() {
        return get2(filtered_suggestions);
      },
      get value() {
        return value();
      },
      set value($$value) {
        value($$value);
      }
    });
  }
  pop();
  $$cleanup();
}

// src/lib/paths.ts
function split(path) {
  if (path.length < 2) {
    return ["", path];
  }
  const lastIndexOfSlash = path.lastIndexOf("/", path.length - 2);
  const lastIndexOfBackslash = path.lastIndexOf("\\", path.length - 2);
  const lastIndex = lastIndexOfSlash > lastIndexOfBackslash ? lastIndexOfSlash : lastIndexOfBackslash;
  if (lastIndex < 0) {
    return ["", path];
  }
  return [path.substring(0, lastIndex + 1), path.substring(lastIndex + 1)];
}
function basename(filename2) {
  return split(filename2)[1];
}
function ext(filename2) {
  const match = /\.(\w+)$/.exec(filename2);
  return match?.[1] ?? "";
}
function document_has_account(filename2, account) {
  const accountParts = account.split(":").reverse();
  const folders = filename2.split(/\/|\\/).reverse().slice(1);
  return accountParts.every((part, index2) => part === folders[index2]);
}

// src/lib/tree.ts
function stratify_accounts(data, id, init2) {
  return stratify(
    [...data].sort((a, b) => compare_strings(id(a), id(b))),
    id,
    init2,
    parent
  );
}
function stratify(data, id, init2, parent2) {
  const root93 = { children: [], ...init2("") };
  const map = /* @__PURE__ */ new Map();
  map.set("", root93);
  function add_node(name, datum2) {
    const existing = map.get(name);
    if (existing) {
      Object.assign(existing, init2(name, datum2));
      return existing;
    }
    const node = { children: [], ...init2(name, datum2) };
    map.set(name, node);
    const parentName = parent2(name);
    const parentNode = map.get(parentName) ?? add_node(parentName);
    parentNode.children.push(node);
    return node;
  }
  [...data].forEach((datum2) => {
    add_node(id(datum2), datum2);
  });
  return root93;
}
function* all_matching(root93, predicate) {
  if (predicate(root93)) {
    yield root93;
  }
  for (const child2 of root93.children) {
    for (const match of all_matching(child2, predicate)) {
      yield match;
    }
  }
}

// src/modals/ModalBase.svelte
var root28 = from_html(`<dialog class="svelte-17bkxwi"><div class="content svelte-17bkxwi"><!> <button type="button" class="muted close svelte-17bkxwi">x</button></div></dialog>`);
function ModalBase($$anchor, $$props) {
  push($$props, true);
  let close_handler = prop($$props, "close_handler", 19, () => router.close_overlay);
  const modal = (el) => {
    el.showModal();
    const focus_el = $$props.focus != null ? el.querySelector($$props.focus) : null;
    if (focus_el instanceof HTMLElement) {
      focus_el.focus();
    }
    return () => {
      el.close();
    };
  };
  let pressed_on_backdrop = false;
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var dialog = root28();
      var div = child(dialog);
      var node_1 = child(div);
      snippet(node_1, () => $$props.children);
      var button = sibling(node_1, 2);
      reset(div);
      reset(dialog);
      attach(dialog, () => modal);
      event("cancel", dialog, (event2) => {
        event2.preventDefault();
        close_handler()();
      });
      delegated("mousedown", dialog, (event2) => {
        pressed_on_backdrop = event2.button === 0 && event2.target === event2.currentTarget;
      });
      delegated("mouseup", dialog, (event2) => {
        if (pressed_on_backdrop && event2.target === event2.currentTarget) {
          close_handler()();
        }
        pressed_on_backdrop = false;
      });
      delegated("click", button, function(...$$args) {
        close_handler()?.apply(this, $$args);
      });
      append($$anchor2, dialog);
    };
    if_block(node, ($$render) => {
      if ($$props.shown) $$render(consequent);
    });
  }
  append($$anchor, fragment);
  pop();
}
delegate(["mousedown", "mouseup", "click"]);

// src/reports/documents/stores.ts
var selected_account = writable("");

// src/reports/documents/Accounts.svelte
var root29 = from_html(`<button type="button" class="unset toggle svelte-1howsa4"> </button>`);
var root_127 = from_html(`<span class="count svelte-1howsa4"> </span>`);
var root_213 = from_html(`<p><!> <button type="button" class="unset leaf svelte-1howsa4"> </button> <!></p>`);
var root_36 = from_html(`<li><!></li>`);
var root_44 = from_html(`<ul class="svelte-1howsa4"></ul>`);
var root_53 = from_html(`<!> <!>`, 1);
function Accounts_1($$anchor, $$props) {
  push($$props, true);
  const $toggled_accounts = () => store_get(toggled_accounts, "$toggled_accounts", $$stores);
  const $selected_account = () => store_get(selected_account, "$selected_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let account = user_derived(() => $$props.node.name);
  let drag = state(false);
  let is_toggled = user_derived(() => $toggled_accounts().has(get2(account)));
  let hasChildren = user_derived(() => $$props.node.children.length > 0);
  let selected = user_derived(() => $selected_account() === $$props.node.name);
  function dragenter(event2) {
    const types = event2.dataTransfer?.types ?? [];
    if (types.includes("fava/filename")) {
      event2.preventDefault();
      set(drag, true);
    }
  }
  function drop(event2) {
    event2.preventDefault();
    const filename2 = event2.dataTransfer?.getData("fava/filename");
    if (filename2 != null) {
      $$props.move({ account: $$props.node.name, filename: filename2 });
      set(drag, false);
    }
  }
  var fragment = root_53();
  var node_1 = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var p = root_213();
      let classes;
      var node_2 = child(p);
      {
        var consequent = ($$anchor3) => {
          var button = root29();
          var text2 = child(button, true);
          reset(button);
          template_effect(() => set_text(text2, get2(is_toggled) ? "\u25B8" : "\u25BE"));
          delegated("click", button, (event2) => {
            toggle_account(get2(account), event2);
            event2.stopPropagation();
          });
          append($$anchor3, button);
        };
        if_block(node_2, ($$render) => {
          if (get2(hasChildren)) $$render(consequent);
        });
      }
      var button_1 = sibling(node_2, 2);
      var text_1 = child(button_1, true);
      reset(button_1);
      var node_3 = sibling(button_1, 2);
      {
        var consequent_1 = ($$anchor3) => {
          var span = root_127();
          var text_2 = child(span, true);
          reset(span);
          template_effect(() => set_text(text_2, $$props.node.count));
          append($$anchor3, span);
        };
        if_block(node_3, ($$render) => {
          if ($$props.node.count > 0) $$render(consequent_1);
        });
      }
      reset(p);
      template_effect(
        ($0) => {
          set_attribute(p, "title", get2(account));
          classes = set_class(p, 1, "droptarget svelte-1howsa4", null, classes, { selected: get2(selected), drag: get2(drag) });
          set_attribute(p, "data-account-name", get2(account));
          set_text(text_1, $0);
        },
        [() => leaf(get2(account))]
      );
      event("dragenter", p, dragenter);
      event("dragover", p, dragenter);
      event("dragleave", p, () => {
        set(drag, false);
      });
      event("drop", p, drop);
      delegated("click", button_1, () => {
        store_set(selected_account, get2(selected) ? "" : get2(account));
      });
      append($$anchor2, p);
    };
    if_block(node_1, ($$render) => {
      if (get2(account)) $$render(consequent_2);
    });
  }
  var node_4 = sibling(node_1, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ul = root_44();
      each(ul, 21, () => $$props.node.children, (child2) => child2.name, ($$anchor3, child2) => {
        var li = root_36();
        var node_5 = child(li);
        Accounts_1(node_5, {
          get node() {
            return get2(child2);
          },
          get move() {
            return $$props.move;
          }
        });
        reset(li);
        append($$anchor3, li);
      });
      reset(ul);
      append($$anchor2, ul);
    };
    if_block(node_4, ($$render) => {
      if (get2(hasChildren) && !get2(is_toggled)) $$render(consequent_3);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/editor/DocumentPreviewEditor.svelte
var root30 = from_html(`<div class="svelte-d0l25j"></div>`);
function DocumentPreviewEditor($$anchor, $$props) {
  push($$props, true);
  const editor2 = $$props.codemirror_bql.init_document_preview_editor();
  const set_editor_content = (value) => {
    if (value !== editor2.state.sliceDoc()) {
      editor2.dispatch($$props.codemirror_bql.replace_contents(editor2.state, value));
    }
  };
  user_effect(() => {
    fetch_text($$props.url).then(set_editor_content, () => {
      set_editor_content(`Loading ${$$props.url} failed...`);
    });
  });
  var div = root30();
  attach(div, () => attach_editor(editor2));
  append($$anchor, div);
  pop();
}

// src/reports/documents/DocumentPreview.svelte
var plainTextExtensions = ["csv", "json", "qfx", "txt", "xml"];
var imageExtensions = ["gif", "jpg", "jpeg", "png", "svg", "webp", "bmp", "ico"];
var root31 = from_html(`<object class="svelte-lbsh4h"></object>`);
var root_128 = from_html(`<img class="svelte-lbsh4h"/>`);
var root_214 = from_html(`<iframe sandbox="" class="svelte-lbsh4h"></iframe>`);
function DocumentPreview($$anchor, $$props) {
  push($$props, true);
  const $url_for_raw = () => store_get(url_for_raw, "$url_for_raw", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let extension = user_derived(() => ext($$props.filename).toLowerCase());
  let url = user_derived(() => $url_for_raw()("document/", { filename: $$props.filename }));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var object = root31();
      template_effect(() => {
        set_attribute(object, "title", $$props.filename);
        set_attribute(object, "data", get2(url));
      });
      append($$anchor2, object);
    };
    var consequent_1 = ($$anchor2) => {
      var fragment_1 = comment();
      var node_1 = first_child(fragment_1);
      await_block(node_1, () => import("./bql-76XJMPXB.js"), null, ($$anchor3, codemirror_bql) => {
        DocumentPreviewEditor($$anchor3, {
          get url() {
            return get2(url);
          },
          get codemirror_bql() {
            return get2(codemirror_bql);
          }
        });
      });
      append($$anchor2, fragment_1);
    };
    var d = user_derived(() => plainTextExtensions.includes(get2(extension)));
    var consequent_2 = ($$anchor2) => {
      var img = root_128();
      template_effect(() => {
        set_attribute(img, "src", get2(url));
        set_attribute(img, "alt", $$props.filename);
      });
      append($$anchor2, img);
    };
    var d_1 = user_derived(() => imageExtensions.includes(get2(extension)));
    var consequent_3 = ($$anchor2) => {
      var iframe = root_214();
      template_effect(() => {
        set_attribute(iframe, "src", get2(url));
        set_attribute(iframe, "title", $$props.filename);
      });
      append($$anchor2, iframe);
    };
    var d_2 = user_derived(() => ["html", "htm"].includes(get2(extension)));
    var alternate = ($$anchor2) => {
      var text2 = text();
      template_effect(() => set_text(text2, `Preview for file \`${$$props.filename ?? ""}\` with file type \`${get2(extension) ?? ""}\` is not implemented`));
      append($$anchor2, text2);
    };
    if_block(node, ($$render) => {
      if (get2(extension) === "pdf") $$render(consequent);
      else if (get2(d)) $$render(consequent_1, 1);
      else if (get2(d_1)) $$render(consequent_2, 2);
      else if (get2(d_2)) $$render(consequent_3, 3);
      else $$render(alternate, -1);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/documents/Table.svelte
var root32 = from_html(`<tr><td> </td><td> </td></tr>`);
var root_129 = from_html(`<table class="svelte-h1lesc"><thead><tr class="svelte-h1lesc"></tr></thead><tbody></tbody></table>`);
function Table($$anchor, $$props) {
  push($$props, true);
  const $selected_account = () => store_get(selected_account, "$selected_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let selected = prop($$props, "selected", 15, null);
  function name(doc) {
    const base = basename(doc.filename);
    return base.startsWith(doc.date) ? base.substring(11) : base;
  }
  const columns = [
    new DateColumn(_("Date")),
    new StringColumn(_("Name"), (d) => name(d))
  ];
  let sorter = state(proxy(new Sorter(columns[0], "desc")));
  let is_descendant_of_selected = user_derived(() => is_descendant_or_equal($selected_account()));
  let filtered_documents = user_derived(() => $$props.data.filter((doc) => get2(is_descendant_of_selected)(doc.account)));
  let sorted_documents = user_derived(() => get2(sorter).sort(get2(filtered_documents)));
  var table = root_129();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_documents), index, ($$anchor2, doc) => {
    var tr_1 = root32();
    set_attribute(tr_1, "draggable", true);
    let classes;
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(
      ($0) => {
        set_attribute(tr_1, "title", get2(doc).filename);
        classes = set_class(tr_1, 1, "svelte-h1lesc", null, classes, { selected: selected() === get2(doc) });
        set_text(text2, get2(doc).date);
        set_text(text_1, $0);
      },
      [() => name(get2(doc))]
    );
    event("dragstart", tr_1, (ev) => {
      ev.dataTransfer?.setData("fava/filename", get2(doc).filename);
    });
    delegated("click", tr_1, () => {
      selected(get2(doc));
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/documents/Documents.svelte
var root33 = from_html(`<form><h3> </h3> <p><code> </code></p> <p><!> <input/> <button type="submit"> </button></p></form>`);
var root_130 = from_html(`<!> <div class="fixed-fullsize-container svelte-1cxxz8m"><!> <div><!></div> <!></div>`, 1);
function Documents($$anchor, $$props) {
  push($$props, true);
  let grouped = user_derived(() => group($$props.documents, (d) => d.account));
  let node = user_derived(() => stratify_accounts(get2(grouped).entries(), ([s]) => s, (name, d) => ({ name, count: d?.[1].length ?? 0 })));
  let selected = state(null);
  let moving = state(null);
  function keyup(ev) {
    if (ev.key === "F2" && get2(selected) && !get2(moving)) {
      set(
        moving,
        {
          account: get2(selected).account,
          filename: get2(selected).filename,
          new_name: basename(get2(selected).filename)
        },
        true
      );
    }
  }
  async function move2(event2) {
    event2.preventDefault();
    if (get2(moving)) {
      const moved = await move_document(get2(moving).filename, get2(moving).account, get2(moving).new_name);
      if (moved) {
        set(moving, null);
        router.reload();
      }
    }
  }
  var fragment = root_130();
  event("keyup", $window, keyup);
  var node_1 = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      ModalBase($$anchor2, {
        shown: true,
        close_handler: () => {
          set(moving, null);
        },
        children: ($$anchor3, $$slotProps) => {
          var form = root33();
          var h3 = child(form);
          var text2 = child(h3, true);
          reset(h3);
          var p = sibling(h3, 2);
          var code = child(p);
          var text_1 = child(code, true);
          reset(code);
          reset(p);
          var p_1 = sibling(p, 2);
          var node_2 = child(p_1);
          AccountInput(node_2, {
            get value() {
              return get2(moving).account;
            },
            set value($$value) {
              get2(moving).account = $$value;
            }
          });
          var input = sibling(node_2, 2);
          remove_input_defaults(input);
          set_attribute(input, "size", 40);
          var button = sibling(input, 2);
          var text_2 = child(button, true);
          reset(button);
          reset(p_1);
          reset(form);
          template_effect(
            ($0, $1) => {
              set_text(text2, $0);
              set_text(text_1, get2(moving).filename);
              set_text(text_2, $1);
            },
            [() => _("Move or rename document"), () => _("Move")]
          );
          event("submit", form, move2);
          bind_value(input, () => get2(moving).new_name, ($$value) => get2(moving).new_name = $$value);
          append($$anchor3, form);
        },
        $$slots: { default: true }
      });
    };
    if_block(node_1, ($$render) => {
      if (get2(moving)) $$render(consequent);
    });
  }
  var div = sibling(node_1, 2);
  var node_3 = child(div);
  Accounts_1(node_3, {
    get node() {
      return get2(node);
    },
    move: (arg) => {
      set(moving, { ...arg, new_name: basename(arg.filename) }, true);
    }
  });
  var div_1 = sibling(node_3, 2);
  var node_4 = child(div_1);
  Table(node_4, {
    get data() {
      return $$props.documents;
    },
    get selected() {
      return get2(selected);
    },
    set selected($$value) {
      set(selected, $$value, true);
    }
  });
  reset(div_1);
  var node_5 = sibling(div_1, 2);
  {
    var consequent_1 = ($$anchor2) => {
      DocumentPreview($$anchor2, {
        get filename() {
          return get2(selected).filename;
        }
      });
    };
    if_block(node_5, ($$render) => {
      if (get2(selected)) $$render(consequent_1);
    });
  }
  reset(div);
  append($$anchor, fragment);
  pop();
}

// src/reports/documents/index.ts
var documents2 = new Route(
  "documents",
  Documents,
  async (url) => get_documents(get_url_filters(url)).then((data) => ({
    documents: data
  })),
  () => _("Documents")
);

// src/editor/SaveButton.svelte
var root34 = from_html(`<button type="submit"> </button>`);
function SaveButton($$anchor, $$props) {
  push($$props, true);
  let buttonContent = user_derived(() => $$props.saving ? _("Saving\u2026") : _("Save"));
  var button = root34();
  var text2 = child(button, true);
  reset(button);
  attach(button, () => keyboardShortcut({ key: "Control+s", mac: "Meta+s" }));
  template_effect(() => {
    button.disabled = !$$props.changed;
    set_text(text2, get2(buttonContent));
  });
  append($$anchor, button);
  pop();
}

// src/reports/editor/AppMenu.svelte
var root35 = from_html(`<div role="menubar" class="svelte-1aqjxq1"><!></div>`);
function AppMenu($$anchor, $$props) {
  var div = root35();
  var node = child(div);
  snippet(node, () => $$props.children);
  reset(div);
  append($$anchor, div);
}

// src/reports/editor/AppMenuItem.svelte
var root36 = from_html(`<span tabindex="0" role="menuitem"> <ul role="menu" class="svelte-15fjecu"><!></ul></span>`);
function AppMenuItem($$anchor, $$props) {
  let open = state(false);
  var span = root36();
  let classes;
  var text2 = child(span);
  var ul = sibling(text2);
  var node = child(ul);
  snippet(node, () => $$props.children);
  reset(ul);
  reset(span);
  template_effect(() => {
    classes = set_class(span, 1, "svelte-15fjecu", null, classes, { open: get2(open) });
    set_text(text2, `${$$props.name ?? ""} `);
  });
  event("blur", span, () => {
    set(open, false);
  });
  delegated("keydown", span, (event2) => {
    if (event2.key === "Escape") {
      set(open, false);
    } else if (event2.key === "ArrowDown") {
      set(open, true);
    }
  });
  append($$anchor, span);
}
delegate(["keydown"]);

// src/reports/editor/AppMenuSubItem.svelte
var root37 = from_html(`<span class="svelte-130gbuy"><!></span>`);
var root_131 = from_html(`<li role="menuitem"><!> <!></li>`);
function AppMenuSubItem($$anchor, $$props) {
  push($$props, true);
  let selected = prop($$props, "selected", 3, false);
  var li = root_131();
  let classes;
  var node = child(li);
  snippet(node, () => $$props.children);
  var node_1 = sibling(node, 2);
  {
    var consequent = ($$anchor2) => {
      var span = root37();
      var node_2 = child(span);
      snippet(node_2, () => $$props.right);
      reset(span);
      append($$anchor2, span);
    };
    if_block(node_1, ($$render) => {
      if ($$props.right) $$render(consequent);
    });
  }
  reset(li);
  template_effect(() => {
    set_attribute(li, "title", $$props.title);
    classes = set_class(li, 1, "svelte-130gbuy", null, classes, { selected: selected() });
  });
  delegated("click", li, function(...$$args) {
    $$props.action?.apply(this, $$args);
  });
  delegated("keydown", li, (event2) => {
    if (event2.key === "Enter") {
      $$props.action();
    }
  });
  append($$anchor, li);
  pop();
}
delegate(["click", "keydown"]);

// src/reports/editor/Key.svelte
var root38 = from_html(`<kbd> </kbd> `, 1);
function Key($$anchor, $$props) {
  push($$props, true);
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 18, () => $$props.key, (part) => part, ($$anchor2, part, index2) => {
    var fragment_1 = root38();
    var kbd = first_child(fragment_1);
    var text2 = child(kbd, true);
    reset(kbd);
    var text_1 = sibling(kbd, 1, true);
    template_effect(() => {
      set_text(text2, part);
      set_text(text_1, get2(index2) === $$props.key.length - 1 ? "" : "+");
    });
    append($$anchor2, fragment_1);
  });
  append($$anchor, fragment);
  pop();
}

// src/lib/sources.ts
function is_directory(node) {
  return node.children.length > 0;
}
function build_compressed_sources_tree(sources2) {
  const root93 = stratify(
    sources2,
    (path) => path,
    (path) => ({ name: basename(path), path }),
    (path) => split(path)[0]
  );
  return compress_tree(root93);
}
function compress_tree(parent2) {
  const { children: children2, name, path } = parent2;
  if (children2.length === 0) {
    return parent2;
  }
  const [first_child2] = children2;
  if (children2.length === 1 && first_child2 != null) {
    if (first_child2.children.length === 0) {
      return parent2;
    }
    return compress_tree({
      name: name + first_child2.name,
      path: first_child2.path,
      children: first_child2.children
    });
  } else {
    return { name, path, children: children2.map(compress_tree) };
  }
}

// src/reports/editor/stores.ts
var sources_tree = derived(sources, build_compressed_sources_tree);
var expanded_directories = writable(
  /* @__PURE__ */ new Map()
);
function toggle_directory(directory, expand, event2) {
  const $sources_tree = get(sources_tree);
  expanded_directories.update(($expanded_directories) => {
    const new_expanded_directories = new Map($expanded_directories);
    new_expanded_directories.set(directory, expand);
    if (event2.shiftKey) {
      const descendants = all_matching(
        $sources_tree,
        (node) => is_directory(node) && node.path.startsWith(directory)
      );
      for (const node of descendants) {
        new_expanded_directories.set(node.path, expand);
      }
    } else if (event2.ctrlKey || event2.metaKey) {
      const direct_children = all_matching(
        $sources_tree,
        (node) => is_directory(node) && split(node.path)[0] === directory
      );
      for (const node of direct_children) {
        new_expanded_directories.set(node.path, expand);
      }
    }
    return new_expanded_directories;
  });
}

// src/reports/editor/Sources.svelte
var root39 = from_html(`<button type="button" title="Beancount data root directory
Shift-Click to expand/collapse immediate directories
Ctrl-/Cmd-/Meta-Click to expand/collapse all directories." class="unset root svelte-1848zi3"> </button>`);
var root_132 = from_html(`<button type="button" class="unset toggle svelte-1848zi3"> </button>`);
var root_215 = from_html(`<p class="svelte-1848zi3"><!> <button type="button" class="unset leaf svelte-1848zi3"> </button></p>`);
var root_37 = from_html(`<ul class="svelte-1848zi3"></ul>`);
var root_45 = from_html(`<li role="menuitem"><!> <!></li>`);
function Sources_1($$anchor, $$props) {
  push($$props, true);
  const $expanded_directories = () => store_get(expanded_directories, "$expanded_directories", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let is_root = prop($$props, "is_root", 3, false);
  let is_expanded = user_derived(() => {
    const result = $expanded_directories().get($$props.node.path);
    return result ?? (!is_root() && $$props.selected.startsWith($$props.node.path));
  });
  let is_directory2 = user_derived(() => $$props.node.children.length > 0);
  let is_selected = user_derived(() => get2(is_directory2) && !get2(is_expanded) && !is_root() ? $$props.selected.startsWith($$props.node.path) : $$props.selected === $$props.node.path);
  let action = (event2) => {
    if (get2(is_directory2)) {
      toggle_directory($$props.node.path, !get2(is_expanded), event2);
    } else {
      $$props.on_select($$props.node.path);
    }
    event2.stopPropagation();
  };
  var li = root_45();
  let classes;
  var node_1 = child(li);
  {
    var consequent = ($$anchor2) => {
      var button = root39();
      var text2 = child(button, true);
      reset(button);
      template_effect(() => set_text(text2, $$props.node.name));
      delegated("click", button, action);
      append($$anchor2, button);
    };
    var alternate = ($$anchor2) => {
      var p = root_215();
      var node_2 = child(p);
      {
        var consequent_1 = ($$anchor3) => {
          var button_1 = root_132();
          var text_1 = child(button_1, true);
          reset(button_1);
          template_effect(() => set_text(text_1, get2(is_expanded) ? "\u25BE" : "\u25B8"));
          delegated("click", button_1, action);
          append($$anchor3, button_1);
        };
        if_block(node_2, ($$render) => {
          if (get2(is_directory2)) $$render(consequent_1);
        });
      }
      var button_2 = sibling(node_2, 2);
      var text_2 = child(button_2, true);
      reset(button_2);
      reset(p);
      template_effect(() => set_text(text_2, $$props.node.name));
      delegated("click", button_2, action);
      append($$anchor2, p);
    };
    if_block(node_1, ($$render) => {
      if (is_root()) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  var node_3 = sibling(node_1, 2);
  {
    var consequent_2 = ($$anchor2) => {
      var ul = root_37();
      each(ul, 21, () => $$props.node.children, (child2) => child2.path, ($$anchor3, child2) => {
        Sources_1($$anchor3, {
          get node() {
            return get2(child2);
          },
          get on_select() {
            return $$props.on_select;
          },
          get selected() {
            return $$props.selected;
          }
        });
      });
      reset(ul);
      append($$anchor2, ul);
    };
    if_block(node_3, ($$render) => {
      if (get2(is_directory2) && (get2(is_expanded) || is_root())) $$render(consequent_2);
    });
  }
  reset(li);
  template_effect(() => classes = set_class(li, 1, "svelte-1848zi3", null, classes, { selected: get2(is_selected) }));
  append($$anchor, li);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/editor/EditorMenu.svelte
var root40 = from_html(`<!> <!> <!> <!>`, 1);
var root_133 = from_html(`<span> </span>`);
var root_216 = from_html(`<!> <!> <!>`, 1);
var root_38 = from_html(`<div class="svelte-f4bgnn"><!> <!></div>`);
function EditorMenu($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const $sources_tree = () => store_get(sources_tree, "$sources_tree", $$stores);
  const $insert_entry = () => store_get(insert_entry, "$insert_entry", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  function go_to_file_and_line(filename2, line) {
    const url = $url_for()("editor/", { file_path: filename2, line });
    const load = filename2 !== $$props.file_path;
    router.navigate(url, load);
    if (!load && line != null) {
      $$props.editor.dispatch($$props.codemirror_beancount.scroll_to_line($$props.editor.state, line));
      $$props.editor.focus();
    }
  }
  var div = root_38();
  var node = child(div);
  AppMenu(node, {
    children: ($$anchor2, $$slotProps) => {
      var fragment = root_216();
      var node_1 = first_child(fragment);
      {
        let $0 = user_derived(() => _("File"));
        AppMenuItem(node_1, {
          get name() {
            return get2($0);
          },
          children: ($$anchor3, $$slotProps2) => {
            Sources_1($$anchor3, {
              is_root: true,
              get node() {
                return $sources_tree();
              },
              on_select: (source2) => {
                go_to_file_and_line(source2);
              },
              get selected() {
                return $$props.file_path;
              }
            });
          },
          $$slots: { default: true }
        });
      }
      var node_2 = sibling(node_1, 2);
      {
        let $0 = user_derived(() => _("Edit"));
        AppMenuItem(node_2, {
          get name() {
            return get2($0);
          },
          children: ($$anchor3, $$slotProps2) => {
            var fragment_2 = root40();
            var node_3 = first_child(fragment_2);
            {
              const right2 = ($$anchor4) => {
                {
                  let $02 = user_derived(() => [modKey, "d"]);
                  Key($$anchor4, {
                    get key() {
                      return get2($02);
                    }
                  });
                }
              };
              AppMenuSubItem(node_3, {
                action: () => $$props.codemirror_beancount.beancount_format($$props.editor),
                right: right2,
                children: ($$anchor4, $$slotProps3) => {
                  next();
                  var text2 = text();
                  template_effect(($02) => set_text(text2, $02), [() => _("Align Amounts")]);
                  append($$anchor4, text2);
                },
                $$slots: { right: true, default: true }
              });
            }
            var node_4 = sibling(node_3, 2);
            {
              const right2 = ($$anchor4) => {
                {
                  let $02 = user_derived(() => [modKey, "/"]);
                  Key($$anchor4, {
                    get key() {
                      return get2($02);
                    }
                  });
                }
              };
              AppMenuSubItem(node_4, {
                action: () => $$props.codemirror_beancount.toggleComment($$props.editor),
                right: right2,
                children: ($$anchor4, $$slotProps3) => {
                  next();
                  var text_1 = text();
                  template_effect(($02) => set_text(text_1, $02), [() => _("Toggle Comment (selection)")]);
                  append($$anchor4, text_1);
                },
                $$slots: { right: true, default: true }
              });
            }
            var node_5 = sibling(node_4, 2);
            {
              const right2 = ($$anchor4) => {
                Key($$anchor4, { key: ["Ctrl", "Alt", "]"] });
              };
              AppMenuSubItem(node_5, {
                action: () => $$props.codemirror_beancount.unfoldAll($$props.editor),
                right: right2,
                children: ($$anchor4, $$slotProps3) => {
                  next();
                  var text_2 = text();
                  template_effect(($02) => set_text(text_2, $02), [() => _("Open all folds")]);
                  append($$anchor4, text_2);
                },
                $$slots: { right: true, default: true }
              });
            }
            var node_6 = sibling(node_5, 2);
            {
              const right2 = ($$anchor4) => {
                Key($$anchor4, { key: ["Ctrl", "Alt", "["] });
              };
              AppMenuSubItem(node_6, {
                action: () => $$props.codemirror_beancount.foldAll($$props.editor),
                right: right2,
                children: ($$anchor4, $$slotProps3) => {
                  next();
                  var text_3 = text();
                  template_effect(($02) => set_text(text_3, $02), [() => _("Close all folds")]);
                  append($$anchor4, text_3);
                },
                $$slots: { right: true, default: true }
              });
            }
            append($$anchor3, fragment_2);
          },
          $$slots: { default: true }
        });
      }
      var node_7 = sibling(node_2, 2);
      {
        var consequent = ($$anchor3) => {
          {
            let $0 = user_derived(() => `'insert-entry' ${_("Options")}`);
            AppMenuItem($$anchor3, {
              get name() {
                return get2($0);
              },
              children: ($$anchor4, $$slotProps2) => {
                var fragment_12 = comment();
                var node_8 = first_child(fragment_12);
                each(node_8, 1, $insert_entry, (opt) => `${opt.filename}:${opt.lineno.toString()}`, ($$anchor5, opt) => {
                  {
                    const right2 = ($$anchor6) => {
                      var span = root_133();
                      var text_4 = child(span, true);
                      reset(span);
                      template_effect(() => set_text(text_4, get2(opt).date));
                      append($$anchor6, span);
                    };
                    let $02 = user_derived(() => `${get2(opt).filename}:${get2(opt).lineno.toString()}`);
                    AppMenuSubItem($$anchor5, {
                      get title() {
                        return get2($02);
                      },
                      action: () => {
                        go_to_file_and_line(get2(opt).filename, get2(opt).lineno - 1);
                      },
                      right: right2,
                      children: ($$anchor6, $$slotProps3) => {
                        next();
                        var text_5 = text();
                        template_effect(() => set_text(text_5, get2(opt).re));
                        append($$anchor6, text_5);
                      },
                      $$slots: { right: true, default: true }
                    });
                  }
                });
                append($$anchor4, fragment_12);
              },
              $$slots: { default: true }
            });
          }
        };
        if_block(node_7, ($$render) => {
          if ($insert_entry().length) $$render(consequent);
        });
      }
      append($$anchor2, fragment);
    },
    $$slots: { default: true }
  });
  var node_9 = sibling(node, 2);
  snippet(node_9, () => $$props.children);
  reset(div);
  append($$anchor, div);
  pop();
  $$cleanup();
}

// src/reports/editor/Editor.svelte
var root41 = from_html(`<form class="fixed-fullsize-container svelte-1yv7z86"><!> <div class="svelte-1yv7z86"></div></form>`);
function Editor($$anchor, $$props) {
  push($$props, true);
  const $indent = () => store_get(indent, "$indent", $$stores);
  const $currency_column = () => store_get(currency_column, "$currency_column", $$stores);
  const $insert_entry = () => store_get(insert_entry, "$insert_entry", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let file_path = user_derived(() => $$props.source.file_path);
  let changed = state(false);
  const onDocChanges = () => {
    set(changed, true);
  };
  let sha256sum = state("");
  let saving = state(false);
  async function save(cm) {
    set(saving, true);
    try {
      set(
        sha256sum,
        await put_source({
          file_path: get2(file_path),
          source: cm.state.sliceDoc(),
          sha256sum: get2(sha256sum)
        }),
        true
      );
      set(changed, false);
      cm.focus();
      get_errors().then(
        (v) => {
          errors.set(v);
        },
        log_error
      );
    } catch (error) {
      notify_err(error, (e) => e.message);
    } finally {
      set(saving, false);
    }
  }
  const editor2 = $$props.codemirror_beancount.init_beancount_editor(
    "",
    onDocChanges,
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save(editor2).catch(() => {
          });
          return true;
        }
      }
    ],
    $indent(),
    $currency_column()
  );
  user_effect(() => {
    void $$props.source;
    untrack(() => {
      editor2.dispatch($$props.codemirror_beancount.replace_contents(editor2.state, $$props.source.source));
      set(sha256sum, $$props.source.sha256sum, true);
      editor2.focus();
      set(changed, false);
    });
  });
  user_effect(() => {
    const last_insert_opt = untrack(() => $insert_entry().filter((f) => f.filename === get2(file_path)).at(-1));
    let line = editor2.state.doc.lines;
    if ($$props.line_search_param != null) {
      line = $$props.line_search_param;
    } else if (last_insert_opt) {
      line = last_insert_opt.lineno - 1;
    }
    editor2.dispatch($$props.codemirror_beancount.scroll_to_line(editor2.state, line));
  });
  user_effect(() => {
    const errorsForFile = $errors().filter((err2) => err2.source == null || err2.source.filename === get2(file_path));
    editor2.dispatch($$props.codemirror_beancount.set_errors(editor2.state, errorsForFile));
  });
  user_effect(() => get2(changed) ? router.add_interrupt_handler(() => "There are unsaved changes. Are you sure you want to leave?") : void 0);
  var form = root41();
  var node = child(form);
  EditorMenu(node, {
    get file_path() {
      return get2(file_path);
    },
    get editor() {
      return editor2;
    },
    get codemirror_beancount() {
      return $$props.codemirror_beancount;
    },
    children: ($$anchor2, $$slotProps) => {
      SaveButton($$anchor2, {
        get changed() {
          return get2(changed);
        },
        get saving() {
          return get2(saving);
        }
      });
    },
    $$slots: { default: true }
  });
  var div = sibling(node, 2);
  attach(div, () => attach_editor(editor2));
  reset(form);
  event("submit", form, async (event2) => {
    event2.preventDefault();
    return save(editor2);
  });
  append($$anchor, form);
  pop();
  $$cleanup();
}

// src/reports/editor/index.ts
var editor = new Route(
  "editor",
  Editor,
  async (url) => {
    const line = url.searchParams.get("line");
    const line_search_param = line != null ? Number.parseInt(line, 10) : null;
    const [source2, codemirror_beancount] = await Promise.all([
      get_source({
        filename: url.searchParams.get("file_path") ?? ""
      }),
      import("./beancount-OG2DLLWG.js")
    ]);
    return {
      source: source2,
      line_search_param,
      init_beancount_editor: codemirror_beancount.init_beancount_editor,
      codemirror_beancount
    };
  },
  () => _("Editor")
);

// src/reports/errors/Errors.svelte
var root42 = from_html(`<td> </td> <td class="num"><a class="source"> </a></td>`, 1);
var root_134 = from_html(`<td></td> <td class="num"></td>`, 1);
var root_217 = from_html(`<a> </a>`);
var root_39 = from_html(`<tr><!><td class="pre"></td></tr>`);
var root_46 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
var root_54 = from_html(`<p> </p>`);
function Errors($$anchor, $$props) {
  push($$props, true);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  const $url_for_source = () => store_get(url_for_source, "$url_for_source", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let account_re = user_derived(() => new RegExp(`(${$accounts().join("|")})`));
  function extract_accounts(msg) {
    return msg.split(get2(account_re)).map((text2, index2) => index2 % 2 === 0 ? ["text", text2] : ["account", text2]);
  }
  const columns = [
    new StringColumn(_("File"), (d) => d.source?.filename ?? ""),
    new NumberColumn(_("Line"), (d) => d.source?.lineno ?? 0),
    new StringColumn(_("Error"), (d) => d.message)
  ];
  let sorter = state(proxy(new Sorter(columns[0], "desc")));
  let sorted_errors = user_derived(() => get2(sorter).sort($errors()));
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent_2 = ($$anchor2) => {
      var table = root_46();
      var thead = child(table);
      var tr = child(thead);
      each(tr, 20, () => columns, (column) => column, ($$anchor3, column) => {
        SortHeader($$anchor3, {
          get column() {
            return column;
          },
          get sorter() {
            return get2(sorter);
          },
          set sorter($$value) {
            set(sorter, $$value, true);
          }
        });
      });
      reset(tr);
      reset(thead);
      var tbody = sibling(thead);
      each(tbody, 21, () => get2(sorted_errors), index, ($$anchor3, $$item) => {
        let message = () => get2($$item).message;
        let source2 = () => get2($$item).source;
        var tr_1 = root_39();
        var node_1 = child(tr_1);
        {
          var consequent = ($$anchor4) => {
            const url = user_derived(() => $url_for_source()(source2().filename, source2().lineno.toString()));
            const title = user_derived(() => format2(_("Show source %(file)s:%(lineno)s"), { file: source2().filename, lineno: source2().lineno.toString() }));
            var fragment_2 = root42();
            var td = first_child(fragment_2);
            var text_1 = child(td, true);
            reset(td);
            var td_1 = sibling(td, 2);
            var a = child(td_1);
            var text_2 = child(a, true);
            reset(a);
            reset(td_1);
            template_effect(() => {
              set_text(text_1, source2().filename);
              set_attribute(a, "href", get2(url));
              set_attribute(a, "title", get2(title));
              set_text(text_2, source2().lineno);
            });
            append($$anchor4, fragment_2);
          };
          var alternate = ($$anchor4) => {
            var fragment_3 = root_134();
            next(2);
            append($$anchor4, fragment_3);
          };
          if_block(node_1, ($$render) => {
            if (source2()) $$render(consequent);
            else $$render(alternate, -1);
          });
        }
        var td_2 = sibling(node_1);
        each(td_2, 21, () => extract_accounts(message()), index, ($$anchor4, $$item2) => {
          var $$array = user_derived(() => to_array(get2($$item2), 2));
          let type = () => get2($$array)[0];
          let text2 = () => get2($$array)[1];
          var fragment_4 = comment();
          var node_2 = first_child(fragment_4);
          {
            var consequent_1 = ($$anchor5) => {
              var text_3 = text();
              template_effect(() => set_text(text_3, text2()));
              append($$anchor5, text_3);
            };
            var alternate_1 = ($$anchor5) => {
              var a_1 = root_217();
              var text_4 = child(a_1, true);
              reset(a_1);
              template_effect(
                ($0) => {
                  set_attribute(a_1, "href", $0);
                  set_text(text_4, text2());
                },
                [() => $url_for_account()(text2())]
              );
              append($$anchor5, a_1);
            };
            if_block(node_2, ($$render) => {
              if (type() === "text") $$render(consequent_1);
              else $$render(alternate_1, -1);
            });
          }
          append($$anchor4, fragment_4);
        });
        reset(td_2);
        reset(tr_1);
        append($$anchor3, tr_1);
      });
      reset(tbody);
      reset(table);
      append($$anchor2, table);
    };
    var alternate_2 = ($$anchor2) => {
      var p = root_54();
      var text_5 = child(p, true);
      reset(p);
      template_effect(($0) => set_text(text_5, $0), [() => _("No errors.")]);
      append($$anchor2, p);
    };
    if_block(node, ($$render) => {
      if ($errors().length) $$render(consequent_2);
      else $$render(alternate_2, -1);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/errors/index.ts
var errors2 = new DatalessRoute(
  "errors",
  Errors,
  () => _("Errors")
);

// src/reports/events/EventTable.svelte
var root43 = from_html(`<tr><td> </td><td> </td></tr>`);
var root_135 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function EventTable($$anchor, $$props) {
  push($$props, true);
  const columns = [
    new DateColumn(_("Date")),
    new StringColumn(_("Description"), (d) => d.description)
  ];
  let sorter = state(proxy(new Sorter(columns[0], "desc")));
  let sorted_events = user_derived(() => get2(sorter).sort($$props.events));
  var table = root_135();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_events), (event2) => `${event2.date}-${event2.description}`, ($$anchor2, event2) => {
    var tr_1 = root43();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(() => {
      set_text(text2, get2(event2).date);
      set_text(text_1, get2(event2).description);
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
}

// src/reports/events/Events.svelte
var root44 = from_html(`<div class="left"><h3> </h3> <!></div>`);
var root_136 = from_html(`<!> <!>`, 1);
var root_218 = from_html(`<p> </p>`);
function Events($$anchor, $$props) {
  push($$props, true);
  let groups = user_derived(() => [...group($$props.events, (e) => e.type)]);
  let charts = user_derived(() => [
    new ScatterPlot(_("Events"), $$props.events.map(({ date: date3, type, description }) => ({ date: new Date(date3), type, description })))
  ]);
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var fragment_1 = root_136();
      var node_1 = first_child(fragment_1);
      ChartSwitcher(node_1, {
        get charts() {
          return get2(charts);
        }
      });
      var node_2 = sibling(node_1, 2);
      each(node_2, 17, () => get2(groups), ([type, events_in_group]) => type, ($$anchor3, $$item) => {
        var $$array = user_derived(() => to_array(get2($$item), 2));
        let type = () => get2($$array)[0];
        let events_in_group = () => get2($$array)[1];
        var div = root44();
        var h3 = child(div);
        var text2 = child(h3, true);
        reset(h3);
        var node_3 = sibling(h3, 2);
        EventTable(node_3, {
          get events() {
            return events_in_group();
          }
        });
        reset(div);
        template_effect(($0) => set_text(text2, $0), [() => format2(_("Event: %(type)s"), { type: type() })]);
        append($$anchor3, div);
      });
      append($$anchor2, fragment_1);
    };
    var alternate = ($$anchor2) => {
      var p = root_218();
      var text_1 = child(p, true);
      reset(p);
      template_effect(($0) => set_text(text_1, $0), [() => _("No events.")]);
      append($$anchor2, p);
    };
    if_block(node, ($$render) => {
      if (get2(groups).length) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  append($$anchor, fragment);
  pop();
}

// src/reports/events/index.ts
var events = new Route(
  "events",
  Events,
  async (url) => get_events(get_url_filters(url)).then((data) => ({ events: data })),
  () => _("Events")
);

// src/reports/help/Help.svelte
var root45 = from_html(`<li class="svelte-bf9q6i"><a> </a></li>`);
var root_137 = from_html(`<div class="help svelte-bf9q6i"><nav class="help-sidebar svelte-bf9q6i"><h3> </h3> <ul class="svelte-bf9q6i"></ul></nav> <div class="help-text svelte-bf9q6i"></div></div>`);
function Help($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var div = root_137();
  var nav = child(div);
  var h3 = child(nav);
  var text2 = child(h3, true);
  reset(h3);
  var ul = sibling(h3, 2);
  each(ul, 21, () => $$props.pages, ([slug, title]) => slug, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let slug = () => get2($$array)[0];
    let title = () => get2($$array)[1];
    var li = root45();
    var a = child(li);
    let classes;
    var text_1 = child(a, true);
    reset(a);
    reset(li);
    template_effect(
      ($0) => {
        set_attribute(a, "href", $0);
        classes = set_class(a, 1, "svelte-bf9q6i", null, classes, { selected: slug() === $$props.page_slug });
        set_text(text_1, title());
      },
      [
        () => $url_for()(slug() === "_index" ? "help/" : `help/${slug()}`)
      ]
    );
    append($$anchor2, li);
  });
  reset(ul);
  reset(nav);
  var div_1 = sibling(nav, 2);
  html(div_1, () => $$props.html, true);
  reset(div_1);
  reset(div);
  template_effect(($0) => set_text(text2, $0), [() => _("Help pages")]);
  append($$anchor, div);
  pop();
  $$cleanup();
}

// src/reports/help/index.ts
function get_page_slug(url) {
  const [, page_slug] = get_url_path(url).unwrap().split("/");
  return page_slug != null && page_slug !== "" ? page_slug : "_index";
}
var help = new Route(
  "help",
  Help,
  async (url) => {
    const page_slug = get_page_slug(url);
    const { html: html2, pages } = await get_help({ page_slug });
    return { page_slug, html: html2, pages };
  },
  ({ pages, page_slug }) => {
    const title = pages.find(([s]) => s === page_slug)?.[1];
    return title != null ? `${_("Help")} - ${title}` : _("Help");
  }
);

// src/reports/query/QueryLinks.svelte
var root46 = from_html(`, <a data-remote="">XLSX</a> , or <a data-remote="">ODS</a>`, 1);
var root_138 = from_html(`<span class="svelte-abjflr"> <a data-remote="">CSV</a><!>)</span>`);
function QueryLinks($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const $HAVE_EXCEL = () => store_get(HAVE_EXCEL, "$HAVE_EXCEL", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let params = user_derived(() => ({ query_string: $$props.query }));
  var span = root_138();
  var text2 = child(span);
  var a = sibling(text2);
  var node = sibling(a);
  {
    var consequent = ($$anchor2) => {
      var fragment = root46();
      var a_1 = sibling(first_child(fragment));
      var a_2 = sibling(a_1, 2);
      template_effect(
        ($0, $1) => {
          set_attribute(a_1, "href", $0);
          set_attribute(a_2, "href", $1);
        },
        [
          () => $url_for()("download-query/query_result.xlsx", get2(params)),
          () => $url_for()("download-query/query_result.ods", get2(params))
        ]
      );
      append($$anchor2, fragment);
    };
    if_block(node, ($$render) => {
      if ($HAVE_EXCEL()) $$render(consequent);
    });
  }
  next();
  reset(span);
  template_effect(
    ($0, $1) => {
      set_text(text2, `(${$0 ?? ""} `);
      set_attribute(a, "href", $1);
    },
    [
      () => _("Download as"),
      () => $url_for()("download-query/query_result.csv", get2(params))
    ]
  );
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/reports/query/QueryTable.svelte
var root47 = from_html(`<td>&nbsp;</td>`);
var root_139 = from_html(`<td> </td>`);
var root_219 = from_html(`<td class="num"> </td>`);
var root_310 = from_html(`<a> </a> <!>`, 1);
var root_47 = from_html(`<a> </a>`);
var root_55 = from_html(`<td><!></td>`);
var root_62 = from_html(`&lbrace;<span> </span>&rbrace;`, 1);
var root_7 = from_html(`<td class="num"><span> </span> <!></td>`);
var root_8 = from_html(`<span> </span> <br/>`, 1);
var root_9 = from_html(`<td class="num"></td>`);
var root_10 = from_html(`<tr></tr>`);
var root_11 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function QueryTable($$anchor, $$props) {
  push($$props, true);
  const $num = () => store_get(num, "$num", $$stores);
  const $accounts_set = () => store_get(accounts_set, "$accounts_set", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let filter_empty_column_index = user_derived(() => $$props.table.columns.findIndex((column) => column.name === $$props.filter_empty));
  let filtered_rows = user_derived(() => get2(filter_empty_column_index) > -1 ? $$props.table.rows.filter((row) => {
    const cell = row[get2(filter_empty_column_index)];
    return !(cell instanceof Inventory && is_empty(cell.value));
  }) : $$props.table.rows);
  let sorter = state(new Sorter(new UnsortedColumn("<Dummy>"), "asc"));
  let sorted_rows = user_derived(() => get2(sorter).sort(get2(filtered_rows)));
  var table_1 = root_11();
  var thead = child(table_1);
  var tr = child(thead);
  each(tr, 21, () => $$props.table.columns, (column) => column.name, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return get2(column);
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 20, () => get2(sorted_rows), (row) => row, ($$anchor2, row) => {
    var tr_1 = root_10();
    each(tr_1, 21, () => row, index, ($$anchor3, value, index2) => {
      var fragment_1 = comment();
      var node = first_child(fragment_1);
      {
        var consequent = ($$anchor4) => {
          var td = root47();
          append($$anchor4, td);
        };
        var consequent_1 = ($$anchor4) => {
          var td_1 = root_139();
          var text2 = child(td_1, true);
          reset(td_1);
          template_effect(($0) => set_text(text2, $0), [() => get2(value).toString().toUpperCase()]);
          append($$anchor4, td_1);
        };
        var consequent_2 = ($$anchor4) => {
          var td_2 = root_219();
          var text_1 = child(td_2, true);
          reset(td_2);
          template_effect(($0) => set_text(text_1, $0), [
            () => $$props.table.columns[index2]?.dtype === "int" ? get2(value).toString() : $num()(get2(value))
          ]);
          append($$anchor4, td_2);
        };
        var consequent_5 = ($$anchor4) => {
          var td_3 = root_55();
          var node_1 = child(td_3);
          {
            var consequent_3 = ($$anchor5) => {
              var fragment_2 = root_310();
              var a = first_child(fragment_2);
              var text_2 = child(a, true);
              reset(a);
              var node_2 = sibling(a, 2);
              AccountIndicator(node_2, {
                get account() {
                  return get2(value);
                },
                small: true
              });
              template_effect(
                ($0) => {
                  set_attribute(a, "href", $0);
                  set_text(text_2, get2(value));
                },
                [() => $url_for_account()(get2(value))]
              );
              append($$anchor5, fragment_2);
            };
            var d = user_derived(() => $accounts_set().has(get2(value)));
            var consequent_4 = ($$anchor5) => {
              var a_1 = root_47();
              var text_3 = child(a_1, true);
              reset(a_1);
              template_effect(() => {
                set_attribute(a_1, "href", `#context-${get2(value)}`);
                set_text(text_3, get2(value));
              });
              append($$anchor5, a_1);
            };
            var d_1 = user_derived(() => get2(value).length === 32 && /[a-z0-9]/.test(get2(value)));
            var alternate = ($$anchor5) => {
              var text_4 = text();
              template_effect(() => set_text(text_4, get2(value)));
              append($$anchor5, text_4);
            };
            if_block(node_1, ($$render) => {
              if (get2(d)) $$render(consequent_3);
              else if (get2(d_1)) $$render(consequent_4, 1);
              else $$render(alternate, -1);
            });
          }
          reset(td_3);
          append($$anchor4, td_3);
        };
        var consequent_6 = ($$anchor4) => {
          var td_4 = root_139();
          var text_5 = child(td_4, true);
          reset(td_4);
          template_effect(($0) => set_text(text_5, $0), [() => get2(value).join(",")]);
          append($$anchor4, td_4);
        };
        var d_2 = user_derived(() => Array.isArray(get2(value)));
        var consequent_7 = ($$anchor4) => {
          var td_5 = root_139();
          var text_6 = child(td_5, true);
          reset(td_5);
          template_effect(($0) => set_text(text_6, $0), [() => day(get2(value))]);
          append($$anchor4, td_5);
        };
        var consequent_8 = ($$anchor4) => {
          var td_6 = root_219();
          var text_7 = child(td_6, true);
          reset(td_6);
          template_effect(
            ($0, $1) => {
              set_attribute(td_6, "title", $0);
              set_text(text_7, $1);
            },
            [
              () => $currency_name()(get2(value).currency),
              () => get2(value).str($ctx())
            ]
          );
          append($$anchor4, td_6);
        };
        var consequent_10 = ($$anchor4) => {
          var td_7 = root_7();
          var span = child(td_7);
          var text_8 = child(span, true);
          reset(span);
          var node_3 = sibling(span, 2);
          {
            var consequent_9 = ($$anchor5) => {
              var fragment_4 = root_62();
              var span_1 = sibling(first_child(fragment_4));
              var text_9 = child(span_1, true);
              reset(span_1);
              next();
              template_effect(
                ($0, $1) => {
                  set_attribute(span_1, "title", $0);
                  set_text(text_9, $1);
                },
                [
                  () => $currency_name()(get2(value).cost.currency),
                  () => get2(value).cost.str($ctx())
                ]
              );
              append($$anchor5, fragment_4);
            };
            if_block(node_3, ($$render) => {
              if (get2(value).cost) $$render(consequent_9);
            });
          }
          reset(td_7);
          template_effect(
            ($0, $1) => {
              set_attribute(span, "title", $0);
              set_text(text_8, $1);
            },
            [
              () => $currency_name()(get2(value).units.currency),
              () => get2(value).units.str($ctx())
            ]
          );
          append($$anchor4, td_7);
        };
        var consequent_11 = ($$anchor4) => {
          var td_8 = root_9();
          each(td_8, 21, () => Object.entries(get2(value).value), ([currency, number4]) => currency, ($$anchor5, $$item) => {
            var $$array = user_derived(() => to_array(get2($$item), 2));
            let currency = () => get2($$array)[0];
            let number4 = () => get2($$array)[1];
            var fragment_5 = root_8();
            var span_2 = first_child(fragment_5);
            var text_10 = child(span_2, true);
            reset(span_2);
            next(2);
            template_effect(
              ($0, $1) => {
                set_attribute(span_2, "title", $0);
                set_text(text_10, $1);
              },
              [
                () => $currency_name()(currency()),
                () => $ctx().amount(number4(), currency())
              ]
            );
            append($$anchor5, fragment_5);
          });
          reset(td_8);
          append($$anchor4, td_8);
        };
        if_block(node, ($$render) => {
          if (get2(value) == null) $$render(consequent);
          else if (typeof get2(value) === "boolean") $$render(consequent_1, 1);
          else if (typeof get2(value) === "number") $$render(consequent_2, 2);
          else if (typeof get2(value) === "string") $$render(consequent_5, 3);
          else if (get2(d_2)) $$render(consequent_6, 4);
          else if (get2(value) instanceof Date) $$render(consequent_7, 5);
          else if (get2(value) instanceof Amount) $$render(consequent_8, 6);
          else if (get2(value) instanceof Position) $$render(consequent_10, 7);
          else if (get2(value) instanceof Inventory) $$render(consequent_11, 8);
        });
      }
      append($$anchor3, fragment_1);
    });
    reset(tr_1);
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table_1);
  append($$anchor, table_1);
  pop();
  $$cleanup();
}

// src/reports/holdings/Holdings.svelte
var root48 = from_html(`<a> </a>`);
var root_140 = from_html(`<div class="headerline"><h3><!></h3> <h3><!></h3> <h3><!></h3> <h3><!></h3></div> <p><a> </a> <!></p> <!>`, 1);
function Holdings($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var fragment = root_140();
  var div = first_child(fragment);
  var h3 = child(div);
  var node = child(h3);
  {
    var consequent = ($$anchor2) => {
      var text2 = text();
      template_effect(($0) => set_text(text2, $0), [() => _("Holdings")]);
      append($$anchor2, text2);
    };
    var alternate = ($$anchor2) => {
      var a = root48();
      var text_1 = child(a, true);
      reset(a);
      template_effect(
        ($0, $1) => {
          set_attribute(a, "href", $0);
          set_text(text_1, $1);
        },
        [() => $url_for()("holdings/"), () => _("Holdings")]
      );
      append($$anchor2, a);
    };
    if_block(node, ($$render) => {
      if ($$props.aggregation_key === "all") $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  reset(h3);
  var h3_1 = sibling(h3, 2);
  var node_1 = child(h3_1);
  {
    var consequent_1 = ($$anchor2) => {
      var text_2 = text();
      template_effect(($0, $1) => set_text(text_2, `${$0 ?? ""} ${$1 ?? ""}`), [() => _("Holdings by"), () => _("Account")]);
      append($$anchor2, text_2);
    };
    var alternate_1 = ($$anchor2) => {
      var a_1 = root48();
      var text_3 = child(a_1);
      reset(a_1);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_1, "href", $0);
          set_text(text_3, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $url_for()("holdings/by_account/"),
          () => _("Holdings by"),
          () => _("Account")
        ]
      );
      append($$anchor2, a_1);
    };
    if_block(node_1, ($$render) => {
      if ($$props.aggregation_key === "by_account") $$render(consequent_1);
      else $$render(alternate_1, -1);
    });
  }
  reset(h3_1);
  var h3_2 = sibling(h3_1, 2);
  var node_2 = child(h3_2);
  {
    var consequent_2 = ($$anchor2) => {
      var text_4 = text();
      template_effect(($0, $1) => set_text(text_4, `${$0 ?? ""} ${$1 ?? ""}`), [() => _("Holdings by"), () => _("Currency")]);
      append($$anchor2, text_4);
    };
    var alternate_2 = ($$anchor2) => {
      var a_2 = root48();
      var text_5 = child(a_2);
      reset(a_2);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_2, "href", $0);
          set_text(text_5, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $url_for()("holdings/by_currency/"),
          () => _("Holdings by"),
          () => _("Currency")
        ]
      );
      append($$anchor2, a_2);
    };
    if_block(node_2, ($$render) => {
      if ($$props.aggregation_key === "by_currency") $$render(consequent_2);
      else $$render(alternate_2, -1);
    });
  }
  reset(h3_2);
  var h3_3 = sibling(h3_2, 2);
  var node_3 = child(h3_3);
  {
    var consequent_3 = ($$anchor2) => {
      var text_6 = text();
      template_effect(($0, $1) => set_text(text_6, `${$0 ?? ""} ${$1 ?? ""}`), [() => _("Holdings by"), () => _("Cost currency")]);
      append($$anchor2, text_6);
    };
    var alternate_3 = ($$anchor2) => {
      var a_3 = root48();
      var text_7 = child(a_3);
      reset(a_3);
      template_effect(
        ($0, $1, $2) => {
          set_attribute(a_3, "href", $0);
          set_text(text_7, `${$1 ?? ""}
        ${$2 ?? ""}`);
        },
        [
          () => $url_for()("holdings/by_cost_currency/"),
          () => _("Holdings by"),
          () => _("Cost currency")
        ]
      );
      append($$anchor2, a_3);
    };
    if_block(node_3, ($$render) => {
      if ($$props.aggregation_key === "by_cost_currency") $$render(consequent_3);
      else $$render(alternate_3, -1);
    });
  }
  reset(h3_3);
  reset(div);
  var p = sibling(div, 2);
  var a_4 = child(p);
  var text_8 = child(a_4, true);
  reset(a_4);
  var node_4 = sibling(a_4, 2);
  QueryLinks(node_4, {
    get query() {
      return $$props.query_string;
    }
  });
  reset(p);
  var node_5 = sibling(p, 2);
  QueryTable(node_5, {
    get table() {
      return $$props.query_result_table;
    },
    filter_empty: "units"
  });
  template_effect(
    ($0, $1) => {
      set_attribute(a_4, "href", $0);
      set_text(text_8, $1);
    },
    [
      () => $url_for()("query/", { query_string: $$props.query_string }),
      () => _("Query")
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/holdings/index.ts
var to_report_type2 = (s) => s === "by_account" || s === "by_currency" || s === "by_cost_currency" ? s : "all";
var QUERIES = {
  all: `
SELECT
  account,
  units(sum(position)) as units,
  cost_number as cost,
  first(getprice(currency, cost_currency)) as price,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct,
  cost_date as acquisition_date
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY account, cost_date, currency, cost_currency, cost_number, account_sortkey(account)
ORDER BY account_sortkey(account), currency, cost_date
`.trim(),
  by_account: `
SELECT
  account,
  units(sum(position)) as units,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY account, cost_currency, account_sortkey(account), currency
ORDER BY account_sortkey(account), currency
`.trim(),
  by_currency: `
SELECT
  units(sum(position)) as units,
  safediv(number(only(first(cost_currency), cost(sum(position)))), number(only(first(currency), units(sum(position))))) as average_cost,
  first(getprice(currency, cost_currency)) as price,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY currency, cost_currency
ORDER BY currency, cost_currency
`.trim(),
  by_cost_currency: `
SELECT
  units(sum(position)) as units,
  cost(sum(position)) as book_value,
  value(sum(position)) as market_value,
  safediv((abs(sum(number(value(position)))) - abs(sum(number(cost(position))))), sum(number(cost(position)))) * 100 as unrealized_profit_pct
WHERE account_sortkey(account) ~ "^[01]"
GROUP BY cost_currency
ORDER BY cost_currency
`.trim()
};
var holdings = new Route(
  "holdings",
  Holdings,
  async (url) => {
    const [, key2 = ""] = get_url_path(url).unwrap().split("/");
    const aggregation_key = to_report_type2(key2);
    const query_string = QUERIES[aggregation_key];
    const query_result_table = await get_query({
      query_string,
      ...get_url_filters(url)
    });
    if (query_result_table.t !== "table") {
      throw new Error("Internal error: expected a query result table");
    }
    return { aggregation_key, query_string, query_result_table };
  },
  () => _("Holdings")
);

// node_modules/svelte/src/reactivity/map.js
var SvelteMap = class extends Map {
  /** @type {Map<K, Source<number>>} */
  #sources = /* @__PURE__ */ new Map();
  #version = state(0);
  #size = state(0);
  #update_version = update_version || -1;
  /**
   * @param {Iterable<readonly [K, V]> | null | undefined} [value]
   */
  constructor(value) {
    super();
    if (false_default) {
      value = new Map(value);
      tag(this.#version, "SvelteMap version");
      tag(this.#size, "SvelteMap.size");
    }
    if (value) {
      for (var [key2, v] of value) {
        super.set(key2, v);
      }
      this.#size.v = super.size;
    }
  }
  /**
   * If the source is being created inside the same reaction as the SvelteMap instance,
   * we use `state` so that it will not be a dependency of the reaction. Otherwise we
   * use `source` so it will be.
   *
   * @template T
   * @param {T} value
   * @returns {Source<T>}
   */
  #source(value) {
    return update_version === this.#update_version ? state(value) : source(value);
  }
  /** @param {K} key */
  has(key2) {
    var sources2 = this.#sources;
    var s = sources2.get(key2);
    if (s === void 0) {
      if (super.has(key2)) {
        s = this.#source(0);
        if (false_default) {
          tag(s, `SvelteMap get(${label(key2)})`);
        }
        sources2.set(key2, s);
      } else {
        get2(this.#version);
        return false;
      }
    }
    get2(s);
    return true;
  }
  /**
   * @param {(value: V, key: K, map: Map<K, V>) => void} callbackfn
   * @param {any} [this_arg]
   */
  forEach(callbackfn, this_arg) {
    this.#read_all();
    super.forEach(callbackfn, this_arg);
  }
  /** @param {K} key */
  get(key2) {
    var sources2 = this.#sources;
    var s = sources2.get(key2);
    if (s === void 0) {
      if (super.has(key2)) {
        s = this.#source(0);
        if (false_default) {
          tag(s, `SvelteMap get(${label(key2)})`);
        }
        sources2.set(key2, s);
      } else {
        get2(this.#version);
        return void 0;
      }
    }
    get2(s);
    return super.get(key2);
  }
  /**
   * @param {K} key
   * @param {V} value
   * */
  set(key2, value) {
    var sources2 = this.#sources;
    var s = sources2.get(key2);
    var prev_res = super.get(key2);
    var res = super.set(key2, value);
    var version = this.#version;
    if (s === void 0) {
      s = this.#source(0);
      if (false_default) {
        tag(s, `SvelteMap get(${label(key2)})`);
      }
      sources2.set(key2, s);
      set(this.#size, super.size);
      increment(version);
    } else if (prev_res !== value) {
      increment(s);
      var v_reactions = version.reactions === null ? null : new Set(version.reactions);
      var needs_version_increase = v_reactions === null || !s.reactions?.every(
        (r) => (
          /** @type {NonNullable<typeof v_reactions>} */
          v_reactions.has(r)
        )
      );
      if (needs_version_increase) {
        increment(version);
      }
    }
    return res;
  }
  /** @param {K} key */
  delete(key2) {
    var sources2 = this.#sources;
    var s = sources2.get(key2);
    var res = super.delete(key2);
    if (s !== void 0) {
      sources2.delete(key2);
      set(s, -1);
    }
    if (res) {
      set(this.#size, super.size);
      increment(this.#version);
    }
    return res;
  }
  clear() {
    if (super.size === 0) {
      return;
    }
    super.clear();
    var sources2 = this.#sources;
    set(this.#size, 0);
    for (var s of sources2.values()) {
      set(s, -1);
    }
    increment(this.#version);
    sources2.clear();
  }
  #read_all() {
    get2(this.#version);
    var sources2 = this.#sources;
    if (this.#size.v !== sources2.size) {
      for (var key2 of super.keys()) {
        if (!sources2.has(key2)) {
          var s = this.#source(0);
          if (false_default) {
            tag(s, `SvelteMap get(${label(key2)})`);
          }
          sources2.set(key2, s);
        }
      }
    }
    for ([, s] of this.#sources) {
      get2(s);
    }
  }
  keys() {
    get2(this.#version);
    return super.keys();
  }
  values() {
    this.#read_all();
    return super.values();
  }
  entries() {
    this.#read_all();
    return super.entries();
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  get size() {
    get2(this.#size);
    return super.size;
  }
};

// node_modules/svelte/src/reactivity/url-search-params.js
var REPLACE = /* @__PURE__ */ Symbol("replace");
var SvelteURLSearchParams = class extends URLSearchParams {
  #version = false_default ? tag(state(0), "SvelteURLSearchParams version") : state(0);
  #url = get_current_url();
  #updating = false;
  #update_url() {
    if (!this.#url || this.#updating) return;
    this.#updating = true;
    const search = this.toString();
    this.#url.search = search && `?${search}`;
    this.#updating = false;
  }
  /**
   * @param {URLSearchParams} params
   * @internal
   */
  [REPLACE](params) {
    if (this.#updating) return;
    if (params.toString() === super.toString()) return;
    this.#updating = true;
    for (const key2 of [...super.keys()]) {
      super.delete(key2);
    }
    for (const [key2, value] of params) {
      super.append(key2, value);
    }
    increment(this.#version);
    this.#updating = false;
  }
  /**
   * @param {string} name
   * @param {string} value
   * @returns {void}
   */
  append(name, value) {
    super.append(name, value);
    this.#update_url();
    increment(this.#version);
  }
  /**
   * @param {string} name
   * @param {string=} value
   * @returns {void}
   */
  delete(name, value) {
    var has_value = super.has(name, value);
    super.delete(name, value);
    if (has_value) {
      this.#update_url();
      increment(this.#version);
    }
  }
  /**
   * @param {string} name
   * @returns {string|null}
   */
  get(name) {
    get2(this.#version);
    return super.get(name);
  }
  /**
   * @param {string} name
   * @returns {string[]}
   */
  getAll(name) {
    get2(this.#version);
    return super.getAll(name);
  }
  /**
   * @param {string} name
   * @param {string=} value
   * @returns {boolean}
   */
  has(name, value) {
    get2(this.#version);
    return super.has(name, value);
  }
  keys() {
    get2(this.#version);
    return super.keys();
  }
  /**
   * @param {(value: string, key: string, parent: URLSearchParams) => void} callback
   * @param {any} [this_arg]
   * @returns {void}
   */
  forEach(callback, this_arg) {
    get2(this.#version);
    super.forEach(callback, this_arg);
  }
  /**
   * @param {string} name
   * @param {string} value
   * @returns {void}
   */
  set(name, value) {
    var previous = super.getAll(name);
    super.set(name, value);
    var current = super.getAll(name);
    if (previous.length !== current.length || previous.some((value2, i) => value2 !== current[i])) {
      this.#update_url();
      increment(this.#version);
    }
  }
  sort() {
    super.sort();
    this.#update_url();
    increment(this.#version);
  }
  toString() {
    get2(this.#version);
    return super.toString();
  }
  values() {
    get2(this.#version);
    return super.values();
  }
  entries() {
    get2(this.#version);
    return super.entries();
  }
  [Symbol.iterator]() {
    return this.entries();
  }
  get size() {
    get2(this.#version);
    return super.size;
  }
};

// node_modules/svelte/src/reactivity/url.js
var current_url = null;
function get_current_url() {
  return current_url;
}

// src/entry-forms/AddMetadataButton.svelte
var root49 = from_html(`<button type="button" class="muted round">m</button>`);
function AddMetadataButton($$anchor, $$props) {
  push($$props, true);
  let meta = prop($$props, "meta", 15);
  var button = root49();
  set_attribute(button, "tabindex", -1);
  template_effect(($0) => set_attribute(button, "title", $0), [() => _("Add metadata")]);
  delegated("click", button, () => {
    meta(meta().add());
  });
  append($$anchor, button);
  pop();
}
delegate(["click"]);

// src/entry-forms/EntryMetadata.svelte
var root50 = from_html(`<button type="button" class="muted round">+</button>`);
var root_141 = from_html(`<div class="flex-row svelte-1jhkfcj"><button type="button" class="muted round remove-row">\xD7</button> <input type="text" class="key svelte-1jhkfcj" required=""/> : <input type="text" class="value svelte-1jhkfcj"/> <!></div>`);
function EntryMetadata($$anchor, $$props) {
  push($$props, true);
  let meta = prop($$props, "meta", 15);
  let meta_entries = user_derived(() => meta().entries());
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 17, () => get2(meta_entries), index, ($$anchor2, $$item, index2) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let key2 = () => get2($$array)[0];
    let value = () => get2($$array)[1];
    var div = root_141();
    var button = child(div);
    set_attribute(button, "tabindex", -1);
    var input = sibling(button, 2);
    remove_input_defaults(input);
    var input_1 = sibling(input, 2);
    remove_input_defaults(input_1);
    var node_1 = sibling(input_1, 2);
    {
      var consequent = ($$anchor3) => {
        var button_1 = root50();
        template_effect(
          ($0, $1) => {
            set_attribute(button_1, "aria-label", $0);
            set_attribute(button_1, "title", $1);
          },
          [() => _("Add metadata"), () => _("Add metadata")]
        );
        delegated("click", button_1, () => {
          meta(meta().add());
        });
        append($$anchor3, button_1);
      };
      if_block(node_1, ($$render) => {
        if (index2 === get2(meta_entries).length - 1 && key2()) $$render(consequent);
      });
    }
    reset(div);
    template_effect(
      ($0, $1) => {
        set_attribute(input, "placeholder", $0);
        set_value(input, key2());
        set_attribute(input_1, "placeholder", $1);
        set_value(input_1, value());
      },
      [() => _("Key"), () => _("Value")]
    );
    delegated("click", button, () => {
      meta(meta().delete(key2()));
    });
    delegated("change", input, (event2) => {
      meta(meta().update_key(key2(), event2.currentTarget.value));
    });
    delegated("change", input_1, (event2) => {
      meta(meta().set_string(key2(), event2.currentTarget.value));
    });
    append($$anchor2, div);
  });
  append($$anchor, fragment);
  pop();
}
delegate(["click", "change"]);

// src/entry-forms/Balance.svelte
var root51 = from_html(`<div class="flex-row"><input type="date" required=""/> <h4> </h4> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <input type="text" inputmode="numeric" pattern="-?[0-9.,]*" required=""/> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <!></div> <!>`, 1);
function Balance2($$anchor, $$props) {
  push($$props, true);
  const $currencies = () => store_get(currencies, "$currencies", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let entry = prop($$props, "entry", 15);
  var fragment = root51();
  var div = first_child(fragment);
  var input = child(div);
  remove_input_defaults(input);
  var h4 = sibling(input, 2);
  var text2 = child(h4, true);
  reset(h4);
  var node = sibling(h4, 2);
  var bind_get = () => entry().account;
  var bind_set = (account) => {
    entry(entry().set("account", account));
  };
  {
    css_props(node, () => ({ "--autocomplete-wrapper-flex": "1" }));
    AccountInput(node.lastChild, {
      get value() {
        return bind_get();
      },
      set value($$value) {
        bind_set($$value);
      },
      get date() {
        return entry().date;
      },
      required: true
    });
    reset(node);
  }
  var input_1 = sibling(node, 2);
  remove_input_defaults(input_1);
  set_attribute(input_1, "size", 10);
  var node_1 = sibling(input_1, 2);
  var bind_get_1 = () => entry().amount.currency;
  var bind_set_1 = (currency) => {
    entry(entry().set("amount", entry().amount.set_currency(currency)));
  };
  {
    let $0 = user_derived(() => _("Currency"));
    css_props(node_1, () => ({ "--autocomplete-wrapper-flex": "0 6em" }));
    AutocompleteInput(node_1.lastChild, {
      get placeholder() {
        return get2($0);
      },
      get suggestions() {
        return $currencies();
      },
      get value() {
        return bind_get_1();
      },
      set value($$value) {
        bind_set_1($$value);
      },
      required: true
    });
    reset(node_1);
  }
  var node_2 = sibling(node_1, 2);
  var bind_get_2 = () => entry().meta;
  var bind_set_2 = (meta) => {
    entry(entry().set("meta", meta));
  };
  AddMetadataButton(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  reset(div);
  var node_3 = sibling(div, 2);
  var bind_get_3 = () => entry().meta;
  var bind_set_3 = (meta) => {
    entry(entry().set("meta", meta));
  };
  EntryMetadata(node_3, {
    get meta() {
      return bind_get_3();
    },
    set meta($$value) {
      bind_set_3($$value);
    }
  });
  template_effect(
    ($0, $1) => {
      set_text(text2, $0);
      set_attribute(input_1, "placeholder", $1);
    },
    [() => _("Balance"), () => _("Number")]
  );
  bind_value(input, () => entry().date, (date3) => {
    entry(entry().set("date", date3));
  });
  bind_value(input_1, () => entry().amount.number, (number4) => {
    entry(entry().set("amount", entry().amount.set_number(number4)));
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/entry-forms/Note.svelte
var root52 = from_html(`<div class="flex-row"><input type="date" name="date" required=""/> <h4> </h4> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <!></div> <textarea placeholder="Comment" class="svelte-1qdvdaw"></textarea> <!>`, 1);
function Note2($$anchor, $$props) {
  push($$props, true);
  let entry = prop($$props, "entry", 15);
  var fragment = root52();
  var div = first_child(fragment);
  var input = child(div);
  remove_input_defaults(input);
  var h4 = sibling(input, 2);
  var text2 = child(h4, true);
  reset(h4);
  var node = sibling(h4, 2);
  var bind_get = () => entry().account;
  var bind_set = (account) => {
    entry(entry().set("account", account));
  };
  {
    css_props(node, () => ({ "--autocomplete-wrapper-flex": "1" }));
    AccountInput(node.lastChild, {
      get value() {
        return bind_get();
      },
      set value($$value) {
        bind_set($$value);
      },
      get date() {
        return entry().date;
      },
      required: true
    });
    reset(node);
  }
  var node_1 = sibling(node, 2);
  var bind_get_1 = () => entry().meta;
  var bind_set_1 = (meta) => {
    entry(entry().set("meta", meta));
  };
  AddMetadataButton(node_1, {
    get meta() {
      return bind_get_1();
    },
    set meta($$value) {
      bind_set_1($$value);
    }
  });
  reset(div);
  var textarea = sibling(div, 2);
  remove_textarea_child(textarea);
  set_attribute(textarea, "rows", 2);
  var node_2 = sibling(textarea, 2);
  var bind_get_2 = () => entry().meta;
  var bind_set_2 = (meta) => {
    entry(entry().set("meta", meta));
  };
  EntryMetadata(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  template_effect(($0) => set_text(text2, $0), [() => _("Note")]);
  bind_value(input, () => entry().date, (date3) => {
    entry(entry().set("date", date3));
  });
  bind_value(textarea, () => entry().comment, (comment2) => {
    entry(entry().set("comment", comment2));
  });
  append($$anchor, fragment);
  pop();
}

// src/entry-forms/AmountInput.svelte
function AmountInput($$anchor, $$props) {
  push($$props, true);
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $currencies = () => store_get(currencies, "$currencies", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let value = prop($$props, "value", 15);
  let number4 = user_derived(() => /^-?[0-9]*\.?[0-9]*/.exec(value().trimStart())?.[0] ?? "");
  let currency_options = user_derived(() => {
    const account_currencies = $$props.account != null ? $account_details()[$$props.account]?.currencies : null;
    return account_currencies != null && account_currencies.length > 0 ? account_currencies : $currencies();
  });
  let suggestions = user_derived(() => get2(number4) ? get2(currency_options).map((c) => `${get2(number4)} ${c}`) : []);
  {
    let $0 = user_derived(() => _("Amount"));
    AutocompleteInput($$anchor, {
      get placeholder() {
        return get2($0);
      },
      get suggestions() {
        return get2(suggestions);
      },
      automatic_selection: true,
      get value() {
        return value();
      },
      set value($$value) {
        value($$value);
      }
    });
  }
  pop();
  $$cleanup();
}

// src/entry-forms/Posting.svelte
var root53 = from_html(`<div role="group"><button type="button" class="muted round remove-row svelte-zhsp22">\xD7</button> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <!></div> <!>`, 1);
function Posting2($$anchor, $$props) {
  push($$props, true);
  let posting = prop($$props, "posting", 15);
  let drag = state(false);
  let draggable = state(true);
  function onmousemove(event2) {
    set(draggable, !(event2.target instanceof HTMLInputElement));
  }
  function ondragstart(event2) {
    event2.dataTransfer?.setData("fava/posting", $$props.index.toString());
  }
  function ondragenter(event2) {
    const types = event2.dataTransfer?.types ?? [];
    if (types.includes("fava/posting")) {
      event2.preventDefault();
      set(drag, true);
    }
  }
  function ondragleave() {
    set(drag, false);
  }
  function ondrop(event2) {
    event2.preventDefault();
    const from = event2.dataTransfer?.getData("fava/posting");
    if (from != null) {
      $$props.move({ from: +from, to: $$props.index });
      set(drag, false);
    }
  }
  var fragment = root53();
  var div = first_child(fragment);
  let classes;
  var button = child(div);
  set_attribute(button, "tabindex", -1);
  var node = sibling(button, 2);
  var bind_get = () => posting().account;
  var bind_set = (account) => {
    posting(posting().set("account", account));
  };
  {
    css_props(node, () => ({ "--autocomplete-wrapper-flex": "2" }));
    AccountInput(node.lastChild, {
      get value() {
        return bind_get();
      },
      set value($$value) {
        bind_set($$value);
      },
      get suggestions() {
        return $$props.suggestions;
      },
      get date() {
        return $$props.date;
      }
    });
    reset(node);
  }
  var node_1 = sibling(node, 2);
  var bind_get_1 = () => posting().amount;
  var bind_set_1 = (amount) => {
    posting(posting().set("amount", amount));
  };
  {
    css_props(node_1, () => ({ "--autocomplete-wrapper-flex": "1" }));
    AmountInput(node_1.lastChild, {
      get value() {
        return bind_get_1();
      },
      set value($$value) {
        bind_set_1($$value);
      },
      get account() {
        return posting().account;
      }
    });
    reset(node_1);
  }
  var node_2 = sibling(node_1, 2);
  var bind_get_2 = () => posting().meta;
  var bind_set_2 = (meta) => {
    posting(posting().set("meta", meta));
  };
  AddMetadataButton(node_2, {
    get meta() {
      return bind_get_2();
    },
    set meta($$value) {
      bind_set_2($$value);
    }
  });
  reset(div);
  var node_3 = sibling(div, 2);
  var bind_get_3 = () => posting().meta;
  var bind_set_3 = (meta) => {
    posting(posting().set("meta", meta));
  };
  EntryMetadata(node_3, {
    get meta() {
      return bind_get_3();
    },
    set meta($$value) {
      bind_set_3($$value);
    }
  });
  template_effect(() => {
    classes = set_class(div, 1, "flex-row svelte-zhsp22", null, classes, { drag: get2(drag) });
    set_attribute(div, "draggable", get2(draggable));
  });
  delegated("mousemove", div, onmousemove);
  event("dragstart", div, ondragstart);
  event("dragenter", div, ondragenter);
  event("dragover", div, ondragenter);
  event("dragleave", div, ondragleave);
  event("drop", div, ondrop);
  delegated("click", button, function(...$$args) {
    $$props.remove?.apply(this, $$args);
  });
  append($$anchor, fragment);
  pop();
}
delegate(["mousemove", "click"]);

// src/entry-forms/suggestions.svelte.ts
var FetchCoalescer = class {
  #data = state();
  get data() {
    return get2(this.#data);
  }
  set data(value) {
    set(this.#data, value);
  }
  #loader;
  #error_msg;
  #mtime = null;
  #inflight = null;
  constructor(loader, error_msg) {
    this.#loader = loader;
    this.#error_msg = error_msg;
  }
  /** Fetch the data, reusing cached data or a parallel fetch operation that is in flight. */
  load(mtime) {
    if (this.data != null && this.#mtime === mtime) {
      return this;
    }
    if (this.#inflight) {
      return this;
    }
    this.#inflight = this.#loader().then((data) => {
      this.data = data;
      this.#mtime = mtime;
      this.#inflight = null;
    }).catch((error) => {
      notify_err(error, (err2) => this.#error_msg(err2));
      this.#inflight = null;
    });
    return this;
  }
};
var narrations = new FetchCoalescer(get_narrations, (err2) => `Fetching narration suggestions failed: ${err2.message}`);
function fetch_narrations(mtime) {
  return narrations.load(mtime);
}
var payee_accounts = /* @__PURE__ */ new Map();
function fetch_payee_accounts(mtime, payee) {
  let fetcher = payee_accounts.get(payee);
  if (fetcher == null) {
    fetcher = new FetchCoalescer(async () => get_payee_accounts({ payee }), (err2) => `Fetching account suggestions for payee '${payee}' failed: ${err2.message}`);
    payee_accounts.set(payee, fetcher);
  }
  return fetcher.load(mtime);
}

// src/entry-forms/Transaction.svelte
var root54 = from_html(`<div class="flex-row"><input type="date" required=""/> <input type="text" name="flag" required="" class="svelte-1b60r2s"/> <label><span class="hide-on-desktop svelte-1b60r2s"> </span> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper></label> <label><span class="hide-on-desktop svelte-1b60r2s"> </span> <svelte-css-wrapper style="display: contents"><!></svelte-css-wrapper> <!></label></div> <!> <div class="flex-row hide-on-desktop svelte-1b60r2s"><span class="label"> </span></div> <!>`, 1);
function Transaction2($$anchor, $$props) {
  push($$props, true);
  const $payees = () => store_get(payees, "$payees", $$stores);
  const $ledger_mtime = () => store_get(ledger_mtime, "$ledger_mtime", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let entry = prop($$props, "entry", 15);
  let payee = user_derived(() => entry().payee);
  let narration = user_derived(() => entry().get_narration_tags_links());
  let payee_accounts2 = user_derived(() => $payees().includes(get2(payee)) ? fetch_payee_accounts($ledger_mtime(), get2(payee)) : void 0);
  async function autocomplete_select_payee() {
    if (entry().narration || entry().postings.some((p) => !p.is_empty())) {
      return;
    }
    const transaction = await get_payee_transaction({ payee: get2(payee) });
    entry(transaction.set("date", entry().date));
  }
  async function autocomplete_select_narration() {
    if (entry().payee || entry().postings.some((p) => !p.is_empty())) {
      return;
    }
    const transaction = await get_narration_transaction({ narration: get2(narration) });
    entry(transaction.set("date", entry().date));
  }
  user_effect(() => {
    if (!entry().postings.some((p) => p.is_empty())) {
      entry(entry().set("postings", entry().postings.concat(Posting.empty())));
    }
  });
  var fragment = root54();
  var div = first_child(fragment);
  var input = child(div);
  remove_input_defaults(input);
  var input_1 = sibling(input, 2);
  remove_input_defaults(input_1);
  var label2 = sibling(input_1, 2);
  var span = child(label2);
  var text2 = child(span);
  reset(span);
  var node = sibling(span, 2);
  {
    let $0 = user_derived(() => _("Payee"));
    css_props(node, () => ({ "--autocomplete-wrapper-flex": "1" }));
    AutocompleteInput(node.lastChild, {
      get placeholder() {
        return get2($0);
      },
      get value() {
        return entry().payee;
      },
      onchange: (value) => {
        entry(entry().set("payee", value));
      },
      get suggestions() {
        return $payees();
      },
      onselect: autocomplete_select_payee
    });
    reset(node);
  }
  reset(label2);
  var label_1 = sibling(label2, 2);
  var span_1 = child(label_1);
  var text_1 = child(span_1);
  reset(span_1);
  var node_1 = sibling(span_1, 2);
  {
    let $0 = user_derived(() => _("Narration"));
    let $1 = user_derived(() => fetch_narrations($ledger_mtime()).data);
    css_props(node_1, () => ({ "--autocomplete-wrapper-flex": "2" }));
    AutocompleteInput(node_1.lastChild, {
      get placeholder() {
        return get2($0);
      },
      get value() {
        return get2(narration);
      },
      get suggestions() {
        return get2($1);
      },
      onchange: (value) => {
        entry(entry().set_narration_tags_links(value));
      },
      onselect: autocomplete_select_narration
    });
    reset(node_1);
  }
  var node_2 = sibling(node_1, 2);
  var bind_get = () => entry().meta;
  var bind_set = (meta) => {
    entry(entry().set("meta", meta));
  };
  AddMetadataButton(node_2, {
    get meta() {
      return bind_get();
    },
    set meta($$value) {
      bind_set($$value);
    }
  });
  reset(label_1);
  reset(div);
  var node_3 = sibling(div, 2);
  var bind_get_1 = () => entry().meta;
  var bind_set_1 = (meta) => {
    entry(entry().set("meta", meta));
  };
  EntryMetadata(node_3, {
    get meta() {
      return bind_get_1();
    },
    set meta($$value) {
      bind_set_1($$value);
    }
  });
  var div_1 = sibling(node_3, 2);
  var span_2 = child(div_1);
  var text_2 = child(span_2);
  reset(span_2);
  reset(div_1);
  var node_4 = sibling(div_1, 2);
  each(node_4, 17, () => entry().postings, index, ($$anchor2, posting, index2) => {
    var bind_get_2 = () => get2(posting);
    var bind_set_2 = (posting2) => {
      entry(entry().set("postings", entry().postings.with(index2, posting2)));
    };
    {
      let $0 = user_derived(() => get2(payee_accounts2)?.data);
      Posting2($$anchor2, {
        get posting() {
          return bind_get_2();
        },
        set posting($$value) {
          bind_set_2($$value);
        },
        index: index2,
        get suggestions() {
          return get2($0);
        },
        get date() {
          return entry().date;
        },
        move: ({ from, to }) => {
          entry(entry().set("postings", move(entry().postings, from, to)));
        },
        remove: () => {
          entry(entry().set("postings", entry().postings.toSpliced(index2, 1)));
        }
      });
    }
  });
  template_effect(
    ($0, $1, $2) => {
      set_text(text2, `${$0 ?? ""}:`);
      set_text(text_1, `${$1 ?? ""}:`);
      set_text(text_2, `${$2 ?? ""}:`);
    },
    [() => _("Payee"), () => _("Narration"), () => _("Postings")]
  );
  bind_value(input, () => entry().date, (date3) => {
    entry(entry().set("date", date3));
  });
  bind_value(input_1, () => entry().flag, (flag) => {
    entry(entry().set("flag", flag));
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/entry-forms/Entry.svelte
var root55 = from_html(`<div><!></div>`);
function Entry($$anchor, $$props) {
  push($$props, true);
  let entry = prop($$props, "entry", 15), duplicate = prop($$props, "duplicate", 3, false);
  var div = root55();
  let classes;
  var node = child(div);
  {
    var consequent = ($$anchor2) => {
      Balance2($$anchor2, {
        get entry() {
          return entry();
        },
        set entry($$value) {
          entry($$value);
        }
      });
    };
    var consequent_1 = ($$anchor2) => {
      Note2($$anchor2, {
        get entry() {
          return entry();
        },
        set entry($$value) {
          entry($$value);
        }
      });
    };
    var consequent_2 = ($$anchor2) => {
      Transaction2($$anchor2, {
        get entry() {
          return entry();
        },
        set entry($$value) {
          entry($$value);
        }
      });
    };
    var alternate = ($$anchor2) => {
      var text2 = text();
      template_effect(() => set_text(text2, `Entry type ${entry().t ?? ""} is not supported for editing.`));
      append($$anchor2, text2);
    };
    if_block(node, ($$render) => {
      if (entry() instanceof Balance) $$render(consequent);
      else if (entry() instanceof Note) $$render(consequent_1, 1);
      else if (entry() instanceof Transaction) $$render(consequent_2, 2);
      else $$render(alternate, -1);
    });
  }
  reset(div);
  template_effect(() => classes = set_class(div, 1, "flex-column svelte-cw4dkw", null, classes, { duplicate: duplicate() }));
  append($$anchor, div);
  pop();
}

// src/reports/import/Extract.svelte
var root56 = from_html(`<button type="button" class="muted">\u23EE</button> <button type="button" class="muted"> </button>`, 1);
var root_142 = from_html(`<button type="submit"> </button> <button type="button" class="muted">\u23ED</button>`, 1);
var root_220 = from_html(`<button type="submit"> </button>`);
var root_311 = from_html(`<hr/> <h3> <!></h3> <pre class="svelte-1xhhups"> </pre>`, 1);
var root_48 = from_html(`<div class="flex-row"><h3> </h3> <span class="spacer"></span> <label class="button muted"><input type="checkbox"/> </label></div> <!> <div class="flex-row"><!> <span class="spacer"></span> <!></div> <!>`, 1);
var root_56 = from_html(`<form class="flex-column"><h3> </h3> <!></form>`);
function Extract($$anchor, $$props) {
  push($$props, true);
  let entries = prop($$props, "entries", 15);
  let currentIndex = state(0);
  let count = user_derived(() => entries().length);
  let shown = user_derived(() => get2(count) > 0);
  let entry = user_derived(() => entries()[get2(currentIndex)]);
  let duplicate = user_derived(() => get2(entry)?.is_duplicate() ?? false);
  let count_duplicates = user_derived(() => entries().filter((e) => e.is_duplicate()).length);
  user_effect(() => {
    if (get2(count) > 0 && get2(currentIndex) >= get2(count)) {
      set(currentIndex, 0);
    }
  });
  function submit_or_next(event2) {
    event2.preventDefault();
    if (get2(currentIndex) < get2(count) - 1) {
      set(currentIndex, get2(currentIndex) + 1);
    } else {
      $$props.save();
    }
  }
  function previous_entry() {
    set(currentIndex, Math.max(get2(currentIndex) - 1, 0));
  }
  function toggle_duplicate() {
    if (get2(entry)) {
      entries(entries()[get2(currentIndex)] = get2(entry).set_meta("__duplicate__", !get2(entry).is_duplicate()), true);
    }
  }
  let current_index_from_one = user_derived(() => get2(currentIndex) + 1);
  let count_without_duplicates = user_derived(() => get2(count) - get2(count_duplicates));
  ModalBase($$anchor, {
    get shown() {
      return get2(shown);
    },
    get close_handler() {
      return $$props.close;
    },
    children: ($$anchor2, $$slotProps) => {
      var form = root_56();
      var h3 = child(form);
      var text2 = child(h3, true);
      reset(h3);
      var node = sibling(h3, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var fragment_1 = root_48();
          var div = first_child(fragment_1);
          var h3_1 = child(div);
          var text_1 = child(h3_1);
          reset(h3_1);
          var label2 = sibling(h3_1, 4);
          var input = child(label2);
          remove_input_defaults(input);
          var text_2 = sibling(input);
          reset(label2);
          reset(div);
          var node_1 = sibling(div, 2);
          var bind_get = () => get2(entry);
          var bind_set = (entry2) => {
            entries(entries()[get2(currentIndex)] = entry2, true);
          };
          Entry(node_1, {
            get entry() {
              return bind_get();
            },
            set entry($$value) {
              bind_set($$value);
            },
            get duplicate() {
              return get2(duplicate);
            }
          });
          var div_1 = sibling(node_1, 2);
          var node_2 = child(div_1);
          {
            var consequent = ($$anchor4) => {
              var fragment_2 = root56();
              var button = first_child(fragment_2);
              var button_1 = sibling(button, 2);
              var text_3 = child(button_1, true);
              reset(button_1);
              template_effect(($0) => set_text(text_3, $0), [() => _("Previous")]);
              delegated("click", button, () => {
                set(currentIndex, 0);
              });
              delegated("click", button_1, previous_entry);
              append($$anchor4, fragment_2);
            };
            if_block(node_2, ($$render) => {
              if (get2(currentIndex) > 0) $$render(consequent);
            });
          }
          var node_3 = sibling(node_2, 4);
          {
            var consequent_1 = ($$anchor4) => {
              var fragment_3 = root_142();
              var button_2 = first_child(fragment_3);
              var text_4 = child(button_2, true);
              reset(button_2);
              var button_3 = sibling(button_2, 2);
              template_effect(($0) => set_text(text_4, $0), [() => _("Next")]);
              delegated("click", button_3, () => {
                set(currentIndex, entries().length - 1);
              });
              append($$anchor4, fragment_3);
            };
            var alternate = ($$anchor4) => {
              var button_4 = root_220();
              var text_5 = child(button_4, true);
              reset(button_4);
              template_effect(($0) => set_text(text_5, $0), [() => _("Save")]);
              append($$anchor4, button_4);
            };
            if_block(node_3, ($$render) => {
              if (get2(currentIndex) < entries().length - 1) $$render(consequent_1);
              else $$render(alternate, -1);
            });
          }
          reset(div_1);
          var node_4 = sibling(div_1, 2);
          {
            var consequent_3 = ($$anchor4) => {
              var fragment_4 = root_311();
              var h3_2 = sibling(first_child(fragment_4), 2);
              var text_6 = child(h3_2);
              var node_5 = sibling(text_6);
              {
                var consequent_2 = ($$anchor5) => {
                  var text_7 = text();
                  template_effect(($0) => set_text(text_7, `(${$0 ?? ""}: ${get2(entry).meta.lineno ?? ""})`), [() => _("Line")]);
                  append($$anchor5, text_7);
                };
                if_block(node_5, ($$render) => {
                  if (get2(entry).meta.lineno) $$render(consequent_2);
                });
              }
              reset(h3_2);
              var pre = sibling(h3_2, 2);
              var text_8 = child(pre, true);
              reset(pre);
              template_effect(
                ($0, $1) => {
                  set_text(text_6, `${$0 ?? ""} `);
                  set_text(text_8, $1);
                },
                [() => _("Source"), () => get2(entry).meta.get("__source__")]
              );
              append($$anchor4, fragment_4);
            };
            var d = user_derived(() => get2(entry).meta.get("__source__"));
            if_block(node_4, ($$render) => {
              if (get2(d)) $$render(consequent_3);
            });
          }
          template_effect(
            ($0) => {
              set_text(text_1, `Entry
          ${get2(current_index_from_one) ?? ""}
          of
          ${get2(count) ?? ""}
          (${get2(count_without_duplicates) ?? ""}
          to import):`);
              set_checked(input, get2(duplicate));
              set_text(text_2, ` ${$0 ?? ""}`);
            },
            [() => _("ignore duplicate")]
          );
          delegated("click", input, toggle_duplicate);
          append($$anchor3, fragment_1);
        };
        if_block(node, ($$render) => {
          if (get2(entry)) $$render(consequent_4);
        });
      }
      reset(form);
      template_effect(
        ($0) => {
          form.noValidate = get2(duplicate);
          set_text(text2, $0);
        },
        [() => _("Import")]
      );
      event("submit", form, submit_or_next);
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
}
delegate(["click"]);

// src/reports/import/FileList.svelte
var root57 = from_html(`<button type="button"> </button>`);
var root_143 = from_html(`<button type="button"> </button> <!> `, 1);
var root_221 = from_html(`<form class="flex-row"><!> <input/> <button type="submit"> </button> <!></form>`);
var root_312 = from_html(`<div><button type="button" class="unset svelte-r9ferv"> </button> <button type="button" class="round svelte-r9ferv">\xD7</button></div> <div class="flex-column"></div>`, 1);
function FileList($$anchor, $$props) {
  push($$props, true);
  let selected = prop($$props, "selected", 15);
  async function move2(filename2, account, new_name) {
    const moved = await move_document(filename2, account, new_name);
    if (moved) {
      router.reload();
    }
  }
  async function remove2(filename2) {
    if (!window.confirm(_("Delete this file?"))) {
      return;
    }
    const removed = await delete_document(filename2);
    if (removed) {
      router.reload();
    }
  }
  var fragment = comment();
  var node = first_child(fragment);
  each(node, 17, () => $$props.files, (file) => file.name, ($$anchor2, file) => {
    var fragment_1 = root_312();
    var div = first_child(fragment_1);
    let classes;
    var button = child(div);
    var text2 = child(button, true);
    reset(button);
    var button_1 = sibling(button, 2);
    set_attribute(button_1, "tabindex", -1);
    reset(div);
    var div_1 = sibling(div, 2);
    each(div_1, 21, () => get2(file).importers, (info) => info.importer_name, ($$anchor3, info) => {
      const file_importer_key = user_derived(() => `${get2(file).name}:${get2(info).importer_name ?? ""}`);
      const account = user_derived(() => $$props.file_accounts.get(get2(file_importer_key)) ?? get2(info).account);
      const new_name = user_derived(() => $$props.file_names.get(get2(file_importer_key)) ?? get2(info).new_name);
      var form = root_221();
      var node_1 = child(form);
      var bind_get = () => get2(account);
      var bind_set = (value) => {
        $$props.file_accounts.set(get2(file_importer_key), value);
      };
      AccountInput(node_1, {
        get value() {
          return bind_get();
        },
        set value($$value) {
          bind_set($$value);
        },
        required: true
      });
      var input = sibling(node_1, 2);
      remove_input_defaults(input);
      set_attribute(input, "size", 40);
      var button_2 = sibling(input, 2);
      var text_1 = child(button_2, true);
      reset(button_2);
      var node_2 = sibling(button_2, 2);
      {
        var consequent_1 = ($$anchor4) => {
          const is_cached = user_derived(() => $$props.extract_cache.has(get2(file_importer_key)));
          var fragment_2 = root_143();
          var button_3 = first_child(fragment_2);
          var text_2 = child(button_3, true);
          reset(button_3);
          var node_3 = sibling(button_3, 2);
          {
            var consequent = ($$anchor5) => {
              var button_4 = root57();
              var text_3 = child(button_4, true);
              reset(button_4);
              template_effect(($0) => set_text(text_3, $0), [() => _("Clear")]);
              delegated("click", button_4, () => {
                $$props.extract_cache.delete(get2(file_importer_key));
              });
              append($$anchor5, button_4);
            };
            if_block(node_3, ($$render) => {
              if (get2(is_cached)) $$render(consequent);
            });
          }
          var text_4 = sibling(node_3);
          template_effect(
            ($0, $1) => {
              set_attribute(button_3, "title", `${$0 ?? ""} with importer ${get2(info).importer_name ?? ""}`);
              set_text(text_2, $1);
              set_text(text_4, ` ${get2(info).importer_name ?? ""}`);
            },
            [
              () => _("Extract"),
              () => get2(is_cached) ? _("Continue") : _("Extract")
            ]
          );
          delegated("click", button_3, () => {
            if (get2(info).importer_name != null) {
              $$props.extract(get2(file).name, get2(info).importer_name);
            }
          });
          append($$anchor4, fragment_2);
        };
        if_block(node_2, ($$render) => {
          if (get2(info).importer_name != null) $$render(consequent_1);
        });
      }
      reset(form);
      template_effect(($0) => set_text(text_1, $0), [() => _("Move")]);
      event("submit", form, (event2) => {
        event2.preventDefault();
        move2(get2(file).name, get2(account), get2(new_name)).catch(log_error);
      });
      bind_value(input, () => get2(new_name), (value) => {
        $$props.file_names.set(get2(file_importer_key), value);
      });
      append($$anchor3, form);
    });
    reset(div_1);
    template_effect(
      ($0) => {
        classes = set_class(div, 1, "header svelte-r9ferv", null, classes, { selected: selected() === get2(file).name });
        set_attribute(div, "title", get2(file).name);
        set_text(text2, get2(file).basename);
        set_attribute(button_1, "title", $0);
      },
      [() => _("Delete")]
    );
    delegated("click", button, () => {
      selected(selected() === get2(file).name ? void 0 : get2(file).name);
    });
    delegated("click", button_1, () => {
      remove2(get2(file).name).catch(log_error);
    });
    append($$anchor2, fragment_1);
  });
  append($$anchor, fragment);
  pop();
}
delegate(["click"]);

// src/reports/import/ImportFileUpload.svelte
var root58 = from_html(`<form><h2> </h2> <input multiple="" type="file"/> <button type="submit"> </button></form>`);
function ImportFileUpload($$anchor, $$props) {
  push($$props, true);
  let input = state(void 0);
  async function upload_imports(event2) {
    event2.preventDefault();
    if (get2(input)?.files == null) {
      return;
    }
    const files = Array.from(get2(input).files);
    await Promise.all(files.map(async (file) => {
      const form_data = new FormData();
      form_data.append("file", file, file.name);
      return put_upload_import_file(form_data).then(notify, (error) => {
        notify_err(error, (err2) => `Upload error: ${err2.message}`);
      });
    }));
    get2(input).value = "";
    router.reload();
  }
  var form = root58();
  var h2 = child(form);
  var text2 = child(h2, true);
  reset(h2);
  var input_1 = sibling(h2, 2);
  bind_this(input_1, ($$value) => set(input, $$value), () => get2(input));
  var button = sibling(input_1, 2);
  var text_1 = child(button, true);
  reset(button);
  reset(form);
  template_effect(
    ($0, $1) => {
      set_text(text2, $0);
      set_text(text_1, $1);
    },
    [() => _("Upload files for import"), () => _("Upload")]
  );
  event("submit", form, upload_imports);
  append($$anchor, form);
  pop();
}

// src/reports/import/Import.svelte
var root59 = from_html(`<p>No importers configured. See <a>Help (Import)</a> for more information.</p>`);
var root_144 = from_html(`<p> </p>`);
var root_222 = from_html(`<h2> </h2> <!>`, 1);
var root_313 = from_html(`<details><summary> </summary> <!></details>`);
var root_49 = from_html(`<div class="svelte-1va9edq"><!></div>`);
var root_57 = from_html(`<!> <div class="fixed-fullsize-container svelte-1va9edq"><div class="filelist flex-column svelte-1va9edq"><!> <!> <!> <!></div> <!></div>`, 1);
function Import($$anchor, $$props) {
  push($$props, true);
  const $search_params = () => store_get(search_params, "$search_params", $$stores);
  const $import_config = () => store_get(import_config, "$import_config", $$stores);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const show_other_files_initially = $$props.files.every((file) => !file.identified_by_importers);
  let show_other_files = state(show_other_files_initially);
  let entries = state(proxy([]));
  let selected = state(void 0);
  let extract_cache = new SvelteMap();
  let file_accounts = new SvelteMap();
  let file_names = new SvelteMap();
  let importable_files = user_derived(() => $$props.files.filter((file) => file.identified_by_importers));
  let other_files = user_derived(() => $$props.files.filter((file) => !file.identified_by_importers));
  let has_unfinished_imports = user_derived(() => extract_cache.size > 0);
  user_effect(() => get2(has_unfinished_imports) ? router.add_interrupt_handler(({ current, target }) => target?.pathname !== current.pathname ? "There are unfinished imports, are you sure you want to continue?" : null) : void 0);
  user_effect(() => {
    if (!$$props.files.some(({ name }) => name === get2(selected))) {
      set(selected, void 0);
    }
  });
  const extract_filename = user_derived(() => $search_params().get("extract_filename"));
  const extract_importer = user_derived(() => $search_params().get("extract_importer"));
  async function load_extract(filename2, importer) {
    try {
      set(entries, await loading_state.await(get_extract({ filename: filename2, importer })), true);
      if (get2(entries).length) {
        extract_cache.set(`${filename2}:${importer}`, get2(entries));
      } else {
        notify("No entries to import from this file.", "warning");
      }
    } catch (error) {
      notify_err(error);
    }
  }
  user_effect(() => {
    if (get2(extract_filename) != null && get2(extract_importer) != null) {
      const cached = extract_cache.get(`${get2(extract_filename)}:${get2(extract_importer)}`);
      if (cached) {
        set(entries, cached, true);
      } else {
        load_extract(get2(extract_filename), get2(extract_importer)).catch(log_error);
      }
    } else {
      set(entries, [], true);
    }
  });
  function extract(filename2, importer) {
    const target = new URL(router.current);
    set_query_param(target, "extract_filename", filename2);
    set_query_param(target, "extract_importer", importer);
    router.navigate(target, false);
  }
  function close_extract() {
    extract("", "");
  }
  async function save() {
    const without_duplicates = get2(entries).filter((e) => !e.is_duplicate());
    if (get2(extract_filename) != null && get2(extract_importer) != null) {
      extract_cache.delete(`${get2(extract_filename)}:${get2(extract_importer)}`);
    }
    close_extract();
    if (is_non_empty(without_duplicates)) {
      await save_entries(without_duplicates);
    }
  }
  var fragment = comment();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var p = root59();
      var a = sibling(child(p));
      next();
      reset(p);
      template_effect(($0) => set_attribute(a, "href", $0), [() => $url_for()("help/import")]);
      append($$anchor2, p);
    };
    var alternate = ($$anchor2) => {
      var fragment_1 = root_57();
      var node_1 = first_child(fragment_1);
      Extract(node_1, {
        close: close_extract,
        save,
        get entries() {
          return get2(entries);
        },
        set entries($$value) {
          set(entries, $$value, true);
        }
      });
      var div = sibling(node_1, 2);
      var div_1 = child(div);
      var node_2 = child(div_1);
      {
        var consequent_1 = ($$anchor3) => {
          var p_1 = root_144();
          var text2 = child(p_1, true);
          reset(p_1);
          template_effect(($0) => set_text(text2, $0), [() => _("No files were found for import.")]);
          append($$anchor3, p_1);
        };
        if_block(node_2, ($$render) => {
          if ($$props.files.length === 0) $$render(consequent_1);
        });
      }
      var node_3 = sibling(node_2, 2);
      {
        var consequent_2 = ($$anchor3) => {
          var fragment_2 = root_222();
          var h2 = first_child(fragment_2);
          var text_1 = child(h2, true);
          reset(h2);
          var node_4 = sibling(h2, 2);
          FileList(node_4, {
            get files() {
              return get2(importable_files);
            },
            get extract_cache() {
              return extract_cache;
            },
            get file_accounts() {
              return file_accounts;
            },
            get file_names() {
              return file_names;
            },
            extract,
            get selected() {
              return get2(selected);
            },
            set selected($$value) {
              set(selected, $$value);
            }
          });
          template_effect(($0) => set_text(text_1, $0), [() => _("Importable Files")]);
          append($$anchor3, fragment_2);
        };
        if_block(node_3, ($$render) => {
          if (get2(importable_files).length > 0) $$render(consequent_2);
        });
      }
      var node_5 = sibling(node_3, 2);
      {
        var consequent_3 = ($$anchor3) => {
          var details = root_313();
          var summary = child(details);
          var text_2 = child(summary, true);
          reset(summary);
          var node_6 = sibling(summary, 2);
          FileList(node_6, {
            get files() {
              return get2(other_files);
            },
            get extract_cache() {
              return extract_cache;
            },
            get file_accounts() {
              return file_accounts;
            },
            get file_names() {
              return file_names;
            },
            extract,
            get selected() {
              return get2(selected);
            },
            set selected($$value) {
              set(selected, $$value);
            }
          });
          reset(details);
          template_effect(($0) => set_text(text_2, $0), [() => _("Non-importable Files")]);
          bind_property("open", "toggle", details, ($$value) => set(show_other_files, $$value), () => get2(show_other_files));
          append($$anchor3, details);
        };
        if_block(node_5, ($$render) => {
          if (get2(other_files).length > 0) $$render(consequent_3);
        });
      }
      var node_7 = sibling(node_5, 2);
      ImportFileUpload(node_7, {});
      reset(div_1);
      var node_8 = sibling(div_1, 2);
      {
        var consequent_4 = ($$anchor3) => {
          var div_2 = root_49();
          var node_9 = child(div_2);
          DocumentPreview(node_9, {
            get filename() {
              return get2(selected);
            }
          });
          reset(div_2);
          append($$anchor3, div_2);
        };
        if_block(node_8, ($$render) => {
          if (get2(selected)) $$render(consequent_4);
        });
      }
      reset(div);
      append($$anchor2, fragment_1);
    };
    if_block(node, ($$render) => {
      if ($import_config() == null) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/import/index.ts
function new_filename(date3, basename2) {
  return /^\d{4}-\d{2}-\d{2}/.test(basename2) ? basename2 : `${date3} ${basename2}`;
}
var FileImporterInfo = class {
  /** Account that the importer determined. */
  account;
  /** Name of the importer (uniquely identifies the importer). */
  importer_name;
  /** New file basename, as initially determined by the importer */
  new_name;
  constructor(account, importer_name, new_name) {
    this.account = account;
    this.importer_name = importer_name;
    this.new_name = new_name;
  }
};
var import_report = new Route(
  "import",
  Import,
  async () => get_imports().then((files) => {
    const today = today_as_string();
    return files.map(({ name, basename: basename2, importers }) => ({
      name,
      basename: basename2,
      identified_by_importers: importers.length > 0,
      importers: importers.length > 0 ? importers.map(
        ({ account, importer_name, date: date3, name: name2 }) => new FileImporterInfo(
          account,
          importer_name,
          new_filename(date3, name2)
        )
      ) : [new FileImporterInfo("", null, new_filename(today, basename2))]
    }));
  }).then((files) => ({ files })),
  () => _("Import")
);

// src/reports/journal/Journal.svelte
function Journal($$anchor, $$props) {
  JournalTable($$anchor, {
    get journal() {
      return $$props.journal;
    },
    get initial_sort() {
      return $$props.initial_sort;
    },
    get all_pages() {
      return $$props.all_pages;
    },
    show_change_and_balance: false
  });
}

// src/reports/journal/index.ts
var journal = new Route(
  "journal",
  Journal,
  async (url) => {
    const filters = get_url_filters(url);
    const $journal_sort = get(journal_sort);
    const order = shallow_equal($journal_sort, ["date", "asc"]) ? "asc" : "desc";
    const { journal: journal2, total_pages } = await get_journal_page({
      ...filters,
      page: 1,
      order
    });
    let error_shown = false;
    const pages = range(2, total_pages + 1);
    const all_pages = pages.map(async (page) => {
      return get_journal_page({ ...filters, page, order }).then(
        (res) => fragment_from_string(res.journal),
        (error) => {
          log_error(`Failed to fetch page ${page.toString()}`, error);
          if (!error_shown) {
            notify_err(new Error("Failed to fetch some journal pages"));
            error_shown = true;
          }
          return null;
        }
      );
    });
    return {
      journal: fragment_from_string(journal2),
      initial_sort: ["date", order],
      all_pages
    };
  },
  () => _("Journal")
);

// src/stores/color_scheme.ts
var color_scheme_validator = constants("light dark", "dark", "light");
var color_scheme = local_storage_synced_store(
  "theme",
  color_scheme_validator,
  () => "light dark",
  () => [
    ["light dark", `\u2699\uFE0F ${_("System")}`],
    ["dark", `\u{1F319} ${_("Dark")}`],
    ["light", `\u2600\uFE0F ${_("Light")}`]
  ]
);
function init_color_scheme() {
  color_scheme.subscribe(($theme) => {
    document.documentElement.dataset.colorScheme = $theme;
  });
}

// src/reports/options/OptionsTable.svelte
var root60 = from_html(`<tr><td class="svelte-1jxngny"> </td><td class="svelte-1jxngny"><pre> </pre></td></tr>`);
var root_145 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function OptionsTable($$anchor, $$props) {
  push($$props, true);
  const columns = [
    new StringColumn(_("Key"), (d) => d[0]),
    new StringColumn(_("Value"), (d) => d[1])
  ];
  let sorter = state(proxy(new Sorter(columns[0], "asc")));
  let options_array = user_derived(() => Object.entries($$props.options));
  let sorted_options = user_derived(() => get2(sorter).sort(get2(options_array)));
  var table = root_145();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_options), ([key2, value]) => key2, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let key2 = () => get2($$array)[0];
    let value = () => get2($$array)[1];
    var tr_1 = root60();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var pre = child(td_1);
    var text_1 = child(pre, true);
    reset(pre);
    reset(td_1);
    reset(tr_1);
    template_effect(() => {
      set_text(text2, key2());
      set_text(text_1, value());
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
}

// src/reports/options/Options.svelte
var root61 = from_html(`<h2> </h2> <p><!></p> <h2> <a> </a></h2> <!> <h2> </h2> <!>`, 1);
function Options($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var fragment = root61();
  var h2 = first_child(fragment);
  var text2 = child(h2, true);
  reset(h2);
  var p = sibling(h2, 2);
  var node = child(p);
  ModeSwitch(node, {
    get store() {
      return color_scheme;
    }
  });
  reset(p);
  var h2_1 = sibling(p, 2);
  var text_1 = child(h2_1);
  var a = sibling(text_1);
  var text_2 = child(a);
  reset(a);
  reset(h2_1);
  var node_1 = sibling(h2_1, 2);
  OptionsTable(node_1, {
    get options() {
      return $$props.fava_options;
    }
  });
  var h2_2 = sibling(node_1, 2);
  var text_3 = child(h2_2, true);
  reset(h2_2);
  var node_2 = sibling(h2_2, 2);
  OptionsTable(node_2, {
    get options() {
      return $$props.beancount_options;
    }
  });
  template_effect(
    ($0, $1, $2, $3, $4) => {
      set_text(text2, $0);
      set_text(text_1, `${$1 ?? ""} `);
      set_attribute(a, "href", $2);
      set_text(text_2, `(${$3 ?? ""})`);
      set_text(text_3, $4);
    },
    [
      () => _("Color scheme"),
      () => _("Fava options"),
      () => $url_for()("help/options"),
      () => _("help"),
      () => _("Beancount options")
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/options/index.ts
var options2 = new Route(
  "options",
  Options,
  async () => get_options(),
  () => _("Options")
);

// src/stores/query.ts
var { update, set: set2, subscribe } = local_storage_synced_store(
  "query-history",
  array(string),
  () => []
);
var query_shell_history = {
  subscribe,
  /** Completely clear the history. */
  clear() {
    set2([]);
  },
  /** Add a new entry to the query history (this does avoid duplicates). */
  add(query2) {
    if (query2) {
      update((hist) => [.../* @__PURE__ */ new Set([query2, ...hist])]);
    }
  },
  /** Remove a query string from the query history. */
  remove(query2) {
    if (query2) {
      update((hist) => hist.filter((item) => item !== query2));
    }
  }
};

// src/charts/query-charts.ts
function get_query_chart(table, $chart_context) {
  const { columns } = table;
  const [first, second2] = columns;
  if (!first || !second2 || columns.length > 2) {
    return null;
  }
  if (first.dtype === "str" && second2.dtype === "Inventory") {
    const grouped = table.rows.map(
      ([group2, inv]) => ({ group: group2, balance: inv.value })
    );
    const root93 = stratify_accounts(
      grouped,
      (d) => d.group,
      (account, d) => ({ account, balance: d?.balance ?? {} })
    );
    root93.account = "(root)";
    return new ParsedHierarchyChart(null, root93).with_context($chart_context);
  }
  if (first.dtype === "date" && second2.dtype === "Inventory") {
    const bals = table.rows.map(([date3, inv]) => ({
      date: date3,
      balance: inv.value
    }));
    return new ParsedLineChart(null, bals).with_context();
  }
  return null;
}

// src/reports/query/ReadonlyQueryEditor.svelte
var root62 = from_html(`<pre></pre>`);
function ReadonlyQueryEditor($$anchor, $$props) {
  push($$props, true);
  let error = prop($$props, "error", 3, false);
  let editor2 = user_derived(() => $$props.codemirror_bql.init_readonly_query_editor($$props.value));
  var pre = root62();
  let classes;
  attach(pre, () => attach_editor(get2(editor2)));
  template_effect(() => classes = set_class(pre, 1, "svelte-1d6zhmz", null, classes, { error: error() }));
  append($$anchor, pre);
  pop();
}

// src/reports/query/QueryBox.svelte
var root63 = from_html(`<pre class="svelte-1h7nsvv"><code> </code></pre>`);
var root_146 = from_html(`<!> <!>`, 1);
var root_223 = from_html(`<details class="svelte-1h7nsvv"><summary><!> <span class="spacer"></span> <!> <button type="button">x</button></summary> <div class="svelte-1h7nsvv"><!></div></details>`);
function QueryBox($$anchor, $$props) {
  push($$props, true);
  const $chart_context = () => store_get(chart_context, "$chart_context", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let open = prop($$props, "open", 15);
  let inactive = user_derived(() => !$$props.result);
  var details = root_223();
  var summary = child(details);
  let classes;
  var node = child(summary);
  {
    let $0 = user_derived(() => $$props.result?.is_err);
    ReadonlyQueryEditor(node, {
      get value() {
        return $$props.query;
      },
      get error() {
        return get2($0);
      },
      get codemirror_bql() {
        return $$props.codemirror_bql;
      }
    });
  }
  var node_1 = sibling(node, 4);
  {
    var consequent = ($$anchor2) => {
      QueryLinks($$anchor2, {
        get query() {
          return $$props.query;
        }
      });
    };
    if_block(node_1, ($$render) => {
      if ($$props.result != null && $$props.result.is_ok && $$props.result.value.t === "table") $$render(consequent);
    });
  }
  var button = sibling(node_1, 2);
  reset(summary);
  var div = sibling(summary, 2);
  var node_2 = child(div);
  {
    var consequent_4 = ($$anchor2) => {
      var fragment_1 = comment();
      var node_3 = first_child(fragment_1);
      {
        var consequent_3 = ($$anchor3) => {
          var fragment_2 = comment();
          var node_4 = first_child(fragment_2);
          {
            var consequent_1 = ($$anchor4) => {
              var pre = root63();
              var code = child(pre);
              var text2 = child(code, true);
              reset(code);
              reset(pre);
              template_effect(() => set_text(text2, $$props.result.value.contents));
              append($$anchor4, pre);
            };
            var alternate = ($$anchor4) => {
              const chart = user_derived(() => get_query_chart($$props.result.value, $chart_context()));
              var fragment_3 = root_146();
              var node_5 = first_child(fragment_3);
              {
                var consequent_2 = ($$anchor5) => {
                  Chart($$anchor5, {
                    get chart() {
                      return get2(chart);
                    }
                  });
                };
                if_block(node_5, ($$render) => {
                  if (get2(chart)) $$render(consequent_2);
                });
              }
              var node_6 = sibling(node_5, 2);
              QueryTable(node_6, {
                get table() {
                  return $$props.result.value;
                }
              });
              append($$anchor4, fragment_3);
            };
            if_block(node_4, ($$render) => {
              if ($$props.result.value.t === "string") $$render(consequent_1);
              else $$render(alternate, -1);
            });
          }
          append($$anchor3, fragment_2);
        };
        var alternate_1 = ($$anchor3) => {
          var pre_1 = root63();
          var code_1 = child(pre_1);
          var text_1 = child(code_1, true);
          reset(code_1);
          reset(pre_1);
          template_effect(() => set_text(text_1, $$props.result.error));
          append($$anchor3, pre_1);
        };
        if_block(node_3, ($$render) => {
          if ($$props.result.is_ok) $$render(consequent_3);
          else $$render(alternate_1, -1);
        });
      }
      append($$anchor2, fragment_1);
    };
    if_block(node_2, ($$render) => {
      if ($$props.result) $$render(consequent_4);
    });
  }
  reset(div);
  reset(details);
  template_effect(() => classes = set_class(summary, 1, "svelte-1h7nsvv", null, classes, { inactive: get2(inactive) }));
  delegated("click", summary, function(...$$args) {
    (get2(inactive) ? $$props.onselect : null)?.apply(this, $$args);
  });
  delegated("click", button, (ev) => {
    ev.stopPropagation();
    $$props.ondelete();
  });
  bind_property("open", "toggle", details, open, open);
  append($$anchor, details);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/reports/query/QueryEditor.svelte
var root64 = from_html(`<form class="svelte-qhxsgh"><div class="svelte-qhxsgh"></div> <button type="submit" class="svelte-qhxsgh"> </button></form>`);
function QueryEditor($$anchor, $$props) {
  push($$props, true);
  let value = prop($$props, "value", 15);
  const editor2 = $$props.codemirror_bql.init_query_editor(
    value(),
    (state2) => {
      value(state2.sliceDoc());
    },
    _("\u2026enter a BQL query. 'help' to list available commands."),
    () => $$props.submit
  );
  user_effect(() => {
    if (value() !== editor2.state.sliceDoc()) {
      editor2.dispatch($$props.codemirror_bql.replace_contents(editor2.state, value()));
    }
  });
  var form = root64();
  var div = child(form);
  attach(div, () => attach_editor(editor2));
  var button = sibling(div, 2);
  var text2 = child(button, true);
  reset(button);
  attach(button, () => keyboardShortcut("Control+Enter"));
  reset(form);
  template_effect(($0) => set_text(text2, $0), [() => _("Submit")]);
  event("submit", form, (event2) => {
    event2.preventDefault();
    $$props.submit();
  });
  append($$anchor, form);
  pop();
}

// src/reports/query/Query.svelte
var root65 = from_html(`<!> <!>`, 1);
function Query($$anchor, $$props) {
  push($$props, true);
  const $filter_params = () => store_get(filter_params, "$filter_params", $$stores);
  const $query_shell_history = () => store_get(query_shell_history, "$query_shell_history", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let query_string = state("");
  let results = state(proxy({}));
  const is_open = proxy({});
  onMount(() => search_params.subscribe(($search_params) => {
    const search_query_string = $search_params.get("query_string") ?? "";
    if (search_query_string !== get2(query_string)) {
      set(query_string, search_query_string);
      submit();
    }
  }));
  onMount(() => filter_params.subscribe(() => {
    rerun_all_open();
  }));
  function submit() {
    const query2 = get2(query_string);
    if (!query2) {
      return;
    }
    if (query2.trim().toUpperCase() === "CLEAR") {
      query_shell_history.clear();
      set(query_string, "");
      router.set_search_param("query_string", "");
      return;
    }
    query_shell_history.add(query2);
    router.set_search_param("query_string", query2);
    get_query({ query_string: query2, ...$filter_params() }).then((res) => ok(res), (error) => err(error instanceof Error ? error.message : "INTERNAL ERROR")).then((res) => {
      get2(results)[query2] = res;
      is_open[query2] = true;
      document.querySelector("article")?.scroll(0, 0);
    }).catch(log_error);
  }
  function rerun_all_open() {
    const to_rerun = Object.entries(is_open).filter(([, is_open2]) => is_open2).map(([query2]) => query2);
    set(results, {}, true);
    for (const query2 of to_rerun) {
      get_query({ query_string: query2, ...$filter_params() }).then((res) => ok(res), (error) => err(error instanceof Error ? error.message : "INTERNAL ERROR")).then((res) => {
        get2(results)[query2] = res;
      }).catch(log_error);
    }
  }
  function delete_item(query2) {
    query_shell_history.remove(query2);
    if (get2(query_string) === query2) {
      set(query_string, "");
      router.set_search_param("query_string", "");
    }
  }
  var fragment = root65();
  var node = first_child(fragment);
  QueryEditor(node, {
    submit,
    get codemirror_bql() {
      return $$props.codemirror_bql;
    },
    get value() {
      return get2(query_string);
    },
    set value($$value) {
      set(query_string, $$value);
    }
  });
  var node_1 = sibling(node, 2);
  each(node_1, 1, $query_shell_history, (query2) => query2, ($$anchor2, query2) => {
    QueryBox($$anchor2, {
      get query() {
        return get2(query2);
      },
      get result() {
        return get2(results)[get2(query2)];
      },
      onselect: () => {
        set(query_string, get2(query2));
        submit();
      },
      ondelete: () => {
        delete_item(get2(query2));
      },
      get codemirror_bql() {
        return $$props.codemirror_bql;
      },
      get open() {
        return is_open[get2(query2)];
      },
      set open($$value) {
        is_open[get2(query2)] = $$value;
      }
    });
  });
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/query/index.ts
var query = new Route(
  "query",
  Query,
  async () => {
    const codemirror_bql = await import("./bql-76XJMPXB.js");
    return { codemirror_bql };
  },
  () => _("Query")
);

// src/reports/statistics/EntriesByType.svelte
var root66 = from_html(`<tr><td> </td><td class="num"> </td></tr>`);
var root_147 = from_html(`<table><thead><tr></tr></thead><tbody></tbody><tfoot><tr><td> </td><td class="num"> </td></tr></tfoot></table>`);
function EntriesByType($$anchor, $$props) {
  push($$props, true);
  let total = user_derived(() => sum(Object.values($$props.entries_by_type)));
  const columns = [
    new StringColumn(_("Type"), (d) => d[0].valueOf()),
    new NumberColumn(_("# Entries"), (d) => d[1])
  ];
  let sorter = state(proxy(new Sorter(columns[0], "asc")));
  let sorted_entries_by_type = user_derived(() => get2(sorter).sort(Object.entries($$props.entries_by_type)));
  var table = root_147();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_entries_by_type), ([type, count]) => type, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let type = () => get2($$array)[0];
    let count = () => get2($$array)[1];
    var tr_1 = root66();
    var td = child(tr_1);
    var text2 = child(td, true);
    reset(td);
    var td_1 = sibling(td);
    var text_1 = child(td_1, true);
    reset(td_1);
    reset(tr_1);
    template_effect(() => {
      set_text(text2, type());
      set_text(text_1, count());
    });
    append($$anchor2, tr_1);
  });
  reset(tbody);
  var tfoot = sibling(tbody);
  var tr_2 = child(tfoot);
  var td_2 = child(tr_2);
  var text_2 = child(td_2, true);
  reset(td_2);
  var td_3 = sibling(td_2);
  var text_3 = child(td_3, true);
  reset(td_3);
  reset(tr_2);
  reset(tfoot);
  reset(table);
  template_effect(
    ($0) => {
      set_text(text_2, $0);
      set_text(text_3, get2(total));
    },
    [() => _("Total")]
  );
  append($$anchor, table);
  pop();
}

// src/reports/statistics/UpdateActivity.svelte
var root67 = from_html(`<span> </span> <br/>`, 1);
var root_148 = from_html(`<tr><td class="account"><a> </a></td><td><!></td><td><a> </a></td><td class="num"><!></td></tr>`);
var root_224 = from_html(`<table><thead><tr></tr></thead><tbody></tbody></table>`);
function UpdateActivity($$anchor, $$props) {
  push($$props, true);
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $name_assets = () => store_get(name_assets, "$name_assets", $$stores);
  const $name_liabilities = () => store_get(name_liabilities, "$name_liabilities", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let accounts2 = user_derived(() => Object.entries($account_details()).filter(([account_name]) => account_name.startsWith($name_assets()) || account_name.startsWith($name_liabilities())));
  const status_sortorder = { red: 3, yellow: 2, green: 1 };
  const columns = [
    new StringColumn(_("Account"), (d) => d[0].valueOf()),
    new NumberColumn("", ([, d]) => d.uptodate_status == null ? 0 : status_sortorder[d.uptodate_status]),
    new NumberColumn(_("Last Entry"), ([, d]) => d.last_entry != null ? +d.last_entry.date : 0),
    new UnsortedColumn(_("Balance"))
  ];
  let sorter = state(proxy(new Sorter(columns[0], "asc")));
  let sorted_accounts = user_derived(() => get2(sorter).sort(get2(accounts2)));
  var table = root_224();
  var thead = child(table);
  var tr = child(thead);
  each(tr, 20, () => columns, (column) => column, ($$anchor2, column) => {
    SortHeader($$anchor2, {
      get column() {
        return column;
      },
      get sorter() {
        return get2(sorter);
      },
      set sorter($$value) {
        set(sorter, $$value, true);
      }
    });
  });
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 21, () => get2(sorted_accounts), ([account_name, { last_entry, uptodate_status }]) => account_name, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let account_name = () => get2($$array)[0];
    let last_entry = () => get2($$array)[1].last_entry;
    let uptodate_status = () => get2($$array)[1].uptodate_status;
    var fragment_1 = comment();
    var node = first_child(fragment_1);
    {
      var consequent_2 = ($$anchor3) => {
        const inventory = user_derived(() => $$props.balances[account_name()]);
        var tr_1 = root_148();
        var td = child(tr_1);
        var a = child(td);
        var text2 = child(a, true);
        reset(a);
        reset(td);
        var td_1 = sibling(td);
        var node_1 = child(td_1);
        {
          var consequent = ($$anchor4) => {
            AccountIndicator($$anchor4, {
              get account() {
                return account_name();
              },
              small: true
            });
          };
          if_block(node_1, ($$render) => {
            if (uptodate_status()) $$render(consequent);
          });
        }
        reset(td_1);
        var td_2 = sibling(td_1);
        var a_1 = child(td_2);
        var text_1 = child(a_1, true);
        reset(a_1);
        reset(td_2);
        var td_3 = sibling(td_2);
        var node_2 = child(td_3);
        {
          var consequent_1 = ($$anchor4) => {
            var fragment_3 = comment();
            var node_3 = first_child(fragment_3);
            each(node_3, 17, () => Object.entries(get2(inventory).value), ([currency, number4]) => currency, ($$anchor5, $$item2) => {
              var $$array_1 = user_derived(() => to_array(get2($$item2), 2));
              let currency = () => get2($$array_1)[0];
              let number4 = () => get2($$array_1)[1];
              var fragment_4 = root67();
              var span = first_child(fragment_4);
              var text_2 = child(span, true);
              reset(span);
              next(2);
              template_effect(
                ($0, $1) => {
                  set_attribute(span, "title", $0);
                  set_text(text_2, $1);
                },
                [
                  () => $currency_name()(currency()),
                  () => $ctx().amount(number4(), currency())
                ]
              );
              append($$anchor5, fragment_4);
            });
            append($$anchor4, fragment_3);
          };
          if_block(node_2, ($$render) => {
            if (get2(inventory)) $$render(consequent_1);
          });
        }
        reset(td_3);
        reset(tr_1);
        template_effect(
          ($0, $1) => {
            set_attribute(a, "href", $0);
            set_text(text2, account_name());
            set_attribute(a_1, "href", `#context-${last_entry().entry_hash}`);
            set_text(text_1, $1);
          },
          [
            () => $url_for_account()(account_name()),
            () => day(last_entry().date)
          ]
        );
        append($$anchor3, tr_1);
      };
      if_block(node, ($$render) => {
        if (last_entry()) $$render(consequent_2);
      });
    }
    append($$anchor2, fragment_1);
  });
  reset(tbody);
  reset(table);
  append($$anchor, table);
  pop();
  $$cleanup();
}

// src/reports/statistics/Statistics.svelte
var root68 = from_html(`<div class="left"><h3> <a> </a>)</h3> <!></div> <div class="left"><h3> <copyable-text> </copyable-text></h3> <!></div> <div class="left"><h3> </h3> <!></div>`, 3);
function Statistics($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var fragment = root68();
  var div = first_child(fragment);
  var h3 = child(div);
  var text2 = child(h3);
  var a = sibling(text2);
  var text_1 = child(a, true);
  reset(a);
  next();
  reset(h3);
  var node = sibling(h3, 2);
  QueryTable(node, {
    get table() {
      return $$props.postings_per_account;
    }
  });
  reset(div);
  var div_1 = sibling(div, 2);
  var h3_1 = child(div_1);
  var text_2 = child(h3_1);
  var copyable_text = sibling(text_2);
  set_class(copyable_text, 1, "button right");
  template_effect(() => set_custom_element_data(copyable_text, "title", _("Click to copy balance directives for accounts (except green ones) to the clipboard.")));
  template_effect(() => set_custom_element_data(copyable_text, "data-clipboard-text", $$props.all_balance_directives));
  var text_3 = child(copyable_text, true);
  reset(copyable_text);
  reset(h3_1);
  var node_1 = sibling(h3_1, 2);
  UpdateActivity(node_1, {
    get balances() {
      return $$props.balances;
    }
  });
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  var h3_2 = child(div_2);
  var text_4 = child(h3_2, true);
  reset(h3_2);
  var node_2 = sibling(h3_2, 2);
  EntriesByType(node_2, {
    get entries_by_type() {
      return $$props.entries_by_type;
    }
  });
  reset(div_2);
  template_effect(
    ($0, $1, $2, $3, $4, $5) => {
      set_text(text2, `${$0 ?? ""}
    (`);
      set_attribute(a, "href", $1);
      set_text(text_1, $2);
      set_text(text_2, `${$3 ?? ""} `);
      set_text(text_3, $4);
      set_text(text_4, $5);
    },
    [
      () => _("Postings per Account"),
      () => $url_for()("query/", { query_string: postings_per_account_query }),
      () => _("Query"),
      () => _("Update Activity"),
      () => _("Copy balance directives"),
      () => _("Entries per Type")
    ]
  );
  append($$anchor, fragment);
  pop();
  $$cleanup();
}

// src/reports/statistics/index.ts
var postings_per_account_query = "SELECT account, count(account) ORDER BY account";
var statistics = new Route(
  "statistics",
  Statistics,
  async (url) => {
    const postings_per_account = await get_query({
      query_string: postings_per_account_query,
      ...get_url_filters(url)
    });
    const { all_balance_directives, balances, entries_by_type } = await get_statistics(get_url_filters(url));
    if (postings_per_account.t !== "table") {
      throw new Error("Internal error: expected a query result table");
    }
    return {
      all_balance_directives,
      balances,
      entries_by_type,
      postings_per_account
    };
  },
  () => _("Statistics")
);

// src/tree-table/TreeTableNode.svelte
var root69 = from_html(` <!>`, 1);
var root_149 = from_html(`<span><!></span>`);
var root_225 = from_html(`<span> </span> <!> <br/>`, 1);
var root_314 = from_html(`<ol></ol>`);
var root_410 = from_html(`<li><p><!> <!> <span></span></p> <!></li>`);
function TreeTableNode_1($$anchor, $$props) {
  push($$props, true);
  const $toggled_accounts = () => store_get(toggled_accounts, "$toggled_accounts", $$stores);
  const $operating_currency = () => store_get(operating_currency, "$operating_currency", $$stores);
  const $ctx = () => store_get(ctx, "$ctx", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const not_shown = getTreeTableNotShownContext();
  let account = user_derived(() => $$props.node.account), children2 = user_derived(() => $$props.node.children);
  let is_toggled = user_derived(() => $toggled_accounts().has(get2(account)));
  let has_balance = user_derived(() => !is_empty($$props.node.balance));
  let show_balance = user_derived(() => !get2(is_toggled) && get2(has_balance));
  let shown_balance = user_derived(() => get2(show_balance) ? $$props.node.balance : $$props.node.balance_children);
  let shown_cost = user_derived(() => get2(show_balance) ? $$props.node.cost : $$props.node.cost_children);
  let shown_balance_other = user_derived(() => Object.entries(get2(shown_balance)).sort().filter(([c]) => !$operating_currency().includes(c)));
  let dimmed = user_derived(() => !get2(is_toggled) && !get2(has_balance));
  var li = root_410();
  var p = child(li);
  var node_1 = child(p);
  AccountCell(node_1, {
    get node() {
      return $$props.node;
    }
  });
  var node_2 = sibling(node_1, 2);
  each(node_2, 1, $operating_currency, (currency) => currency, ($$anchor2, currency) => {
    const num2 = user_derived(() => get2(shown_balance)[get2(currency)]);
    const cost_num = user_derived(() => get2(shown_cost)?.[get2(currency)] ?? 0);
    var span = root_149();
    let classes;
    var node_3 = child(span);
    {
      var consequent_1 = ($$anchor3) => {
        var fragment = root69();
        var text2 = first_child(fragment);
        var node_4 = sibling(text2);
        {
          var consequent = ($$anchor4) => {
            const diff = user_derived(() => $$props.invert * (get2(num2) - get2(cost_num)));
            {
              let $0 = user_derived(() => $$props.invert * get2(cost_num));
              Diff($$anchor4, {
                get diff() {
                  return get2(diff);
                },
                get num() {
                  return get2($0);
                },
                get currency() {
                  return get2(currency);
                }
              });
            }
          };
          if_block(node_4, ($$render) => {
            if (get2(cost_num) && get2(num2) - get2(cost_num)) $$render(consequent);
          });
        }
        template_effect(($0) => set_text(text2, `${$0 ?? ""} `), [
          () => $ctx().num($$props.invert * get2(num2), get2(currency))
        ]);
        append($$anchor3, fragment);
      };
      if_block(node_3, ($$render) => {
        if (get2(num2)) $$render(consequent_1);
      });
    }
    reset(span);
    template_effect(() => classes = set_class(span, 1, "num", null, classes, { dimmed: get2(dimmed) }));
    append($$anchor2, span);
  });
  var span_1 = sibling(node_2, 2);
  let classes_1;
  each(span_1, 21, () => get2(shown_balance_other), ([currency, num2]) => currency, ($$anchor2, $$item) => {
    var $$array = user_derived(() => to_array(get2($$item), 2));
    let currency = () => get2($$array)[0];
    let num2 = () => get2($$array)[1];
    const cost_num = user_derived(() => get2(shown_cost)?.[currency()] ?? 0);
    var fragment_2 = root_225();
    var span_2 = first_child(fragment_2);
    var text_1 = child(span_2, true);
    reset(span_2);
    var node_5 = sibling(span_2, 2);
    {
      var consequent_2 = ($$anchor3) => {
        const diff = user_derived(() => $$props.invert * (num2() - get2(cost_num)));
        {
          let $0 = user_derived(() => $$props.invert * get2(cost_num));
          Diff($$anchor3, {
            get diff() {
              return get2(diff);
            },
            get num() {
              return get2($0);
            },
            get currency() {
              return currency();
            }
          });
        }
      };
      if_block(node_5, ($$render) => {
        if (get2(cost_num) && num2() - get2(cost_num)) $$render(consequent_2);
      });
    }
    next(2);
    template_effect(
      ($0, $1) => {
        set_attribute(span_2, "title", $0);
        set_text(text_1, $1);
      },
      [
        () => $currency_name()(currency()),
        () => $ctx().amount($$props.invert * num2(), currency())
      ]
    );
    append($$anchor2, fragment_2);
  });
  reset(span_1);
  reset(p);
  var node_6 = sibling(p, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ol = root_314();
      each(ol, 21, () => get2(children2).filter((n) => !$not_shown().has(n.account)), (child2) => child2.account, ($$anchor3, child2) => {
        TreeTableNode_1($$anchor3, {
          get node() {
            return get2(child2);
          },
          get invert() {
            return $$props.invert;
          }
        });
      });
      reset(ol);
      append($$anchor2, ol);
    };
    var d = user_derived(() => !get2(is_toggled) && get2(children2).some((n) => !$not_shown().has(n.account)));
    if_block(node_6, ($$render) => {
      if (get2(d)) $$render(consequent_3);
    });
  }
  reset(li);
  template_effect(() => classes_1 = set_class(span_1, 1, "num other", null, classes_1, { dimmed: get2(dimmed) }));
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/tree-table/TreeTable.svelte
var root70 = from_html(`<span class="num"> </span>`);
var root_150 = from_html(`<ol><li class="head"><p><!> <!> <span class="num other"> </span></p></li> <!></ol>`);
function TreeTable($$anchor, $$props) {
  push($$props, true);
  const $not_shown = () => store_get(not_shown, "$not_shown", $$stores);
  const $get_not_shown = () => store_get(get_not_shown, "$get_not_shown", $$stores);
  const $operating_currency = () => store_get(operating_currency, "$operating_currency", $$stores);
  const $currency_name = () => store_get(currency_name, "$currency_name", $$stores);
  const $invert_account = () => store_get(invert_account, "$invert_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let account = user_derived(() => $$props.tree.account);
  const not_shown = writable(/* @__PURE__ */ new Set());
  setTreeTableNotShownContext(not_shown);
  user_effect(() => {
    store_set(not_shown, $get_not_shown()($$props.tree, $$props.end));
  });
  var ol = root_150();
  let classes;
  var li = child(ol);
  var p = child(li);
  var node_1 = child(p);
  AccountCellHeader(node_1, {
    get account() {
      return get2(account);
    }
  });
  var node_2 = sibling(node_1, 2);
  each(node_2, 1, $operating_currency, (currency) => currency, ($$anchor2, currency) => {
    var span = root70();
    var text2 = child(span, true);
    reset(span);
    template_effect(
      ($0) => {
        set_attribute(span, "title", $0);
        set_text(text2, get2(currency));
      },
      [() => $currency_name()(get2(currency))]
    );
    append($$anchor2, span);
  });
  var span_1 = sibling(node_2, 2);
  var text_1 = child(span_1, true);
  reset(span_1);
  reset(p);
  reset(li);
  var node_3 = sibling(li, 2);
  each(node_3, 17, () => get2(account) === "" ? $$props.tree.children : [$$props.tree], (node) => node.account, ($$anchor2, node) => {
    {
      let $0 = user_derived(() => $invert_account()(get2(node).account) ? -1 : 1);
      TreeTableNode_1($$anchor2, {
        get node() {
          return get2(node);
        },
        get invert() {
          return get2($0);
        }
      });
    }
  });
  reset(ol);
  template_effect(
    ($0) => {
      classes = set_class(ol, 1, "flex-table tree-table-new svelte-j6lgp", null, classes, { wider: $operating_currency().length > 1 });
      set_text(text_1, $0);
    },
    [() => _("Other")]
  );
  append($$anchor, ol);
  pop();
  $$cleanup();
}

// src/reports/tree_reports/BalanceSheet.svelte
var root71 = from_html(`<!> <div class="row"><div class="column"></div> <div class="column"></div></div>`, 1);
function BalanceSheet($$anchor, $$props) {
  push($$props, true);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  var fragment = root71();
  var node = first_child(fragment);
  ChartSwitcher(node, {
    get charts() {
      return $$props.charts;
    }
  });
  var div = sibling(node, 2);
  var div_1 = child(div);
  each(div_1, 21, () => $$props.trees.slice(0, 1), (tree) => tree.account, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get2(tree);
      },
      get end() {
        return get2(end);
      }
    });
  });
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  each(div_2, 21, () => $$props.trees.slice(1), (tree) => tree.account, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get2(tree);
      },
      get end() {
        return get2(end);
      }
    });
  });
  reset(div_2);
  reset(div);
  append($$anchor, fragment);
  pop();
}

// src/reports/tree_reports/IncomeStatement.svelte
var root72 = from_html(`<!> <div class="row"><div class="column"></div> <div class="column"></div></div>`, 1);
function IncomeStatement($$anchor, $$props) {
  push($$props, true);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  var fragment = root72();
  var node = first_child(fragment);
  ChartSwitcher(node, {
    get charts() {
      return $$props.charts;
    }
  });
  var div = sibling(node, 2);
  var div_1 = child(div);
  each(div_1, 21, () => $$props.trees.slice(0, 2), (tree) => tree.account, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get2(tree);
      },
      get end() {
        return get2(end);
      }
    });
  });
  reset(div_1);
  var div_2 = sibling(div_1, 2);
  each(div_2, 21, () => $$props.trees.slice(2), (tree) => tree.account, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get2(tree);
      },
      get end() {
        return get2(end);
      }
    });
  });
  reset(div_2);
  reset(div);
  append($$anchor, fragment);
  pop();
}

// src/reports/tree_reports/TrialBalance.svelte
var root73 = from_html(`<!> <div class="row"></div>`, 1);
function TrialBalance($$anchor, $$props) {
  push($$props, true);
  let end = user_derived(() => $$props.date_range?.end ?? null);
  var fragment = root73();
  var node = first_child(fragment);
  ChartSwitcher(node, {
    get charts() {
      return $$props.charts;
    }
  });
  var div = sibling(node, 2);
  each(div, 21, () => $$props.trees, (tree) => tree.account, ($$anchor2, tree) => {
    TreeTable($$anchor2, {
      get tree() {
        return get2(tree);
      },
      get end() {
        return get2(end);
      }
    });
  });
  reset(div);
  append($$anchor, fragment);
  pop();
}

// src/reports/tree_reports/index.ts
var income_statement = new Route(
  "income_statement",
  IncomeStatement,
  async (url) => {
    const report = await get_income_statement(get_url_filters(url));
    const [income, _profit, expenses] = report.trees;
    if (income && expenses) {
      report.charts.push(
        ParsedHierarchyChart.from_node(income),
        ParsedHierarchyChart.from_node(expenses)
      );
    }
    return report;
  },
  () => _("Income Statement")
);
var balance_sheet = new Route(
  "balance_sheet",
  BalanceSheet,
  async (url) => {
    const report = await get_balance_sheet(get_url_filters(url));
    report.charts.push(...report.trees.map(ParsedHierarchyChart.from_node));
    return report;
  },
  () => _("Balance Sheet")
);
var trial_balance = new Route(
  "trial_balance",
  TrialBalance,
  async (url) => {
    const report = await get_trial_balance(get_url_filters(url));
    const root93 = report.trees[0];
    if (root93) {
      report.charts.push(...root93.children.map(ParsedHierarchyChart.from_node));
    }
    return report;
  },
  () => _("Trial Balance")
);

// src/reports/routes.ts
var frontend_routes = [
  account_report,
  balance_sheet,
  commodities,
  documents2,
  editor,
  errors2,
  events,
  help,
  holdings,
  import_report,
  income_statement,
  journal,
  options2,
  query,
  statistics,
  trial_balance
];

// src/stores/editor.ts
var reload_after_saving_entry_slice = local_storage_synced_store(
  "reload-after-saving-entry-slice",
  boolean,
  () => true
);
var add_entry_continue = local_storage_synced_store(
  "add-entry-continue",
  boolean,
  () => false
);

// src/modals/AddEntry.svelte
var root74 = from_html(`<button type="button"> </button>`);
var root_151 = from_html(`<form class="flex-column"><h3 class="svelte-u0fdop"> <!></h3> <!> <div class="flex-row"><span class="spacer"></span> <label class="svelte-u0fdop"><input type="checkbox"/> <span class="svelte-u0fdop"> </span></label> <button type="submit"> </button></div></form>`);
function AddEntry($$anchor, $$props) {
  push($$props, true);
  const $add_entry_continue = () => store_get(add_entry_continue, "$add_entry_continue", $$stores);
  const $hash = () => store_get(hash, "$hash", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const entryTypes = [
    [Transaction, _("Transaction")],
    [Balance, _("Balance")],
    [Note, _("Note")]
  ];
  let entry = state(Transaction.empty(today_as_string()));
  async function submit(event2) {
    event2.preventDefault();
    await save_entries([get2(entry)]);
    const added_entry_date = get2(entry).date;
    set(entry, get2(entry).constructor.empty(added_entry_date));
    if (!$add_entry_continue()) {
      router.close_overlay();
    }
  }
  let shown = user_derived(() => $hash() === "add-transaction");
  ModalBase($$anchor, {
    get shown() {
      return get2(shown);
    },
    focus: "input[autocomplete=off]",
    children: ($$anchor2, $$slotProps) => {
      var form = root_151();
      var h3 = child(form);
      var text2 = child(h3);
      var node = sibling(text2);
      each(node, 17, () => entryTypes, ([Cls, displayName]) => displayName, ($$anchor3, $$item) => {
        var $$array = user_derived(() => to_array(get2($$item), 2));
        let Cls = () => get2($$array)[0];
        let displayName = () => get2($$array)[1];
        var button = root74();
        let classes;
        var text_1 = child(button, true);
        reset(button);
        template_effect(() => {
          classes = set_class(button, 1, "svelte-u0fdop", null, classes, { muted: !(get2(entry) instanceof Cls()) });
          set_text(text_1, displayName());
        });
        delegated("click", button, () => {
          set(entry, Cls().empty(get2(entry).date));
        });
        append($$anchor3, button);
      });
      reset(h3);
      var node_1 = sibling(h3, 2);
      Entry(node_1, {
        get entry() {
          return get2(entry);
        },
        set entry($$value) {
          set(entry, $$value);
        }
      });
      var div = sibling(node_1, 2);
      var label2 = sibling(child(div), 2);
      var input = child(label2);
      remove_input_defaults(input);
      var span = sibling(input, 2);
      var text_2 = child(span, true);
      reset(span);
      reset(label2);
      var button_1 = sibling(label2, 2);
      var text_3 = child(button_1, true);
      reset(button_1);
      reset(div);
      reset(form);
      template_effect(
        ($0, $1, $2) => {
          set_text(text2, `${$0 ?? ""} `);
          set_text(text_2, $1);
          set_text(text_3, $2);
        },
        [() => _("Add"), () => _("continue"), () => _("Save")]
      );
      event("submit", form, submit);
      bind_checked(input, $add_entry_continue, ($$value) => store_set(add_entry_continue, $$value));
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/editor/DeleteButton.svelte
var root75 = from_html(`<button type="button" class="muted"> </button>`);
function DeleteButton($$anchor, $$props) {
  push($$props, true);
  let deleting = state(false);
  let content = user_derived(() => get2(deleting) ? _("Deleting\u2026") : _("Delete"));
  async function onclick() {
    set(deleting, true);
    try {
      await $$props.ondelete();
    } finally {
      set(deleting, false);
    }
  }
  var button = root75();
  var text2 = child(button, true);
  reset(button);
  template_effect(() => {
    set_attribute(button, "title", get2(content));
    set_text(text2, get2(content));
  });
  delegated("click", button, onclick);
  append($$anchor, button);
  pop();
}
delegate(["click"]);

// src/editor/SliceEditor.svelte
var root76 = from_html(`<button type="button" class="muted"> </button>`);
var root_152 = from_html(`<form class="flex-column"><h3 class="svelte-1pzee4e"> </h3> <!> <div class="flex-row"><span class="spacer"></span> <button type="submit"> </button></div></form>`);
var root_226 = from_html(`<form class="flex-column"><div class="editor svelte-1pzee4e"></div> <div class="flex-row"><!> <span class="spacer"></span> <label><input type="checkbox"/> <span> </span></label> <!> <!></div></form> <!>`, 1);
function SliceEditor($$anchor, $$props) {
  push($$props, true);
  const $reload_after_saving_entry_slice = () => store_get(reload_after_saving_entry_slice, "$reload_after_saving_entry_slice", $$stores);
  const $indent = () => store_get(indent, "$indent", $$stores);
  const $currency_column = () => store_get(currency_column, "$currency_column", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let entry_hash = prop($$props, "entry_hash", 15), sha256sum = prop($$props, "sha256sum", 15);
  const initial_slice = $$props.slice;
  let current_slice = state(proxy(initial_slice));
  let changed = user_derived(() => get2(current_slice) !== initial_slice);
  let duplicated_entry = state(void 0);
  let saving = state(false);
  async function save(event2) {
    event2?.preventDefault();
    set(saving, true);
    try {
      sha256sum(await put_source_slice({
        entry_hash: entry_hash(),
        source: get2(current_slice),
        sha256sum: sha256sum()
      }));
      if ($reload_after_saving_entry_slice()) {
        router.reload();
      }
      router.close_overlay();
    } catch (error) {
      notify_err(error, (err2) => `Saving failed: ${err2.message}`);
    } finally {
      set(saving, false);
    }
  }
  async function save_duplicated_entry(event2) {
    event2.preventDefault();
    try {
      if (get2(duplicated_entry) != null) {
        await save_entries([get2(duplicated_entry)]);
      }
      router.close_overlay();
    } finally {
      set(duplicated_entry, void 0);
    }
  }
  async function delete_slice() {
    try {
      await delete_source_slice({ entry_hash: entry_hash(), sha256sum: sha256sum() });
      entry_hash("");
      if ($reload_after_saving_entry_slice()) {
        router.reload();
      }
      router.close_overlay();
    } catch (error) {
      notify_err(error, (err2) => `Deleting failed: ${err2.message}`);
    }
  }
  const editor2 = $$props.codemirror_beancount.init_beancount_editor(
    initial_slice,
    (state2) => {
      set(current_slice, state2.sliceDoc(), true);
    },
    [
      {
        key: "Control-s",
        mac: "Meta-s",
        run: () => {
          save().catch(() => {
          });
          return true;
        }
      }
    ],
    $indent(),
    $currency_column()
  );
  var fragment = root_226();
  var form = first_child(fragment);
  var div = child(form);
  attach(div, () => attach_editor(editor2));
  var div_1 = sibling(div, 2);
  var node = child(div_1);
  {
    var consequent = ($$anchor2) => {
      var button = root76();
      var text2 = child(button, true);
      reset(button);
      template_effect(($0) => set_text(text2, $0), [() => _("Duplicate")]);
      delegated("click", button, () => {
        if (get2(duplicated_entry) == null) {
          set(duplicated_entry, $$props.entry.set("date", today_as_string()));
        } else {
          set(duplicated_entry, void 0);
        }
      });
      append($$anchor2, button);
    };
    var d = user_derived(() => is_editable($$props.entry));
    if_block(node, ($$render) => {
      if (get2(d)) $$render(consequent);
    });
  }
  var label2 = sibling(node, 4);
  var input = child(label2);
  remove_input_defaults(input);
  var span = sibling(input, 2);
  var text_1 = child(span, true);
  reset(span);
  reset(label2);
  var node_1 = sibling(label2, 2);
  DeleteButton(node_1, { ondelete: delete_slice });
  var node_2 = sibling(node_1, 2);
  SaveButton(node_2, {
    get changed() {
      return get2(changed);
    },
    get saving() {
      return get2(saving);
    }
  });
  reset(div_1);
  reset(form);
  var node_3 = sibling(form, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var form_1 = root_152();
      var h3 = child(form_1);
      var text_2 = child(h3);
      reset(h3);
      var node_4 = sibling(h3, 2);
      Entry(node_4, {
        get entry() {
          return get2(duplicated_entry);
        },
        set entry($$value) {
          set(duplicated_entry, $$value);
        }
      });
      var div_2 = sibling(node_4, 2);
      var button_1 = sibling(child(div_2), 2);
      var text_3 = child(button_1, true);
      reset(button_1);
      reset(div_2);
      reset(form_1);
      template_effect(
        ($0, $1, $2) => {
          set_text(text_2, `${$0 ?? ""} ${$1 ?? ""}`);
          set_text(text_3, $2);
        },
        [
          () => _("Add"),
          () => _(get2(duplicated_entry).t),
          () => _("Save")
        ]
      );
      event("submit", form_1, save_duplicated_entry);
      append($$anchor2, form_1);
    };
    if_block(node_3, ($$render) => {
      if (get2(duplicated_entry)) $$render(consequent_1);
    });
  }
  template_effect(($0) => set_text(text_1, $0), [() => _("reload")]);
  event("submit", form, save);
  bind_checked(input, $reload_after_saving_entry_slice, ($$value) => store_set(reload_after_saving_entry_slice, $$value));
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/modals/EntryContextBalances.svelte
var root77 = from_html(`<th> </th>`);
var root_153 = from_html(` <br/>`, 1);
var root_227 = from_html(`<td class="num"></td>`);
var root_315 = from_html(`<tr><td><a> </a></td><td class="num"></td><!></tr>`);
var root_411 = from_html(`<details><summary><span> </span></summary> <div><table><thead><tr><th> </th><th> </th><!></tr></thead><tbody></tbody></table></div></details>`);
function EntryContextBalances($$anchor, $$props) {
  push($$props, true);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let accounts2 = user_derived(() => [
    .../* @__PURE__ */ new Set([
      ...Object.keys($$props.balances_before),
      ...Object.keys($$props.balances_after ?? {})
    ])
  ].sort());
  var details = root_411();
  var summary = child(details);
  var span = child(summary);
  var text2 = child(span, true);
  reset(span);
  reset(summary);
  var div = sibling(summary, 2);
  var table = child(div);
  var thead = child(table);
  var tr = child(thead);
  var th = child(tr);
  var text_1 = child(th, true);
  reset(th);
  var th_1 = sibling(th);
  var text_2 = child(th_1, true);
  reset(th_1);
  var node = sibling(th_1);
  {
    var consequent = ($$anchor2) => {
      var th_2 = root77();
      var text_3 = child(th_2, true);
      reset(th_2);
      template_effect(($0) => set_text(text_3, $0), [() => _("Balances after entry")]);
      append($$anchor2, th_2);
    };
    if_block(node, ($$render) => {
      if ($$props.balances_after) $$render(consequent);
    });
  }
  reset(tr);
  reset(thead);
  var tbody = sibling(thead);
  each(tbody, 20, () => get2(accounts2), (account) => account, ($$anchor2, account) => {
    var tr_1 = root_315();
    var td = child(tr_1);
    var a = child(td);
    var text_4 = child(a, true);
    reset(a);
    reset(td);
    var td_1 = sibling(td);
    each(td_1, 20, () => $$props.balances_before[account], (amount) => amount, ($$anchor3, amount) => {
      next();
      var fragment = root_153();
      var text_5 = first_child(fragment);
      next();
      template_effect(() => set_text(text_5, `${amount ?? ""} `));
      append($$anchor3, fragment);
    });
    reset(td_1);
    var node_1 = sibling(td_1);
    {
      var consequent_1 = ($$anchor3) => {
        var td_2 = root_227();
        each(td_2, 20, () => $$props.balances_after[account], (amount) => amount, ($$anchor4, amount) => {
          next();
          var fragment_1 = root_153();
          var text_6 = first_child(fragment_1);
          next();
          template_effect(() => set_text(text_6, `${amount ?? ""} `));
          append($$anchor4, fragment_1);
        });
        reset(td_2);
        append($$anchor3, td_2);
      };
      if_block(node_1, ($$render) => {
        if ($$props.balances_after) $$render(consequent_1);
      });
    }
    reset(tr_1);
    template_effect(
      ($0) => {
        set_attribute(a, "href", $0);
        set_text(text_4, account);
      },
      [() => $url_for_account()(account)]
    );
    append($$anchor2, tr_1);
  });
  reset(tbody);
  reset(table);
  reset(div);
  reset(details);
  template_effect(
    ($0, $1, $2) => {
      set_text(text2, $0);
      set_text(text_1, $1);
      set_text(text_2, $2);
    },
    [
      () => _("Context"),
      () => _("Account"),
      () => _("Balances before entry")
    ]
  );
  append($$anchor, details);
  pop();
  $$cleanup();
}

// src/modals/EntryContextLocation.svelte
var root78 = from_html(`<p> <code class="svelte-13btny6"><a> </a></code></p>`);
function EntryContextLocation($$anchor, $$props) {
  push($$props, true);
  const $url_for_source = () => store_get(url_for_source, "$url_for_source", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var p = root78();
  var text2 = child(p);
  var code = sibling(text2);
  var a = child(code);
  var text_1 = child(a);
  reset(a);
  reset(code);
  reset(p);
  template_effect(
    ($0, $1) => {
      set_text(text2, `${$0 ?? ""}: `);
      set_attribute(a, "href", $1);
      set_text(text_1, `${$$props.entry.meta.filename ?? ""}:${$$props.entry.meta.lineno ?? ""}`);
    },
    [
      () => _("Location"),
      () => $url_for_source()($$props.entry.meta.filename, $$props.entry.meta.lineno)
    ]
  );
  append($$anchor, p);
  pop();
  $$cleanup();
}

// src/modals/Context.svelte
var root79 = from_html(`<p>Loading entry slice...</p>`);
var root_154 = from_html(`<!> <!> <!>`, 1);
var root_228 = from_html(`<p>Loading entry context...</p>`);
var root_316 = from_html(`<div class="content"><!></div>`);
function Context($$anchor, $$props) {
  push($$props, true);
  const $hash = () => store_get(hash, "$hash", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let shown = user_derived(() => $hash().startsWith("context"));
  let entry_hash = user_derived(() => get2(shown) ? $hash().slice(8) : "");
  ModalBase($$anchor, {
    get shown() {
      return get2(shown);
    },
    children: ($$anchor2, $$slotProps) => {
      var div = root_316();
      var node = child(div);
      {
        var consequent_2 = ($$anchor3) => {
          var fragment_1 = comment();
          var node_1 = first_child(fragment_1);
          await_block(
            node_1,
            () => get_context({ entry_hash: get2(entry_hash) }),
            ($$anchor4) => {
              var p_1 = root_228();
              append($$anchor4, p_1);
            },
            ($$anchor4, $$source) => {
              var $$value = user_derived(() => {
                var { entry: entry2, balances_after: balances_after2, balances_before: balances_before2 } = get2($$source);
                return { entry: entry2, balances_after: balances_after2, balances_before: balances_before2 };
              });
              var entry = user_derived(() => get2($$value).entry);
              var balances_after = user_derived(() => get2($$value).balances_after);
              var balances_before = user_derived(() => get2($$value).balances_before);
              var fragment_2 = root_154();
              var node_2 = first_child(fragment_2);
              EntryContextLocation(node_2, {
                get entry() {
                  return get2(entry);
                }
              });
              var node_3 = sibling(node_2, 2);
              {
                var consequent = ($$anchor5) => {
                  EntryContextBalances($$anchor5, {
                    get balances_before() {
                      return get2(balances_before);
                    },
                    get balances_after() {
                      return get2(balances_after);
                    }
                  });
                };
                if_block(node_3, ($$render) => {
                  if (get2(balances_before)) $$render(consequent);
                });
              }
              var node_4 = sibling(node_3, 2);
              {
                var consequent_1 = ($$anchor5) => {
                  var fragment_4 = comment();
                  var node_5 = first_child(fragment_4);
                  await_block(
                    node_5,
                    () => Promise.all([
                      get_source_slice({ entry_hash: get2(entry_hash) }),
                      import("./beancount-OG2DLLWG.js")
                    ]),
                    ($$anchor6) => {
                      var p = root79();
                      append($$anchor6, p);
                    },
                    ($$anchor6, $$source2) => {
                      var $$value2 = user_derived(() => {
                        var [{ slice: slice2, sha256sum: sha256sum2 }, codemirror_beancount2] = get2($$source2);
                        return { slice: slice2, sha256sum: sha256sum2, codemirror_beancount: codemirror_beancount2 };
                      });
                      var slice = user_derived(() => get2($$value2).slice);
                      var sha256sum = user_derived(() => get2($$value2).sha256sum);
                      var codemirror_beancount = user_derived(() => get2($$value2).codemirror_beancount);
                      SliceEditor($$anchor6, {
                        get entry() {
                          return get2(entry);
                        },
                        get entry_hash() {
                          return get2(entry_hash);
                        },
                        get slice() {
                          return get2(slice);
                        },
                        get sha256sum() {
                          return get2(sha256sum);
                        },
                        get codemirror_beancount() {
                          return get2(codemirror_beancount);
                        }
                      });
                    },
                    ($$anchor6, error) => {
                      {
                        let $0 = user_derived(() => _("Context"));
                        ReportLoadError($$anchor6, {
                          get title() {
                            return get2($0);
                          },
                          get error() {
                            return get2(error);
                          }
                        });
                      }
                    }
                  );
                  append($$anchor5, fragment_4);
                };
                var d = user_derived(() => get2(entry).meta.lineno !== "0" && !get2(entry).meta.filename.startsWith("<"));
                if_block(node_4, ($$render) => {
                  if (get2(d)) $$render(consequent_1);
                });
              }
              append($$anchor4, fragment_2);
            },
            ($$anchor4, error) => {
              {
                let $0 = user_derived(() => _("Context"));
                ReportLoadError($$anchor4, {
                  get title() {
                    return get2($0);
                  },
                  get error() {
                    return get2(error);
                  }
                });
              }
            }
          );
          append($$anchor3, fragment_1);
        };
        if_block(node, ($$render) => {
          if (get2(shown)) $$render(consequent_2);
        });
      }
      reset(div);
      append($$anchor2, div);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/modals/DocumentUpload.svelte
var root80 = from_html(`<input class="file svelte-tu0hmy"/>`);
var root_155 = from_html(`<option> </option>`);
var root_229 = from_html(`<form><h3> </h3> <label class="svelte-tu0hmy"><span class="svelte-tu0hmy"> </span> <input type="file" multiple=""/></label> <!> <label class="svelte-tu0hmy"><span class="svelte-tu0hmy"> </span> <select></select></label> <label class="svelte-tu0hmy"><span class="svelte-tu0hmy"> </span> <!></label> <button type="submit"> </button></form>`);
function DocumentUpload($$anchor, $$props) {
  push($$props, true);
  const $documents = () => store_get(documents, "$documents", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let account = state("");
  let files = state(null);
  let entry_date = state(null);
  let entry_hash = state(null);
  let documents_folder = state(proxy($documents()[0] ?? ""));
  const new_file_names = new SvelteMap();
  let shown = user_derived(() => get2(files) != null);
  function ondragenter(event2) {
    if (is_supported_datatransfer(event2.dataTransfer)) {
      const droptarget = get_el(event2.target)?.closest(".droptarget");
      if (droptarget) {
        droptarget.classList.add("dragover");
        event2.preventDefault();
      }
    }
  }
  function ondragover(event2) {
    const dragover = get_el(event2.target)?.closest(".dragover");
    if (dragover) {
      event2.preventDefault();
    }
  }
  function ondragleave(event2) {
    const dragover = get_el(event2.target)?.closest(".dragover");
    dragover?.classList.remove("dragover");
  }
  function ondrop(event2) {
    const dragover = get_el(event2.target)?.closest(".dragover");
    const { dataTransfer } = event2;
    const target_account = dragover?.getAttribute("data-account-name");
    if (dragover == null || target_account == null || dataTransfer == null) {
      return;
    }
    dragover.classList.remove("dragover");
    event2.preventDefault();
    if (dataTransfer.types.includes("Files")) {
      set(account, target_account, true);
      set(entry_date, dragover.getAttribute("data-entry-date"), true);
      set(entry_hash, dragover.getAttribute("data-entry-hash"), true);
      set(files, dataTransfer.files, true);
    } else if (dataTransfer.types.includes("text/uri-list")) {
      const url = dataTransfer.getData("URL");
      let filename2 = new URL(url).searchParams.get("filename");
      const entry_hash2 = dragover.getAttribute("data-entry-hash");
      if (filename2 != null && entry_hash2 != null) {
        if (document_has_account(filename2, target_account)) {
          filename2 = basename(filename2);
        }
        put_attach_document({ filename: filename2, entry_hash: entry_hash2 }).then(notify, (error) => {
          notify_err(error, (e) => `Adding document metadata failed: ${e.message}`);
        });
      }
    }
  }
  function close_handler() {
    set(account, "");
    set(entry_date, null);
    set(entry_hash, null);
    set(files, null);
    new_file_names.clear();
  }
  function get_name(file) {
    const new_file_name = new_file_names.get(file);
    if (new_file_name != null) {
      return new_file_name;
    }
    return /^\d{4}-\d{2}-\d{2}/.test(file.name) ? file.name : `${get2(entry_date) ?? today_as_string()} ${file.name}`;
  }
  async function onsubmit(event2) {
    if (get2(files) == null) {
      return;
    }
    event2.preventDefault();
    await Promise.all(Array.from(get2(files)).map(async (file) => {
      const formData = new FormData();
      formData.set("account", get2(account));
      if (get2(entry_hash) != null) {
        formData.set("hash", get2(entry_hash));
      }
      formData.set("folder", get2(documents_folder));
      const name = get_name(file);
      formData.set("file", file, name);
      return put_add_document(formData).then(notify, (error) => {
        notify_err(error, (err2) => `Uploading ${name} failed: ${err2.message}`);
      });
    }));
    close_handler();
    router.reload();
  }
  event("dragenter", $document, ondragenter);
  event("dragover", $document, ondragover);
  event("dragleave", $document, ondragleave);
  event("drop", $document, ondrop);
  ModalBase($$anchor, {
    get shown() {
      return get2(shown);
    },
    close_handler,
    children: ($$anchor2, $$slotProps) => {
      var form = root_229();
      var h3 = child(form);
      var text2 = child(h3);
      reset(h3);
      var label2 = sibling(h3, 2);
      var span = child(label2);
      var text_1 = child(span);
      reset(span);
      var input = sibling(span, 2);
      reset(label2);
      var node = sibling(label2, 2);
      each(node, 16, () => get2(files), (file) => file, ($$anchor3, file) => {
        var input_1 = root80();
        remove_input_defaults(input_1);
        bind_value(input_1, () => get_name(file), (new_file_name) => {
          new_file_names.set(file, new_file_name);
        });
        append($$anchor3, input_1);
      });
      var label_1 = sibling(node, 2);
      var span_1 = child(label_1);
      var text_2 = child(span_1);
      reset(span_1);
      var select = sibling(span_1, 2);
      each(select, 5, $documents, (folder) => folder, ($$anchor3, folder) => {
        var option = root_155();
        var text_3 = child(option, true);
        reset(option);
        var option_value = {};
        template_effect(() => {
          set_text(text_3, get2(folder));
          if (option_value !== (option_value = get2(folder))) {
            option.__value = get2(folder);
          }
        });
        append($$anchor3, option);
      });
      reset(select);
      reset(label_1);
      var label_2 = sibling(label_1, 2);
      var span_2 = child(label_2);
      var text_4 = child(span_2);
      reset(span_2);
      var node_1 = sibling(span_2, 2);
      AccountInput(node_1, {
        required: true,
        get value() {
          return get2(account);
        },
        set value($$value) {
          set(account, $$value, true);
        }
      });
      reset(label_2);
      var button = sibling(label_2, 2);
      var text_5 = child(button, true);
      reset(button);
      reset(form);
      template_effect(
        ($0, $1, $2, $3, $4) => {
          set_text(text2, `${$0 ?? ""}:`);
          set_text(text_1, `${$1 ?? ""}:`);
          set_text(text_2, `${$2 ?? ""}:`);
          set_text(text_4, `${$3 ?? ""}:`);
          set_text(text_5, $4);
        },
        [
          () => _("Upload file(s)"),
          () => _("Files"),
          () => _("Documents folder"),
          () => _("Account"),
          () => _("Upload")
        ]
      );
      event("submit", form, onsubmit);
      bind_files(input, () => get2(files), ($$value) => set(files, $$value));
      bind_select_value(select, () => get2(documents_folder), ($$value) => set(documents_folder, $$value));
      append($$anchor2, form);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/modals/Export.svelte
var root81 = from_html(`<div><h3> </h3> <a data-remote=""> </a></div>`);
function Export($$anchor, $$props) {
  push($$props, true);
  const $hash = () => store_get(hash, "$hash", $$stores);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let shown = user_derived(() => $hash() === "export");
  ModalBase($$anchor, {
    get shown() {
      return get2(shown);
    },
    children: ($$anchor2, $$slotProps) => {
      var fragment_1 = comment();
      var node = first_child(fragment_1);
      {
        var consequent = ($$anchor3) => {
          var div = root81();
          var h3 = child(div);
          var text2 = child(h3);
          reset(h3);
          var a = sibling(h3, 2);
          var text_1 = child(a, true);
          reset(a);
          reset(div);
          template_effect(
            ($0, $1, $2) => {
              set_text(text2, `${$0 ?? ""}:`);
              set_attribute(a, "href", $1);
              set_text(text_1, $2);
            },
            [
              () => _("Export"),
              () => $url_for()("download-journal"),
              () => _("Download currently filtered entries as a Beancount file")
            ]
          );
          append($$anchor3, div);
        };
        if_block(node, ($$render) => {
          if (get2(shown)) $$render(consequent);
        });
      }
      append($$anchor2, fragment_1);
    },
    $$slots: { default: true }
  });
  pop();
  $$cleanup();
}

// src/modals/Modals.svelte
var root82 = from_html(`<!> <!> <!> <!>`, 1);
function Modals($$anchor) {
  var fragment = root82();
  var node = first_child(fragment);
  AddEntry(node, {});
  var node_1 = sibling(node, 2);
  Context(node_1, {});
  var node_2 = sibling(node_1, 2);
  DocumentUpload(node_2, {});
  var node_3 = sibling(node_2, 2);
  Export(node_3, {});
  append($$anchor, fragment);
}

// src/sidebar/AccountSelector.svelte
var root83 = from_html(`<li class="svelte-it8mzc"><!></li>`);
function AccountSelector($$anchor, $$props) {
  push($$props, true);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let value = state("");
  let autocomplete = state(void 0);
  function select() {
    if (get2(value)) {
      router.navigate($url_for_account()(get2(value)));
      get2(autocomplete)?.blur();
      set(value, "");
    }
  }
  var li = root83();
  var node = child(li);
  {
    let $0 = user_derived(() => _("Go to account"));
    bind_this(
      AutocompleteInput(node, {
        get placeholder() {
          return get2($0);
        },
        get suggestions() {
          return $accounts();
        },
        key: "g a",
        onselect: select,
        onenter: select,
        get value() {
          return get2(value);
        },
        set value($$value) {
          set(value, $$value, true);
        }
      }),
      ($$value) => set(autocomplete, $$value),
      () => get2(autocomplete)
    );
  }
  reset(li);
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/sidebar/SidebarLink.svelte
var root84 = from_html(`<span> </span>`);
var root_156 = from_html(`<li class="svelte-qqccl2"><a> <!></a> <!></li>`);
function SidebarLink($$anchor, $$props) {
  push($$props, true);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const $pathname = () => store_get(pathname, "$pathname", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let href = user_derived(() => $$props.remote ? $$props.report : $url_for()(`${$$props.report}/`));
  let selected = user_derived(() => $$props.remote ? false : get2(href).includes($pathname()));
  var li = root_156();
  var a = child(li);
  let classes;
  var text2 = child(a);
  var node = sibling(text2);
  {
    var consequent = ($$anchor2) => {
      var span = root84();
      let classes_1;
      var text_1 = child(span, true);
      reset(span);
      template_effect(() => {
        classes_1 = set_class(span, 1, "bubble svelte-qqccl2", null, classes_1, { error: $$props.bubble[1] === "error" });
        set_text(text_1, $$props.bubble[0]);
      });
      append($$anchor2, span);
    };
    if_block(node, ($$render) => {
      if ($$props.bubble && $$props.bubble[0] > 0) $$render(consequent);
    });
  }
  reset(a);
  attach(a, () => keyboardShortcut($$props.key));
  var node_1 = sibling(a, 2);
  snippet(node_1, () => $$props.children ?? noop);
  reset(li);
  template_effect(() => {
    set_attribute(a, "href", get2(href));
    set_attribute(a, "data-remote", $$props.remote);
    classes = set_class(a, 1, "svelte-qqccl2", null, classes, { selected: get2(selected) });
    set_text(text2, `${$$props.name ?? ""} `);
  });
  append($$anchor, li);
  pop();
  $$cleanup();
}

// src/sidebar/AsideContents.svelte
var root85 = from_html(`<ul class="navigation svelte-1mpjckc"></ul>`);
var root_157 = from_html(`<li class="svelte-1mpjckc"><a class="svelte-1mpjckc"> </a></li>`);
var root_230 = from_html(`<ul class="submenu svelte-1mpjckc"></ul>`);
var root_317 = from_html(`<a href="#add-transaction" class="secondary add-transaction svelte-1mpjckc">+</a>`);
var root_412 = from_html(`<a href="#export" class="secondary svelte-1mpjckc">\u2B07</a>`);
var root_58 = from_html(`<button type="button" class="secondary link svelte-1mpjckc">?</button>`);
var root_63 = from_html(`<!> <ul class="navigation svelte-1mpjckc"><!> <!> <!> <!> <!> <!></ul> <ul class="navigation svelte-1mpjckc"><!> <!> <!> <!> <!></ul> <ul class="navigation svelte-1mpjckc"><!> <!> <!> <!> <!></ul> <!>`, 1);
function AsideContents($$anchor, $$props) {
  push($$props, true);
  const $ledger_data = () => store_get(ledger_data, "$ledger_data", $$stores);
  const $extensions = () => store_get(extensions, "$extensions", $$stores);
  const $url_for = () => store_get(url_for, "$url_for", $$stores);
  const $errors = () => store_get(errors, "$errors", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  const truncate = (s) => s.length < 25 ? s : `${s.slice(25)}\u2026`;
  let user_queries = user_derived(() => $ledger_data().user_queries);
  let upcoming_events_count = user_derived(() => $ledger_data().upcoming_events_count);
  let sidebar_links = user_derived(() => $ledger_data().sidebar_links);
  let extension_reports = user_derived(() => $extensions().filter((e) => e.report_title != null));
  var fragment = root_63();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var ul = root85();
      each(ul, 21, () => get2(sidebar_links), ([label2, link]) => link, ($$anchor3, $$item) => {
        var $$array = user_derived(() => to_array(get2($$item), 2));
        let label2 = () => get2($$array)[0];
        let link = () => get2($$array)[1];
        SidebarLink($$anchor3, {
          get report() {
            return link();
          },
          get name() {
            return label2();
          },
          remote: true
        });
      });
      reset(ul);
      append($$anchor2, ul);
    };
    if_block(node, ($$render) => {
      if (get2(sidebar_links).length) $$render(consequent);
    });
  }
  var ul_1 = sibling(node, 2);
  var node_1 = child(ul_1);
  {
    let $0 = user_derived(() => _("Income Statement"));
    SidebarLink(node_1, {
      report: "income_statement",
      get name() {
        return get2($0);
      },
      key: "g i"
    });
  }
  var node_2 = sibling(node_1, 2);
  {
    let $0 = user_derived(() => _("Balance Sheet"));
    SidebarLink(node_2, {
      report: "balance_sheet",
      get name() {
        return get2($0);
      },
      key: "g b"
    });
  }
  var node_3 = sibling(node_2, 2);
  {
    let $0 = user_derived(() => _("Trial Balance"));
    SidebarLink(node_3, {
      report: "trial_balance",
      get name() {
        return get2($0);
      },
      key: "g t"
    });
  }
  var node_4 = sibling(node_3, 2);
  {
    let $0 = user_derived(() => _("Journal"));
    SidebarLink(node_4, {
      report: "journal",
      get name() {
        return get2($0);
      },
      key: "g j"
    });
  }
  var node_5 = sibling(node_4, 2);
  {
    let $0 = user_derived(() => _("Query"));
    SidebarLink(node_5, {
      report: "query",
      get name() {
        return get2($0);
      },
      key: "g q",
      children: ($$anchor2, $$slotProps) => {
        var fragment_2 = comment();
        var node_6 = first_child(fragment_2);
        {
          var consequent_1 = ($$anchor3) => {
            var ul_2 = root_230();
            each(ul_2, 21, () => get2(user_queries), ({ query_string, name }) => query_string, ($$anchor4, $$item) => {
              let query_string = () => get2($$item).query_string;
              let name = () => get2($$item).name;
              var li = root_157();
              var a = child(li);
              var text2 = child(a, true);
              reset(a);
              reset(li);
              template_effect(
                ($02, $1) => {
                  set_attribute(a, "href", $02);
                  set_text(text2, $1);
                },
                [
                  () => $url_for()("query/", { query_string: query_string() }),
                  () => truncate(name())
                ]
              );
              append($$anchor4, li);
            });
            reset(ul_2);
            append($$anchor3, ul_2);
          };
          if_block(node_6, ($$render) => {
            if (get2(user_queries).length) $$render(consequent_1);
          });
        }
        append($$anchor2, fragment_2);
      },
      $$slots: { default: true }
    });
  }
  var node_7 = sibling(node_5, 2);
  AccountSelector(node_7, {});
  reset(ul_1);
  var ul_3 = sibling(ul_1, 2);
  var node_8 = child(ul_3);
  {
    let $0 = user_derived(() => _("Holdings"));
    SidebarLink(node_8, {
      report: "holdings",
      get name() {
        return get2($0);
      },
      key: "g h"
    });
  }
  var node_9 = sibling(node_8, 2);
  {
    let $0 = user_derived(() => _("Commodities"));
    SidebarLink(node_9, {
      report: "commodities",
      get name() {
        return get2($0);
      },
      key: "g c"
    });
  }
  var node_10 = sibling(node_9, 2);
  {
    let $0 = user_derived(() => _("Documents"));
    SidebarLink(node_10, {
      report: "documents",
      get name() {
        return get2($0);
      },
      key: "g d"
    });
  }
  var node_11 = sibling(node_10, 2);
  {
    let $0 = user_derived(() => _("Events"));
    let $1 = user_derived(() => [get2(upcoming_events_count), "info"]);
    SidebarLink(node_11, {
      report: "events",
      get name() {
        return get2($0);
      },
      key: "g E",
      get bubble() {
        return get2($1);
      }
    });
  }
  var node_12 = sibling(node_11, 2);
  {
    let $0 = user_derived(() => _("Statistics"));
    SidebarLink(node_12, {
      report: "statistics",
      get name() {
        return get2($0);
      },
      key: "g s"
    });
  }
  reset(ul_3);
  var ul_4 = sibling(ul_3, 2);
  var node_13 = child(ul_4);
  {
    let $0 = user_derived(() => _("Editor"));
    SidebarLink(node_13, {
      report: "editor",
      get name() {
        return get2($0);
      },
      key: "g e",
      children: ($$anchor2, $$slotProps) => {
        var a_1 = root_317();
        attach(a_1, () => keyboardShortcut("n"));
        template_effect(($02) => set_attribute(a_1, "title", $02), [() => _("Add Journal Entry")]);
        append($$anchor2, a_1);
      },
      $$slots: { default: true }
    });
  }
  var node_14 = sibling(node_13, 2);
  {
    var consequent_2 = ($$anchor2) => {
      {
        let $0 = user_derived(() => _("Errors"));
        let $1 = user_derived(() => [$errors().length, "error"]);
        SidebarLink($$anchor2, {
          report: "errors",
          get name() {
            return get2($0);
          },
          get bubble() {
            return get2($1);
          }
        });
      }
    };
    if_block(node_14, ($$render) => {
      if ($errors().length > 0) $$render(consequent_2);
    });
  }
  var node_15 = sibling(node_14, 2);
  {
    let $0 = user_derived(() => _("Import"));
    SidebarLink(node_15, {
      report: "import",
      get name() {
        return get2($0);
      },
      key: "g n",
      children: ($$anchor2, $$slotProps) => {
        var a_2 = root_412();
        template_effect(($02) => set_attribute(a_2, "title", $02), [() => _("Export")]);
        append($$anchor2, a_2);
      },
      $$slots: { default: true }
    });
  }
  var node_16 = sibling(node_15, 2);
  {
    let $0 = user_derived(() => _("Options"));
    SidebarLink(node_16, {
      report: "options",
      get name() {
        return get2($0);
      },
      key: "g o"
    });
  }
  var node_17 = sibling(node_16, 2);
  {
    let $0 = user_derived(() => _("Help"));
    SidebarLink(node_17, {
      report: "help",
      get name() {
        return get2($0);
      },
      key: "g H",
      children: ($$anchor2, $$slotProps) => {
        var button = root_58();
        attach(button, () => keyboardShortcut("?"));
        template_effect(($02) => set_attribute(button, "title", $02), [() => _("Show keyboard shortcuts")]);
        delegated("click", button, function(...$$args) {
          show_keyboard_shortcuts?.apply(this, $$args);
        });
        append($$anchor2, button);
      },
      $$slots: { default: true }
    });
  }
  reset(ul_4);
  var node_18 = sibling(ul_4, 2);
  {
    var consequent_3 = ($$anchor2) => {
      var ul_5 = root85();
      each(ul_5, 21, () => get2(extension_reports), (ext2) => ext2.name, ($$anchor3, ext2) => {
        {
          let $0 = user_derived(() => `extension/${get2(ext2).name}`);
          let $1 = user_derived(() => get2(ext2).report_title ?? "");
          SidebarLink($$anchor3, {
            get report() {
              return get2($0);
            },
            get name() {
              return get2($1);
            }
          });
        }
      });
      reset(ul_5);
      append($$anchor2, ul_5);
    };
    if_block(node_18, ($$render) => {
      if (get2(extension_reports).length) $$render(consequent_3);
    });
  }
  append($$anchor, fragment);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/sidebar/AsideWithButton.svelte
var root86 = from_html(`<div class="overlay svelte-1j8fgfq" aria-hidden="true"></div>`);
var root_158 = from_html(`<!> <div><button type="button" class="svelte-1j8fgfq">\u2630</button> <a class="button svelte-1j8fgfq" href="#add-transaction">+</a></div> <aside><!></aside>`, 1);
function AsideWithButton($$anchor) {
  let active = state(false);
  const toggle2 = () => {
    set(active, !get2(active));
  };
  var fragment = root_158();
  var node = first_child(fragment);
  {
    var consequent = ($$anchor2) => {
      var div = root86();
      delegated("click", div, toggle2);
      append($$anchor2, div);
    };
    if_block(node, ($$render) => {
      if (get2(active)) $$render(consequent);
    });
  }
  var div_1 = sibling(node, 2);
  let classes;
  var button = child(div_1);
  next(2);
  reset(div_1);
  var aside = sibling(div_1, 2);
  let classes_1;
  var node_1 = child(aside);
  AsideContents(node_1, {});
  reset(aside);
  template_effect(() => {
    classes = set_class(div_1, 1, "aside-buttons svelte-1j8fgfq", null, classes, { active: get2(active) });
    classes_1 = set_class(aside, 1, "svelte-1j8fgfq", null, classes_1, { active: get2(active) });
  });
  delegated("click", button, toggle2);
  append($$anchor, fragment);
}
delegate(["click"]);

// src/sidebar/FilterForm.svelte
var root87 = from_html(`<div class="flex-row svelte-1cc11g6"><!> <!> <!></div>`);
function FilterForm($$anchor, $$props) {
  push($$props, true);
  const $tags = () => store_get(tags, "$tags", $$stores);
  const $links = () => store_get(links, "$links", $$stores);
  const $payees = () => store_get(payees, "$payees", $$stores);
  const $time_filter = () => store_get(time_filter, "$time_filter", $$stores);
  const $years = () => store_get(years, "$years", $$stores);
  const $account_filter = () => store_get(account_filter, "$account_filter", $$stores);
  const $accounts = () => store_get(accounts, "$accounts", $$stores);
  const $fql_filter = () => store_get(fql_filter, "$fql_filter", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let fql_filter_suggestions = user_derived(() => [
    ...$tags().map((tag2) => `#${tag2}`),
    ...$links().map((link) => `^${link}`),
    ...$payees().map((payee) => `payee:"${escape_for_regex(payee)}"`)
  ]);
  function value_extractor(value, input) {
    const match = /\S*$/.exec(value.slice(0, input.selectionStart ?? void 0));
    return match?.[0] ?? value;
  }
  function value_selector(value, input) {
    const selectionStart = input.selectionStart ?? 0;
    const match = /\S*$/.exec(input.value.slice(0, selectionStart));
    const matchLength = match?.[0]?.length;
    return matchLength !== void 0 ? `${input.value.slice(0, selectionStart - matchLength)}${value}${input.value.slice(selectionStart)}` : value;
  }
  var div = root87();
  var node = child(div);
  {
    let $0 = user_derived(() => _("Time"));
    AutocompleteInput(node, {
      get value() {
        return $time_filter();
      },
      get placeholder() {
        return get2($0);
      },
      get suggestions() {
        return $years();
      },
      key: "f t",
      clear_button: true,
      set_size: true,
      onchange: (v) => {
        router.set_search_param("time", v);
      }
    });
  }
  var node_1 = sibling(node, 2);
  {
    let $0 = user_derived(() => _("Account"));
    AutocompleteInput(node_1, {
      get value() {
        return $account_filter();
      },
      get placeholder() {
        return get2($0);
      },
      get suggestions() {
        return $accounts();
      },
      key: "f a",
      clear_button: true,
      set_size: true,
      onchange: (v) => {
        router.set_search_param("account", v);
      }
    });
  }
  var node_2 = sibling(node_1, 2);
  {
    let $0 = user_derived(() => _("Filter by tag, payee, \u2026"));
    AutocompleteInput(node_2, {
      get value() {
        return $fql_filter();
      },
      get placeholder() {
        return get2($0);
      },
      get suggestions() {
        return get2(fql_filter_suggestions);
      },
      key: "f f",
      clear_button: true,
      set_size: true,
      value_extractor,
      value_selector,
      onchange: (v) => {
        router.set_search_param("filter", v);
      }
    });
  }
  reset(div);
  append($$anchor, div);
  pop();
  $$cleanup();
}

// src/sidebar/HeaderIcon.svelte
var root88 = from_svg(`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="25" viewBox="0 0 24 27"><path fill="#FFF" d="M14 17.854c0 1.537-.498 2.86-1.493 3.97-.995 1.11-2.288 1.796-3.88 2.057v2.64c0 .14-.044.26-.134.35-.09.09-.205.14-.345.14H6.122c-.13 0-.242-.04-.337-.14-.095-.09-.143-.21-.143-.34v-2.64c-.66-.09-1.298-.24-1.913-.46-.62-.22-1.13-.44-1.53-.67-.4-.22-.77-.46-1.11-.72-.34-.26-.58-.45-.7-.57-.13-.12-.21-.21-.26-.27-.17-.21-.18-.42-.03-.62l1.54-2.03c.07-.1.18-.16.34-.18.15-.02.27.03.36.14l.03.03c1.13 1 2.34 1.63 3.64 1.89.37.08.74.12 1.11.12.81 0 1.52-.21 2.14-.64.61-.43.92-1.04.92-1.83 0-.28-.08-.55-.23-.8-.15-.25-.32-.46-.51-.63-.19-.17-.48-.36-.88-.56-.4-.21-.73-.37-.99-.48-.26-.12-.66-.28-1.2-.49l-.93-.38c-.23-.09-.54-.22-.93-.4-.39-.17-.7-.33-.94-.46s-.52-.31-.85-.53c-.33-.22-.6-.43-.8-.64-.21-.202-.42-.45-.65-.74-.23-.28-.41-.572-.53-.87-.13-.295-.23-.63-.32-1-.06-.4-.1-.79-.1-1.2 0-1.39.49-2.6 1.47-3.65S4.07 3.5 5.64 3.2V.48c0-.13.05-.243.143-.34.097-.09.21-.14.34-.14H8.15c.14 0 .254.045.344.136.09.09.135.206.135.346v2.652c.57.06 1.12.176 1.65.346.53.17.97.34 1.3.505.33.166.65.354.95.565.3.21.49.357.58.437.09.08.16.15.22.21.17.182.19.373.07.574l-1.21 2.2c-.08.15-.2.23-.35.24-.14.04-.28 0-.41-.1-.03-.03-.1-.09-.22-.18s-.31-.22-.59-.4c-.28-.17-.57-.33-.88-.48-.31-.14-.69-.27-1.12-.39-.44-.11-.86-.17-1.28-.17-.95 0-1.73.22-2.33.65-.6.44-.9.99-.9 1.68 0 .26.04.5.13.72.08.22.23.43.44.63s.41.36.59.5.464.29.84.47c.374.18.677.31.907.41.23.09.58.23 1.05.41.53.2.94.36 1.22.48s.66.29 1.14.53c.48.24.86.45 1.13.64.28.19.59.44.93.76.35.31.61.63.8.95.19.33.345.71.475 1.16.13.44.192.92.192 1.42z" class="svelte-1ifuyh2"></path><path fill="#A6C4DA" d="M10 17.854c0 1.537.498 2.86 1.493 3.97.995 1.11 2.288 1.796 3.88 2.057v2.64c0 .14.044.26.134.35.09.09.205.14.345.14h2.026c.13 0 .242-.04.337-.14.095-.09.143-.21.143-.34v-2.64c.66-.09 1.298-.24 1.913-.46.62-.22 1.13-.44 1.53-.67.4-.22.77-.46 1.11-.72.34-.26.58-.45.7-.57.13-.12.21-.21.26-.27.17-.21.18-.42.03-.62l-1.54-2.03c-.07-.1-.18-.16-.34-.18-.15-.02-.27.03-.36.14l-.03.03c-1.13 1-2.34 1.63-3.64 1.89-.37.08-.74.12-1.11.12-.81 0-1.52-.21-2.14-.64-.61-.43-.92-1.04-.92-1.83 0-.28.08-.55.23-.8.15-.25.32-.46.51-.63.19-.17.48-.36.88-.56.4-.21.73-.37.99-.48.26-.12.66-.28 1.2-.49l.93-.38c.23-.09.54-.22.93-.4.39-.17.7-.33.94-.46s.52-.31.85-.53c.33-.22.6-.43.8-.64.21-.202.42-.45.65-.74.23-.28.41-.572.53-.87.13-.295.23-.63.32-1s.13-.762.13-1.174c0-1.382-.49-2.6-1.47-3.642s-2.27-1.74-3.84-2.04V.49c0-.13-.05-.245-.14-.34-.14-.1-.25-.15-.38-.15h-2.03c-.14 0-.254.045-.344.136-.09.09-.135.206-.135.346v2.652c-.57.06-1.122.176-1.657.346-.535.17-.97.34-1.306.505-.335.166-.652.354-.953.565-.3.21-.495.357-.585.437-.09.08-.166.15-.226.21-.17.182-.195.373-.075.574l1.215 2.2c.08.15.195.23.345.24.14.04.28 0 .41-.1.03-.03.1-.09.22-.18s.31-.22.59-.4c.27-.17.56-.33.87-.48.31-.14.68-.27 1.12-.39.43-.11.86-.17 1.28-.17.95 0 1.72.22 2.32.65.6.44.9.99.9 1.68 0 .26-.04.5-.13.72-.09.22-.24.43-.45.63-.21.2-.41.36-.6.5s-.47.29-.84.47c-.38.18-.68.31-.91.41-.23.09-.58.23-1.05.41-.53.2-.94.36-1.22.48s-.66.29-1.14.53c-.48.24-.86.45-1.14.64s-.58.44-.93.76c-.34.31-.61.63-.79.95-.19.33-.35.71-.48 1.16-.13.44-.2.92-.2 1.42z" class="svelte-1ifuyh2"></path></svg>`);
function HeaderIcon($$anchor) {
  const $is_loading = () => store_get(is_loading, "$is_loading", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  var svg = root88();
  let classes;
  template_effect(() => classes = set_class(svg, 0, "svelte-1ifuyh2", null, classes, { loading: $is_loading() }));
  append($$anchor, svg);
  $$cleanup();
}

// src/sidebar/AccountPageTitle.svelte
var root89 = from_html(`<a class="svelte-1y1rsog"> </a><!>`, 1);
var root_159 = from_html(`<span class="last-activity svelte-1y1rsog">(Last entry: <a class="svelte-1y1rsog"> </a>)</span>`);
var root_231 = from_html(`<span class="droptarget svelte-1y1rsog"><!> <!> <!></span>`);
function AccountPageTitle($$anchor, $$props) {
  push($$props, true);
  const $account_details = () => store_get(account_details, "$account_details", $$stores);
  const $url_for_account = () => store_get(url_for_account, "$url_for_account", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let parts = user_derived(() => ancestors($$props.account));
  let details = user_derived(() => $account_details()[$$props.account]);
  let last = user_derived(() => get2(details)?.last_entry);
  var span = root_231();
  var node = child(span);
  each(node, 17, () => get2(parts), index, ($$anchor2, name, index2) => {
    var fragment = root89();
    var a = first_child(fragment);
    var text2 = child(a, true);
    reset(a);
    var node_1 = sibling(a);
    {
      var consequent = ($$anchor3) => {
        var text_1 = text(":");
        append($$anchor3, text_1);
      };
      if_block(node_1, ($$render) => {
        if (index2 < get2(parts).length - 1) $$render(consequent);
      });
    }
    template_effect(
      ($0, $1) => {
        set_attribute(a, "href", $0);
        set_attribute(a, "title", get2(name));
        set_text(text2, $1);
      },
      [
        () => $url_for_account()(get2(name)),
        () => leaf(get2(name))
      ]
    );
    append($$anchor2, fragment);
  });
  var node_2 = sibling(node, 2);
  AccountIndicator(node_2, {
    get account() {
      return $$props.account;
    }
  });
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var span_1 = root_159();
      var a_1 = sibling(child(span_1));
      var text_2 = child(a_1, true);
      reset(a_1);
      next();
      reset(span_1);
      template_effect(
        ($0) => {
          set_attribute(a_1, "href", `#context-${get2(last).entry_hash ?? ""}`);
          set_text(text_2, $0);
        },
        [() => day(get2(last).date)]
      );
      append($$anchor2, span_1);
    };
    if_block(node_3, ($$render) => {
      if (get2(last)) $$render(consequent_1);
    });
  }
  reset(span);
  template_effect(() => set_attribute(span, "data-account-name", $$props.account));
  append($$anchor, span);
  pop();
  $$cleanup();
}

// src/sidebar/PageTitle.svelte
var root90 = from_html(`<strong class="svelte-1l8uvkv"><!></strong>`);
function PageTitle($$anchor) {
  const $page_title = () => store_get(page_title, "$page_title", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let title = user_derived(() => $page_title().title), type = user_derived(() => $page_title().type);
  let is_account = user_derived(() => get2(type) === "account");
  var strong = root90();
  var node = child(strong);
  {
    var consequent = ($$anchor2) => {
      var text2 = text();
      template_effect(() => set_text(text2, get2(title)));
      append($$anchor2, text2);
    };
    var alternate = ($$anchor2) => {
      AccountPageTitle($$anchor2, {
        get account() {
          return get2(title);
        }
      });
    };
    if_block(node, ($$render) => {
      if (!get2(is_account)) $$render(consequent);
      else $$render(alternate, -1);
    });
  }
  reset(strong);
  append($$anchor, strong);
  $$cleanup();
}

// src/sidebar/Header.svelte
var root91 = from_html(`<li><a data-remote="" class="svelte-1qq0r0v"> </a></li>`);
var root_160 = from_html(`<div class="beancount-files svelte-1qq0r0v"><ul class="svelte-1qq0r0v"></ul></div>`);
var root_232 = from_html(`<header><!> <h1 class="svelte-1qq0r0v"> <!><!> <!></h1> <button type="button" class="reload-page svelte-1qq0r0v">&#8635;</button> <span class="spacer"></span> <!></header>`);
function Header($$anchor, $$props) {
  push($$props, true);
  const $ledger_data = () => store_get(ledger_data, "$ledger_data", $$stores);
  const $ledger_title = () => store_get(ledger_title, "$ledger_title", $$stores);
  const $has_changes = () => store_get(has_changes, "$has_changes", $$stores);
  const [$$stores, $$cleanup] = setup_stores();
  let other_ledgers = user_derived(() => $ledger_data().other_ledgers);
  let has_dropdown = user_derived(() => get2(other_ledgers).length);
  var header = root_232();
  var node = child(header);
  HeaderIcon(node, {});
  var h1 = sibling(node, 2);
  var text2 = child(h1, true);
  var node_1 = sibling(text2);
  {
    var consequent = ($$anchor2) => {
      var text_1 = text("\xA0\u25BE");
      append($$anchor2, text_1);
    };
    if_block(node_1, ($$render) => {
      if (get2(has_dropdown)) $$render(consequent);
    });
  }
  var node_2 = sibling(node_1);
  PageTitle(node_2, {});
  var node_3 = sibling(node_2, 2);
  {
    var consequent_1 = ($$anchor2) => {
      var div = root_160();
      var ul = child(div);
      each(ul, 21, () => get2(other_ledgers), ([name, url]) => url, ($$anchor3, $$item) => {
        var $$array = user_derived(() => to_array(get2($$item), 2));
        let name = () => get2($$array)[0];
        let url = () => get2($$array)[1];
        var li = root91();
        var a = child(li);
        var text_2 = child(a, true);
        reset(a);
        reset(li);
        template_effect(() => {
          set_attribute(a, "href", url());
          set_text(text_2, name());
        });
        append($$anchor3, li);
      });
      reset(ul);
      reset(div);
      append($$anchor2, div);
    };
    if_block(node_3, ($$render) => {
      if (get2(has_dropdown)) $$render(consequent_1);
    });
  }
  reset(h1);
  var button = sibling(h1, 2);
  attach(button, () => keyboardShortcut("r"));
  var node_4 = sibling(button, 4);
  FilterForm(node_4, {});
  reset(header);
  template_effect(() => {
    set_text(text2, $ledger_title());
    set_attribute(button, "hidden", !$has_changes());
  });
  delegated("click", button, function(...$$args) {
    router.reload?.apply(this, $$args);
  });
  append($$anchor, header);
  pop();
  $$cleanup();
}
delegate(["click"]);

// src/sidebar/HeaderAndAside.svelte
var root92 = from_html(`<!> <!>`, 1);
function HeaderAndAside($$anchor) {
  var fragment = root92();
  var node = first_child(fragment);
  Header(node, {});
  var node_1 = sibling(node, 2);
  AsideWithButton(node_1, {});
  append($$anchor, fragment);
}

// src/sidebar/index.ts
function init_sidebar() {
  page_title.subscribe(({ title }) => {
    document.title = `${title} - ${get(ledger_title)}`;
  });
  const anchor = document.querySelector("article");
  mount(
    HeaderAndAside,
    anchor ? { target: document.body, anchor } : { target: document.body }
  );
  mount(Modals, {
    target: document.body
  });
}

// src/sort/sortable-table.ts
var SortableTable = class extends HTMLTableElement {
  constructor() {
    super();
    const body = this.tBodies.item(0);
    if (!this.tHead || !body) {
      return;
    }
    const headers = [...this.tHead.querySelectorAll("th[data-sort]")];
    headers.forEach((header, index2) => {
      header.addEventListener("click", () => {
        const order = header.getAttribute("data-order") === "asc" ? "desc" : "asc";
        const type = header.getAttribute("data-sort");
        headers.forEach((e) => {
          e.removeAttribute("data-order");
        });
        header.setAttribute("data-order", order);
        sort_elements(
          body,
          [...body.querySelectorAll("tr")],
          (tr) => tr.cells.item(index2),
          get_direction(order),
          type
        );
      });
    });
  }
};

// src/svelte-custom-elements.ts
var SvelteCustomElementComponent = class {
  type;
  Component;
  validate;
  constructor(type, Component, validate) {
    this.type = type;
    this.Component = Component;
    this.validate = validate;
  }
  /** Load data and render the component for this route to the given target. */
  render(target, data) {
    const res = this.validate(data);
    if (res.is_err) {
      target.set_error(
        `Rendering component '${this.type}' failed due to invalid JSON data:`,
        domHelpers.br(),
        res.error.message
      );
      log_error(res.error);
      log_error("Invalid JSON for component:", data);
      return void 0;
    }
    const instance = mount(this.Component, { target, props: res.value });
    return () => {
      void unmount(instance);
    };
  }
};
var components = [
  new SvelteCustomElementComponent(
    "charts",
    ChartSwitcher,
    (data) => charts_validator(data).map((charts) => ({ charts }))
  ),
  new SvelteCustomElementComponent(
    "query-table",
    QueryTable,
    (data) => query_table_validator(data).map((table) => ({ table }))
  ),
  new SvelteCustomElementComponent(
    "tree-table",
    TreeTable,
    (data) => account_hierarchy_validator(data).map((tree) => ({ tree, end: null }))
  )
];
var SvelteCustomElement = class extends HTMLElement {
  destroy;
  /** Show some error content. */
  set_error(...nodes_or_strings) {
    this.classList.add("error");
    this.replaceChildren("Error: ", ...nodes_or_strings);
  }
  connectedCallback() {
    if (this.destroy) {
      return;
    }
    const type = this.getAttribute("type");
    if (type == null) {
      this.set_error("Component is missing type");
      return;
    }
    const comp = components.find((t) => t.type === type);
    if (!comp) {
      this.set_error(`Unknown component type: '${type}'`);
      return;
    }
    const script = this.querySelector("script");
    this.destroy = comp.render(
      this,
      script?.type === "application/json" ? JSON.parse(script.innerHTML) : null
    );
  }
  disconnectedCallback() {
    try {
      this.destroy?.();
      this.destroy = void 0;
    } catch {
    }
  }
};

// src/tree-table/tree-table-custom-element.ts
var TreeTableCustomElement = class extends HTMLElement {
  constructor() {
    super();
    const expandAllLink = this.querySelector(".expand-all");
    expandAllLink?.addEventListener("click", () => {
      expandAllLink.classList.add("hidden");
      this.querySelectorAll(".toggled").forEach((el) => {
        el.classList.remove("toggled");
      });
    });
    this.addEventListener("click", (event2) => {
      const { target } = event2;
      if (!(target instanceof HTMLElement) || target instanceof HTMLAnchorElement || !target.closest("span.has-children")) {
        return;
      }
      const row = target.closest("li");
      if (!row) {
        return;
      }
      const willShow = row.classList.contains("toggled");
      if (event2.shiftKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", !willShow);
        });
      }
      if (event2.ctrlKey || event2.metaKey) {
        this.querySelectorAll("li").forEach((el) => {
          el.classList.toggle("toggled", willShow);
        });
      }
      row.classList.toggle("toggled");
      expandAllLink?.classList.toggle(
        "hidden",
        !this.querySelectorAll(".toggled").length
      );
    });
  }
};

// src/app.ts
function define_custom_elements() {
  customElements.define("beancount-textarea", BeancountTextarea, {
    extends: "textarea"
  });
  customElements.define("copyable-text", CopyableText);
  customElements.define("svelte-component", SvelteCustomElement);
  customElements.define("sortable-table", SortableTable, { extends: "table" });
  customElements.define("tree-table", TreeTableCustomElement);
}
function on_changes() {
  get_ledger_data().then((v) => {
    ledger_data.set(v);
  }).catch((e) => {
    notify_err(e, (err2) => `Error fetching ledger data: ${err2.message}`);
  });
  if (get(auto_reload) && !router.has_interrupt_handler) {
    router.reload();
  } else {
    get_errors().then((v) => {
      errors.set(v);
    }, log_error);
    notify(_("File change detected. Click to reload."), "warning", () => {
      router.reload();
    });
  }
}
function poll_for_changes() {
  get_changed().catch(log_error);
}
function init() {
  const initial = get_script_tag_value("#ledger-data", ledgerDataValidator);
  if (initial.is_ok) {
    ledger_data.set(initial.value);
  } else {
    log_error(initial.error);
  }
  read_mtime();
  let initial_mtime = true;
  ledger_mtime.subscribe(() => {
    if (initial_mtime) {
      initial_mtime = false;
      return;
    }
    has_changes.set(true);
    on_changes();
  });
  init_sidebar();
  init_global_keyboard_shortcuts();
  define_custom_elements();
  setInterval(poll_for_changes, 5e3);
  router.init(frontend_routes).catch(log_error);
  ledger_data.subscribe((val) => {
    errors.set(val.errors);
  });
  init_color_scheme();
  invert_gains_losses_colors.subscribe(($invert) => {
    document.documentElement.classList.toggle("invert-gains-losses", $invert);
  });
}
init();
/*! Bundled license information:

@ungap/custom-elements/index.js:
  (*! (c) Andrea Giammarchi @webreflection ISC *)
  (*! (c) Andrea Giammarchi - ISC *)
*/
//# sourceMappingURL=app.js.map
