/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD AND TERSER
if you want to view the source, please visit the github repository of this plugin
*/

"use strict";

var __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __hasOwnProp = Object.prototype.hasOwnProperty, __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
  enumerable: true,
  configurable: true,
  writable: true,
  value
}) : obj[key] = value, __export = (target, all) => {
  for (var name in all) __defProp(target, name, {
    get: all[name],
    enumerable: true
  });
}, __copyProps = (to, from, except, desc) => {
  if (from && "object" == typeof from || "function" == typeof from) for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
    get: () => from[key],
    enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
  });
  return to;
}, __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
  value: true
}), mod), __publicField = (obj, key, value) => {
  __defNormalProp(obj, "symbol" != typeof key ? key + "" : key, value);
  return value;
}, main_exports = {};

__export(main_exports, {
  default: () => TagFolderPlugin5
});

module.exports = __toCommonJS(main_exports);

var import_obsidian8 = require("obsidian"), enumShowListIn = {
  "": "Sidebar",
  CURRENT_PANE: "Current pane",
  SPLIT_PANE: "New pane"
}, DEFAULT_SETTINGS = {
  displayMethod: "NAME",
  alwaysOpen: false,
  ignoreDocTags: "",
  ignoreTags: "",
  hideOnRootTags: "",
  sortType: "DISPNAME_ASC",
  sortExactFirst: false,
  sortTypeTag: "NAME_ASC",
  expandLimit: 0,
  disableNestedTags: false,
  hideItems: "NONE",
  ignoreFolders: "",
  targetFolders: "",
  scanDelay: 250,
  useTitle: true,
  reduceNestedParent: true,
  frontmatterKey: "title",
  useTagInfo: false,
  tagInfo: "pininfo.md",
  mergeRedundantCombination: false,
  useVirtualTag: false,
  useFrontmatterTagsForNewNotes: false,
  doNotSimplifyTags: false,
  overrideTagClicking: false,
  useMultiPaneList: false,
  archiveTags: "",
  disableNarrowingDown: false,
  expandUntaggedToRoot: false,
  disableDragging: false,
  linkConfig: {
    incoming: {
      enabled: true,
      key: ""
    },
    outgoing: {
      enabled: true,
      key: ""
    }
  },
  linkShowOnlyFDR: true,
  linkCombineOtherTree: true,
  showListIn: ""
}, VIEW_TYPE_SCROLL = "tagfolder-view-scroll", EPOCH_MINUTE = 60, EPOCH_HOUR = 60 * EPOCH_MINUTE, EPOCH_DAY = 24 * EPOCH_HOUR, FRESHNESS_1 = "FRESHNESS_01", FRESHNESS_2 = "FRESHNESS_02", FRESHNESS_3 = "FRESHNESS_03", FRESHNESS_4 = "FRESHNESS_04", FRESHNESS_5 = "FRESHNESS_05", tagDispDict = {
  FRESHNESS_01: "🕐",
  FRESHNESS_02: "📖",
  FRESHNESS_03: "📗",
  FRESHNESS_04: "📚",
  FRESHNESS_05: "🗄",
  _VIRTUAL_TAG_FRESHNESS: "⌛",
  _VIRTUAL_TAG_CANVAS: "📋 Canvas"
}, VIEW_TYPE_TAGFOLDER = "tagfolder-view", VIEW_TYPE_TAGFOLDER_LINK = "tagfolder-link-view", VIEW_TYPE_TAGFOLDER_LIST = "tagfolder-view-list", OrderKeyTag = {
  NAME: "Tag name",
  ITEMS: "Count of items"
}, OrderDirection = {
  ASC: "Ascending",
  DESC: "Descending"
}, OrderKeyItem = {
  DISPNAME: "Displaying name",
  NAME: "File name",
  MTIME: "Modified time",
  CTIME: "Created time",
  FULLPATH: "Fullpath of the file"
};

function noop() {}

function assign(tar, src) {
  for (const k in src) tar[k] = src[k];
  return tar;
}

function run(fn) {
  return fn();
}

function blank_object() {
  return Object.create(null);
}

function run_all(fns) {
  fns.forEach(run);
}

function is_function(thing) {
  return "function" == typeof thing;
}

function safe_not_equal(a, b) {
  return a != a ? b == b : a !== b || a && "object" == typeof a || "function" == typeof a;
}

function is_empty(obj) {
  return 0 === Object.keys(obj).length;
}

function subscribe(store, ...callbacks) {
  if (null == store) {
    for (const callback of callbacks) callback(void 0);
    return noop;
  }
  const unsub = store.subscribe(...callbacks);
  return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}

function component_subscribe(component, store, callback) {
  component.$$.on_destroy.push(subscribe(store, callback));
}

function create_slot(definition, ctx, $$scope, fn) {
  if (definition) {
    const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
    return definition[0](slot_ctx);
  }
}

function get_slot_context(definition, ctx, $$scope, fn) {
  return definition[1] && fn ? assign($$scope.ctx.slice(), definition[1](fn(ctx))) : $$scope.ctx;
}

function get_slot_changes(definition, $$scope, dirty, fn) {
  if (definition[2] && fn) {
    const lets = definition[2](fn(dirty));
    if (void 0 === $$scope.dirty) return lets;
    if ("object" == typeof lets) {
      const merged = [], len = Math.max($$scope.dirty.length, lets.length);
      for (let i = 0; i < len; i += 1) merged[i] = $$scope.dirty[i] | lets[i];
      return merged;
    }
    return $$scope.dirty | lets;
  }
  return $$scope.dirty;
}

function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
  if (slot_changes) {
    const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
    slot.p(slot_context, slot_changes);
  }
}

function get_all_dirty_from_scope($$scope) {
  if ($$scope.ctx.length > 32) {
    const dirty = [], length = $$scope.ctx.length / 32;
    for (let i = 0; i < length; i++) dirty[i] = -1;
    return dirty;
  }
  return -1;
}

function null_to_empty(value) {
  return null == value ? "" : value;
}

var globals = "undefined" != typeof window ? window : "undefined" != typeof globalThis ? globalThis : global, ResizeObserverSingleton = class _ResizeObserverSingleton {
  constructor(options) {
    __publicField(this, "_listeners", "WeakMap" in globals ? new WeakMap : void 0);
    __publicField(this, "_observer");
    __publicField(this, "options");
    this.options = options;
  }
  observe(element2, listener) {
    this._listeners.set(element2, listener);
    this._getObserver().observe(element2, this.options);
    return () => {
      this._listeners.delete(element2);
      this._observer.unobserve(element2);
    };
  }
  _getObserver() {
    var _a;
    return null != (_a = this._observer) ? _a : this._observer = new ResizeObserver((entries => {
      var _a2;
      for (const entry of entries) {
        _ResizeObserverSingleton.entries.set(entry.target, entry);
        null == (_a2 = this._listeners.get(entry.target)) || _a2(entry);
      }
    }));
  }
};

ResizeObserverSingleton.entries = "WeakMap" in globals ? new WeakMap : void 0;

var is_hydrating = false;

function start_hydrating() {
  is_hydrating = true;
}

function end_hydrating() {
  is_hydrating = false;
}

function append(target, node) {
  target.appendChild(node);
}

function append_styles(target, style_sheet_id, styles) {
  const append_styles_to = get_root_for_style(target);
  if (!append_styles_to.getElementById(style_sheet_id)) {
    const style = element("style");
    style.id = style_sheet_id;
    style.textContent = styles;
    append_stylesheet(append_styles_to, style);
  }
}

function get_root_for_style(node) {
  if (!node) return document;
  const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
  if (root && root.host) return root; else return node.ownerDocument;
}

function append_stylesheet(node, style) {
  append(node.head || node, style);
  return style.sheet;
}

function insert(target, node, anchor) {
  target.insertBefore(node, anchor || null);
}

function detach(node) {
  if (node.parentNode) node.parentNode.removeChild(node);
}

function destroy_each(iterations, detaching) {
  for (let i = 0; i < iterations.length; i += 1) if (iterations[i]) iterations[i].d(detaching);
}

function element(name) {
  return document.createElement(name);
}

function svg_element(name) {
  return document.createElementNS("http://www.w3.org/2000/svg", name);
}

function text(data) {
  return document.createTextNode(data);
}

function space() {
  return text(" ");
}

function empty() {
  return text("");
}

function listen(node, event, handler, options) {
  node.addEventListener(event, handler, options);
  return () => node.removeEventListener(event, handler, options);
}

function stop_propagation(fn) {
  return function(event) {
    event.stopPropagation();
    return fn.call(this, event);
  };
}

function attr(node, attribute, value) {
  if (null == value) node.removeAttribute(attribute); else if (node.getAttribute(attribute) !== value) node.setAttribute(attribute, value);
}

function children(element2) {
  return Array.from(element2.childNodes);
}

function set_data(text2, data) {
  data = "" + data;
  if (text2.data !== data) text2.data = data;
}

function set_input_value(input, value) {
  input.value = null == value ? "" : value;
}

function set_style(node, key, value, important) {
  if (null == value) node.style.removeProperty(key); else node.style.setProperty(key, value, important ? "important" : "");
}

function toggle_class(element2, name, toggle) {
  element2.classList.toggle(name, !!toggle);
}

var current_component, HtmlTag = class {
  constructor(is_svg = false) {
    __publicField(this, "is_svg", false);
    __publicField(this, "e");
    __publicField(this, "n");
    __publicField(this, "t");
    __publicField(this, "a");
    this.is_svg = is_svg;
    this.e = this.n = null;
  }
  c(html) {
    this.h(html);
  }
  m(html, target, anchor = null) {
    if (!this.e) {
      if (this.is_svg) this.e = svg_element(target.nodeName); else this.e = element(11 === target.nodeType ? "TEMPLATE" : target.nodeName);
      this.t = "TEMPLATE" !== target.tagName ? target : target.content;
      this.c(html);
    }
    this.i(anchor);
  }
  h(html) {
    this.e.innerHTML = html;
    this.n = Array.from("TEMPLATE" === this.e.nodeName ? this.e.content.childNodes : this.e.childNodes);
  }
  i(anchor) {
    for (let i = 0; i < this.n.length; i += 1) insert(this.t, this.n[i], anchor);
  }
  p(html) {
    this.d();
    this.h(html);
    this.i(this.a);
  }
  d() {
    this.n.forEach(detach);
  }
};

function get_custom_elements_slots(element2) {
  const result = {};
  element2.childNodes.forEach((node => {
    result[node.slot || "default"] = true;
  }));
  return result;
}

function set_current_component(component) {
  current_component = component;
}

function get_current_component() {
  if (!current_component) throw new Error("Function called outside component initialization");
  return current_component;
}

function onMount(fn) {
  get_current_component().$$.on_mount.push(fn);
}

function onDestroy(fn) {
  get_current_component().$$.on_destroy.push(fn);
}

function setContext(key, context) {
  get_current_component().$$.context.set(key, context);
  return context;
}

function getContext(key) {
  return get_current_component().$$.context.get(key);
}

var dirty_components = [], binding_callbacks = [], render_callbacks = [], flush_callbacks = [], resolved_promise = Promise.resolve(), update_scheduled = false;

function schedule_update() {
  if (!update_scheduled) {
    update_scheduled = true;
    resolved_promise.then(flush);
  }
}

function tick() {
  schedule_update();
  return resolved_promise;
}

function add_render_callback(fn) {
  render_callbacks.push(fn);
}

function add_flush_callback(fn) {
  flush_callbacks.push(fn);
}

var seen_callbacks = new Set, flushidx = 0;

function flush() {
  if (0 !== flushidx) return;
  const saved_component = current_component;
  do {
    try {
      for (;flushidx < dirty_components.length; ) {
        const component = dirty_components[flushidx];
        flushidx++;
        set_current_component(component);
        update(component.$$);
      }
    } catch (e) {
      dirty_components.length = 0;
      flushidx = 0;
      throw e;
    }
    set_current_component(null);
    dirty_components.length = 0;
    flushidx = 0;
    for (;binding_callbacks.length; ) binding_callbacks.pop()();
    for (let i = 0; i < render_callbacks.length; i += 1) {
      const callback = render_callbacks[i];
      if (!seen_callbacks.has(callback)) {
        seen_callbacks.add(callback);
        callback();
      }
    }
    render_callbacks.length = 0;
  } while (dirty_components.length);
  for (;flush_callbacks.length; ) flush_callbacks.pop()();
  update_scheduled = false;
  seen_callbacks.clear();
  set_current_component(saved_component);
}

function update($$) {
  if (null !== $$.fragment) {
    $$.update();
    run_all($$.before_update);
    const dirty = $$.dirty;
    $$.dirty = [ -1 ];
    $$.fragment && $$.fragment.p($$.ctx, dirty);
    $$.after_update.forEach(add_render_callback);
  }
}

function flush_render_callbacks(fns) {
  const filtered = [], targets = [];
  render_callbacks.forEach((c => -1 === fns.indexOf(c) ? filtered.push(c) : targets.push(c)));
  targets.forEach((c => c()));
  render_callbacks = filtered;
}

var outros, outroing = new Set;

function group_outros() {
  outros = {
    r: 0,
    c: [],
    p: outros
  };
}

function check_outros() {
  if (!outros.r) run_all(outros.c);
  outros = outros.p;
}

function transition_in(block, local) {
  if (block && block.i) {
    outroing.delete(block);
    block.i(local);
  }
}

function transition_out(block, local, detach2, callback) {
  if (block && block.o) {
    if (outroing.has(block)) return;
    outroing.add(block);
    outros.c.push((() => {
      outroing.delete(block);
      if (callback) {
        if (detach2) block.d(1);
        callback();
      }
    }));
    block.o(local);
  } else if (callback) callback();
}

function ensure_array_like(array_like_or_iterator) {
  return void 0 !== (null == array_like_or_iterator ? void 0 : array_like_or_iterator.length) ? array_like_or_iterator : Array.from(array_like_or_iterator);
}

var SvelteElement, _boolean_attributes = [ "allowfullscreen", "allowpaymentrequest", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected" ], boolean_attributes = new Set([ ..._boolean_attributes ]);

function bind(component, name, callback) {
  const index = component.$$.props[name];
  if (void 0 !== index) {
    component.$$.bound[index] = callback;
    callback(component.$$.ctx[index]);
  }
}

function create_component(block) {
  block && block.c();
}

function mount_component(component, target, anchor) {
  const {fragment, after_update} = component.$$;
  fragment && fragment.m(target, anchor);
  add_render_callback((() => {
    const new_on_destroy = component.$$.on_mount.map(run).filter(is_function);
    if (component.$$.on_destroy) component.$$.on_destroy.push(...new_on_destroy); else run_all(new_on_destroy);
    component.$$.on_mount = [];
  }));
  after_update.forEach(add_render_callback);
}

function destroy_component(component, detaching) {
  const $$ = component.$$;
  if (null !== $$.fragment) {
    flush_render_callbacks($$.after_update);
    run_all($$.on_destroy);
    $$.fragment && $$.fragment.d(detaching);
    $$.on_destroy = $$.fragment = null;
    $$.ctx = [];
  }
}

function make_dirty(component, i) {
  if (-1 === component.$$.dirty[0]) {
    dirty_components.push(component);
    schedule_update();
    component.$$.dirty.fill(0);
  }
  component.$$.dirty[i / 31 | 0] |= 1 << i % 31;
}

function init(component, options, instance7, create_fragment7, not_equal, props, append_styles2 = null, dirty = [ -1 ]) {
  const parent_component = current_component;
  set_current_component(component);
  const $$ = component.$$ = {
    fragment: null,
    ctx: [],
    props,
    update: noop,
    not_equal,
    bound: blank_object(),
    on_mount: [],
    on_destroy: [],
    on_disconnect: [],
    before_update: [],
    after_update: [],
    context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
    callbacks: blank_object(),
    dirty,
    skip_bound: false,
    root: options.target || parent_component.$$.root
  };
  append_styles2 && append_styles2($$.root);
  let ready = false;
  $$.ctx = instance7 ? instance7(component, options.props || {}, ((i, ret, ...rest) => {
    const value = rest.length ? rest[0] : ret;
    if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
      if (!$$.skip_bound && $$.bound[i]) $$.bound[i](value);
      if (ready) make_dirty(component, i);
    }
    return ret;
  })) : [];
  $$.update();
  ready = true;
  run_all($$.before_update);
  $$.fragment = create_fragment7 ? create_fragment7($$.ctx) : false;
  if (options.target) {
    if (options.hydrate) {
      start_hydrating();
      const nodes = children(options.target);
      $$.fragment && $$.fragment.l(nodes);
      nodes.forEach(detach);
    } else $$.fragment && $$.fragment.c();
    if (options.intro) transition_in(component.$$.fragment);
    mount_component(component, options.target, options.anchor);
    end_hydrating();
    flush();
  }
  set_current_component(parent_component);
}

if ("function" == typeof HTMLElement) SvelteElement = class extends HTMLElement {
  constructor($$componentCtor, $$slots, use_shadow_dom) {
    super();
    __publicField(this, "$$ctor");
    __publicField(this, "$$s");
    __publicField(this, "$$c");
    __publicField(this, "$$cn", false);
    __publicField(this, "$$d", {});
    __publicField(this, "$$r", false);
    __publicField(this, "$$p_d", {});
    __publicField(this, "$$l", {});
    __publicField(this, "$$l_u", new Map);
    this.$$ctor = $$componentCtor;
    this.$$s = $$slots;
    if (use_shadow_dom) this.attachShadow({
      mode: "open"
    });
  }
  addEventListener(type, listener, options) {
    this.$$l[type] = this.$$l[type] || [];
    this.$$l[type].push(listener);
    if (this.$$c) {
      const unsub = this.$$c.$on(type, listener);
      this.$$l_u.set(listener, unsub);
    }
    super.addEventListener(type, listener, options);
  }
  removeEventListener(type, listener, options) {
    super.removeEventListener(type, listener, options);
    if (this.$$c) {
      const unsub = this.$$l_u.get(listener);
      if (unsub) {
        unsub();
        this.$$l_u.delete(listener);
      }
    }
  }
  async connectedCallback() {
    this.$$cn = true;
    if (!this.$$c) {
      let create_slot2 = function(name) {
        return () => {
          let node;
          return {
            c: function create() {
              node = element("slot");
              if ("default" !== name) attr(node, "name", name);
            },
            m: function mount(target, anchor) {
              insert(target, node, anchor);
            },
            d: function destroy(detaching) {
              if (detaching) detach(node);
            }
          };
        };
      };
      await Promise.resolve();
      if (!this.$$cn || this.$$c) return;
      const $$slots = {}, existing_slots = get_custom_elements_slots(this);
      for (const name of this.$$s) if (name in existing_slots) $$slots[name] = [ create_slot2(name) ];
      for (const attribute of this.attributes) {
        const name = this.$$g_p(attribute.name);
        if (!(name in this.$$d)) this.$$d[name] = get_custom_element_value(name, attribute.value, this.$$p_d, "toProp");
      }
      for (const key in this.$$p_d) if (!(key in this.$$d) && void 0 !== this[key]) {
        this.$$d[key] = this[key];
        delete this[key];
      }
      this.$$c = new this.$$ctor({
        target: this.shadowRoot || this,
        props: {
          ...this.$$d,
          $$slots,
          $$scope: {
            ctx: []
          }
        }
      });
      const reflect_attributes = () => {
        this.$$r = true;
        for (const key in this.$$p_d) {
          this.$$d[key] = this.$$c.$$.ctx[this.$$c.$$.props[key]];
          if (this.$$p_d[key].reflect) {
            const attribute_value = get_custom_element_value(key, this.$$d[key], this.$$p_d, "toAttribute");
            if (null == attribute_value) this.removeAttribute(this.$$p_d[key].attribute || key); else this.setAttribute(this.$$p_d[key].attribute || key, attribute_value);
          }
        }
        this.$$r = false;
      };
      this.$$c.$$.after_update.push(reflect_attributes);
      reflect_attributes();
      for (const type in this.$$l) for (const listener of this.$$l[type]) {
        const unsub = this.$$c.$on(type, listener);
        this.$$l_u.set(listener, unsub);
      }
      this.$$l = {};
    }
  }
  attributeChangedCallback(attr2, _oldValue, newValue) {
    var _a;
    if (!this.$$r) {
      attr2 = this.$$g_p(attr2);
      this.$$d[attr2] = get_custom_element_value(attr2, newValue, this.$$p_d, "toProp");
      null == (_a = this.$$c) || _a.$set({
        [attr2]: this.$$d[attr2]
      });
    }
  }
  disconnectedCallback() {
    this.$$cn = false;
    Promise.resolve().then((() => {
      if (!this.$$cn) {
        this.$$c.$destroy();
        this.$$c = void 0;
      }
    }));
  }
  $$g_p(attribute_name) {
    return Object.keys(this.$$p_d).find((key => this.$$p_d[key].attribute === attribute_name || !this.$$p_d[key].attribute && key.toLowerCase() === attribute_name)) || attribute_name;
  }
};

function get_custom_element_value(prop, value, props_definition, transform) {
  var _a;
  const type = null == (_a = props_definition[prop]) ? void 0 : _a.type;
  value = "Boolean" === type && "boolean" != typeof value ? null != value : value;
  if (!transform || !props_definition[prop]) return value; else if ("toAttribute" === transform) switch (type) {
   case "Object":
   case "Array":
    return null == value ? null : JSON.stringify(value);

   case "Boolean":
    return value ? "" : null;

   case "Number":
    return null == value ? null : value;

   default:
    return value;
  } else switch (type) {
   case "Object":
   case "Array":
    return value && JSON.parse(value);

   case "Boolean":
    return value;

   case "Number":
    return null != value ? +value : value;

   default:
    return value;
  }
}

var SvelteComponent = class {
  constructor() {
    __publicField(this, "$$");
    __publicField(this, "$$set");
  }
  $destroy() {
    destroy_component(this, 1);
    this.$destroy = noop;
  }
  $on(type, callback) {
    if (!is_function(callback)) return noop;
    const callbacks = this.$$.callbacks[type] || (this.$$.callbacks[type] = []);
    callbacks.push(callback);
    return () => {
      const index = callbacks.indexOf(callback);
      if (-1 !== index) callbacks.splice(index, 1);
    };
  }
  $set(props) {
    if (this.$$set && !is_empty(props)) {
      this.$$.skip_bound = true;
      this.$$set(props);
      this.$$.skip_bound = false;
    }
  }
}, PUBLIC_VERSION = "4", subscriber_queue = [];

function writable(value, start = noop) {
  let stop;
  const subscribers = new Set;
  function set(new_value) {
    if (safe_not_equal(value, new_value)) {
      value = new_value;
      if (stop) {
        const run_queue = !subscriber_queue.length;
        for (const subscriber of subscribers) {
          subscriber[1]();
          subscriber_queue.push(subscriber, value);
        }
        if (run_queue) {
          for (let i = 0; i < subscriber_queue.length; i += 2) subscriber_queue[i][0](subscriber_queue[i + 1]);
          subscriber_queue.length = 0;
        }
      }
    }
  }
  function update2(fn) {
    set(fn(value));
  }
  return {
    set,
    update: update2,
    subscribe: function subscribe2(run2, invalidate = noop) {
      const subscriber = [ run2, invalidate ];
      subscribers.add(subscriber);
      if (1 === subscribers.size) stop = start(set, update2) || noop;
      run2(value);
      return () => {
        subscribers.delete(subscriber);
        if (0 === subscribers.size && stop) {
          stop();
          stop = null;
        }
      };
    }
  };
}

var currentFile = writable(""), maxDepth = writable(0), searchString = writable(""), tagInfo = writable({}), tagFolderSetting = writable(DEFAULT_SETTINGS), selectedTags = writable(), allViewItems = writable(), allViewItemsByLink = writable(), appliedFiles = writable(), v2expandedTags = writable(new Set), performHide = writable(0);

function unique(items) {
  return [ ...new Set([ ...items ]) ];
}

function trimSlash(src, keepStart = false, keepEnd = false) {
  const st = keepStart ? 0 : "/" == src[0] ? 1 : 0, end = keepEnd ? void 0 : src.endsWith("/") ? -1 : void 0;
  if (0 == st && null == end) return src; else return src.slice(st, end);
}

function trimPrefix(source, prefix) {
  if (source.startsWith(prefix)) return source.substring(prefix.length); else return source;
}

function ancestorToTags(ancestors) {
  return [ ...ancestors ].reduce(((p, i) => "/" != i[0] ? [ ...p, i ] : [ ...p, p.pop() + "/" + i.substring(1) ]), []);
}

function ancestorToLongestTag(ancestors) {
  return ancestors.reduceRight(((a, e) => {
    var _a;
    return !a ? [ e ] : (null == (_a = a[0]) ? void 0 : _a.startsWith(e)) ? a : [ e, ...a ];
  }), []);
}

function isSpecialTag(tagSrc) {
  const tag = trimSlash(tagSrc);
  return "_untagged" == tag || tag in tagDispDict;
}

var tagDispAlternativeDict = {};

tagInfo.subscribe((tagInfo2 => {
  tagDispAlternativeDict = {
    ...tagDispDict
  };
  if (null == tagInfo2) return;
  const items = Object.entries(tagInfo2);
  for (const [key, info] of items) if (null == info ? void 0 : info.alt) tagDispAlternativeDict[key] = info.alt;
}));

function renderSpecialTag(tagSrc) {
  const tag = trimSlash(tagSrc);
  return tag in tagDispAlternativeDict ? tagDispAlternativeDict[tag] : tagSrc;
}

function secondsToFreshness(totalAsMSec) {
  const totalAsSec = ~~(totalAsMSec / 1e3), totalSec = ~~(totalAsSec * (totalAsSec / Math.abs(totalAsSec)));
  if (totalSec < EPOCH_HOUR) return FRESHNESS_1;
  if (totalSec < 6 * EPOCH_HOUR) return FRESHNESS_2;
  if (totalSec < 3 * EPOCH_DAY) return FRESHNESS_3;
  if (totalSec < 7 * EPOCH_DAY) return FRESHNESS_4; else return FRESHNESS_5;
}

var queues = [];

function waitForRequestAnimationFrame() {
  return new Promise((res => requestAnimationFrame((() => res()))));
}

function delay(num) {
  return new Promise((res => setTimeout((() => res()), num || 5)));
}

function nextTick() {
  return new Promise((res => setTimeout((() => res()), 0)));
}

var waits = [ nextTick, delay, nextTick, delay, delay, nextTick ], waitIdx = 0, pumping = false, startContinuousProcessing = Date.now();

async function pump() {
  if (!pumping) try {
    pumping = true;
    for (;;) {
      const proc = queues.shift();
      if (proc) {
        proc();
        if (Date.now() - startContinuousProcessing > 120) {
          const w = waits[waitIdx];
          waitIdx = (waitIdx + 1) % waits.length;
          await w();
          startContinuousProcessing = Date.now();
        }
      } else break;
    }
  } finally {
    pumping = false;
  }
}

var doEvents = () => new Promise((res => {
  queues.push((() => {
    res();
  }));
  pump();
}));

function compare(x, y) {
  return `${x || ""}`.localeCompare(y, void 0, {
    numeric: true
  });
}

function getTagName(tagName, subtreePrefix, tagInfo2, invert) {
  if (null == tagInfo2) return tagName;
  const prefix = -1 == invert ? "" : "", unpinned = 1 == invert ? "" : "";
  if (tagName in tagInfo2 && tagInfo2[tagName]) if ("key" in tagInfo2[tagName]) return `${prefix}_${subtreePrefix}_-${tagInfo2[tagName].key}__${tagName}`;
  return `${prefix}_${subtreePrefix}_${unpinned}_${tagName}`;
}

function removeIntermediatePath(paths) {
  const passed = [];
  for (const v of paths) {
    const last = passed.pop();
    if (void 0 !== last) if (!(trimTrailingSlash(v.toLowerCase()) + "/").startsWith(trimTrailingSlash(last.toLowerCase()) + "/")) passed.push(last);
    passed.push(v);
  }
  return passed.reverse();
}

function getTagMark(tagInfo2) {
  if (!tagInfo2) return "";
  if ("key" in tagInfo2) if ("mark" in tagInfo2 && "" != tagInfo2.mark) return tagInfo2.mark; else return "📌"; else if ("mark" in tagInfo2 && "" != tagInfo2.mark) return tagInfo2.mark; else return "";
}

function escapeStringToHTML(str) {
  if (!str) return ""; else return str.replace(/[<>&"'`]/g, (match => ({
    "<": "&lt;",
    ">": "&gt;",
    "&": "&amp;",
    '"': "&quot;",
    "'": "&#39;",
    "`": "&#x60;"
  }[match])));
}

var V2FI_IDX_TAG = 0, V2FI_IDX_TAGNAME = 1, V2FI_IDX_TAGDISP = 2, V2FI_IDX_CHILDREN = 3;

function selectCompareMethodTags(settings, tagInfo2) {
  const _tagInfo = tagInfo2, invert = settings.sortTypeTag.contains("_DESC") ? -1 : 1, subTreeChar = {
    [-1]: "􏿿",
    [1]: "_"
  }, sortByName = (a, b) => {
    const isASubTree = "" == a[V2FI_IDX_TAGDISP][0], isBSubTree = "" == b[V2FI_IDX_TAGDISP][0], aName = a[V2FI_IDX_TAGNAME], bName = b[V2FI_IDX_TAGNAME], aPrefix = isASubTree ? subTreeChar[invert] : "", bPrefix = isBSubTree ? subTreeChar[invert] : "";
    return compare(getTagName(aName, aPrefix, settings.useTagInfo ? _tagInfo : void 0, invert), getTagName(bName, bPrefix, settings.useTagInfo ? _tagInfo : void 0, invert)) * invert;
  };
  switch (settings.sortTypeTag) {
   case "ITEMS_ASC":
   case "ITEMS_DESC":
    return (a, b) => {
      const aName = a[V2FI_IDX_TAGNAME], bName = b[V2FI_IDX_TAGNAME], aCount = a[V2FI_IDX_CHILDREN].length - (settings.useTagInfo && aName in _tagInfo && "key" in _tagInfo[aName] ? 1e5 * invert : 0), bCount = b[V2FI_IDX_CHILDREN].length - (settings.useTagInfo && bName in _tagInfo && "key" in _tagInfo[bName] ? 1e5 * invert : 0);
      if (aCount == bCount) return sortByName(a, b); else return (aCount - bCount) * invert;
    };

   case "NAME_ASC":
   case "NAME_DESC":
    return sortByName;

   default:
    console.warn("Compare method (tags) corrupted");
    return (a, b) => {
      const isASubTree = "" == a[V2FI_IDX_TAGDISP][0], isBSubTree = "" == b[V2FI_IDX_TAGDISP][0], aName = a[V2FI_IDX_TAGNAME], bName = b[V2FI_IDX_TAGNAME];
      return compare((isASubTree ? subTreeChar[invert] : "") + aName, (isBSubTree ? subTreeChar[invert] : "") + bName) * invert;
    };
  }
}

function uniqueCaseIntensive(pieces) {
  const delMap = new Set, ret = [];
  for (const piece of pieces) if (!delMap.has(piece.toLowerCase())) {
    ret.push(piece);
    delMap.add(piece.toLowerCase());
  }
  return ret;
}

function _sorterTagLength(a, b, invert) {
  const diff = a.split("/").length - b.split("/").length;
  if (0 != diff) return diff * (invert ? -1 : 1); else return (a.length - b.length) * (invert ? -1 : 1);
}

function getExtraTags(tags, trail, reduceNestedParent) {
  let tagsLeft = uniqueCaseIntensive(tags), removeTrailItems = [];
  if (reduceNestedParent) removeTrailItems = trail.sort(((a, b) => _sorterTagLength(a, b, true))); else removeTrailItems = removeIntermediatePath(trail);
  for (const t of removeTrailItems) {
    const trimLength = t.endsWith("/") ? t.length : t.length;
    if (reduceNestedParent) tagsLeft = tagsLeft.map((e => (e + "/").toLowerCase().startsWith(t.toLowerCase()) ? e.substring(trimLength) : e)); else {
      const f = tagsLeft.findIndex((e => (e + "/").toLowerCase().startsWith(t.toLowerCase())));
      if (-1 !== f) tagsLeft[f] = tagsLeft[f].substring(trimLength);
    }
  }
  return tagsLeft.filter((e => "" != e.trim()));
}

function trimTrailingSlash(src) {
  return trimSlash(src, true, false);
}

function joinPartialPath(path) {
  return path.reduce(((p, c) => c.endsWith("/") && p.length > 0 ? [ c + p[0], ...p.slice(1) ] : [ c, ...p ]), []);
}

function pathMatch(haystackLC, needleLC) {
  if (haystackLC == needleLC) return true;
  if ("/" == needleLC[needleLC.length - 1]) if (0 === (haystackLC + "/").indexOf(needleLC)) return true;
  return false;
}

function parseTagName(thisName, _tagInfo) {
  let tagNameDisp = [ "" ];
  const names = thisName.split("/").filter((e => "" != e.trim()));
  let inSubTree = false, tagName = "";
  if (names.length > 1) {
    tagName = `${names[names.length - 1]}`;
    inSubTree = true;
  } else tagName = thisName;
  if (tagName.endsWith("/")) tagName = tagName.substring(0, tagName.length - 1);
  const tagMark = getTagMark(tagName in _tagInfo ? _tagInfo[tagName] : void 0);
  tagNameDisp = [ `${tagMark}${renderSpecialTag(tagName)}` ];
  if (inSubTree) tagNameDisp = [ `${tagMark}`, `${renderSpecialTag(tagName)}` ];
  return [ tagName, tagNameDisp ];
}

function parseAllForwardReference(metaCache, filename, passed) {
  var _a;
  return unique(Object.keys(null != (_a = null == metaCache ? void 0 : metaCache[filename]) ? _a : {}).filter((e => !passed.contains(e))));
}

function parseAllReverseReference(metaCache, filename, passed) {
  return unique(Object.entries(metaCache).filter((([, links]) => filename in links)).map((([name]) => name)).filter((e => !passed.contains(e))));
}

function parseAllReference(metaCache, filename, conf) {
  var _a, _b;
  let linked = [ ...!(null == (_a = null == conf ? void 0 : conf.outgoing) ? void 0 : _a.enabled) ? [] : parseAllForwardReference(metaCache, filename, []), ...!(null == (_b = null == conf ? void 0 : conf.incoming) ? void 0 : _b.enabled) ? [] : parseAllReverseReference(metaCache, filename, []) ];
  if (0 != linked.length) linked = unique([ filename, ...linked ]);
  return linked;
}

function fileCacheToCompare(cache) {
  if (!cache) return ""; else return {
    l: cache.links,
    t: cache.tags
  };
}

var allViewItemsMap = new Map;

allViewItemsByLink.subscribe((e => {
  updateItemsLinkMap(e);
}));

function updateItemsLinkMap(e) {
  allViewItemsMap.clear();
  if (e) e.forEach((item => allViewItemsMap.set(item.path, item)));
}

function getViewItemFromPath(path) {
  return allViewItemsMap.get(path);
}

function getAllLinksRecursive(item, trail) {
  const leftLinks = item.links.filter((e => !trail.contains(e))), allChildLinks = leftLinks.flatMap((itemName => {
    const item2 = getViewItemFromPath(itemName);
    if (!item2) return []; else return getAllLinksRecursive(item2, [ ...trail, itemName ]);
  }));
  return unique([ ...leftLinks, ...allChildLinks ]);
}

function isSameViewItems(a, b) {
  if (a === b) return true;
  if (a.length != b.length) return false;
  for (const i in a) {
    if (a[i].length != b[i].length) return false;
    if (!_isSameViewItem(a[i], b[i])) return false;
  }
  return true;
}

function _isSameViewItem(a, b) {
  if (!a || !b) return false;
  if (a === b) return true;
  if (a.length != b.length) return false;
  for (const j in a) {
    if (a[j] === b[j]) return true;
    for (const k in a[j]) if (!isSameObj(a[j][k], b[j][k])) return false;
  }
  return true;
}

function isSameV2FolderItem(a, b) {
  if (a === b) return true;
  if (a.length != b.length) return false;
  for (const i in a) {
    if (a[i].length != b[i].length) return false;
    if (a[i] === b[i]) return true;
    for (const j in a[i]) {
      if (a[i][j][V2FI_IDX_TAG] !== b[i][j][V2FI_IDX_TAG]) return false;
      if (a[i][j][V2FI_IDX_TAGNAME] !== b[i][j][V2FI_IDX_TAGNAME]) return false;
      if (!isSameObj(a[i][j][V2FI_IDX_TAGDISP], b[i][j][V2FI_IDX_TAGDISP])) return false;
      if (!_isSameViewItem(a[i][j][V2FI_IDX_CHILDREN], b[i][j][V2FI_IDX_CHILDREN])) return false;
    }
  }
  return true;
}

function isSameObj(a, b) {
  if (a === b) return true;
  if ("string" == typeof a || "number" == typeof a) return a == b;
  if (a.length != b.length) return false;
  const len = a.length;
  for (let i = 0; i < len; i++) if (!isSameObj(a[i], b[i])) return false;
  return true;
}

var waitingProcess = new Map, runningProcess = new Set;

async function scheduleOnceIfDuplicated(key, proc) {
  if (!runningProcess.has(key)) try {
    runningProcess.add(key);
    await delay(3);
    if (waitingProcess.has(key)) {
      const nextProc = waitingProcess.get(key);
      waitingProcess.delete(key);
      runningProcess.delete(key);
      return scheduleOnceIfDuplicated(key, nextProc);
    } else await proc();
  } finally {
    runningProcess.delete(key);
  } else waitingProcess.set(key, proc);
}

function isSameAny(a, b) {
  if (typeof a != typeof b) return false;
  switch (typeof a) {
   case "string":
   case "number":
   case "bigint":
   case "boolean":
   case "symbol":
   case "function":
   case "undefined":
    return a == b;

   case "object":
    if (a === b) return true;
    if (a instanceof Map || a instanceof Set) {
      if (a.size != b.size) return false;
      const v = [ ...a ], w = [ ...b ];
      for (let i = 0; i < v.length; i++) if (v[i] != w[i]) return false;
      return true;
    }
    if (Array.isArray(a)) {
      for (let i = 0; i < a.length; i++) if (!isSameAny(a[i], b[i])) return false;
      return true;
    }
    {
      const x = Object.values(a), y = Object.values(b);
      if (x.length != y.length) return false;
      for (let i = 0; i < x.length; i++) if (!isSameAny(x[i], y[i])) return false;
      return true;
    }

   default:
    return false;
  }
}

var import_obsidian2 = require("obsidian");

if ("undefined" != typeof window) (window.__svelte || (window.__svelte = {
  v: new Set
})).v.add(PUBLIC_VERSION);

var import_obsidian = require("obsidian");

function add_css(target) {
  append_styles(target, "svelte-1qfikme", ".markdownBody.svelte-1qfikme{user-select:text;-webkit-user-select:text}");
}

function create_fragment(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "markdownBody svelte-1qfikme");
      set_style(div, "min-height", "1em");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      ctx[4](div);
    },
    p: noop,
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(div);
      ctx[4](null);
    }
  };
}

function instance($$self, $$props, $$invalidate) {
  let el, {file = {
    path: ""
  }} = $$props, {observer} = $$props, renderedContent = "";
  function onAppearing(_) {
    if (file.content && el && renderedContent != file.content) {
      import_obsidian.MarkdownRenderer.renderMarkdown(file.content, el, file.path, null);
      $$invalidate(3, renderedContent = file.content);
    }
  }
  onMount((() => {
    observer.observe(el);
    el.addEventListener("appearing", onAppearing);
  }));
  onDestroy((() => {
    observer.unobserve(el);
    el.removeEventListener("appearing", onAppearing);
  }));
  $$self.$$set = $$props2 => {
    if ("file" in $$props2) $$invalidate(1, file = $$props2.file);
    if ("observer" in $$props2) $$invalidate(2, observer = $$props2.observer);
  };
  $$self.$$.update = () => {
    if (11 & $$self.$$.dirty) if (renderedContent && file && file.content && el && renderedContent != file.content) {
      $$invalidate(0, el.style.minHeight = `${el.clientHeight}px`, el);
      $$invalidate(0, el.innerHTML = "", el);
      import_obsidian.MarkdownRenderer.renderMarkdown(file.content, el, file.path, null);
      $$invalidate(3, renderedContent = file.content);
      $$invalidate(0, el.style.minHeight = "20px", el);
    }
  };
  return [ el, file, observer, renderedContent, function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"]((() => {
      el = $$value;
      $$invalidate(0, el), $$invalidate(3, renderedContent), $$invalidate(1, file);
    }));
  } ];
}

var ScrollViewMarkdownComponent = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance, create_fragment, safe_not_equal, {
      file: 1,
      observer: 2
    }, add_css);
  }
}, ScrollViewMarkdownComponent_default = ScrollViewMarkdownComponent;

function add_css2(target) {
  append_styles(target, "svelte-s1mg0b", ".header.svelte-s1mg0b{background-color:var(--background-secondary-alt);position:sticky;top:0;color:var(--text-normal);margin-bottom:8px}.file.svelte-s1mg0b{cursor:pointer}.path.svelte-s1mg0b{font-size:75%}hr.svelte-s1mg0b{margin:8px auto}");
}

function get_each_context(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[11] = list[i];
  return child_ctx;
}

function create_each_block(ctx) {
  let div1, div0, span0, t0, t1, span1, t2, t3, t4, t5, scrollviewmarkdown, t6, hr, t7, current, mounted, dispose, t0_value = ctx[11].title + "", t3_value = ctx[11].path + "";
  scrollviewmarkdown = new ScrollViewMarkdownComponent_default({
    props: {
      file: ctx[11],
      observer: ctx[1]
    }
  });
  function click_handler(...args) {
    return ctx[8](ctx[11], ...args);
  }
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      span0 = element("span");
      t0 = text(t0_value);
      t1 = space();
      span1 = element("span");
      t2 = text("(");
      t3 = text(t3_value);
      t4 = text(")");
      t5 = space();
      create_component(scrollviewmarkdown.$$.fragment);
      t6 = space();
      hr = element("hr");
      t7 = space();
      attr(span1, "class", "path svelte-s1mg0b");
      attr(div0, "class", "header svelte-s1mg0b");
      attr(hr, "class", "svelte-s1mg0b");
      attr(div1, "class", "file svelte-s1mg0b");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, span0);
      append(span0, t0);
      append(div0, t1);
      append(div0, span1);
      append(span1, t2);
      append(span1, t3);
      append(span1, t4);
      append(div1, t5);
      mount_component(scrollviewmarkdown, div1, null);
      append(div1, t6);
      append(div1, hr);
      append(div1, t7);
      ctx[9](div1);
      current = true;
      if (!mounted) {
        dispose = listen(div1, "click", click_handler);
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if ((!current || 8 & dirty) && t0_value !== (t0_value = ctx[11].title + "")) set_data(t0, t0_value);
      if ((!current || 8 & dirty) && t3_value !== (t3_value = ctx[11].path + "")) set_data(t3, t3_value);
      const scrollviewmarkdown_changes = {};
      if (8 & dirty) scrollviewmarkdown_changes.file = ctx[11];
      if (2 & dirty) scrollviewmarkdown_changes.observer = ctx[1];
      scrollviewmarkdown.$set(scrollviewmarkdown_changes);
    },
    i(local) {
      if (!current) {
        transition_in(scrollviewmarkdown.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(scrollviewmarkdown.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(div1);
      destroy_component(scrollviewmarkdown);
      ctx[9](null);
      mounted = false;
      dispose();
    }
  };
}

function create_fragment2(ctx) {
  let div1, div0, t0, t1, t2, hr, t3, current, each_value = ensure_array_like(ctx[3]), each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
  const out = i => transition_out(each_blocks[i], 1, 1, (() => {
    each_blocks[i] = null;
  }));
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      t0 = text("Files with ");
      t1 = text(ctx[2]);
      t2 = space();
      hr = element("hr");
      t3 = space();
      for (let i = 0; i < each_blocks.length; i += 1) each_blocks[i].c();
      attr(div0, "class", "header svelte-s1mg0b");
      attr(hr, "class", "svelte-s1mg0b");
      attr(div1, "class", "x");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, t0);
      append(div0, t1);
      append(div1, t2);
      append(div1, hr);
      append(div1, t3);
      for (let i = 0; i < each_blocks.length; i += 1) if (each_blocks[i]) each_blocks[i].m(div1, null);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (!current || 4 & dirty) set_data(t1, ctx2[2]);
      if (27 & dirty) {
        each_value = ensure_array_like(ctx2[3]);
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div1, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) out(i);
        check_outros();
      }
    },
    i(local) {
      if (!current) {
        for (let i = 0; i < each_value.length; i += 1) transition_in(each_blocks[i]);
        current = true;
      }
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) transition_out(each_blocks[i]);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(div1);
      destroy_each(each_blocks, detaching);
    }
  };
}

function instance2($$self, $$props, $$invalidate) {
  let files, tagPath, scrollEl, observer, {store = writable({
    files: [],
    title: "",
    tagPath: ""
  })} = $$props, {openfile} = $$props, state = {
    files: [],
    title: "",
    tagPath: ""
  };
  function handleOpenFile(e, file) {
    openfile(file.path, false);
    e.preventDefault();
  }
  const onAppearing = new CustomEvent("appearing", {
    detail: {}
  });
  onMount((() => {
    $$invalidate(1, observer = new IntersectionObserver((entries => {
      for (const entry of entries) if (entry.isIntersecting) entry.target.dispatchEvent(onAppearing);
    }), {
      root: scrollEl,
      rootMargin: "10px",
      threshold: 0
    }));
  }));
  onDestroy((() => {
    observer.disconnect();
  }));
  $$self.$$set = $$props2 => {
    if ("store" in $$props2) $$invalidate(5, store = $$props2.store);
    if ("openfile" in $$props2) $$invalidate(6, openfile = $$props2.openfile);
  };
  $$self.$$.update = () => {
    if (32 & $$self.$$.dirty) store.subscribe((_state => {
      $$invalidate(7, state = {
        ..._state
      });
      return () => {};
    }));
    if (128 & $$self.$$.dirty) $$invalidate(3, files = state.files);
    if (128 & $$self.$$.dirty) $$invalidate(2, tagPath = state.tagPath.split(", ").map((e => "#" + trimTrailingSlash(e).split("/").map((e2 => renderSpecialTag(e2.trim()))).join("/"))).join(", "));
  };
  return [ scrollEl, observer, tagPath, files, handleOpenFile, store, openfile, state, (file, evt) => handleOpenFile(evt, file), function div1_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"]((() => {
      scrollEl = $$value;
      $$invalidate(0, scrollEl);
    }));
  } ];
}

var ScrollViewComponent = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance2, create_fragment2, safe_not_equal, {
      store: 5,
      openfile: 6
    }, add_css2);
  }
}, ScrollViewComponent_default = ScrollViewComponent, ScrollView = class extends import_obsidian2.ItemView {
  constructor(leaf, plugin) {
    super(leaf);
    this.state = {
      files: [],
      title: "",
      tagPath: ""
    };
    this.plugin = plugin;
    this.store = writable({
      files: [],
      title: "",
      tagPath: ""
    });
  }
  getIcon() {
    return "sheets-in-box";
  }
  getViewType() {
    return VIEW_TYPE_SCROLL;
  }
  getDisplayText() {
    return this.state.tagPath || "Tags scroll";
  }
  async setFile(filenames) {
    this.state = {
      ...this.state,
      files: filenames
    };
    await this.updateView();
  }
  async setState(state, result) {
    this.state = {
      ...state
    };
    this.title = state.title;
    await this.updateView();
  }
  getState() {
    return this.state;
  }
  isFileOpened(path) {
    return this.state.files.some((e => e.path == path));
  }
  getScrollViewState() {
    return this.state;
  }
  async updateView() {
    const items = [];
    for (const item of this.state.files) if (item.content) items.push(item); else {
      const f = this.app.vault.getAbstractFileByPath(item.path);
      if (null == f || !(f instanceof import_obsidian2.TFile)) {
        console.log(`File not found:${item.path}`);
        items.push(item);
        continue;
      }
      const title = this.plugin.getFileTitle(f), w = await this.app.vault.read(f);
      await doEvents();
      item.content = w;
      item.title = title;
      items.push(item);
    }
    this.state = {
      ...this.state,
      files: [ ...items ]
    };
    this.store.set(this.state);
  }
  async onOpen() {
    this.component = new ScrollViewComponent_default({
      target: this.contentEl,
      props: {
        store: this.store,
        openfile: this.plugin.focusFile
      }
    });
  }
  async onClose() {
    this.component.$destroy();
  }
}, import_obsidian6 = require("obsidian");

function performSortExactFirst(_items, children2, leftOverItems) {
  const childrenPathsArr = children2.map((e => e[V2FI_IDX_CHILDREN].map((ee => ee.path)))).flat(), childrenPaths = new Set(childrenPathsArr), exactHerePaths = new Set(_items.map((e => e.path)));
  childrenPaths.forEach((path => exactHerePaths.delete(path)));
  return [ ...[ ...leftOverItems ].sort(((a, b) => (exactHerePaths.has(a.path) ? -1 : 0) + (exactHerePaths.has(b.path) ? 1 : 0))) ];
}

function delay2() {
  return new Promise((res => setTimeout((() => res()), 5)));
}

function nextTick2() {
  return new Promise((res => setTimeout((() => res()), 0)));
}

var delays = [ nextTick2, delay2, nextTick2, waitForRequestAnimationFrame ], delayIdx = 0;

async function collectChildren(previousTrail, tags, _tagInfo, _items) {
  const previousTrailLC = previousTrail.toLowerCase(), children2 = [], tagPerItem = new Map, lowercaseMap = new Map;
  for (const item of _items) item.tags.forEach((itemTag => {
    var _a;
    const tagLc = null != (_a = lowercaseMap.get(itemTag)) ? _a : lowercaseMap.set(itemTag, itemTag.toLowerCase()).get(itemTag);
    if (!tagPerItem.has(tagLc)) tagPerItem.set(tagLc, []);
    tagPerItem.get(tagLc).push(item);
  }));
  for (const tag of tags) {
    const tagLC = tag.toLowerCase(), tagNestedLC = trimPrefix(tagLC, previousTrailLC), items = [];
    for (const [itemTag, tempItems] of tagPerItem) if (pathMatch(itemTag, tagLC)) items.push(...tempItems); else if (pathMatch(itemTag, tagNestedLC)) items.push(...tempItems);
    children2.push([ tag, ...parseTagName(tag, _tagInfo), [ ...new Set(items) ] ]);
    delayIdx++;
    delayIdx %= 4;
    await delays[delayIdx]();
  }
  return children2;
}

async function collectTreeChildren({key, expandLimit, depth, tags, trailLower, _setting, isMainTree, isSuppressibleLevel, viewType, previousTrail, _tagInfo, _items, linkedItems, isRoot, sortFunc}) {
  let suppressLevels = [], children2 = [];
  if (expandLimit && depth >= expandLimit) {
    children2 = [];
    suppressLevels = getExtraTags(tags, trailLower, _setting.reduceNestedParent);
  } else if (!isMainTree) children2 = []; else if (isSuppressibleLevel) {
    children2 = [];
    suppressLevels = getExtraTags(tags, trailLower, _setting.reduceNestedParent);
  } else {
    let wChildren = [];
    if ("tags" == viewType) wChildren = await collectChildren(previousTrail, tags, _tagInfo, _items); else if ("links" == viewType) wChildren = tags.map((tag => {
      var _a;
      const selfInfo = getViewItemFromPath(tag), dispName = !selfInfo ? tag : selfInfo.displayName;
      return [ tag, dispName, [ dispName ], null != (_a = linkedItems.get(tag)) ? _a : [] ];
    }));
    if ("tags" == viewType) {
      if (_setting.mergeRedundantCombination) {
        const out = [], isShown = new Set;
        for (const [tag, tagName, tagsDisp, items] of wChildren) {
          const list = [];
          for (const v of items) if (!isShown.has(v.path)) {
            list.push(v);
            isShown.add(v.path);
          }
          if (0 != list.length) out.push([ tag, tagName, tagsDisp, list ]);
        }
        wChildren = out;
      }
      if (isMainTree && isRoot) {
        const archiveTags = _setting.archiveTags.toLowerCase().replace(/[\n ]/g, "").split(",");
        wChildren = wChildren.map((e => archiveTags.some((aTag => `${aTag}//`.startsWith(e[V2FI_IDX_TAG].toLowerCase() + "/"))) ? e : [ e[V2FI_IDX_TAG], e[V2FI_IDX_TAGNAME], e[V2FI_IDX_TAGDISP], e[V2FI_IDX_CHILDREN].filter((items => !items.tags.some((e2 => archiveTags.contains(e2.toLowerCase()))))) ])).filter((child => 0 != child[V2FI_IDX_CHILDREN].length));
      }
    }
    wChildren = wChildren.sort(sortFunc);
    children2 = wChildren;
  }
  return {
    suppressLevels,
    children: children2
  };
}

var get_default_slot_changes = dirty => ({
  isVisible: 1 & dirty
}), get_default_slot_context = ctx => ({
  isVisible: ctx[0]
});

function create_fragment3(ctx) {
  let div, current;
  const default_slot_template = ctx[5].default, default_slot = create_slot(default_slot_template, ctx, ctx[4], get_default_slot_context);
  return {
    c() {
      div = element("div");
      if (default_slot) default_slot.c();
      attr(div, "class", ctx[1]);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if (default_slot) default_slot.m(div, null);
      ctx[6](div);
      current = true;
    },
    p(ctx2, [dirty]) {
      if (default_slot) if (default_slot.p && (!current || 17 & dirty)) update_slot_base(default_slot, default_slot_template, ctx2, ctx2[4], !current ? get_all_dirty_from_scope(ctx2[4]) : get_slot_changes(default_slot_template, ctx2[4], dirty, get_default_slot_changes), get_default_slot_context);
      if (!current || 2 & dirty) attr(div, "class", ctx2[1]);
    },
    i(local) {
      if (!current) {
        transition_in(default_slot, local);
        current = true;
      }
    },
    o(local) {
      transition_out(default_slot, local);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(div);
      if (default_slot) default_slot.d(detaching);
      ctx[6](null);
    }
  };
}

function instance3($$self, $$props, $$invalidate) {
  let {$$slots: slots = {}, $$scope} = $$props, {cssClass = ""} = $$props, {isVisible = false} = $$props, hidingScheduled = false;
  const {observe, unobserve} = getContext("observer");
  function setIsVisible(visibility) {
    if (isVisible != visibility) if (visibility) $$invalidate(0, isVisible = visibility);
    hidingScheduled = !visibility;
  }
  onMount((() => {
    performHide.subscribe((() => {
      if (hidingScheduled) {
        $$invalidate(0, isVisible = false);
        hidingScheduled = false;
      }
    }));
  }));
  onDestroy((() => {
    if (_el) unobserve(_el);
  }));
  let _el, el;
  $$self.$$set = $$props2 => {
    if ("cssClass" in $$props2) $$invalidate(1, cssClass = $$props2.cssClass);
    if ("isVisible" in $$props2) $$invalidate(0, isVisible = $$props2.isVisible);
    if ("$$scope" in $$props2) $$invalidate(4, $$scope = $$props2.$$scope);
  };
  $$self.$$.update = () => {
    if (12 & $$self.$$.dirty) if (_el != el) {
      if (_el) unobserve(_el);
      $$invalidate(3, _el = el);
      if (el) observe(el, setIsVisible);
    }
  };
  return [ isVisible, cssClass, el, _el, $$scope, slots, function div_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"]((() => {
      el = $$value;
      $$invalidate(2, el);
    }));
  } ];
}

var OnDemandRender = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance3, create_fragment3, safe_not_equal, {
      cssClass: 1,
      isVisible: 0
    });
  }
}, OnDemandRender_default = OnDemandRender;

function create_if_block(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      attr(div, "class", "tf-taglist");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      div.innerHTML = ctx[5];
    },
    p(ctx2, dirty) {
      if (32 & dirty) div.innerHTML = ctx2[5];
    },
    d(detaching) {
      if (detaching) detach(div);
    }
  };
}

function create_default_slot(ctx) {
  let div1, div0, t0, t1, div1_data_path_value, mounted, dispose, t0_value = (ctx[20] ? ctx[0].displayName : "") + "", if_block = ctx[20] && create_if_block(ctx);
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      t0 = text(t0_value);
      t1 = space();
      if (if_block) if_block.c();
      attr(div0, "class", "tree-item-inner nav-file-title-content lsl-f");
      attr(div1, "class", "tree-item-self is-clickable nav-file-title");
      attr(div1, "draggable", ctx[6]);
      attr(div1, "data-path", div1_data_path_value = ctx[0].path);
      toggle_class(div1, "is-active", ctx[7]);
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, t0);
      append(div1, t1);
      if (if_block) if_block.m(div1, null);
      if (!mounted) {
        dispose = [ listen(div1, "dragstart", ctx[9]), listen(div1, "click", ctx[14]), listen(div1, "mouseover", ctx[15]), listen(div1, "focus", focus_handler), listen(div1, "contextmenu", ctx[16]) ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (1048577 & dirty && t0_value !== (t0_value = (ctx2[20] ? ctx2[0].displayName : "") + "")) set_data(t0, t0_value);
      if (ctx2[20]) if (if_block) if_block.p(ctx2, dirty); else {
        if_block = create_if_block(ctx2);
        if_block.c();
        if_block.m(div1, null);
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
      if (64 & dirty) attr(div1, "draggable", ctx2[6]);
      if (1 & dirty && div1_data_path_value !== (div1_data_path_value = ctx2[0].path)) attr(div1, "data-path", div1_data_path_value);
      if (128 & dirty) toggle_class(div1, "is-active", ctx2[7]);
    },
    d(detaching) {
      if (detaching) detach(div1);
      if (if_block) if_block.d();
      mounted = false;
      run_all(dispose);
    }
  };
}

function create_fragment4(ctx) {
  let ondemandrender, updating_isVisible, current;
  function ondemandrender_isVisible_binding(value) {
    ctx[17](value);
  }
  let ondemandrender_props = {
    cssClass: "tree-item nav-file",
    $$slots: {
      default: [ create_default_slot, ({isVisible}) => ({
        20: isVisible
      }), ({isVisible}) => isVisible ? 1048576 : 0 ]
    },
    $$scope: {
      ctx
    }
  };
  if (void 0 !== ctx[4]) ondemandrender_props.isVisible = ctx[4];
  ondemandrender = new OnDemandRender_default({
    props: ondemandrender_props
  });
  binding_callbacks.push((() => bind(ondemandrender, "isVisible", ondemandrender_isVisible_binding)));
  return {
    c() {
      create_component(ondemandrender.$$.fragment);
    },
    m(target, anchor) {
      mount_component(ondemandrender, target, anchor);
      current = true;
    },
    p(ctx2, [dirty]) {
      const ondemandrender_changes = {};
      if (3145967 & dirty) ondemandrender_changes.$$scope = {
        dirty,
        ctx: ctx2
      };
      if (!updating_isVisible && 16 & dirty) {
        updating_isVisible = true;
        ondemandrender_changes.isVisible = ctx2[4];
        add_flush_callback((() => updating_isVisible = false));
      }
      ondemandrender.$set(ondemandrender_changes);
    },
    i(local) {
      if (!current) {
        transition_in(ondemandrender.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(ondemandrender.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(ondemandrender, detaching);
    }
  };
}

var focus_handler = () => {};

function instance4($$self, $$props, $$invalidate) {
  let isActive, draggable, $tagFolderSetting;
  component_subscribe($$self, tagFolderSetting, ($$value => $$invalidate(18, $tagFolderSetting = $$value)));
  let {viewType = "tags"} = $$props, {item} = $$props, {trail} = $$props, {openFile} = $$props, {showMenu} = $$props, {hoverPreview} = $$props;
  function handleMouseover(e, path) {
    hoverPreview(e, path);
  }
  let _currentActiveFilePath = "", _setting = $tagFolderSetting;
  currentFile.subscribe((path => {
    $$invalidate(12, _currentActiveFilePath = path);
  }));
  tagFolderSetting.subscribe((setting => {
    $$invalidate(13, _setting = setting);
  }));
  let extraTagsHtml = "", isItemVisible = false;
  const dm = app.dragManager;
  $$self.$$set = $$props2 => {
    if ("viewType" in $$props2) $$invalidate(10, viewType = $$props2.viewType);
    if ("item" in $$props2) $$invalidate(0, item = $$props2.item);
    if ("trail" in $$props2) $$invalidate(1, trail = $$props2.trail);
    if ("openFile" in $$props2) $$invalidate(2, openFile = $$props2.openFile);
    if ("showMenu" in $$props2) $$invalidate(3, showMenu = $$props2.showMenu);
    if ("hoverPreview" in $$props2) $$invalidate(11, hoverPreview = $$props2.hoverPreview);
  };
  $$self.$$.update = () => {
    if (4097 & $$self.$$.dirty) $$invalidate(7, isActive = item.path == _currentActiveFilePath);
    if (8211 & $$self.$$.dirty) if (isItemVisible) {
      const tagsLeft = uniqueCaseIntensive(getExtraTags(item.tags, [ ...trail ], _setting.reduceNestedParent).map((e => trimSlash(e, false, true))).filter((e => "" != e)));
      $$invalidate(5, extraTagsHtml = `${tagsLeft.map((e => `<span class="tf-tag">${escapeStringToHTML(renderSpecialTag(e))}</span>`)).join("")}`);
    }
    if (8192 & $$self.$$.dirty) $$invalidate(6, draggable = !_setting.disableDragging);
  };
  return [ item, trail, openFile, showMenu, isItemVisible, extraTagsHtml, draggable, isActive, handleMouseover, function dragStartFile(args) {
    if (!draggable) return;
    const file = app.vault.getAbstractFileByPath(item.path), param = dm.dragFile(args, file);
    if (param) return dm.onDragStart(args, param);
  }, viewType, hoverPreview, _currentActiveFilePath, _setting, evt => openFile(item.path, evt.metaKey || evt.ctrlKey), e => {
    handleMouseover(e, item.path);
  }, evt => showMenu(evt, trail, void 0, [ item ]), function ondemandrender_isVisible_binding(value) {
    isItemVisible = value;
    $$invalidate(4, isItemVisible);
  } ];
}

var V2TreeItemComponent = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance4, create_fragment4, safe_not_equal, {
      viewType: 10,
      item: 0,
      trail: 1,
      openFile: 2,
      showMenu: 3,
      hoverPreview: 11
    });
  }
}, V2TreeItemComponent_default = V2TreeItemComponent;

function get_each_context2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}

function get_each_context_1(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[71] = list[i];
  return child_ctx;
}

function get_each_context_2(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[13] = list[i];
  return child_ctx;
}

function get_each_context_3(ctx, list, i) {
  const child_ctx = ctx.slice();
  child_ctx[76] = list[i][0];
  child_ctx[0] = list[i][1];
  child_ctx[1] = list[i][2];
  child_ctx[77] = list[i][3];
  return child_ctx;
}

function create_else_block(ctx) {
  let ondemandrender, updating_isVisible, current;
  function ondemandrender_isVisible_binding(value) {
    ctx[53](value);
  }
  let ondemandrender_props = {
    cssClass: `tree-item-self${!ctx[4] ? " is-clickable mod-collapsible" : ""} nav-folder-title tag-folder-title${ctx[25] ? " is-active" : ""}`,
    $$slots: {
      default: [ create_default_slot2 ]
    },
    $$scope: {
      ctx
    }
  };
  if (void 0 !== ctx[17]) ondemandrender_props.isVisible = ctx[17];
  ondemandrender = new OnDemandRender_default({
    props: ondemandrender_props
  });
  binding_callbacks.push((() => bind(ondemandrender, "isVisible", ondemandrender_isVisible_binding)));
  return {
    c() {
      create_component(ondemandrender.$$.fragment);
    },
    m(target, anchor) {
      mount_component(ondemandrender, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const ondemandrender_changes = {};
      if (33554448 & dirty[0]) ondemandrender_changes.cssClass = `tree-item-self${!ctx2[4] ? " is-clickable mod-collapsible" : ""} nav-folder-title tag-folder-title${ctx2[25] ? " is-active" : ""}`;
      if (96616584 & dirty[0] | 262144 & dirty[2]) ondemandrender_changes.$$scope = {
        dirty,
        ctx: ctx2
      };
      if (!updating_isVisible && 131072 & dirty[0]) {
        updating_isVisible = true;
        ondemandrender_changes.isVisible = ctx2[17];
        add_flush_callback((() => updating_isVisible = false));
      }
      ondemandrender.$set(ondemandrender_changes);
    },
    i(local) {
      if (!current) {
        transition_in(ondemandrender.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(ondemandrender.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(ondemandrender, detaching);
    }
  };
}

function create_if_block_1(ctx) {
  let if_block_anchor, if_block = ctx[4] && create_if_block_2(ctx);
  return {
    c() {
      if (if_block) if_block.c();
      if_block_anchor = empty();
    },
    m(target, anchor) {
      if (if_block) if_block.m(target, anchor);
      insert(target, if_block_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (ctx2[4]) if (if_block) if_block.p(ctx2, dirty); else {
        if_block = create_if_block_2(ctx2);
        if_block.c();
        if_block.m(if_block_anchor.parentNode, if_block_anchor);
      } else if (if_block) {
        if_block.d(1);
        if_block = null;
      }
    },
    i: noop,
    o: noop,
    d(detaching) {
      if (detaching) detach(if_block_anchor);
      if (if_block) if_block.d(detaching);
    }
  };
}

function create_else_block_2(ctx) {
  let svg;
  return {
    c() {
      svg = svg_element("svg");
      attr(svg, "class", "svg-icon");
    },
    m(target, anchor) {
      insert(target, svg, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) detach(svg);
    }
  };
}

function create_if_block_4(ctx) {
  let html_tag, html_anchor;
  return {
    c() {
      html_tag = new HtmlTag(false);
      html_anchor = empty();
      html_tag.a = html_anchor;
    },
    m(target, anchor) {
      html_tag.m(ctx[7], target, anchor);
      insert(target, html_anchor, anchor);
    },
    p(ctx2, dirty) {
      if (128 & dirty[0]) html_tag.p(ctx2[7]);
    },
    d(detaching) {
      if (detaching) {
        detach(html_anchor);
        html_tag.d();
      }
    }
  };
}

function create_else_block_1(ctx) {
  let div;
  return {
    c() {
      div = element("div");
      div.textContent = "...";
      attr(div, "class", "tagfolder-titletagname");
    },
    m(target, anchor) {
      insert(target, div, anchor);
    },
    p: noop,
    d(detaching) {
      if (detaching) detach(div);
    }
  };
}

function create_if_block_3(ctx) {
  let div, mounted, dispose;
  return {
    c() {
      div = element("div");
      attr(div, "class", "tagfolder-titletagname");
      attr(div, "draggable", ctx[22]);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      div.innerHTML = ctx[24];
      if (!mounted) {
        dispose = listen(div, "dragstart", ctx[30]);
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (16777216 & dirty[0]) div.innerHTML = ctx2[24];
      if (4194304 & dirty[0]) attr(div, "draggable", ctx2[22]);
    },
    d(detaching) {
      if (detaching) detach(div);
      mounted = false;
      dispose();
    }
  };
}

function create_default_slot2(ctx) {
  let div0, t0, div2, t1, div1, span, t2, mounted, dispose;
  function select_block_type_1(ctx2, dirty) {
    if (ctx2[17]) return create_if_block_4; else return create_else_block_2;
  }
  let current_block_type = select_block_type_1(ctx), if_block0 = current_block_type(ctx);
  function select_block_type_2(ctx2, dirty) {
    if (ctx2[17]) return create_if_block_3; else return create_else_block_1;
  }
  let current_block_type_1 = select_block_type_2(ctx), if_block1 = current_block_type_1(ctx);
  return {
    c() {
      div0 = element("div");
      if_block0.c();
      t0 = space();
      div2 = element("div");
      if_block1.c();
      t1 = space();
      div1 = element("div");
      span = element("span");
      t2 = text(ctx[23]);
      attr(div0, "class", "tree-item-icon collapse-icon nav-folder-collapse-indicator");
      toggle_class(div0, "is-collapsed", ctx[26]);
      attr(span, "class", "itemscount");
      attr(span, "draggable", ctx[22]);
      attr(div1, "class", "tagfolder-quantity itemscount");
      attr(div2, "class", "tree-item-inner nav-folder-title-content lsl-f");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      if_block0.m(div0, null);
      insert(target, t0, anchor);
      insert(target, div2, anchor);
      if_block1.m(div2, null);
      append(div2, t1);
      append(div2, div1);
      append(div1, span);
      append(span, t2);
      if (!mounted) {
        dispose = [ listen(div0, "click", ctx[28]), listen(span, "dragstart", ctx[29]), listen(div1, "click", ctx[52]), listen(div2, "click", ctx[31]) ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (current_block_type === (current_block_type = select_block_type_1(ctx2)) && if_block0) if_block0.p(ctx2, dirty); else {
        if_block0.d(1);
        if_block0 = current_block_type(ctx2);
        if (if_block0) {
          if_block0.c();
          if_block0.m(div0, null);
        }
      }
      if (67108864 & dirty[0]) toggle_class(div0, "is-collapsed", ctx2[26]);
      if (current_block_type_1 === (current_block_type_1 = select_block_type_2(ctx2)) && if_block1) if_block1.p(ctx2, dirty); else {
        if_block1.d(1);
        if_block1 = current_block_type_1(ctx2);
        if (if_block1) {
          if_block1.c();
          if_block1.m(div2, t1);
        }
      }
      if (8388608 & dirty[0]) set_data(t2, ctx2[23]);
      if (4194304 & dirty[0]) attr(span, "draggable", ctx2[22]);
    },
    d(detaching) {
      if (detaching) {
        detach(div0);
        detach(t0);
        detach(div2);
      }
      if_block0.d();
      if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}

function create_if_block_2(ctx) {
  let div1, div0, t;
  return {
    c() {
      div1 = element("div");
      div0 = element("div");
      t = text(ctx[8]);
      attr(div0, "class", "tree-item-inner nav-folder-title-content");
      attr(div1, "class", "tree-item-self nav-folder-title");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, div0);
      append(div0, t);
    },
    p(ctx2, dirty) {
      if (256 & dirty[0]) set_data(t, ctx2[8]);
    },
    d(detaching) {
      if (detaching) detach(div1);
    }
  };
}

function create_if_block2(ctx) {
  let div, t, current, each_value_2 = ensure_array_like(ctx[18]), each_blocks_1 = [];
  for (let i = 0; i < each_value_2.length; i += 1) each_blocks_1[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
  const out = i => transition_out(each_blocks_1[i], 1, 1, (() => {
    each_blocks_1[i] = null;
  }));
  let each_value = ensure_array_like(ctx[19]), each_blocks = [];
  for (let i = 0; i < each_value.length; i += 1) each_blocks[i] = create_each_block2(get_each_context2(ctx, each_value, i));
  const out_1 = i => transition_out(each_blocks[i], 1, 1, (() => {
    each_blocks[i] = null;
  }));
  return {
    c() {
      div = element("div");
      for (let i = 0; i < each_blocks_1.length; i += 1) each_blocks_1[i].c();
      t = space();
      for (let i = 0; i < each_blocks.length; i += 1) each_blocks[i].c();
      attr(div, "class", "tree-item-children nav-folder-children");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      for (let i = 0; i < each_blocks_1.length; i += 1) if (each_blocks_1[i]) each_blocks_1[i].m(div, null);
      append(div, t);
      for (let i = 0; i < each_blocks.length; i += 1) if (each_blocks[i]) each_blocks[i].m(div, null);
      current = true;
    },
    p(ctx2, dirty) {
      if (368364 & dirty[0]) {
        each_value_2 = ensure_array_like(ctx2[18]);
        let i;
        for (i = 0; i < each_value_2.length; i += 1) {
          const child_ctx = get_each_context_2(ctx2, each_value_2, i);
          if (each_blocks_1[i]) {
            each_blocks_1[i].p(child_ctx, dirty);
            transition_in(each_blocks_1[i], 1);
          } else {
            each_blocks_1[i] = create_each_block_2(child_ctx);
            each_blocks_1[i].c();
            transition_in(each_blocks_1[i], 1);
            each_blocks_1[i].m(div, t);
          }
        }
        group_outros();
        for (i = each_value_2.length; i < each_blocks_1.length; i += 1) out(i);
        check_outros();
      }
      if (593432 & dirty[0]) {
        each_value = ensure_array_like(ctx2[19]);
        let i;
        for (i = 0; i < each_value.length; i += 1) {
          const child_ctx = get_each_context2(ctx2, each_value, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block2(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(div, null);
          }
        }
        group_outros();
        for (i = each_value.length; i < each_blocks.length; i += 1) out_1(i);
        check_outros();
      }
    },
    i(local) {
      if (!current) {
        for (let i = 0; i < each_value_2.length; i += 1) transition_in(each_blocks_1[i]);
        for (let i = 0; i < each_value.length; i += 1) transition_in(each_blocks[i]);
        current = true;
      }
    },
    o(local) {
      each_blocks_1 = each_blocks_1.filter(Boolean);
      for (let i = 0; i < each_blocks_1.length; i += 1) transition_out(each_blocks_1[i]);
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) transition_out(each_blocks[i]);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(div);
      destroy_each(each_blocks_1, detaching);
      destroy_each(each_blocks, detaching);
    }
  };
}

function create_each_block_3(ctx) {
  let v2treefoldercomponent, current;
  v2treefoldercomponent = new V2TreeFolderComponent({
    props: {
      viewType: ctx[2],
      items: ctx[77],
      thisName: ctx[76],
      trail: [ ...ctx[3], ...ctx[16], ctx[76] ],
      folderIcon: ctx[7],
      openFile: ctx[10],
      isRoot: false,
      showMenu: ctx[9],
      isMainTree: ctx[5],
      openScrollView: ctx[12],
      hoverPreview: ctx[11],
      tagName: ctx[0],
      tagNameDisp: ctx[1],
      depth: ctx[15] ? ctx[6] : ctx[6] + 1
    }
  });
  return {
    c() {
      create_component(v2treefoldercomponent.$$.fragment);
    },
    m(target, anchor) {
      mount_component(v2treefoldercomponent, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const v2treefoldercomponent_changes = {};
      if (4 & dirty[0]) v2treefoldercomponent_changes.viewType = ctx2[2];
      if (262144 & dirty[0]) v2treefoldercomponent_changes.items = ctx2[77];
      if (262144 & dirty[0]) v2treefoldercomponent_changes.thisName = ctx2[76];
      if (327688 & dirty[0]) v2treefoldercomponent_changes.trail = [ ...ctx2[3], ...ctx2[16], ctx2[76] ];
      if (128 & dirty[0]) v2treefoldercomponent_changes.folderIcon = ctx2[7];
      if (1024 & dirty[0]) v2treefoldercomponent_changes.openFile = ctx2[10];
      if (512 & dirty[0]) v2treefoldercomponent_changes.showMenu = ctx2[9];
      if (32 & dirty[0]) v2treefoldercomponent_changes.isMainTree = ctx2[5];
      if (4096 & dirty[0]) v2treefoldercomponent_changes.openScrollView = ctx2[12];
      if (2048 & dirty[0]) v2treefoldercomponent_changes.hoverPreview = ctx2[11];
      if (262144 & dirty[0]) v2treefoldercomponent_changes.tagName = ctx2[0];
      if (262144 & dirty[0]) v2treefoldercomponent_changes.tagNameDisp = ctx2[1];
      if (32832 & dirty[0]) v2treefoldercomponent_changes.depth = ctx2[15] ? ctx2[6] : ctx2[6] + 1;
      v2treefoldercomponent.$set(v2treefoldercomponent_changes);
    },
    i(local) {
      if (!current) {
        transition_in(v2treefoldercomponent.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(v2treefoldercomponent.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(v2treefoldercomponent, detaching);
    }
  };
}

function create_each_block_2(ctx) {
  let each_1_anchor, current, each_value_3 = ensure_array_like(ctx[13]), each_blocks = [];
  for (let i = 0; i < each_value_3.length; i += 1) each_blocks[i] = create_each_block_3(get_each_context_3(ctx, each_value_3, i));
  const out = i => transition_out(each_blocks[i], 1, 1, (() => {
    each_blocks[i] = null;
  }));
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) each_blocks[i].c();
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) if (each_blocks[i]) each_blocks[i].m(target, anchor);
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (368364 & dirty[0]) {
        each_value_3 = ensure_array_like(ctx2[13]);
        let i;
        for (i = 0; i < each_value_3.length; i += 1) {
          const child_ctx = get_each_context_3(ctx2, each_value_3, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_3(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value_3.length; i < each_blocks.length; i += 1) out(i);
        check_outros();
      }
    },
    i(local) {
      if (!current) {
        for (let i = 0; i < each_value_3.length; i += 1) transition_in(each_blocks[i]);
        current = true;
      }
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) transition_out(each_blocks[i]);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(each_1_anchor);
      destroy_each(each_blocks, detaching);
    }
  };
}

function create_each_block_1(ctx) {
  let treeitemitemcomponent, current;
  treeitemitemcomponent = new V2TreeItemComponent_default({
    props: {
      item: ctx[71],
      openFile: ctx[10],
      trail: ctx[4] ? [ ...ctx[3] ] : [ ...ctx[3], ...ctx[16] ],
      showMenu: ctx[9],
      hoverPreview: ctx[11]
    }
  });
  return {
    c() {
      create_component(treeitemitemcomponent.$$.fragment);
    },
    m(target, anchor) {
      mount_component(treeitemitemcomponent, target, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      const treeitemitemcomponent_changes = {};
      if (524288 & dirty[0]) treeitemitemcomponent_changes.item = ctx2[71];
      if (1024 & dirty[0]) treeitemitemcomponent_changes.openFile = ctx2[10];
      if (65560 & dirty[0]) treeitemitemcomponent_changes.trail = ctx2[4] ? [ ...ctx2[3] ] : [ ...ctx2[3], ...ctx2[16] ];
      if (512 & dirty[0]) treeitemitemcomponent_changes.showMenu = ctx2[9];
      if (2048 & dirty[0]) treeitemitemcomponent_changes.hoverPreview = ctx2[11];
      treeitemitemcomponent.$set(treeitemitemcomponent_changes);
    },
    i(local) {
      if (!current) {
        transition_in(treeitemitemcomponent.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(treeitemitemcomponent.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      destroy_component(treeitemitemcomponent, detaching);
    }
  };
}

function create_each_block2(ctx) {
  let each_1_anchor, current, each_value_1 = ensure_array_like(ctx[13]), each_blocks = [];
  for (let i = 0; i < each_value_1.length; i += 1) each_blocks[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
  const out = i => transition_out(each_blocks[i], 1, 1, (() => {
    each_blocks[i] = null;
  }));
  return {
    c() {
      for (let i = 0; i < each_blocks.length; i += 1) each_blocks[i].c();
      each_1_anchor = empty();
    },
    m(target, anchor) {
      for (let i = 0; i < each_blocks.length; i += 1) if (each_blocks[i]) each_blocks[i].m(target, anchor);
      insert(target, each_1_anchor, anchor);
      current = true;
    },
    p(ctx2, dirty) {
      if (593432 & dirty[0]) {
        each_value_1 = ensure_array_like(ctx2[13]);
        let i;
        for (i = 0; i < each_value_1.length; i += 1) {
          const child_ctx = get_each_context_1(ctx2, each_value_1, i);
          if (each_blocks[i]) {
            each_blocks[i].p(child_ctx, dirty);
            transition_in(each_blocks[i], 1);
          } else {
            each_blocks[i] = create_each_block_1(child_ctx);
            each_blocks[i].c();
            transition_in(each_blocks[i], 1);
            each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
          }
        }
        group_outros();
        for (i = each_value_1.length; i < each_blocks.length; i += 1) out(i);
        check_outros();
      }
    },
    i(local) {
      if (!current) {
        for (let i = 0; i < each_value_1.length; i += 1) transition_in(each_blocks[i]);
        current = true;
      }
    },
    o(local) {
      each_blocks = each_blocks.filter(Boolean);
      for (let i = 0; i < each_blocks.length; i += 1) transition_out(each_blocks[i]);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(each_1_anchor);
      destroy_each(each_blocks, detaching);
    }
  };
}

function create_fragment5(ctx) {
  let div, current_block_type_index, if_block0, t, div_class_value, current, mounted, dispose;
  const if_block_creators = [ create_if_block_1, create_else_block ], if_blocks = [];
  function select_block_type(ctx2, dirty) {
    if (ctx2[4] || !ctx2[5]) return 0; else return 1;
  }
  current_block_type_index = select_block_type(ctx);
  if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
  let if_block1 = !ctx[26] && create_if_block2(ctx);
  return {
    c() {
      div = element("div");
      if_block0.c();
      t = space();
      if (if_block1) if_block1.c();
      attr(div, "class", div_class_value = `tree-item nav-folder${ctx[26] ? " is-collapsed" : ""}${ctx[4] ? " mod-root" : ""}${ctx[20] ? " updating" : ""}`);
    },
    m(target, anchor) {
      insert(target, div, anchor);
      if_blocks[current_block_type_index].m(div, null);
      append(div, t);
      if (if_block1) if_block1.m(div, null);
      current = true;
      if (!mounted) {
        dispose = [ listen(div, "click", stop_propagation(ctx[28])), listen(div, "contextmenu", stop_propagation(ctx[54])) ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      let previous_block_index = current_block_type_index;
      current_block_type_index = select_block_type(ctx2);
      if (current_block_type_index === previous_block_index) if_blocks[current_block_type_index].p(ctx2, dirty); else {
        group_outros();
        transition_out(if_blocks[previous_block_index], 1, 1, (() => {
          if_blocks[previous_block_index] = null;
        }));
        check_outros();
        if_block0 = if_blocks[current_block_type_index];
        if (!if_block0) {
          if_block0 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx2);
          if_block0.c();
        } else if_block0.p(ctx2, dirty);
        transition_in(if_block0, 1);
        if_block0.m(div, t);
      }
      if (!ctx2[26]) if (if_block1) {
        if_block1.p(ctx2, dirty);
        if (67108864 & dirty[0]) transition_in(if_block1, 1);
      } else {
        if_block1 = create_if_block2(ctx2);
        if_block1.c();
        transition_in(if_block1, 1);
        if_block1.m(div, null);
      } else if (if_block1) {
        group_outros();
        transition_out(if_block1, 1, 1, (() => {
          if_block1 = null;
        }));
        check_outros();
      }
      if (!current || 68157456 & dirty[0] && div_class_value !== (div_class_value = `tree-item nav-folder${ctx2[26] ? " is-collapsed" : ""}${ctx2[4] ? " mod-root" : ""}${ctx2[20] ? " updating" : ""}`)) attr(div, "class", div_class_value);
    },
    i(local) {
      if (!current) {
        transition_in(if_block0);
        transition_in(if_block1);
        current = true;
      }
    },
    o(local) {
      transition_out(if_block0);
      transition_out(if_block1);
      current = false;
    },
    d(detaching) {
      if (detaching) detach(div);
      if_blocks[current_block_type_index].d();
      if (if_block1) if_block1.d();
      mounted = false;
      run_all(dispose);
    }
  };
}

var batchSize = 80;

function shouldResponsibleFor(evt) {
  if (evt.target instanceof Element && evt.target.matchParent(".is-clickable.mod-collapsible.nav-folder-title")) return true; else return false;
}

function splitArrayToBatch(items) {
  const ret = [];
  if (items && items.length > 0) {
    const applyItems = [ ...items ];
    do {
      const batch = applyItems.splice(0, batchSize);
      if (0 == batch.length) break;
      ret.push(batch);
      if (batch.length < batchSize) break;
    } while (applyItems.length > 0);
  }
  return ret;
}

function instance5($$self, $$props, $$invalidate) {
  let filename, trailKey, collapsed, sortFunc, trailLower, isActive, classKey, tagsDispHtml, itemCount, draggable, $tagFolderSetting, $v2expandedTags;
  component_subscribe($$self, tagFolderSetting, ($$value => $$invalidate(61, $tagFolderSetting = $$value)));
  component_subscribe($$self, v2expandedTags, ($$value => $$invalidate(51, $v2expandedTags = $$value)));
  var _a, _b, _c;
  let {viewType = "tags"} = $$props, {thisName = ""} = $$props, {items = []} = $$props, _items = [], {tagName = ""} = $$props, {tagNameDisp = []} = $$props, {trail = []} = $$props, {isRoot} = $$props, {isMainTree} = $$props, {depth = 1} = $$props, {folderIcon = ""} = $$props, {headerTitle = ""} = $$props, {showMenu} = $$props, {openFile} = $$props, {hoverPreview} = $$props, {openScrollView} = $$props;
  v2expandedTags.subscribe((expTags => {
    if (null == trailKey) return;
    const collapsedNew = !expTags.has(trailKey);
    if (collapsed != collapsedNew) $$invalidate(26, collapsed = collapsedNew);
  }));
  let _setting = $tagFolderSetting, expandLimit = 0;
  tagFolderSetting.subscribe((setting => {
    $$invalidate(35, _setting = setting);
    $$invalidate(36, expandLimit = 0);
    if (_setting.expandLimit) if ("links" == viewType) $$invalidate(36, expandLimit = _setting.expandLimit + 1); else $$invalidate(36, expandLimit = _setting.expandLimit);
  }));
  let _tagInfo = {};
  tagInfo.subscribe((info => {
    $$invalidate(37, _tagInfo = info);
  }));
  let _currentActiveFilePath = "";
  currentFile.subscribe((path => {
    $$invalidate(38, _currentActiveFilePath = path);
  }));
  function handleOpenScroll(e, trails, filePaths) {
    if ("tags" == viewType) openScrollView(null, "", joinPartialPath(removeIntermediatePath(trails)).join(", "), filePaths); else if ("links" == viewType) openScrollView(null, "", `Linked to ${filename}`, filePaths);
    e.preventDefault();
  }
  let thisInfo, tags = [], isInDedicatedTag = false, previousTrail = "", isSuppressibleLevel = false, suppressLevels = [], children2 = [], childrenDisp = [], leftOverItems = [], leftOverItemsDisp = [], tagsDisp = [], thisLinks = [], linkedItems = new Map, _lastParam = {}, isUpdating = false;
  const viewContextID = `${null !== (_b = getContext("viewID")) && void 0 !== _b ? _b : ""}`;
  let isFolderVisible = false, queueLeftOverItems = [], batchedLeftOverItems = [];
  async function applyLeftOverItems(items2) {
    if (0 == batchedLeftOverItems.length) if (0 == leftOverItemsDisp.length) try {
      const allOfBatch = splitArrayToBatch(items2);
      if (isSameViewItems(leftOverItemsDisp, allOfBatch)) return;
      batchedLeftOverItems = allOfBatch;
      queueLeftOverItems = [];
      $$invalidate(19, leftOverItemsDisp = []);
      for (const batch of batchedLeftOverItems) {
        $$invalidate(19, leftOverItemsDisp = [ ...leftOverItemsDisp, batch ]);
        if (batch.length == batchSize) {
          await doEvents();
          await tick();
        }
        if (queueLeftOverItems.length > 0) {
          const p = queueLeftOverItems;
          queueLeftOverItems = [];
          batchedLeftOverItems = [];
          return applyLeftOverItems(p);
        }
      }
    } finally {
      batchedLeftOverItems = [];
    } else $$invalidate(19, leftOverItemsDisp = splitArrayToBatch(items2)); else queueLeftOverItems = items2;
  }
  let queuedChildrenDisp = [], batchedChildren = [];
  async function applyChildren(items2) {
    if (0 == batchedChildren.length) if (0 == childrenDisp.length) try {
      const allOfBatch = splitArrayToBatch(items2);
      if (isSameV2FolderItem(childrenDisp, allOfBatch)) return;
      batchedChildren = allOfBatch;
      $$invalidate(18, childrenDisp = []);
      for (const batch of batchedChildren) {
        $$invalidate(18, childrenDisp = [ ...childrenDisp, batch ]);
        if (batch.length == batchSize) {
          await doEvents();
          await tick();
        }
        if (queuedChildrenDisp.length > 0) {
          const p = queuedChildrenDisp;
          queuedChildrenDisp = [];
          batchedChildren = [];
          return applyChildren(p);
        }
      }
    } finally {
      batchedChildren = [];
    } else $$invalidate(18, childrenDisp = splitArrayToBatch(items2)); else queuedChildrenDisp = items2;
  }
  const dm = app.dragManager;
  $$self.$$set = $$props2 => {
    if ("viewType" in $$props2) $$invalidate(2, viewType = $$props2.viewType);
    if ("thisName" in $$props2) $$invalidate(32, thisName = $$props2.thisName);
    if ("items" in $$props2) $$invalidate(13, items = $$props2.items);
    if ("tagName" in $$props2) $$invalidate(0, tagName = $$props2.tagName);
    if ("tagNameDisp" in $$props2) $$invalidate(1, tagNameDisp = $$props2.tagNameDisp);
    if ("trail" in $$props2) $$invalidate(3, trail = $$props2.trail);
    if ("isRoot" in $$props2) $$invalidate(4, isRoot = $$props2.isRoot);
    if ("isMainTree" in $$props2) $$invalidate(5, isMainTree = $$props2.isMainTree);
    if ("depth" in $$props2) $$invalidate(6, depth = $$props2.depth);
    if ("folderIcon" in $$props2) $$invalidate(7, folderIcon = $$props2.folderIcon);
    if ("headerTitle" in $$props2) $$invalidate(8, headerTitle = $$props2.headerTitle);
    if ("showMenu" in $$props2) $$invalidate(9, showMenu = $$props2.showMenu);
    if ("openFile" in $$props2) $$invalidate(10, openFile = $$props2.openFile);
    if ("hoverPreview" in $$props2) $$invalidate(11, hoverPreview = $$props2.hoverPreview);
    if ("openScrollView" in $$props2) $$invalidate(12, openScrollView = $$props2.openScrollView);
  };
  $$self.$$.update = () => {
    if (4 & $$self.$$.dirty[0] | 2 & $$self.$$.dirty[1]) $$invalidate(21, filename = "tags" == viewType ? "" : thisName.substring(thisName.indexOf(":") + 1));
    if (8 & $$self.$$.dirty[0]) $$invalidate(50, trailKey = trail.join("*"));
    if (16 & $$self.$$.dirty[0] | 1572864 & $$self.$$.dirty[1]) $$invalidate(26, collapsed = !isRoot && !$v2expandedTags.has(trailKey));
    if (4 & $$self.$$.dirty[0] | 80 & $$self.$$.dirty[1]) $$invalidate(48, sortFunc = selectCompareMethodTags(_setting, "links" == viewType ? {} : _tagInfo));
    if (8 & $$self.$$.dirty[0]) $$invalidate(49, trailLower = trail.map((e => e.toLowerCase())));
    if (24576 & $$self.$$.dirty[0]) if (!_isSameViewItem(items, _items)) $$invalidate(14, _items = items);
    if (4 & $$self.$$.dirty[0] | 32774 & $$self.$$.dirty[1]) {
      $$invalidate(45, thisLinks = []);
      $$invalidate(46, thisInfo = void 0);
      if ("links" == viewType) {
        $$invalidate(46, thisInfo = getViewItemFromPath(thisName));
        $$invalidate(45, thisLinks = (null !== $$invalidate(33, _a = null == thisInfo ? void 0 : thisInfo.links) && void 0 !== _a ? _a : []).map((e => `${e}`)));
      }
    }
    if (3 & $$self.$$.dirty[0] | 66 & $$self.$$.dirty[1]) if ("" == tagName && 0 == tagNameDisp.length) {
      const [wTagName, wTagNameDisp] = parseTagName(thisName, _tagInfo);
      $$invalidate(0, tagName = wTagName);
      $$invalidate(1, tagNameDisp = wTagNameDisp);
    }
    if (49277 & $$self.$$.dirty[0] | 317234 & $$self.$$.dirty[1]) {
      linkedItems.clear();
      $$invalidate(15, isInDedicatedTag = false);
      let isMixedDedicatedTag = false;
      if (_items) {
        $$invalidate(39, tags = []);
        $$invalidate(40, previousTrail = "");
        if (trail.length >= 1 && trail[trail.length - 1].endsWith("/")) {
          $$invalidate(40, previousTrail = trail[trail.length - 1]);
          $$invalidate(15, isInDedicatedTag = true);
          isMixedDedicatedTag = true;
        }
        if (isMainTree && (!expandLimit || expandLimit && depth < expandLimit)) {
          $$invalidate(41, isSuppressibleLevel = false);
          isMixedDedicatedTag = false;
          let tagsAll = uniqueCaseIntensive(_items.flatMap((e => e.tags)));
          if ("links" == viewType) {
            tagsAll = unique(_items.flatMap((e => e.links)));
            if (!isRoot) {
              tagsAll = thisLinks;
              if (!_setting.linkShowOnlyFDR) tagsAll = thisInfo ? getAllLinksRecursive(thisInfo, [ ...trail ]) : thisLinks;
            }
            if (!isRoot || _setting.expandUntaggedToRoot) tagsAll = tagsAll.filter((e => "_unlinked" != e));
            tagsAll = tagsAll.filter((e => !trail.contains(e)));
            for (const tag of tagsAll) if ("_unlinked" == tag) linkedItems.set(tag, _items.filter((e => e.links.contains(tag)))); else {
              const wItems = _items.filter((e => e.path == tag));
              linkedItems.set(tag, wItems);
            }
            $$invalidate(39, tags = []);
            $$invalidate(43, leftOverItems = []);
            if ("_unlinked" == thisName) $$invalidate(43, leftOverItems = _items); else tagsAll.forEach((tag => {
              if ("_unlinked" == tag) {
                tags.push(tag);
                return;
              }
              const x = getViewItemFromPath(tag);
              if (null == x) return false;
              const existLinks = x.links.filter((e => !trail.contains(e) && e != thisName)), nextDepth = !expandLimit || expandLimit && depth + 1 < expandLimit;
              if (existLinks.length >= 2 && nextDepth) tags.push(tag); else leftOverItems.push(x);
            }));
          } else {
            const lastTrailTagLC = trimTrailingSlash(previousTrail).toLowerCase();
            if (isInDedicatedTag && tagsAll.some((e => e.toLowerCase() == lastTrailTagLC))) $$invalidate(15, isInDedicatedTag = false);
            if (!isRoot || _setting.expandUntaggedToRoot) tagsAll = tagsAll.filter((e => "_untagged" != e));
            let existTags = [ ...tagsAll ];
            existTags = existTags.filter((tag => trail.every((trail2 => trimTrailingSlash(tag.toLowerCase()) !== trimTrailingSlash(trail2.toLowerCase())))));
            existTags = existTags.filter((tag => tag.toLowerCase() != thisName.toLowerCase() && tag.toLowerCase() != tagName.toLowerCase()));
            existTags = existTags.filter((tag => !tag.toLowerCase().endsWith("/" + trimSlash(thisName).toLowerCase())));
            let escapedPreviousTrail = previousTrail;
            if (isInDedicatedTag) existTags = existTags.filter((e => (e + "/").startsWith(previousTrail)));
            if (isMixedDedicatedTag) {
              escapedPreviousTrail = previousTrail.split("/").join("*");
              existTags = existTags.map((e => (e + "/").startsWith(previousTrail) ? escapedPreviousTrail + e.substring(previousTrail.length) : e));
            }
            let existTagsFiltered1 = [];
            if (!_setting.doNotSimplifyTags) if (1 == _items.length) {
              existTagsFiltered1 = existTags;
              $$invalidate(41, isSuppressibleLevel = true);
            } else if (1 == uniqueCaseIntensive(_items.map((e => e.tags.sort().join("**")))).length) {
              $$invalidate(41, isSuppressibleLevel = true);
              existTagsFiltered1 = existTags;
            }
            if (!isSuppressibleLevel) {
              const removeItems = [ thisName.toLowerCase() ];
              if (_setting.reduceNestedParent) removeItems.push(...trailLower);
              let tagsOnNextLevel = [];
              if ("tags" == viewType) tagsOnNextLevel = uniqueCaseIntensive(existTags.map((e => {
                const idx = e.indexOf("/");
                if (idx < 1) return e;
                let piece = e.substring(0, idx + 1), idx2 = idx;
                for (;removeItems.contains(piece.toLowerCase()); ) {
                  idx2 = e.indexOf("/", idx2 + 1);
                  if (-1 === idx2) {
                    piece = e;
                    break;
                  }
                  piece = e.substring(0, idx2 + 1);
                }
                return piece;
              }))); else tagsOnNextLevel = unique(existTags);
              const trailShortest = removeIntermediatePath(trail);
              existTagsFiltered1 = tagsOnNextLevel.filter((tag => trailShortest.every((trail2 => trimTrailingSlash(tag.toLowerCase()) !== trimTrailingSlash(trail2.toLowerCase())))));
            }
            if (isMixedDedicatedTag) existTagsFiltered1 = existTagsFiltered1.map((e => e.replace(escapedPreviousTrail, previousTrail)));
            const existTagsFiltered1LC = existTagsFiltered1.map((e => e.toLowerCase())), existTagsFiltered3 = uniqueCaseIntensive(existTagsFiltered1.map((e => existTagsFiltered1LC.contains(e.toLowerCase() + "/") ? e + "/" : e)));
            if (previousTrail.endsWith("/")) {
              const existTagsFiltered4 = [];
              for (const tag of existTagsFiltered3) if (!existTagsFiltered3.map((e => e.toLowerCase())).contains((previousTrail + tag).toLowerCase())) existTagsFiltered4.push(tag);
              $$invalidate(39, tags = uniqueCaseIntensive(removeIntermediatePath(existTagsFiltered4)));
            } else $$invalidate(39, tags = uniqueCaseIntensive(removeIntermediatePath(existTagsFiltered3)));
          }
        }
      }
    }
    if (147572 & $$self.$$.dirty[0] | 919408 & $$self.$$.dirty[1]) (function updateX(param) {
      if (!isSameAny(param, _lastParam)) {
        _lastParam = {
          ...param
        };
        if (param.isFolderVisible || isRoot) scheduleOnceIfDuplicated("update-children-" + param.key, (async () => {
          $$invalidate(20, isUpdating = true);
          const ret = await collectTreeChildren(param);
          $$invalidate(42, children2 = ret.children);
          $$invalidate(16, suppressLevels = ret.suppressLevels);
          $$invalidate(20, isUpdating = false);
        }));
      }
    })({
      key: trailKey + (isRoot ? "-r" : "-x") + viewContextID,
      expandLimit,
      depth,
      tags,
      trailLower,
      _setting,
      isMainTree,
      isSuppressibleLevel,
      viewType,
      previousTrail,
      _tagInfo,
      _items,
      linkedItems,
      isRoot,
      isFolderVisible,
      sortFunc
    });
    if (49204 & $$self.$$.dirty[0] | 7184 & $$self.$$.dirty[1]) {
      if (_setting.useMultiPaneList && isMainTree) $$invalidate(43, leftOverItems = []); else if (isRoot && isMainTree && !isSuppressibleLevel) if (_setting.expandUntaggedToRoot) $$invalidate(43, leftOverItems = _items.filter((e => e.tags.contains("_untagged") || e.tags.contains("_unlinked")))); else $$invalidate(43, leftOverItems = []); else if (isRoot && !isMainTree) $$invalidate(43, leftOverItems = _items); else if ("tags" == viewType) if ("NONE" == _setting.hideItems) $$invalidate(43, leftOverItems = _items); else if ("DEDICATED_INTERMIDIATES" == _setting.hideItems && isInDedicatedTag || "ALL_EXCEPT_BOTTOM" == _setting.hideItems) $$invalidate(43, leftOverItems = _items.filter((e => !children2.map((e2 => e2[V2FI_IDX_CHILDREN])).flat().find((ee => e.path == ee.path))))); else $$invalidate(43, leftOverItems = _items);
      if (_setting.sortExactFirst) $$invalidate(43, leftOverItems = performSortExactFirst(_items, children2, leftOverItems));
    }
    if (16388 & $$self.$$.dirty[0] | 4482 & $$self.$$.dirty[1]) $$invalidate(25, isActive = _items && _items.some((e => e.path == _currentActiveFilePath)) || "links" == viewType && (thisName == _currentActiveFilePath || tags.contains(_currentActiveFilePath) || leftOverItems.some((e => e.path == _currentActiveFilePath))));
    if (98306 & $$self.$$.dirty[0] | 1024 & $$self.$$.dirty[1]) if (isSuppressibleLevel && isInDedicatedTag) $$invalidate(44, tagsDisp = [ [ ...tagNameDisp, ...suppressLevels.flatMap((e => e.split("/").map((e2 => renderSpecialTag(e2))))) ] ]); else if (isSuppressibleLevel) $$invalidate(44, tagsDisp = [ tagNameDisp, ...suppressLevels.map((e => e.split("/").map((e2 => renderSpecialTag(e2))))) ]); else $$invalidate(44, tagsDisp = [ tagNameDisp ]);
    if (4 & $$self.$$.dirty[0]) $$invalidate(47, classKey = "links" == viewType ? " tf-link" : " tf-tag");
    if (131072 & $$self.$$.dirty[0] | 73728 & $$self.$$.dirty[1]) $$invalidate(24, tagsDispHtml = isFolderVisible ? tagsDisp.map((e => `<span class="tagfolder-tag tag-tag${classKey}">${e.map((ee => `<span class="tf-tag-each">${escapeStringToHTML(ee)}</span>`)).join("")}</span>`)).join("") : "");
    if (16388 & $$self.$$.dirty[0] | 4360 & $$self.$$.dirty[1]) $$invalidate(23, itemCount = "tags" == viewType ? null !== $$invalidate(34, _c = null == _items ? void 0 : _items.length) && void 0 !== _c ? _c : 0 : tags.length + leftOverItems.length);
    if (4096 & $$self.$$.dirty[1]) applyLeftOverItems(leftOverItems);
    if (2048 & $$self.$$.dirty[1]) applyChildren(children2);
    if (16 & $$self.$$.dirty[1]) $$invalidate(22, draggable = !_setting.disableDragging);
  };
  return [ tagName, tagNameDisp, viewType, trail, isRoot, isMainTree, depth, folderIcon, headerTitle, showMenu, openFile, hoverPreview, openScrollView, items, _items, isInDedicatedTag, suppressLevels, isFolderVisible, childrenDisp, leftOverItemsDisp, isUpdating, filename, draggable, itemCount, tagsDispHtml, isActive, collapsed, handleOpenScroll, function toggleFolder(evt) {
    if (shouldResponsibleFor(evt)) {
      evt.preventDefault();
      evt.stopPropagation();
      if (_setting.useMultiPaneList) selectedTags.set(trail);
      v2expandedTags.update((evt2 => {
        if (evt2.has(trailKey)) evt2.delete(trailKey); else evt2.add(trailKey);
        return evt2;
      }));
    }
  }, function dragStartFiles(args) {
    if (!draggable) return;
    const files = _items.map((e => app.vault.getAbstractFileByPath(e.path))), param = dm.dragFiles(args, files);
    if (param) return dm.onDragStart(args, param);
  }, function dragStartName(args) {
    if (!draggable) return;
    if ("links" == viewType) return function dragStartFile(args) {
      if (!draggable) return;
      const file = app.vault.getAbstractFileByPath(filename), param = dm.dragFile(args, file);
      if (param) return dm.onDragStart(args, param); else return;
    }(args);
    const expandedTags = [ ...ancestorToLongestTag(ancestorToTags(joinPartialPath(removeIntermediatePath([ ...trail, ...suppressLevels ])))) ].map((e => trimTrailingSlash(e))).map((e => e.split("/").filter((ee => !isSpecialTag(ee))).join("/"))).filter((e => "" != e)).map((e => "#" + e)).join(" ").trim();
    args.dataTransfer.setData("text/plain", expandedTags);
    args.dataTransfer.setData("Text", expandedTags);
    args.title = expandedTags;
    args.draggable = true;
    dm.onDragStart(args, args);
  }, function handleOpenItem(evt) {
    if ("tags" != viewType) {
      evt.preventDefault();
      evt.stopPropagation();
      openFile(filename, evt.metaKey || evt.ctrlKey);
    }
  }, thisName, _a, _c, _setting, expandLimit, _tagInfo, _currentActiveFilePath, tags, previousTrail, isSuppressibleLevel, children2, leftOverItems, tagsDisp, thisLinks, thisInfo, classKey, sortFunc, trailLower, trailKey, $v2expandedTags, e => handleOpenScroll(e, trail, _items.map((e2 => e2.path))), function ondemandrender_isVisible_binding(value) {
    isFolderVisible = value;
    $$invalidate(17, isFolderVisible);
  }, evt => {
    if (shouldResponsibleFor(evt)) showMenu(evt, [ ...trail, ...suppressLevels ], "tags" == viewType ? tagName : filename, _items);
  } ];
}

var V2TreeFolderComponent = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance5, create_fragment5, safe_not_equal, {
      viewType: 2,
      thisName: 32,
      items: 13,
      tagName: 0,
      tagNameDisp: 1,
      trail: 3,
      isRoot: 4,
      isMainTree: 5,
      depth: 6,
      folderIcon: 7,
      headerTitle: 8,
      showMenu: 9,
      openFile: 10,
      hoverPreview: 11,
      openScrollView: 12
    }, null, [ -1, -1, -1 ]);
  }
}, V2TreeFolderComponent_default = V2TreeFolderComponent, import_obsidian3 = require("obsidian");

function add_css3(target) {
  append_styles(target, "svelte-1xm87ro", ".nav-files-container.svelte-1xm87ro{height:100%}");
}

function create_if_block_32(ctx) {
  let div0, t0, div1, t1, div2, div2_class_value, mounted, dispose;
  return {
    c() {
      div0 = element("div");
      t0 = space();
      div1 = element("div");
      t1 = space();
      div2 = element("div");
      attr(div0, "class", "clickable-icon nav-action-button");
      attr(div0, "aria-label", "Change sort order");
      attr(div1, "class", "clickable-icon nav-action-button");
      attr(div1, "aria-label", "Expand limit");
      attr(div2, "class", div2_class_value = null_to_empty("clickable-icon nav-action-button" + (ctx[14] ? " is-active" : "")) + " svelte-1xm87ro");
      attr(div2, "aria-label", "Search");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      div0.innerHTML = ctx[18];
      insert(target, t0, anchor);
      insert(target, div1, anchor);
      div1.innerHTML = ctx[19];
      insert(target, t1, anchor);
      insert(target, div2, anchor);
      div2.innerHTML = ctx[20];
      if (!mounted) {
        dispose = [ listen(div0, "click", (function() {
          if (is_function(ctx[4])) ctx[4].apply(this, arguments);
        })), listen(div1, "click", (function() {
          if (is_function(ctx[3])) ctx[3].apply(this, arguments);
        })), listen(div2, "click", ctx[28]) ];
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (262144 & dirty[0]) div0.innerHTML = ctx[18];
      if (524288 & dirty[0]) div1.innerHTML = ctx[19];
      if (1048576 & dirty[0]) div2.innerHTML = ctx[20];
      if (16384 & dirty[0] && div2_class_value !== (div2_class_value = null_to_empty("clickable-icon nav-action-button" + (ctx[14] ? " is-active" : "")) + " svelte-1xm87ro")) attr(div2, "class", div2_class_value);
    },
    d(detaching) {
      if (detaching) {
        detach(div0);
        detach(t0);
        detach(div1);
        detach(t1);
        detach(div2);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}

function create_if_block_22(ctx) {
  let div, mounted, dispose;
  return {
    c() {
      div = element("div");
      attr(div, "class", "clickable-icon nav-action-button");
      attr(div, "aria-label", "Switch List/Tree");
    },
    m(target, anchor) {
      insert(target, div, anchor);
      div.innerHTML = ctx[21];
      if (!mounted) {
        dispose = listen(div, "click", ctx[30]);
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (2097152 & dirty[0]) div.innerHTML = ctx2[21];
    },
    d(detaching) {
      if (detaching) detach(div);
      mounted = false;
      dispose();
    }
  };
}

function create_if_block_12(ctx) {
  let div0, t0, div1, t1, div2, mounted, dispose;
  return {
    c() {
      div0 = element("div");
      t0 = space();
      div1 = element("div");
      t1 = space();
      div2 = element("div");
      attr(div0, "class", "clickable-icon nav-action-button");
      attr(div0, "aria-label", "Toggle Incoming");
      toggle_class(div0, "is-active", ctx[12]);
      attr(div1, "class", "clickable-icon nav-action-button");
      attr(div1, "aria-label", "Toggle Outgoing");
      toggle_class(div1, "is-active", ctx[11]);
      attr(div2, "class", "clickable-icon nav-action-button");
      attr(div2, "aria-label", "Toggle Hide indirect notes");
      toggle_class(div2, "is-active", ctx[13]);
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      div0.innerHTML = ctx[23];
      insert(target, t0, anchor);
      insert(target, div1, anchor);
      div1.innerHTML = ctx[22];
      insert(target, t1, anchor);
      insert(target, div2, anchor);
      div2.innerHTML = ctx[24];
      if (!mounted) {
        dispose = [ listen(div0, "click", ctx[31]), listen(div1, "click", ctx[32]), listen(div2, "click", ctx[33]) ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (8388608 & dirty[0]) div0.innerHTML = ctx2[23];
      if (4096 & dirty[0]) toggle_class(div0, "is-active", ctx2[12]);
      if (4194304 & dirty[0]) div1.innerHTML = ctx2[22];
      if (2048 & dirty[0]) toggle_class(div1, "is-active", ctx2[11]);
      if (16777216 & dirty[0]) div2.innerHTML = ctx2[24];
      if (8192 & dirty[0]) toggle_class(div2, "is-active", ctx2[13]);
    },
    d(detaching) {
      if (detaching) {
        detach(div0);
        detach(t0);
        detach(div1);
        detach(t1);
        detach(div2);
      }
      mounted = false;
      run_all(dispose);
    }
  };
}

function create_if_block3(ctx) {
  let div1, input, t, div0, mounted, dispose;
  return {
    c() {
      div1 = element("div");
      input = element("input");
      t = space();
      div0 = element("div");
      attr(input, "type", "search");
      attr(input, "spellcheck", "false");
      attr(input, "placeholder", "Type to start search...");
      attr(div0, "class", "search-input-clear-button");
      attr(div0, "aria-label", "Clear search");
      set_style(div0, "display", "" == ctx[10].trim() ? "none" : "");
      attr(div1, "class", "search-input-container");
    },
    m(target, anchor) {
      insert(target, div1, anchor);
      append(div1, input);
      set_input_value(input, ctx[10]);
      append(div1, t);
      append(div1, div0);
      if (!mounted) {
        dispose = [ listen(input, "input", ctx[43]), listen(div0, "click", ctx[29]) ];
        mounted = true;
      }
    },
    p(ctx2, dirty) {
      if (1024 & dirty[0] && input.value !== ctx2[10]) set_input_value(input, ctx2[10]);
      if (1024 & dirty[0]) set_style(div0, "display", "" == ctx2[10].trim() ? "none" : "");
    },
    d(detaching) {
      if (detaching) detach(div1);
      mounted = false;
      run_all(dispose);
    }
  };
}

function create_fragment6(ctx) {
  let div0, t0, div3, div2, div1, t1, t2, t3, t4, t5, div4, v2treefoldercomponent, current, mounted, dispose, if_block0 = ctx[9] && create_if_block_32(ctx), if_block1 = ctx[7] && create_if_block_22(ctx), if_block2 = "links" == ctx[8] && create_if_block_12(ctx), if_block3 = ctx[14] && ctx[9] && create_if_block3(ctx);
  v2treefoldercomponent = new V2TreeFolderComponent_default({
    props: {
      viewType: ctx[8],
      items: ctx[25],
      folderIcon: ctx[17],
      thisName: "",
      isRoot: true,
      showMenu: ctx[2],
      openFile: ctx[1],
      isMainTree: ctx[9],
      hoverPreview: ctx[0],
      openScrollView: ctx[6],
      depth: 1,
      headerTitle: ctx[27]
    }
  });
  return {
    c() {
      div0 = element("div");
      t0 = space();
      div3 = element("div");
      div2 = element("div");
      div1 = element("div");
      t1 = space();
      if (if_block0) if_block0.c();
      t2 = space();
      if (if_block1) if_block1.c();
      t3 = space();
      if (if_block2) if_block2.c();
      t4 = space();
      if (if_block3) if_block3.c();
      t5 = space();
      div4 = element("div");
      create_component(v2treefoldercomponent.$$.fragment);
      div0.hidden = true;
      attr(div1, "class", "clickable-icon nav-action-button");
      attr(div1, "aria-label", "New note");
      attr(div2, "class", "nav-buttons-container tagfolder-buttons-container");
      attr(div3, "class", "nav-header");
      attr(div4, "class", "nav-files-container node-insert-event svelte-1xm87ro");
    },
    m(target, anchor) {
      insert(target, div0, anchor);
      ctx[42](div0);
      insert(target, t0, anchor);
      insert(target, div3, anchor);
      append(div3, div2);
      append(div2, div1);
      div1.innerHTML = ctx[16];
      append(div2, t1);
      if (if_block0) if_block0.m(div2, null);
      append(div2, t2);
      if (if_block1) if_block1.m(div2, null);
      append(div2, t3);
      if (if_block2) if_block2.m(div2, null);
      insert(target, t4, anchor);
      if (if_block3) if_block3.m(target, anchor);
      insert(target, t5, anchor);
      insert(target, div4, anchor);
      mount_component(v2treefoldercomponent, div4, null);
      ctx[44](div4);
      current = true;
      if (!mounted) {
        dispose = listen(div1, "click", (function() {
          if (is_function(ctx[5])) ctx[5].apply(this, arguments);
        }));
        mounted = true;
      }
    },
    p(new_ctx, dirty) {
      ctx = new_ctx;
      if (!current || 65536 & dirty[0]) div1.innerHTML = ctx[16];
      if (ctx[9]) if (if_block0) if_block0.p(ctx, dirty); else {
        if_block0 = create_if_block_32(ctx);
        if_block0.c();
        if_block0.m(div2, t2);
      } else if (if_block0) {
        if_block0.d(1);
        if_block0 = null;
      }
      if (ctx[7]) if (if_block1) if_block1.p(ctx, dirty); else {
        if_block1 = create_if_block_22(ctx);
        if_block1.c();
        if_block1.m(div2, t3);
      } else if (if_block1) {
        if_block1.d(1);
        if_block1 = null;
      }
      if ("links" == ctx[8]) if (if_block2) if_block2.p(ctx, dirty); else {
        if_block2 = create_if_block_12(ctx);
        if_block2.c();
        if_block2.m(div2, null);
      } else if (if_block2) {
        if_block2.d(1);
        if_block2 = null;
      }
      if (ctx[14] && ctx[9]) if (if_block3) if_block3.p(ctx, dirty); else {
        if_block3 = create_if_block3(ctx);
        if_block3.c();
        if_block3.m(t5.parentNode, t5);
      } else if (if_block3) {
        if_block3.d(1);
        if_block3 = null;
      }
      const v2treefoldercomponent_changes = {};
      if (256 & dirty[0]) v2treefoldercomponent_changes.viewType = ctx[8];
      if (33554432 & dirty[0]) v2treefoldercomponent_changes.items = ctx[25];
      if (131072 & dirty[0]) v2treefoldercomponent_changes.folderIcon = ctx[17];
      if (4 & dirty[0]) v2treefoldercomponent_changes.showMenu = ctx[2];
      if (2 & dirty[0]) v2treefoldercomponent_changes.openFile = ctx[1];
      if (512 & dirty[0]) v2treefoldercomponent_changes.isMainTree = ctx[9];
      if (1 & dirty[0]) v2treefoldercomponent_changes.hoverPreview = ctx[0];
      if (64 & dirty[0]) v2treefoldercomponent_changes.openScrollView = ctx[6];
      if (134217728 & dirty[0]) v2treefoldercomponent_changes.headerTitle = ctx[27];
      v2treefoldercomponent.$set(v2treefoldercomponent_changes);
    },
    i(local) {
      if (!current) {
        transition_in(v2treefoldercomponent.$$.fragment, local);
        current = true;
      }
    },
    o(local) {
      transition_out(v2treefoldercomponent.$$.fragment, local);
      current = false;
    },
    d(detaching) {
      if (detaching) {
        detach(div0);
        detach(t0);
        detach(div3);
        detach(t4);
        detach(t5);
        detach(div4);
      }
      ctx[42](null);
      if (if_block0) if_block0.d();
      if (if_block1) if_block1.d();
      if (if_block2) if_block2.d();
      if (if_block3) if_block3.d(detaching);
      destroy_component(v2treefoldercomponent);
      ctx[44](null);
      mounted = false;
      dispose();
    }
  };
}

function instance6($$self, $$props, $$invalidate) {
  let headerTitle, $tagFolderSetting;
  component_subscribe($$self, tagFolderSetting, ($$value => $$invalidate(47, $tagFolderSetting = $$value)));
  var _a;
  let isMainTree, {hoverPreview} = $$props, {openFile} = $$props, {vaultName = ""} = $$props, {title = ""} = $$props, {tags = []} = $$props, {saveSettings} = $$props, {showMenu} = $$props, {showLevelSelect} = $$props, {showOrder} = $$props, {newNote} = $$props, {openScrollView} = $$props, {isViewSwitchable} = $$props, {switchView} = $$props, {viewType = "tags"} = $$props, viewItemsSrc = [], updatedFiles = [];
  appliedFiles.subscribe((async filenames => {
    updatedFiles = null != filenames ? filenames : [];
  }));
  if ("tags" == viewType) allViewItems.subscribe((items => {
    $$invalidate(40, viewItemsSrc = items);
  })); else if ("links" == viewType) allViewItemsByLink.subscribe((async items => {
    if (viewItemsSrc) {
      const filtered = [ ...viewItemsSrc.filter((e => !updatedFiles.some((filename => e.links.contains(filename))))) ];
      updatedFiles = [];
      $$invalidate(40, viewItemsSrc = filtered);
      await tick();
    }
    $$invalidate(40, viewItemsSrc = items);
  }));
  let search = "";
  searchString.subscribe((newSearch => {
    if (search != newSearch) {
      if ("" != newSearch) $$invalidate(14, showSearch = true);
      $$invalidate(10, search = newSearch);
    }
  }));
  let _setting = $tagFolderSetting, outgoingEnabled = false, incomingEnabled = false, onlyFDREnabled = false;
  tagFolderSetting.subscribe((setting => {
    var _a2, _b, _c, _d, _e, _f;
    $$invalidate(41, _setting = setting);
    $$invalidate(11, outgoingEnabled = null !== (_c = null === (_b = null === (_a2 = _setting.linkConfig) || void 0 === _a2 ? void 0 : _a2.outgoing) || void 0 === _b ? void 0 : _b.enabled) && void 0 !== _c ? _c : false);
    $$invalidate(12, incomingEnabled = null !== (_f = null === (_e = null === (_d = _setting.linkConfig) || void 0 === _d ? void 0 : _d.incoming) || void 0 === _e ? void 0 : _e.enabled) && void 0 !== _f ? _f : false);
    $$invalidate(13, onlyFDREnabled = _setting.linkShowOnlyFDR);
  }));
  let iconDivEl, observer, showSearch = false, newNoteIcon = "", folderIcon = "", upAndDownArrowsIcon = "", stackedLevels = "", searchIcon = "", switchIcon = "", outgoingIcon = "", incomingIcon = "", linkIcon = "", observingElements = new Map;
  function unobserve(el) {
    observer.unobserve(el);
  }
  setContext("observer", {
    observe: function observe(el, callback) {
      if (observingElements.has(el)) unobserve(el);
      observingElements.set(el, {
        callback,
        lastState: void 0
      });
      observer.observe(el);
    },
    unobserve
  });
  onMount((() => {
    observer = new IntersectionObserver((ex => {
      for (const v of ex) if (observingElements.has(v.target)) {
        const tg = observingElements.get(v.target);
        if (tg.lastState !== v.isIntersecting) {
          tg.lastState = v.isIntersecting;
          setTimeout((() => tg.callback(v.isIntersecting)), 10);
        }
      }
    }), {
      root: scrollParent,
      rootMargin: "40px 0px",
      threshold: 0
    });
    (0, import_obsidian3.setIcon)(iconDivEl, "right-triangle");
    $$invalidate(17, folderIcon = `${iconDivEl.innerHTML}`);
    (0, import_obsidian3.setIcon)(iconDivEl, "lucide-edit");
    $$invalidate(16, newNoteIcon = `${iconDivEl.innerHTML}`);
    if (isMainTree) {
      (0, import_obsidian3.setIcon)(iconDivEl, "lucide-sort-asc");
      $$invalidate(18, upAndDownArrowsIcon = iconDivEl.innerHTML);
      (0, import_obsidian3.setIcon)(iconDivEl, "stacked-levels");
      $$invalidate(19, stackedLevels = iconDivEl.innerHTML);
      (0, import_obsidian3.setIcon)(iconDivEl, "search");
      $$invalidate(20, searchIcon = iconDivEl.innerHTML);
    }
    if ("links" == viewType) {
      (0, import_obsidian3.setIcon)(iconDivEl, "links-coming-in");
      $$invalidate(23, incomingIcon = iconDivEl.innerHTML);
      (0, import_obsidian3.setIcon)(iconDivEl, "links-going-out");
      $$invalidate(22, outgoingIcon = iconDivEl.innerHTML);
      (0, import_obsidian3.setIcon)(iconDivEl, "link");
      $$invalidate(24, linkIcon = iconDivEl.innerHTML);
    }
    (0, import_obsidian3.setIcon)(iconDivEl, "lucide-arrow-left-right");
    $$invalidate(21, switchIcon = iconDivEl.innerHTML);
    const int = setInterval((() => {
      performHide.set(Date.now());
    }), 5e3);
    return () => {
      clearInterval(int);
    };
  }));
  onDestroy((() => {
    observer.disconnect();
  }));
  let scrollParent, viewItems = [];
  setContext("viewID", `${Math.random()}`);
  $$self.$$set = $$props2 => {
    if ("hoverPreview" in $$props2) $$invalidate(0, hoverPreview = $$props2.hoverPreview);
    if ("openFile" in $$props2) $$invalidate(1, openFile = $$props2.openFile);
    if ("vaultName" in $$props2) $$invalidate(34, vaultName = $$props2.vaultName);
    if ("title" in $$props2) $$invalidate(35, title = $$props2.title);
    if ("tags" in $$props2) $$invalidate(36, tags = $$props2.tags);
    if ("saveSettings" in $$props2) $$invalidate(37, saveSettings = $$props2.saveSettings);
    if ("showMenu" in $$props2) $$invalidate(2, showMenu = $$props2.showMenu);
    if ("showLevelSelect" in $$props2) $$invalidate(3, showLevelSelect = $$props2.showLevelSelect);
    if ("showOrder" in $$props2) $$invalidate(4, showOrder = $$props2.showOrder);
    if ("newNote" in $$props2) $$invalidate(5, newNote = $$props2.newNote);
    if ("openScrollView" in $$props2) $$invalidate(6, openScrollView = $$props2.openScrollView);
    if ("isViewSwitchable" in $$props2) $$invalidate(7, isViewSwitchable = $$props2.isViewSwitchable);
    if ("switchView" in $$props2) $$invalidate(38, switchView = $$props2.switchView);
    if ("viewType" in $$props2) $$invalidate(8, viewType = $$props2.viewType);
  };
  $$self.$$.update = () => {
    if (1024 & $$self.$$.dirty[0]) searchString.set(search);
    if (256 & $$self.$$.dirty[0] | 24 & $$self.$$.dirty[1]) $$invalidate(27, headerTitle = "" == title ? `${"tags" == viewType ? "Tags" : "Links"}: ${vaultName}` : `Items: ${title}`);
    if (32 & $$self.$$.dirty[1]) $$invalidate(9, isMainTree = 0 == tags.length);
    if (512 & $$self.$$.dirty[0] | 1824 & $$self.$$.dirty[1]) if (viewItemsSrc) if (isMainTree) $$invalidate(25, viewItems = viewItemsSrc); else {
      let items = viewItemsSrc;
      const lowerTags = tags.map((e => e.toLowerCase()));
      for (const tag of lowerTags) items = items.filter((e => e.tags.some((e2 => (e2.toLowerCase() + "/").startsWith(tag)))));
      const firstLevel = trimTrailingSlash(null !== $$invalidate(39, _a = tags.first()) && void 0 !== _a ? _a : "").toLowerCase(), archiveTags = _setting.archiveTags.toLowerCase().replace(/[\n ]/g, "").split(",");
      if (!archiveTags.contains(firstLevel)) items = items.filter((item => !item.tags.some((e => archiveTags.contains(e.toLowerCase())))));
      $$invalidate(25, viewItems = items);
    }
  };
  return [ hoverPreview, openFile, showMenu, showLevelSelect, showOrder, newNote, openScrollView, isViewSwitchable, viewType, isMainTree, search, outgoingEnabled, incomingEnabled, onlyFDREnabled, showSearch, iconDivEl, newNoteIcon, folderIcon, upAndDownArrowsIcon, stackedLevels, searchIcon, switchIcon, outgoingIcon, incomingIcon, linkIcon, viewItems, scrollParent, headerTitle, function toggleSearch() {
    $$invalidate(14, showSearch = !showSearch);
    if (!showSearch) $$invalidate(10, search = "");
  }, function clearSearch() {
    $$invalidate(10, search = "");
  }, function doSwitch() {
    if (switchView) switchView();
  }, async function switchIncoming() {
    let newSet = {
      ..._setting
    };
    newSet.linkConfig.incoming.enabled = !_setting.linkConfig.incoming.enabled;
    if (!newSet.linkConfig.incoming.enabled && !newSet.linkConfig.outgoing.enabled) newSet.linkConfig.incoming.enabled = true;
    if (saveSettings) await saveSettings(newSet);
  }, async function switchOutgoing() {
    let newSet = {
      ..._setting
    };
    newSet.linkConfig.outgoing.enabled = !_setting.linkConfig.outgoing.enabled;
    if (!newSet.linkConfig.incoming.enabled && !newSet.linkConfig.outgoing.enabled) newSet.linkConfig.outgoing.enabled = true;
    if (saveSettings) await saveSettings(newSet);
  }, async function switchOnlyFDR() {
    let newSet = {
      ..._setting
    };
    newSet.linkShowOnlyFDR = !_setting.linkShowOnlyFDR;
    if (saveSettings) await saveSettings(newSet);
  }, vaultName, title, tags, saveSettings, switchView, _a, viewItemsSrc, _setting, function div0_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"]((() => {
      iconDivEl = $$value;
      $$invalidate(15, iconDivEl);
    }));
  }, function input_input_handler() {
    search = this.value;
    $$invalidate(10, search);
  }, function div4_binding($$value) {
    binding_callbacks[$$value ? "unshift" : "push"]((() => {
      scrollParent = $$value;
      $$invalidate(26, scrollParent);
    }));
  } ];
}

var TagFolderViewComponent = class extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, instance6, create_fragment6, safe_not_equal, {
      hoverPreview: 0,
      openFile: 1,
      vaultName: 34,
      title: 35,
      tags: 36,
      saveSettings: 37,
      showMenu: 2,
      showLevelSelect: 3,
      showOrder: 4,
      newNote: 5,
      openScrollView: 6,
      isViewSwitchable: 7,
      switchView: 38,
      viewType: 8
    }, add_css3, [ -1, -1 ]);
  }
}, TagFolderViewComponent_default = TagFolderViewComponent, import_obsidian5 = require("obsidian"), import_obsidian4 = require("obsidian"), askString = (app2, title, placeholder, initialText) => new Promise((res => {
  new PopoverSelectString(app2, title, placeholder, initialText, (result => res(result))).open();
})), PopoverSelectString = class extends import_obsidian4.SuggestModal {
  constructor(app2, title, placeholder, initialText, callback) {
    super(app2);
    this.callback = () => {};
    this.title = "";
    this.app = app2;
    this.title = title;
    this.setPlaceholder(null != placeholder ? placeholder : ">");
    this.callback = callback;
    setTimeout((() => {
      this.inputEl.value = initialText;
    }));
    const parent = this.containerEl.querySelector(".prompt");
    if (parent) parent.addClass("override-input");
  }
  getSuggestions(query) {
    return [ query ];
  }
  renderSuggestion(value, el) {
    el.createDiv({
      text: `${this.title}${value}`
    });
  }
  onChooseSuggestion(item, evt) {
    this.callback(item);
    this.callback = null;
  }
  onClose() {
    setTimeout((() => {
      if (null != this.callback) this.callback(false);
    }), 100);
  }
};

function toggleObjectProp(obj, propName, value) {
  if (false === value) {
    const newTagInfoEntries = Object.entries(obj || {}).filter((([key]) => key != propName));
    if (0 == newTagInfoEntries.length) return {}; else return Object.fromEntries(newTagInfoEntries);
  } else return {
    ...null != obj ? obj : {},
    [propName]: value
  };
}

var TagFolderViewBase = class extends import_obsidian5.ItemView {
  async saveSettings(settings) {
    this.plugin.settings = {
      ...this.plugin.settings,
      ...settings
    };
    await this.plugin.saveSettings();
    this.plugin.updateFileCaches();
  }
  showOrder(evt) {
    const menu = new import_obsidian5.Menu;
    menu.addItem((item => {
      item.setTitle("Tags").setIcon("hashtag").onClick((async evt2 => {
        const menu2 = new import_obsidian5.Menu;
        for (const key in OrderKeyTag) for (const direction in OrderDirection) menu2.addItem((item2 => {
          const newSetting = `${key}_${direction}`;
          item2.setTitle(OrderKeyTag[key] + " " + OrderDirection[direction]).onClick((async () => {
            this.plugin.settings.sortTypeTag = newSetting;
            await this.plugin.saveSettings();
          }));
          if (newSetting == this.plugin.settings.sortTypeTag) item2.setIcon("checkmark");
          return item2;
        }));
        menu2.showAtPosition({
          x: evt.x,
          y: evt.y
        });
      }));
      return item;
    }));
    menu.addItem((item => {
      item.setTitle("Items").setIcon("document").onClick((async evt2 => {
        const menu2 = new import_obsidian5.Menu;
        for (const key in OrderKeyItem) for (const direction in OrderDirection) menu2.addItem((item2 => {
          const newSetting = `${key}_${direction}`;
          item2.setTitle(OrderKeyItem[key] + " " + OrderDirection[direction]).onClick((async () => {
            this.plugin.settings.sortType = newSetting;
            await this.plugin.saveSettings();
          }));
          if (newSetting == this.plugin.settings.sortType) item2.setIcon("checkmark");
          return item2;
        }));
        menu2.showAtPosition({
          x: evt.x,
          y: evt.y
        });
      }));
      return item;
    }));
    menu.showAtMouseEvent(evt);
  }
  showLevelSelect(evt) {
    const menu = new import_obsidian5.Menu, setLevel = async level => {
      this.plugin.settings.expandLimit = level;
      await this.plugin.saveSettings();
      maxDepth.set(level);
    };
    for (const level of [ 2, 3, 4, 5 ]) menu.addItem((item => {
      item.setTitle("Level " + (level - 1)).onClick((() => {
        setLevel(level);
      }));
      if (this.plugin.settings.expandLimit == level) item.setIcon("checkmark");
      return item;
    }));
    menu.addItem((item => {
      item.setTitle("No limit").onClick((() => {
        setLevel(0);
      }));
      if (0 == this.plugin.settings.expandLimit) item.setIcon("checkmark");
      return item;
    }));
    menu.showAtMouseEvent(evt);
  }
  showMenu(evt, trail, targetTag, targetItems) {
    const isTagTree = this.getViewType() == VIEW_TYPE_TAGFOLDER, menu = new import_obsidian5.Menu;
    if (isTagTree) {
      const expandedTagsAll = ancestorToLongestTag(ancestorToTags(joinPartialPath(removeIntermediatePath(trail)))).map((e => trimTrailingSlash(e))), expandedTags = expandedTagsAll.map((e => e.split("/").filter((ee => !isSpecialTag(ee))).join("/"))).filter((e => "" != e)).map((e => "#" + e)).join(" ").trim(), displayExpandedTags = expandedTagsAll.map((e => e.split("/").filter((ee => renderSpecialTag(ee))).join("/"))).filter((e => "" != e)).map((e => "#" + e)).join(" ").trim();
      if (navigator && navigator.clipboard) menu.addItem((item => item.setTitle(`Copy tags:${expandedTags}`).setIcon("hashtag").onClick((async () => {
        await navigator.clipboard.writeText(expandedTags);
        new import_obsidian5.Notice("Copied");
      }))));
      menu.addItem((item => item.setTitle("New note " + (targetTag ? "in here" : "as like this")).setIcon("create-new").onClick((async () => {
        await this.plugin.createNewNote(trail);
      }))));
      if (targetTag) if (this.plugin.settings.useTagInfo && null != this.plugin.tagInfo) {
        const tag = targetTag;
        if (tag in this.plugin.tagInfo && "key" in this.plugin.tagInfo[tag]) menu.addItem((item => item.setTitle("Unpin").setIcon("pin").onClick((async () => {
          this.plugin.tagInfo[tag] = toggleObjectProp(this.plugin.tagInfo[tag], "key", false);
          this.plugin.applyTagInfo();
          await this.plugin.saveTagInfo();
        })))); else menu.addItem((item => {
          item.setTitle("Pin").setIcon("pin").onClick((async () => {
            this.plugin.tagInfo[tag] = toggleObjectProp(this.plugin.tagInfo[tag], "key", "");
            this.plugin.applyTagInfo();
            await this.plugin.saveTagInfo();
          }));
        }));
        menu.addItem((item => {
          item.setTitle("Set an alternative label").setIcon("pencil").onClick((async () => {
            var _a;
            const oldAlt = tag in this.plugin.tagInfo ? null != (_a = this.plugin.tagInfo[tag].alt) ? _a : "" : "", label = await askString(this.app, "", "", oldAlt);
            if (false !== label) {
              this.plugin.tagInfo[tag] = toggleObjectProp(this.plugin.tagInfo[tag], "alt", "" == label ? false : label);
              this.plugin.applyTagInfo();
              await this.plugin.saveTagInfo();
            }
          }));
        }));
        menu.addItem((item => {
          item.setTitle("Change the mark").setIcon("pencil").onClick((async () => {
            var _a;
            const oldMark = tag in this.plugin.tagInfo ? null != (_a = this.plugin.tagInfo[tag].mark) ? _a : "" : "", mark = await askString(this.app, "", "", oldMark);
            if (false !== mark) {
              this.plugin.tagInfo[tag] = toggleObjectProp(this.plugin.tagInfo[tag], "mark", "" == mark ? false : mark);
              this.plugin.applyTagInfo();
              await this.plugin.saveTagInfo();
            }
          }));
        }));
        menu.addItem((item => {
          item.setTitle("Redirect this tag to ...").setIcon("pencil").onClick((async () => {
            var _a;
            const oldRedirect = tag in this.plugin.tagInfo ? null != (_a = this.plugin.tagInfo[tag].redirect) ? _a : "" : "", redirect = await askString(this.app, "", "", oldRedirect);
            if (false !== redirect) {
              this.plugin.tagInfo[tag] = toggleObjectProp(this.plugin.tagInfo[tag], "redirect", "" == redirect ? false : redirect);
              this.plugin.applyTagInfo();
              await this.plugin.saveTagInfo();
            }
          }));
        }));
        if (targetItems) {
          menu.addItem((item => {
            item.setTitle("Open scroll view").setIcon("sheets-in-box").onClick((async () => {
              const files = targetItems.map((e => e.path));
              await this.plugin.openScrollView(null, displayExpandedTags, expandedTagsAll.join(", "), files);
            }));
          }));
          menu.addItem((item => {
            item.setTitle("Open list").setIcon("sheets-in-box").onClick((async () => {
              selectedTags.set(expandedTagsAll);
            }));
          }));
        }
      }
    }
    if (!targetTag && targetItems && 1 == targetItems.length) {
      const path = targetItems[0].path, file = this.app.vault.getAbstractFileByPath(path);
      this.app.workspace.trigger("file-menu", menu, file, "file-explorer");
      menu.addSeparator();
      menu.addItem((item => item.setTitle("Open in new tab").setSection("open").setIcon("lucide-file-plus").onClick((async () => {
        app.workspace.openLinkText(path, path, "tab");
      }))));
      menu.addItem((item => item.setTitle("Open to the right").setSection("open").setIcon("lucide-separator-vertical").onClick((async () => {
        app.workspace.openLinkText(path, path, "split");
      }))));
    } else if (!isTagTree) {
      const path = targetTag, file = this.app.vault.getAbstractFileByPath(path);
      this.app.workspace.trigger("file-menu", menu, file, "file-explorer");
      menu.addSeparator();
      menu.addItem((item => item.setTitle("Open in new tab").setSection("open").setIcon("lucide-file-plus").onClick((async () => {
        app.workspace.openLinkText(path, path, "tab");
      }))));
      menu.addItem((item => item.setTitle("Open to the right").setSection("open").setIcon("lucide-separator-vertical").onClick((async () => {
        app.workspace.openLinkText(path, path, "split");
      }))));
    }
    if ("screenX" in evt) menu.showAtPosition({
      x: evt.pageX,
      y: evt.pageY
    }); else menu.showAtPosition({
      x: evt.nativeEvent.locationX,
      y: evt.nativeEvent.locationY
    });
    evt.preventDefault();
  }
  switchView() {
    let viewType = VIEW_TYPE_TAGFOLDER;
    const currentType = this.getViewType();
    if (currentType == VIEW_TYPE_TAGFOLDER) viewType = VIEW_TYPE_TAGFOLDER_LIST; else if (currentType == VIEW_TYPE_TAGFOLDER_LINK) return; else if (currentType == VIEW_TYPE_TAGFOLDER_LIST) viewType = VIEW_TYPE_TAGFOLDER;
    const leaves = this.app.workspace.getLeavesOfType(viewType).filter((e => !e.getViewState().pinned && e != this.leaf));
    if (leaves.length) this.app.workspace.revealLeaf(leaves[0]);
  }
}, TagFolderView = class extends TagFolderViewBase {
  getIcon() {
    return "stacked-levels";
  }
  constructor(leaf, plugin, viewType) {
    super(leaf);
    this.plugin = plugin;
    this.showMenu = this.showMenu.bind(this);
    this.showOrder = this.showOrder.bind(this);
    this.newNote = this.newNote.bind(this);
    this.showLevelSelect = this.showLevelSelect.bind(this);
    this.switchView = this.switchView.bind(this);
    this.treeViewType = viewType;
  }
  newNote(evt) {
    this.app.commands.executeCommandById("file-explorer:new-file");
  }
  getViewType() {
    return "tags" == this.treeViewType ? VIEW_TYPE_TAGFOLDER : VIEW_TYPE_TAGFOLDER_LINK;
  }
  getDisplayText() {
    return "tags" == this.treeViewType ? "Tag Folder" : "Link Folder";
  }
  async onOpen() {
    this.containerEl.empty();
    this.component = new TagFolderViewComponent_default({
      target: this.containerEl,
      props: {
        openFile: this.plugin.focusFile,
        hoverPreview: this.plugin.hoverPreview,
        vaultName: this.app.vault.getName(),
        showMenu: this.showMenu,
        showLevelSelect: this.showLevelSelect,
        showOrder: this.showOrder,
        newNote: this.newNote,
        openScrollView: this.plugin.openScrollView,
        isViewSwitchable: this.plugin.settings.useMultiPaneList,
        switchView: this.switchView,
        viewType: this.treeViewType,
        saveSettings: this.saveSettings.bind(this)
      }
    });
  }
  async onClose() {
    this.component.$destroy();
  }
}, import_obsidian7 = require("obsidian"), TagFolderList = class extends TagFolderViewBase {
  constructor(leaf, plugin) {
    super(leaf);
    this.state = {
      tags: [],
      title: ""
    };
    this.plugin = plugin;
    this.showMenu = this.showMenu.bind(this);
    this.showOrder = this.showOrder.bind(this);
    this.newNote = this.newNote.bind(this);
    this.showLevelSelect = this.showLevelSelect.bind(this);
    this.switchView = this.switchView.bind(this);
  }
  onPaneMenu(menu, source) {
    super.onPaneMenu(menu, source);
    menu.addItem((item => {
      item.setIcon("pin").setTitle("Pin").onClick((() => {
        this.leaf.togglePinned();
      }));
    }));
  }
  getIcon() {
    return "stacked-levels";
  }
  async setState(state, result) {
    var _a;
    this.state = {
      ...state
    };
    this.title = state.tags.join(",");
    this.component.$set({
      tags: state.tags,
      title: null != (_a = state.title) ? _a : ""
    });
  }
  getState() {
    return this.state;
  }
  async newNote(evt) {
    await this.plugin.createNewNote(this.state.tags);
  }
  getViewType() {
    return VIEW_TYPE_TAGFOLDER_LIST;
  }
  getDisplayText() {
    return `Files with ${this.state.title}`;
  }
  async onOpen() {
    this.containerEl.empty();
    this.component = new TagFolderViewComponent_default({
      target: this.containerEl,
      props: {
        openFile: this.plugin.focusFile,
        hoverPreview: this.plugin.hoverPreview,
        title: "",
        showMenu: this.showMenu,
        showLevelSelect: this.showLevelSelect,
        showOrder: this.showOrder,
        newNote: this.newNote,
        openScrollView: this.plugin.openScrollView,
        isViewSwitchable: this.plugin.settings.useMultiPaneList,
        switchView: this.switchView,
        saveSettings: this.saveSettings.bind(this)
      }
    });
  }
  async onClose() {
    if (this.component) this.component.$destroy();
  }
}, HideItemsType = {
  NONE: "Hide nothing",
  DEDICATED_INTERMIDIATES: "Only intermediates of nested tags",
  ALL_EXCEPT_BOTTOM: "All intermediates"
};

function dotted(object, notation) {
  return notation.split(".").reduce(((a, b) => a && b in a ? a[b] : null), object);
}

function getCompareMethodItems(settings) {
  const invert = settings.sortType.contains("_DESC") ? -1 : 1;
  switch (settings.sortType) {
   case "DISPNAME_ASC":
   case "DISPNAME_DESC":
    return (a, b) => compare(a.displayName, b.displayName) * invert;

   case "FULLPATH_ASC":
   case "FULLPATH_DESC":
    return (a, b) => compare(a.path, b.path) * invert;

   case "MTIME_ASC":
   case "MTIME_DESC":
    return (a, b) => (a.mtime - b.mtime) * invert;

   case "CTIME_ASC":
   case "CTIME_DESC":
    return (a, b) => (a.ctime - b.ctime) * invert;

   case "NAME_ASC":
   case "NAME_DESC":
    return (a, b) => compare(a.filename, b.filename) * invert;

   default:
    console.warn("Compare method (items) corrupted");
    return (a, b) => compare(a.displayName, b.displayName) * invert;
  }
}

function onElement(el, event, selector, callback, options) {
  el.on(event, selector, callback, options);
  return () => el.off(event, selector, callback, options);
}

var TagFolderPlugin5 = class extends import_obsidian8.Plugin {
  constructor() {
    super(...arguments);
    this.settings = {
      ...DEFAULT_SETTINGS
    };
    this.expandedFolders = [ "root" ];
    this.currentOpeningFile = "";
    this.searchString = "";
    this.allViewItems = [];
    this.allViewItemsByLink = [];
    this.compareItems = (_, __) => 0;
    this.focusFile = (path, specialKey) => {
      if (this.currentOpeningFile == path) return;
      const _targetFile = this.app.vault.getAbstractFileByPath(path), targetFile = _targetFile instanceof import_obsidian8.TFile ? _targetFile : this.app.vault.getFiles().find((f => f.path === path));
      if (targetFile) if (specialKey) this.app.workspace.openLinkText(targetFile.path, targetFile.path, "tab"); else this.app.workspace.openLinkText(targetFile.path, targetFile.path);
    };
    this.fileCaches = [];
    this.oldFileCache = "";
    this.parsedFileCache = new Map;
    this.lastSettings = "";
    this.lastSearchString = "";
    this.processingFileInfo = false;
    this.loadFileQueue = [];
    this.loadFileTimer = void 0;
    this.tagInfo = {};
    this.tagInfoFrontMatterBuffer = {};
    this.skipOnce = false;
    this.tagInfoBody = "";
  }
  getView() {
    for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER)) {
      const view = leaf.view;
      if (view instanceof TagFolderView) return view;
    }
    return null;
  }
  getLinkView() {
    for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER_LINK)) {
      const view = leaf.view;
      if (view instanceof TagFolderView) return view;
    }
    return null;
  }
  hoverPreview(e, path) {
    this.app.workspace.trigger("hover-link", {
      event: e,
      source: "file-explorer",
      hoverParent: this,
      targetEl: e.target,
      linktext: path
    });
  }
  setSearchString(search) {
    searchString.set(search);
  }
  getFileTitle(file) {
    if (!this.settings.useTitle) return file.basename;
    const metadata = this.app.metadataCache.getCache(file.path);
    if ((null == metadata ? void 0 : metadata.frontmatter) && this.settings.frontmatterKey) {
      const d = dotted(metadata.frontmatter, this.settings.frontmatterKey);
      if (d) return `${d}`;
    }
    if (null == metadata ? void 0 : metadata.headings) {
      const h1 = metadata.headings.find((e => 1 == e.level));
      if (h1) return h1.heading;
    }
    return file.basename;
  }
  getDisplayName(file) {
    const filename = this.getFileTitle(file) || file.basename;
    if ("NAME" == this.settings.displayMethod) return filename;
    const path = file.path.split("/");
    path.pop();
    const displayPath = path.join("/");
    if ("NAME : PATH" == this.settings.displayMethod) return `${filename} : ${displayPath}`;
    if ("PATH/NAME" == this.settings.displayMethod) return `${displayPath}/${filename}`; else return filename;
  }
  async onload() {
    await this.loadSettings();
    this.hoverPreview = this.hoverPreview.bind(this);
    this.modifyFile = this.modifyFile.bind(this);
    this.setSearchString = this.setSearchString.bind(this);
    this.openScrollView = this.openScrollView.bind(this);
    this.loadFileInfo = (0, import_obsidian8.debounce)(this.loadFileInfo.bind(this), this.settings.scanDelay, true);
    this.registerView(VIEW_TYPE_TAGFOLDER, (leaf => new TagFolderView(leaf, this, "tags")));
    this.registerView(VIEW_TYPE_TAGFOLDER_LINK, (leaf => new TagFolderView(leaf, this, "links")));
    this.registerView(VIEW_TYPE_TAGFOLDER_LIST, (leaf => new TagFolderList(leaf, this)));
    this.registerView(VIEW_TYPE_SCROLL, (leaf => new ScrollView(leaf, this)));
    this.app.workspace.onLayoutReady((async () => {
      this.loadFileInfo();
      if (this.settings.alwaysOpen) {
        await this.initView();
        await this.activateView();
      }
    }));
    this.addCommand({
      id: "tagfolder-open",
      name: "Show Tag Folder",
      callback: () => {
        this.activateView();
      }
    });
    this.addCommand({
      id: "tagfolder-link-open",
      name: "Show Link Folder",
      callback: () => {
        this.activateViewLink();
      }
    });
    this.addCommand({
      id: "tagfolder-rebuild-tree",
      name: "Force Rebuild",
      callback: () => {
        this.refreshAllTree();
      }
    });
    this.addCommand({
      id: "tagfolder-create-similar",
      name: "Create a new note with the same tags",
      editorCallback: async (editor, view) => {
        var _a;
        const file = null == view ? void 0 : view.file;
        if (!file) return;
        const cache = this.app.metadataCache.getFileCache(file);
        if (!cache) return;
        const tagsWithoutPrefix = (null != (_a = (0, import_obsidian8.getAllTags)(cache)) ? _a : []).map((e => trimPrefix(e, "#")));
        await this.createNewNote(tagsWithoutPrefix);
      }
    });
    this.metadataCacheChanged = this.metadataCacheChanged.bind(this);
    this.watchWorkspaceOpen = this.watchWorkspaceOpen.bind(this);
    this.metadataCacheResolve = this.metadataCacheResolve.bind(this);
    this.metadataCacheResolved = this.metadataCacheResolved.bind(this);
    this.loadFileInfo = this.loadFileInfo.bind(this);
    this.registerEvent(this.app.metadataCache.on("changed", this.metadataCacheChanged));
    this.registerEvent(this.app.metadataCache.on("resolve", this.metadataCacheResolve));
    this.registerEvent(this.app.metadataCache.on("resolved", this.metadataCacheResolved));
    this.refreshAllTree = this.refreshAllTree.bind(this);
    this.refreshTree = this.refreshTree.bind(this);
    this.registerEvent(this.app.vault.on("rename", this.refreshTree));
    this.registerEvent(this.app.vault.on("delete", this.refreshTree));
    this.registerEvent(this.app.vault.on("modify", this.modifyFile));
    this.registerEvent(this.app.workspace.on("file-open", this.watchWorkspaceOpen));
    this.watchWorkspaceOpen(this.app.workspace.getActiveFile());
    this.addSettingTab(new TagFolderSettingTab(this.app, this));
    maxDepth.set(this.settings.expandLimit);
    if (this.settings.useTagInfo) this.app.workspace.onLayoutReady((async () => {
      await this.loadTagInfo();
    }));
    searchString.subscribe((search => {
      this.searchString = search;
      this.refreshAllTree();
    }));
    const setTagSearchString = (event, tagString) => {
      if (tagString) {
        const regExpTagStr = new RegExp(`(^|\\s)${tagString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\s|$)`, "u"), regExpTagStrInv = new RegExp(`(^|\\s)-${tagString.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\s|$)`, "u");
        if (event.altKey) return; else if (event.ctrlKey && event.shiftKey) {
          if (this.searchString.match(regExpTagStr)) this.setSearchString(this.searchString.replace(regExpTagStr, "")); else if (!this.searchString.match(regExpTagStrInv)) this.setSearchString(this.searchString + (0 == this.searchString.length ? "" : " ") + `-${tagString}`);
        } else if (event.ctrlKey) {
          if (this.searchString.match(regExpTagStrInv)) this.setSearchString(this.searchString.replace(regExpTagStrInv, "")); else if (!this.searchString.match(regExpTagStr)) this.setSearchString(this.searchString + (0 == this.searchString.length ? "" : " ") + `${tagString}`);
        } else this.setSearchString(tagString);
        event.preventDefault();
        event.stopPropagation();
      }
    };
    this.register(onElement(document, "click", 'a.tag[href^="#"]', ((event, targetEl) => {
      var _a;
      if (!this.settings.overrideTagClicking) return;
      const tagString = targetEl.innerText.substring(1);
      if (tagString) {
        setTagSearchString(event, tagString);
        const leaf = null == (_a = this.getView()) ? void 0 : _a.leaf;
        if (leaf) this.app.workspace.revealLeaf(leaf);
      }
    }), {
      capture: true
    }));
    this.register(onElement(document, "click", "span.cm-hashtag.cm-meta", ((event, targetEl) => {
      var _a;
      if (!this.settings.overrideTagClicking) return;
      let enumTags = targetEl, tagString = "";
      for (;!enumTags.classList.contains("cm-hashtag-begin"); ) {
        enumTags = enumTags.previousElementSibling;
        if (!enumTags) {
          console.log("Error! start tag not found.");
          return;
        }
      }
      do {
        if (enumTags instanceof HTMLElement) {
          tagString += enumTags.innerText;
          if (enumTags.classList.contains("cm-hashtag-end")) break;
        }
        enumTags = enumTags.nextElementSibling;
      } while (enumTags);
      tagString = tagString.substring(1);
      setTagSearchString(event, tagString);
      const leaf = null == (_a = this.getView()) ? void 0 : _a.leaf;
      if (leaf) this.app.workspace.revealLeaf(leaf);
    }), {
      capture: true
    }));
    selectedTags.subscribe((newTags => {
      this.openListView(newTags);
    }));
  }
  watchWorkspaceOpen(file) {
    if (file) this.currentOpeningFile = file.path; else this.currentOpeningFile = "";
    currentFile.set(this.currentOpeningFile);
  }
  metadataCacheChanged(file) {
    this.loadFileInfoAsync(file);
  }
  metadataCacheResolve(file) {
    if (null != this.getLinkView()) this.loadFileInfoAsync(file);
  }
  metadataCacheResolved() {
    if (null != this.getLinkView()) ;
  }
  refreshTree(file, oldName) {
    if (oldName) this.refreshAllTree(); else if (file instanceof import_obsidian8.TFile) this.loadFileInfo(file);
  }
  refreshAllTree() {
    this.loadFileInfo();
  }
  getFileCacheLinks(file) {
    const cachedLinks = this.app.metadataCache.resolvedLinks;
    return [ ...(null == this.getLinkView() ? [] : parseAllReference(cachedLinks, file.path, this.settings.linkConfig)).filter((e => e.endsWith(".md"))).map((e => `${e}`)) ];
  }
  getFileCacheData(file) {
    const metadata = this.app.metadataCache.getFileCache(file);
    if (!metadata) return false; else return {
      file,
      links: this.getFileCacheLinks(file),
      tags: (0, import_obsidian8.getAllTags)(metadata) || []
    };
  }
  updateFileCachesAll() {
    const caches = [ ...this.app.vault.getMarkdownFiles(), ...this.app.vault.getAllLoadedFiles().filter((e => "extension" in e && "canvas" == e.extension)) ].filter((file => {
      var _a;
      return null != (_a = this.parsedFileCache.get(file.path)) ? _a : 0 != file.stat.mtime;
    })).map((entry => this.getFileCacheData(entry))).filter((e => false !== e));
    this.fileCaches = [ ...caches ];
    return this.isFileCacheChanged();
  }
  isFileCacheChanged() {
    const fileCacheDump = JSON.stringify(this.fileCaches.map((e => ({
      path: e.file.path,
      links: e.links,
      tags: e.tags
    }))));
    if (this.oldFileCache == fileCacheDump) return false; else {
      this.oldFileCache = fileCacheDump;
      return true;
    }
  }
  updateFileCaches(diffs = []) {
    let anyUpdated = false;
    if (0 == this.fileCaches.length || 0 == diffs.length) return this.updateFileCachesAll(); else {
      const processDiffs = [ ...diffs ];
      let newCaches = [ ...this.fileCaches ], diff = processDiffs.shift();
      do {
        const procDiff = diff;
        if (!procDiff) break;
        const old = newCaches.find((fileCache => fileCache.file.path == procDiff.path));
        if (old) newCaches = newCaches.filter((fileCache => fileCache !== old));
        const newCache = this.getFileCacheData(procDiff);
        if (newCache) {
          if (null != this.getLinkView()) {
            const oldLinks = (null == old ? void 0 : old.links) || [], newLinks = newCache.links, diffs2 = unique([ ...oldLinks, ...newLinks ]).filter((link => !oldLinks.contains(link) || !newLinks.contains(link)));
            for (const filename of diffs2) {
              const file = this.app.vault.getAbstractFileByPath(filename);
              if (file instanceof import_obsidian8.TFile) processDiffs.push(file);
            }
          }
          newCaches.push(newCache);
        }
        anyUpdated = anyUpdated || JSON.stringify(fileCacheToCompare(old)) != JSON.stringify(fileCacheToCompare(newCache));
        diff = processDiffs.shift();
      } while (void 0 !== diff);
      this.fileCaches = newCaches;
    }
    return anyUpdated;
  }
  async getItemsList(mode) {
    const items = [], ignoreDocTags = this.settings.ignoreDocTags.toLowerCase().replace(/[\n ]/g, "").split(","), ignoreTags = this.settings.ignoreTags.toLowerCase().replace(/[\n ]/g, "").split(","), ignoreFolders = this.settings.ignoreFolders.toLowerCase().replace(/\n/g, "").split(",").map((e => e.trim())).filter((e => !!e)), targetFolders = this.settings.targetFolders.toLowerCase().replace(/\n/g, "").split(",").map((e => e.trim())).filter((e => !!e)), searchItems = this.searchString.toLowerCase().split("|").map((ee => ee.split(" ").map((e => e.trim())))), today = Date.now(), archiveTags = this.settings.archiveTags.toLowerCase().replace(/[\n ]/g, "").split(",");
    for (const fileCache of this.fileCaches) {
      if (targetFolders.length > 0 && !targetFolders.some((e => "" != e && fileCache.file.path.toLowerCase().startsWith(e)))) continue;
      if (ignoreFolders.some((e => "" != e && fileCache.file.path.toLowerCase().startsWith(e)))) continue;
      await doEvents();
      const tagRedirectList = {};
      if (this.settings.useTagInfo && this.tagInfo) for (const [key, taginfo] of Object.entries(this.tagInfo)) if (null == taginfo ? void 0 : taginfo.redirect) tagRedirectList[key] = taginfo.redirect;
      let allTags = [];
      if ("tag" == mode) {
        const allTagsDocs = unique(fileCache.tags);
        allTags = unique(allTagsDocs.map((e => e.substring(1))).map((e => e in tagRedirectList ? tagRedirectList[e] : e)));
      } else allTags = unique(fileCache.links);
      if (this.settings.disableNestedTags && "tag" == mode) allTags = allTags.map((e => e.split("/"))).flat();
      if (0 == allTags.length) if ("tag" == mode) allTags = [ "_untagged" ]; else if ("link" == mode) allTags = [ "_unlinked" ];
      if ("canvas" == fileCache.file.extension) allTags.push("_VIRTUAL_TAG_CANVAS");
      if (this.settings.useVirtualTag) {
        const disp = secondsToFreshness(today - fileCache.file.stat.mtime);
        allTags.push(`_VIRTUAL_TAG_FRESHNESS/${disp}`);
      }
      if (allTags.some((tag => ignoreDocTags.contains(tag.toLowerCase())))) continue;
      if (searchItems.map((searchItem => {
        let bx = false;
        if (0 == allTags.length) return false;
        for (const searchSrc of searchItem) {
          let search = searchSrc, func = "contains";
          if (search.startsWith("#")) {
            search = search.substring(1);
            func = "startsWith";
          }
          if (search.startsWith("-")) bx = bx || allTags.some((tag => tag.toLowerCase()[func](search.substring(1)))); else bx = bx || allTags.every((tag => !tag.toLowerCase()[func](search)));
        }
        return bx;
      })).every((e => e))) continue;
      allTags = allTags.filter((tag => !ignoreTags.contains(tag.toLowerCase())));
      const links = [ ...fileCache.links ];
      if (0 == links.length) links.push("_unlinked");
      if (this.settings.disableNarrowingDown && "tag" == mode) {
        const archiveTagsMatched = allTags.filter((e => archiveTags.contains(e.toLowerCase()))), targetTags = 0 == archiveTagsMatched.length ? allTags : archiveTagsMatched;
        for (const tags of targetTags) items.push({
          tags: [ tags ],
          extraTags: allTags.filter((e => e != tags)),
          path: fileCache.file.path,
          displayName: this.getDisplayName(fileCache.file),
          ancestors: [],
          mtime: fileCache.file.stat.mtime,
          ctime: fileCache.file.stat.ctime,
          filename: fileCache.file.basename,
          links
        });
      } else items.push({
        tags: allTags,
        extraTags: [],
        path: fileCache.file.path,
        displayName: this.getDisplayName(fileCache.file),
        ancestors: [],
        mtime: fileCache.file.stat.mtime,
        ctime: fileCache.file.stat.ctime,
        filename: fileCache.file.basename,
        links
      });
    }
    return items;
  }
  loadFileInfo(diff) {
    this.loadFileInfoAsync(diff).then((e => {}));
  }
  isSettingChanged() {
    const strSetting = JSON.stringify(this.settings), isSettingChanged = strSetting != this.lastSettings, isSearchStringModified = this.searchString != this.lastSearchString;
    if (isSettingChanged) this.lastSettings = strSetting;
    if (isSearchStringModified) this.lastSearchString = this.searchString;
    return isSearchStringModified || isSettingChanged;
  }
  async loadFileInfos(diffs) {
    if (!this.processingFileInfo) try {
      this.processingFileInfo = true;
      const cacheUpdated = this.updateFileCaches(diffs);
      if (this.isSettingChanged() || cacheUpdated) {
        appliedFiles.set(diffs.map((e => e.path)));
        await this.applyFileInfoToView();
      }
      await this.applyUpdateIntoScroll(diffs);
      const af = this.app.workspace.getActiveFile();
      if (af && this.currentOpeningFile != af.path) {
        this.currentOpeningFile = af.path;
        currentFile.set(this.currentOpeningFile);
      }
    } finally {
      this.processingFileInfo = false;
    } else diffs.forEach((e => this.loadFileInfoAsync(e)));
  }
  async applyFileInfoToView() {
    const itemsSorted = (await this.getItemsList("tag")).sort(this.compareItems);
    this.allViewItems = itemsSorted;
    allViewItems.set(this.allViewItems);
    if (null != this.getLinkView()) {
      const itemsLink = await this.getItemsList("link");
      updateItemsLinkMap(itemsLink);
      const itemsLinkSorted = itemsLink.sort(this.compareItems);
      this.allViewItemsByLink = itemsLinkSorted;
      allViewItemsByLink.set(this.allViewItemsByLink);
    }
  }
  async loadFileInfoAsync(diff) {
    if (diff) {
      if (diff && this.loadFileQueue.some((e => e.path == (null == diff ? void 0 : diff.path)))) ; else this.loadFileQueue.push(diff);
      if (this.loadFileTimer) clearTimeout(this.loadFileTimer);
      this.loadFileTimer = setTimeout((() => {
        if (0 === this.loadFileQueue.length) ; else {
          const diffs = [ ...this.loadFileQueue ];
          this.loadFileQueue = [];
          this.loadFileInfos(diffs);
        }
      }), 200);
    } else {
      this.loadFileQueue = [];
      if (this.loadFileTimer) {
        clearTimeout(this.loadFileTimer);
        this.loadFileTimer = void 0;
      }
      await this.loadFileInfos([]);
    }
  }
  onunload() {}
  async openScrollView(leaf, title, tagPath, files) {
    if (!leaf) leaf = this.app.workspace.getLeaf("split");
    await leaf.setViewState({
      type: VIEW_TYPE_SCROLL,
      active: true,
      state: {
        files: files.map((e => ({
          path: e
        }))),
        title,
        tagPath
      }
    });
    this.app.workspace.revealLeaf(leaf);
  }
  async applyUpdateIntoScroll(files) {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_SCROLL);
    for (const leaf of leaves) {
      const view = leaf.view;
      if (!view) continue;
      const viewState = leaf.getViewState(), scrollViewState = null == view ? void 0 : view.getScrollViewState();
      if (!viewState || !scrollViewState) continue;
      const viewStat = {
        ...viewState,
        state: {
          ...scrollViewState
        }
      };
      for (const file of files) if (file && view.isFileOpened(file.path)) {
        const newStat = {
          ...viewStat,
          state: {
            ...viewStat.state,
            files: viewStat.state.files.map((e => e.path == file.path ? {
              path: file.path
            } : e))
          }
        };
        await leaf.setViewState(newStat);
      }
      const tags = viewStat.state.tagPath.split(", ");
      let matchedFiles = this.allViewItems;
      for (const tag of tags) matchedFiles = matchedFiles.filter((item => item.tags.map((tag2 => tag2.toLowerCase())).some((itemTag => itemTag == tag.toLowerCase() || (itemTag + "/").startsWith(tag.toLowerCase() + (tag.endsWith("/") ? "" : "/"))))));
      const newFilesArray = matchedFiles.map((e => e.path));
      if (newFilesArray.sort().join("-") != viewStat.state.files.map((e => e.path)).sort().join("-")) {
        const newStat = {
          ...viewStat,
          state: {
            ...viewStat.state,
            files: newFilesArray.map((path => {
              const old = viewStat.state.files.find((e => e.path == path));
              if (old) return old; else return {
                path
              };
            }))
          }
        };
        await leaf.setViewState(newStat);
      }
    }
  }
  async _initTagView() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER);
    if (0 == leaves.length) await this.app.workspace.getLeftLeaf(false).setViewState({
      type: VIEW_TYPE_TAGFOLDER,
      state: {
        treeViewType: "tags"
      }
    }); else {
      const newState = leaves[0].getViewState();
      leaves[0].setViewState({
        type: VIEW_TYPE_TAGFOLDER,
        state: {
          ...newState,
          treeViewType: "tags"
        }
      });
    }
  }
  async _initLinkView() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER_LINK);
    if (0 == leaves.length) await this.app.workspace.getLeftLeaf(false).setViewState({
      type: VIEW_TYPE_TAGFOLDER_LINK,
      state: {
        treeViewType: "links"
      }
    }); else {
      const newState = leaves[0].getViewState();
      leaves[0].setViewState({
        type: VIEW_TYPE_TAGFOLDER_LINK,
        state: {
          ...newState,
          treeViewType: "links"
        }
      });
    }
  }
  async initView() {
    this.loadFileInfo();
    await this._initTagView();
  }
  async initLinkView() {
    this.loadFileInfo();
    await this._initLinkView();
  }
  async activateView() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER);
    await this.initView();
    if (leaves.length > 0) this.app.workspace.revealLeaf(leaves[0]);
  }
  async activateViewLink() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER_LINK);
    await this.initLinkView();
    if (leaves.length > 0) this.app.workspace.revealLeaf(leaves[0]);
  }
  async modifyFile(file) {
    if (this.settings.useTagInfo) if (!this.skipOnce) {
      if (file.name == this.getTagInfoFilename()) await this.loadTagInfo();
    } else this.skipOnce = false;
  }
  getTagInfoFilename() {
    return (0, import_obsidian8.normalizePath)(this.settings.tagInfo);
  }
  getTagInfoFile() {
    const file = this.app.vault.getAbstractFileByPath(this.getTagInfoFilename());
    if (file instanceof import_obsidian8.TFile) return file; else return null;
  }
  applyTagInfo() {
    if (null != this.tagInfo) if (this.settings.useTagInfo) tagInfo.set(this.tagInfo);
  }
  async loadTagInfo() {
    if (!this.settings.useTagInfo) return;
    if (null == this.tagInfo) this.tagInfo = {};
    const file = this.getTagInfoFile();
    if (null == file) return;
    const data = await this.app.vault.read(file);
    try {
      const bodyStartIndex = data.indexOf("\n---");
      if (!data.startsWith("---") || -1 === bodyStartIndex) return;
      const yaml = data.substring(3, bodyStartIndex), yamlData = (0, import_obsidian8.parseYaml)(yaml), keys = Object.keys(yamlData);
      this.tagInfoBody = data.substring(bodyStartIndex + 5);
      this.tagInfoFrontMatterBuffer = yamlData;
      const newTagInfo = {};
      for (const key of keys) {
        const w = yamlData[key];
        if (!w) continue;
        if ("object" != typeof w) continue;
        const keys2 = [ "key", "mark", "alt", "redirect" ], entries = Object.entries(w).filter((([key2]) => keys2.some((e => key2.contains(e)))));
        if (0 != entries.length) newTagInfo[key] = Object.fromEntries(entries);
      }
      this.tagInfo = newTagInfo;
      this.applyTagInfo();
    } catch (ex) {
      console.log(ex);
    }
  }
  async saveTagInfo() {
    if (!this.settings.useTagInfo) return;
    if (null == this.tagInfo) return;
    let file = this.getTagInfoFile();
    if (null == file) file = await this.app.vault.create(this.getTagInfoFilename(), "");
    await app.fileManager.processFrontMatter(file, (matter => {
      const ti = Object.entries(this.tagInfo);
      for (const [key, value] of ti) if (void 0 === value) delete matter[key]; else matter[key] = value;
    }));
  }
  async refreshAllViewItems() {
    this.parsedFileCache.clear();
    const itemsSorted = (await this.getItemsList("tag")).sort(this.compareItems);
    this.allViewItems = itemsSorted;
    allViewItems.set(this.allViewItems);
    const itemsLinkSorted = (await this.getItemsList("link")).sort(this.compareItems);
    this.allViewItemsByLink = itemsLinkSorted;
    allViewItemsByLink.set(this.allViewItemsByLink);
  }
  async loadSettings() {
    this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    await this.loadTagInfo();
    tagFolderSetting.set(this.settings);
    this.compareItems = getCompareMethodItems(this.settings);
  }
  async saveSettings() {
    await this.saveData(this.settings);
    await this.saveTagInfo();
    tagFolderSetting.set(this.settings);
    this.compareItems = getCompareMethodItems(this.settings);
    this.refreshAllViewItems();
  }
  async openListView(tagSrc) {
    var _a;
    if (!tagSrc) return;
    const tags = "root" == tagSrc.first() ? tagSrc.slice(1) : tagSrc;
    let theLeaf;
    for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER_LIST)) {
      const state = leaf.getViewState();
      if (state.state.tags.slice().sort().join("-") == tags.slice().sort().join("-")) {
        this.app.workspace.setActiveLeaf(leaf, {
          focus: true
        });
        return;
      }
      if (state.pinned) ; else theLeaf = leaf;
    }
    if (!theLeaf) {
      const parent = null == (_a = this.app.workspace.getLeavesOfType(VIEW_TYPE_TAGFOLDER)) ? void 0 : _a.first();
      if (!parent) return;
      switch (this.settings.showListIn) {
       case "CURRENT_PANE":
        theLeaf = this.app.workspace.getLeaf();
        break;

       case "SPLIT_PANE":
        theLeaf = this.app.workspace.getLeaf("split", "horizontal");
        break;

       case "":
       default:
        if (!import_obsidian8.Platform.isMobile) theLeaf = this.app.workspace.createLeafBySplit(parent, "horizontal", false); else theLeaf = this.app.workspace.getLeftLeaf(false);
        break;
      }
    }
    const title = tags.map((e => e.split("/").map((ee => renderSpecialTag(ee))).join("/"))).join(" ");
    await theLeaf.setViewState({
      type: VIEW_TYPE_TAGFOLDER_LIST,
      active: true,
      state: {
        tags,
        title
      }
    });
    this.app.workspace.revealLeaf(theLeaf);
  }
  async createNewNote(tags) {
    const expandedTagsAll = ancestorToLongestTag(ancestorToTags(joinPartialPath(removeIntermediatePath(null != tags ? tags : [])))).map((e => trimTrailingSlash(e))), expandedTags = expandedTagsAll.map((e => e.split("/").filter((ee => !isSpecialTag(ee))).join("/"))).filter((e => "" != e)).map((e => "#" + e)).join(" ").trim(), ww = await this.app.fileManager.createAndOpenMarkdownFile();
    if (this.settings.useFrontmatterTagsForNewNotes) await this.app.fileManager.processFrontMatter(ww, (matter => {
      var _a;
      matter.tags = null != (_a = matter.tags) ? _a : [];
      matter.tags = expandedTagsAll.filter((e => !isSpecialTag(e))).filter((e => matter.tags.indexOf(e) < 0)).concat(matter.tags);
    })); else await this.app.vault.append(ww, expandedTags);
  }
}, TagFolderSettingTab = class extends import_obsidian8.PluginSettingTab {
  constructor(app2, plugin) {
    super(app2, plugin);
    this.plugin = plugin;
  }
  hide() {
    this.plugin.loadFileInfo();
  }
  display() {
    const {containerEl} = this;
    containerEl.empty();
    containerEl.createEl("h2", {
      text: "Settings for TagFolder"
    });
    containerEl.createEl("h3", {
      text: "Behavior"
    });
    new import_obsidian8.Setting(containerEl).setName("Always Open").setDesc("Place TagFolder on the left pane and activate it at every Obsidian launch").addToggle((toggle => toggle.setValue(this.plugin.settings.alwaysOpen).onChange((async value => {
      this.plugin.settings.alwaysOpen = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Use pinning").setDesc("When this feature is enabled, the pin information is saved in the file set in the next configuration.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.useTagInfo).onChange((async value => {
        this.plugin.settings.useTagInfo = value;
        if (this.plugin.settings.useTagInfo) await this.plugin.loadTagInfo();
        await this.plugin.saveSettings();
        pi.setDisabled(!value);
      }));
    }));
    const pi = new import_obsidian8.Setting(containerEl).setName("Pin information file").setDisabled(!this.plugin.settings.useTagInfo).addText((text2 => {
      text2.setValue(this.plugin.settings.tagInfo).onChange((async value => {
        this.plugin.settings.tagInfo = value;
        if (this.plugin.settings.useTagInfo) await this.plugin.loadTagInfo();
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Disable narrowing down").setDesc("When this feature is enabled, relevant tags will be shown with the title instead of making a sub-structure.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.disableNarrowingDown).onChange((async value => {
        this.plugin.settings.disableNarrowingDown = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Files"
    });
    new import_obsidian8.Setting(containerEl).setName("Display method").setDesc("How to show a title of files").addDropdown((dropdown => dropdown.addOptions({
      "PATH/NAME": "PATH/NAME",
      NAME: "NAME",
      "NAME : PATH": "NAME : PATH"
    }).setValue(this.plugin.settings.displayMethod).onChange((async value => {
      this.plugin.settings.displayMethod = value;
      this.plugin.loadFileInfo();
      await this.plugin.saveSettings();
    }))));
    const setOrderMethod = async (key, order) => {
      const oldSetting = this.plugin.settings.sortType.split("_");
      if (!key) key = oldSetting[0];
      if (!order) order = oldSetting[1];
      this.plugin.settings.sortType = `${key}_${order}`;
      await this.plugin.saveSettings();
    };
    new import_obsidian8.Setting(containerEl).setName("Order method").setDesc("how to order items").addDropdown((dd => {
      dd.addOptions(OrderKeyItem).setValue(this.plugin.settings.sortType.split("_")[0]).onChange((key => setOrderMethod(key, void 0)));
    })).addDropdown((dd => {
      dd.addOptions(OrderDirection).setValue(this.plugin.settings.sortType.split("_")[1]).onChange((order => setOrderMethod(void 0, order)));
    }));
    new import_obsidian8.Setting(containerEl).setName("Prioritize items which are not contained in sub-folder").setDesc("If this has been enabled, the items which have no more extra tags are first.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.sortExactFirst).onChange((async value => {
        this.plugin.settings.sortExactFirst = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Use title").setDesc("Use value in the frontmatter or first level one heading for `NAME`.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.useTitle).onChange((async value => {
        this.plugin.settings.useTitle = value;
        fpath.setDisabled(!value);
        await this.plugin.saveSettings();
      }));
    }));
    const fpath = new import_obsidian8.Setting(containerEl).setName("Frontmatter path").setDisabled(!this.plugin.settings.useTitle).addText((text2 => {
      text2.setValue(this.plugin.settings.frontmatterKey).onChange((async value => {
        this.plugin.settings.frontmatterKey = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Tags"
    });
    const setOrderMethodTag = async (key, order) => {
      const oldSetting = this.plugin.settings.sortTypeTag.split("_");
      if (!key) key = oldSetting[0];
      if (!order) order = oldSetting[1];
      this.plugin.settings.sortTypeTag = `${key}_${order}`;
      await this.plugin.saveSettings();
    };
    new import_obsidian8.Setting(containerEl).setName("Order method").setDesc("how to order tags").addDropdown((dd => {
      dd.addOptions(OrderKeyTag).setValue(this.plugin.settings.sortTypeTag.split("_")[0]).onChange((key => setOrderMethodTag(key, void 0)));
    })).addDropdown((dd => {
      dd.addOptions(OrderDirection).setValue(this.plugin.settings.sortTypeTag.split("_")[1]).onChange((order => setOrderMethodTag(void 0, order)));
    }));
    new import_obsidian8.Setting(containerEl).setName("Use virtual tags").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.useVirtualTag).onChange((async value => {
        this.plugin.settings.useVirtualTag = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Store tags in frontmatter for new notes").setDesc("Otherwise, tags are stored with #hashtags at the top of the note").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.useFrontmatterTagsForNewNotes).onChange((async value => {
        this.plugin.settings.useFrontmatterTagsForNewNotes = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Actions"
    });
    new import_obsidian8.Setting(containerEl).setName("Search tags inside TagFolder when clicking tags").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.overrideTagClicking).onChange((async value => {
        this.plugin.settings.overrideTagClicking = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("List files in a separated pane").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.useMultiPaneList).onChange((async value => {
        this.plugin.settings.useMultiPaneList = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Show list in").setDesc("This option applies to the newly opened list").addDropdown((dropdown => {
      dropdown.addOptions(enumShowListIn).setValue(this.plugin.settings.showListIn).onChange((async value => {
        this.plugin.settings.showListIn = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Arrangements"
    });
    new import_obsidian8.Setting(containerEl).setName("Hide Items").setDesc("Hide items on the landing or nested tags").addDropdown((dd => {
      dd.addOptions(HideItemsType).setValue(this.plugin.settings.hideItems).onChange((async key => {
        if ("NONE" == key || "DEDICATED_INTERMIDIATES" == key || "ALL_EXCEPT_BOTTOM" == key) this.plugin.settings.hideItems = key;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Merge redundant combinations").setDesc("When this feature is enabled, a/b and b/a are merged into a/b if there is no intermediates.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.mergeRedundantCombination).onChange((async value => {
        this.plugin.settings.mergeRedundantCombination = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Do not simplify empty folders").setDesc("Keep empty folders, even if they can be simplified.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.doNotSimplifyTags).onChange((async value => {
        this.plugin.settings.doNotSimplifyTags = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Do not treat nested tags as dedicated levels").setDesc("Treat nested tags as normal tags").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.disableNestedTags).onChange((async value => {
        this.plugin.settings.disableNestedTags = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Reduce duplicated parents in nested tags").setDesc("If enabled, #web/css, #web/javascript will merged into web -> css -> javascript").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.reduceNestedParent).onChange((async value => {
        this.plugin.settings.reduceNestedParent = value;
        await this.plugin.saveSettings();
      }));
    }));
    new import_obsidian8.Setting(containerEl).setName("Keep untagged items on the root").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.expandUntaggedToRoot).onChange((async value => {
        this.plugin.settings.expandUntaggedToRoot = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Link Folder"
    });
    new import_obsidian8.Setting(containerEl).setName("Use Incoming").setDesc("").addToggle((toggle => toggle.setValue(this.plugin.settings.linkConfig.incoming.enabled).onChange((async value => {
      this.plugin.settings.linkConfig.incoming.enabled = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Use Outgoing").setDesc("").addToggle((toggle => toggle.setValue(this.plugin.settings.linkConfig.outgoing.enabled).onChange((async value => {
      this.plugin.settings.linkConfig.outgoing.enabled = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Hide indirectly linked notes").setDesc("").addToggle((toggle => toggle.setValue(this.plugin.settings.linkShowOnlyFDR).onChange((async value => {
      this.plugin.settings.linkShowOnlyFDR = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Connect linked tree").setDesc("").addToggle((toggle => toggle.setValue(this.plugin.settings.linkCombineOtherTree).onChange((async value => {
      this.plugin.settings.linkCombineOtherTree = value;
      await this.plugin.saveSettings();
    }))));
    containerEl.createEl("h3", {
      text: "Filters"
    });
    new import_obsidian8.Setting(containerEl).setName("Target Folders").setDesc("If configured, the plugin will only target files in it.").addTextArea((text2 => text2.setValue(this.plugin.settings.targetFolders).setPlaceholder("study,documents/summary").onChange((async value => {
      this.plugin.settings.targetFolders = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Ignore Folders").setDesc("Ignore documents in specific folders.").addTextArea((text2 => text2.setValue(this.plugin.settings.ignoreFolders).setPlaceholder("template,list/standard_tags").onChange((async value => {
      this.plugin.settings.ignoreFolders = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Ignore note Tag").setDesc("If the note has the tag listed below, the note would be treated as there was not.").addTextArea((text2 => text2.setValue(this.plugin.settings.ignoreDocTags).setPlaceholder("test,test1,test2").onChange((async value => {
      this.plugin.settings.ignoreDocTags = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Ignore Tag").setDesc("Tags in the list would be treated as there were not.").addTextArea((text2 => text2.setValue(this.plugin.settings.ignoreTags).setPlaceholder("test,test1,test2").onChange((async value => {
      this.plugin.settings.ignoreTags = value;
      await this.plugin.saveSettings();
    }))));
    new import_obsidian8.Setting(containerEl).setName("Archive tags").setDesc("If configured, notes with these tags will be moved under the tag.").addTextArea((text2 => text2.setValue(this.plugin.settings.archiveTags).setPlaceholder("archived, discontinued").onChange((async value => {
      this.plugin.settings.archiveTags = value;
      await this.plugin.saveSettings();
    }))));
    containerEl.createEl("h3", {
      text: "Misc"
    });
    new import_obsidian8.Setting(containerEl).setName("Tag scanning delay").setDesc("Sets the delay for reflecting metadata changes to the tag tree. (Plugin reload is required.)").addText((text2 => {
      (text2 = text2.setValue(this.plugin.settings.scanDelay + "").onChange((async value => {
        const newDelay = Number.parseInt(value, 10);
        if (newDelay) {
          this.plugin.settings.scanDelay = newDelay;
          await this.plugin.saveSettings();
        }
      }))).inputEl.setAttribute("type", "number");
      text2.inputEl.setAttribute("min", "250");
      return text2;
    }));
    new import_obsidian8.Setting(containerEl).setName("Disable dragging tags").setDesc("The `Dragging tags` is using internal APIs. If something happens, please disable this once and try again.").addToggle((toggle => {
      toggle.setValue(this.plugin.settings.disableDragging).onChange((async value => {
        this.plugin.settings.disableDragging = value;
        await this.plugin.saveSettings();
      }));
    }));
    containerEl.createEl("h3", {
      text: "Utilities"
    });
    new import_obsidian8.Setting(containerEl).setName("Dumping tags for reporting bugs").setDesc("If you want to open an issue to the GitHub, this information can be useful. and, also if you want to keep secrets about names of tags, you can use `disguised`.").addButton((button => button.setButtonText("Copy tags").setDisabled(false).onClick((async () => {
      const items = (await this.plugin.getItemsList("tag")).map((e => e.tags.filter((e2 => "_untagged" != e2)))).filter((e => e.length));
      await navigator.clipboard.writeText(items.map((e => e.map((e2 => `#${e2}`)).join(", "))).join("\n"));
      new import_obsidian8.Notice("Copied to clipboard");
    })))).addButton((button => button.setButtonText("Copy disguised tags").setDisabled(false).onClick((async () => {
      const x = new Map;
      let i = 0;
      const items = (await this.plugin.getItemsList("tag")).map((e => e.tags.filter((e2 => "_untagged" != e2)).map((e2 => x.has(e2) ? x.get(e2) : (x.set(e2, i++), 
      i))))).filter((e => e.length));
      await navigator.clipboard.writeText(items.map((e => e.map((e2 => `#tag${e2}`)).join(", "))).join("\n"));
      new import_obsidian8.Notice("Copied to clipboard");
    }))));
  }
};