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

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    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;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// main.ts
var main_exports = {};
__export(main_exports, {
  DEFAULT_SETTINGS: () => DEFAULT_SETTINGS,
  default: () => ColorfulTag2
});
module.exports = __toCommonJS(main_exports);
var import_obsidian8 = require("obsidian");

// src/utils/css.ts
var css = class {
};
css.defaultCss = `
    .small-input > .setting-item-control > input {
        width: 60px;
    }
    .small-button {
        padding-left: 8px;
        padding-right: 8px;
    }
    .vertical-tab-content {
        overflow-y: overlay;
    }
    .setting-item:first-child {
        padding-top: 0.75em;
    }
    .colorful-tag-setting-header > div > div > .setting-item {
        border-bottom: 1px solid var(--background-modifier-border);
    }
    .colorful-tag-collapse-indicator > svg {
        height: 10px;
        width: 10px;
        margin-right: 8px;
        transform: rotate(90deg);
    }
    .colorful-tag-collapse-indicator.is-collapsed > svg {
        transform: rotate(0deg);
    }
    .colorful-tag-setting-header.is-collapsed > .colorful-tag-setting-body {
        display: none;
    }
    .colorful-tag-popup {
        min-width: 250px;
        min-height: 50px;
        position: absolute;
        transition-property: opacity;
        transition-duration: 0.35s;
        animation-name: fadeIn;
        animation-duration: 0.3s;
    }
    .colorful-tag-popup.hidden {
        opacity: 0;
    }
    .colorful-tag-popup-pin {
        margin-left: auto;
    }
    .colorful-tag-popup-header {
        vertical-align: middle;
        line-height: 24px;
    }
    .colorful-tag-popup-pin > svg {
        vertical-align: middle;
    }
    .colorful-tag-popup-pin.pinned > svg {
        transform: rotate(45deg);
        fill: white;
    }
    .setting-item.colorful-tag-popup-item {
        padding-top: 5px;
        padding-bottom: 5px;
    }
    .colorful-tag-popup-body {
        background-color: var(--background-primary);
    }
	.colorful-tag-popup input[type="text"] {
        border: none;
    }
	.colorful-tag-popup input[type="text"]:focus {
        border: inherit;
    }
    .colorful-tag-popup-body .setting-item-control > textarea {
        border: none;
        resize: vertical;
    }
    .colorful-tag-popup-body .setting-item-control > textarea.readonly {
        resize: none;
    }
    .shadow-text-start {
        vertical-align: bottom;
        font-size: var(--font-smaller);
        color: var(--text-muted);
    }
    .shadow-text-end {
        vertical-align: bottom;
        font-size: var(--font-smaller);
        color: var(--text-muted);
    }
    .colorful-tag-handler > svg {
        vertical-align: middle;
    }
    `;

// src/plugin/shadowTextPlugin.ts
var import_view = require("@codemirror/view");
var import_language = require("@codemirror/language");
var import_view2 = require("@codemirror/view");
var import_view3 = require("@codemirror/view");

// src/tagDetail/fileTagDetail.ts
var import_obsidian2 = require("obsidian");

// src/tagDetail/perTagDetail.ts
var import_obsidian = require("obsidian");

// src/utils/attributeType.ts
var SizeType = /* @__PURE__ */ ((SizeType2) => {
  SizeType2["px"] = "px";
  SizeType2["em"] = "em";
  SizeType2["percent"] = "%";
  SizeType2["rem"] = "rem";
  return SizeType2;
})(SizeType || {});
var AttributeType = /* @__PURE__ */ ((AttributeType2) => {
  AttributeType2["Text"] = "Text";
  AttributeType2["Boolean"] = "Boolean";
  AttributeType2["Color"] = "Color";
  AttributeType2["Size"] = "Size";
  AttributeType2["Number"] = "Number";
  AttributeType2["Date"] = "Date";
  AttributeType2["Dropdown"] = "Dropdown";
  AttributeType2["ReadOnly"] = "ReadOnly";
  AttributeType2["Any"] = "Any";
  return AttributeType2;
})(AttributeType || {});

// src/tagDetail/perTagDetail.ts
var perTagDetail = class {
  constructor(plugin, tagSetting, fileTagDetail, i) {
    this.state = 1 /* ENTER */;
    this.plugin = plugin;
    this.tagSetting = tagSetting;
    this.fileTagDetail = fileTagDetail;
    this.index = i;
    this.popuped = false;
  }
  updateShadowText() {
    let template = this.tagSetting.tagDetail.shadowTextTemplate;
    if (!template || template == "")
      return;
    let value = this.fileTagDetail.getTagData(this.index);
    if (value == null)
      return;
    let defaultValue = this.tagSetting.tagDetail.attributes;
    let items = this.tagSetting.tagDetail.itemType;
    items.forEach((item, k) => {
      let dValue = defaultValue.get(k);
      let key = item[0] || "";
      let v = value.get(key) || dValue || "";
      template = template.replace(`{{${key}}}`, v);
    });
    let temps = template.split("{{TAG}}");
    if (temps.length != 2)
      return;
    let pair = [temps[0], temps[1]];
    FileTagDetail.shadowText[this.index] = pair;
  }
  updateMetaDefaultValues(dValue) {
    if (dValue == null)
      return null;
    dValue = dValue.replace(/{{TAG}}/g, this.tagSetting.name);
    dValue = dValue.replace(/{{DATE}}/g, new Date().toLocaleDateString());
    dValue = dValue.replace(/{{TIME}}/g, new Date().toLocaleTimeString());
    dValue = dValue.replace(/{{DATETIME}}/g, new Date().toLocaleString());
    dValue = dValue.replace(/{{FILE}}/g, this.plugin.app.workspace.getActiveFile().basename);
    dValue = dValue.replace(/{{PATH}}/g, this.plugin.app.workspace.getActiveFile().path);
    return dValue;
  }
  popupBody(body) {
    let defaultValue = this.tagSetting.tagDetail.attributes;
    let items = this.tagSetting.tagDetail.itemType;
    let storeData = this.fileTagDetail.getTagData(this.index);
    if (storeData == null) {
      new import_obsidian.Setting(body).addButton(async (cp) => {
        cp.setButtonText("Add").onClick(async () => {
          this.fileTagDetail.addTagData(this.index);
          await this.fileTagDetail.writeFrontmatter();
          body.childNodes.forEach((v) => v.remove());
          this.popupBody(body);
        });
      });
      return;
    }
    items.forEach((item, k) => {
      let dValue = defaultValue.get(k);
      let setting = new import_obsidian.Setting(body);
      if (!item[0])
        return;
      let key = item[0];
      setting.setName(key);
      dValue = this.updateMetaDefaultValues(dValue || null);
      let value = storeData.get(key) || dValue;
      if (!storeData.get(key) && dValue && item[1] != "ReadOnly" /* ReadOnly */) {
        storeData.set(key, dValue);
        this.fileTagDetail.setTagData(this.index, storeData);
        this.updateShadowText();
        this.fileTagDetail.writeFrontmatter();
        return;
      }
      switch (item[1]) {
        case "Boolean" /* Boolean */: {
          setting.addDropdown((cp) => {
            cp.addOption("True" /* True */, "True").addOption("False" /* False */, "False").setValue(value || "").onChange(async (v) => {
              storeData.set(key, v);
              this.fileTagDetail.setTagData(this.index, storeData);
              this.updateShadowText();
              await this.fileTagDetail.writeFrontmatter();
            });
          });
          break;
        }
        case "Dropdown" /* Dropdown */: {
          let data_ = item[2] || "";
          let options = data_.split(",");
          setting.addDropdown((cp) => {
            options.forEach((v) => {
              cp.addOption(v, v);
            });
            cp.setValue(value || "").onChange(async (v) => {
              storeData == null ? void 0 : storeData.set(key, v);
              this.fileTagDetail.setTagData(this.index, storeData);
              this.updateShadowText();
              await this.fileTagDetail.writeFrontmatter();
            });
          });
          break;
        }
        case "Color" /* Color */: {
          setting.addColorPicker((cp) => {
            cp.setValue(value || "#000000").onChange(async (v) => {
              storeData == null ? void 0 : storeData.set(key, v);
              this.fileTagDetail.setTagData(this.index, storeData);
              this.updateShadowText();
              await this.fileTagDetail.writeFrontmatter();
            });
          });
          break;
        }
        case "ReadOnly" /* ReadOnly */: {
          setting.addTextArea((cp) => {
            cp.setValue(dValue || "").setDisabled(true).inputEl.addClass("readonly");
          });
          break;
        }
        default: {
          setting.addTextArea((cp) => {
            cp.setValue(storeData.get(key) || dValue || "").onChange(async (v) => {
              storeData == null ? void 0 : storeData.set(key, v);
              this.fileTagDetail.setTagData(this.index, storeData);
              this.updateShadowText();
              await this.fileTagDetail.writeFrontmatter();
            });
          });
        }
      }
    });
    this.updateShadowText();
  }
  popupHTML(tagDom, other) {
    if (this.popuped)
      return;
    this.popuped = true;
    let rect = tagDom.getBoundingClientRect();
    let popup = document.createElement("div");
    popup.addClass("colorful-tag-popup");
    popup.addClass(`popup-${this.tagSetting.name}`);
    popup.style.left = `${rect.right + 20}px`;
    popup.style.top = `${rect.bottom + 20}px`;
    let header = popup.createDiv("colorful-tag-popup-header");
    header.createSpan().setText(`#${this.tagSetting.name}`);
    let pin = header.createDiv("colorful-tag-popup-pin");
    (0, import_obsidian.setIcon)(pin, "filled-pin");
    pin.onClickEvent(() => {
      pin.classList.toggle("pinned");
      if (pin.classList.contains("pinned")) {
        this.state = 1 /* ENTER */;
      } else {
        this.state = 0 /* VISIBLE */;
      }
    });
    let body = popup.createDiv("colorful-tag-popup-body");
    this.popupBody(body);
    document.body.appendChild(popup);
    let enter = () => {
      this.state = 1 /* ENTER */;
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = void 0;
      }
      this.popuped = true;
    };
    let leave = () => {
      this.state = 0 /* VISIBLE */;
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = void 0;
      }
      this.timer = setTimeout(() => {
        if (this.state == 0 /* VISIBLE */ && !pin.classList.contains("pinned")) {
          if (popup != null) {
            popup.addClass("hidden");
            if (this.timer) {
              clearTimeout(this.timer1);
              this.timer1 = void 0;
            }
            this.timer1 = setTimeout(() => {
              popup.remove();
              this.popuped = false;
            }, 200);
          }
        }
      }, 1500);
    };
    popup.addEventListener("mouseenter", enter);
    popup.addEventListener("mouseleave", leave);
    tagDom.addEventListener("mouseenter", enter);
    tagDom.addEventListener("mouseleave", leave);
    other.addEventListener("mouseenter", enter);
    other.addEventListener("mouseleave", leave);
  }
};

// src/tagDetail/tagDetailUtils.ts
var TagDetailUtils = class {
  static async hoverTagPopupListener(plugin) {
    if (!plugin.settings.UseTagDetail)
      return;
    let tags_dom = document.querySelectorAll(".workspace-leaf.mod-active .cm-hashtag.cm-hashtag-end");
    if (tags_dom.length == 0)
      return;
    let map = /* @__PURE__ */ new Map();
    plugin.settings.TagSettings.forEach((v) => {
      map.set(v.name, v);
    });
    TagDetailUtils.fileTagDetail = new FileTagDetail(plugin);
    await TagDetailUtils.fileTagDetail.getFrontmatter();
    tags_dom.forEach((tagDom, i) => {
      let tag = map.get(tagDom.getText().split("/")[0]);
      if (tag == void 0)
        return;
      if (!tag.enable)
        return;
      let detailAttr = tag.tagDetail.attributes;
      if (detailAttr.size == 0)
        return;
      let prev = tagDom.previousElementSibling;
      let perTag = new perTagDetail(plugin, tag, TagDetailUtils.fileTagDetail, i);
      this.listener = () => {
        perTag.popupHTML(tagDom, prev);
      };
      tagDom.addEventListener("mouseenter", this.listener);
      prev.addEventListener("mouseenter", this.listener);
      perTag.updateShadowText();
    });
  }
  static removeListener() {
    let tags_dom = document.querySelectorAll(".cm-hashtag.cm-hashtag-end");
    tags_dom.forEach((tagDom) => {
      let prev = tagDom.previousElementSibling;
      tagDom.removeEventListener("mouseenter", this.listener);
      prev.removeEventListener("mouseenter", this.listener);
    });
  }
};

// src/tagDetail/fileTagDetail.ts
var _FileTagDetail = class {
  constructor(plugin) {
    this.kvss = [];
    this.plugin = plugin;
    this.file = this.plugin.app.workspace.getActiveFile();
  }
  getTagData(i) {
    let len = this.kvss.length;
    if (i >= len) {
      for (let j = len; j < i; j++) {
        this.kvss.push(null);
      }
      this.kvss.push(null);
    }
    console.log("get tag data");
    console.log(this.kvss);
    console.log(this.kvss[i]);
    return this.kvss[i];
  }
  setTagData(i, data) {
    let len = this.kvss.length;
    if (i >= len) {
      for (let j = len; j < i; j++) {
        this.kvss.push(null);
      }
    }
    this.kvss[i] = data;
  }
  addTagData(i) {
    let len = this.kvss.length;
    if (i >= len) {
      for (let j = len; j < i; j++) {
        this.kvss.push(null);
      }
    }
    this.kvss[i] = /* @__PURE__ */ new Map();
    console.log("add tag data");
    console.log(this.kvss);
  }
  async readFile() {
    if (this.file == null)
      this.file = this.plugin.app.workspace.getActiveFile();
    this.content = await this.plugin.app.vault.read(this.file);
  }
  async getFrontmatter() {
    var _a;
    if (this.content == null)
      await this.readFile();
    if (this.plugin.settings.StoreTagDetailInYaml == "plugin") {
      let dataMap = this.plugin.settings.TagDetailData;
      let data = dataMap.get(this.file.path);
      if (data == void 0) {
        this.kvss = new Array();
      } else {
        this.kvss = data;
      }
      return;
    }
    const match = (_a = this.content) == null ? void 0 : _a.match(/^---\s+([\w\W]+?)\s+---/);
    if (match) {
      const frontmatterRaw = match[1];
      const yaml = (0, import_obsidian2.parseYaml)(frontmatterRaw);
      this.yaml = yaml;
    }
    this.yaml2map();
  }
  async writeFrontmatter() {
    var _a;
    console.log("write frontmatter");
    if (this.plugin.settings.StoreTagDetailInYaml == "plugin") {
      let dataMap = this.plugin.settings.TagDetailData;
      let arr = new Array();
      this.kvss.forEach((v) => {
        if (v == null) {
          arr.push(/* @__PURE__ */ new Map());
        } else {
          arr.push(v);
        }
      });
      dataMap.set(this.file.path, arr);
      this.plugin.settings.TagDetailData = dataMap;
      this.plugin.saveSettings();
      return;
    }
    ;
    this.map2yaml();
    if ((_a = this.content) == null ? void 0 : _a.match(/^---\s+([\w\W]+?)\s+---/)) {
      this.content = this.content.replace(/^---\s+([\w\W]+?)\s+---/, `---
${(0, import_obsidian2.stringifyYaml)(this.yaml)}---`);
    } else {
      this.content = `---
${(0, import_obsidian2.stringifyYaml)(this.yaml)}---
${this.content}`;
    }
    await this.plugin.app.vault.modify(this.file, this.content || "");
  }
  yaml2map() {
    if (this.yaml == null) {
      this.yaml = {};
      return;
    }
    let tagDetails = this.yaml["colorful-tag"];
    if (tagDetails == void 0)
      return;
    for (let name in tagDetails) {
      let m = /* @__PURE__ */ new Map();
      for (let k in tagDetails[name]) {
        m.set(k, tagDetails[name][k]);
      }
      this.kvss.push(m);
    }
  }
  map2yaml() {
    this.yaml["colorful-tag"] = this.kvss;
  }
  static async handleMetadataChange(file, data, cache, plugin) {
    let activeFile = plugin.app.workspace.getActiveFile();
    if (activeFile == null || file != activeFile)
      return;
    let tags = cache.tags;
    if (tags == void 0)
      tags = [];
    TagDetailUtils.fileTagDetail = new _FileTagDetail(plugin);
    await TagDetailUtils.fileTagDetail.getFrontmatter();
    let metaFileTagDetail = plugin.settings.MetaFileTagDetails;
    let tagsMeta = metaFileTagDetail.get(file.path) || [];
    if (tagsMeta.length == tags.length) {
      let dirty = false;
      tags.forEach((v, i) => {
        let s = v.position.start;
        if (tagsMeta[i] != `${v.tag}-${s.line}-${s.col}-${s.offset}`) {
          dirty = true;
          tagsMeta[i] = `${v.tag}-${s.line}-${s.col}-${s.offset}`;
        }
      });
      if (!dirty)
        return;
    } else if (tagsMeta.length < tags.length) {
      let j = tags.length - tagsMeta.length;
      for (let i = 0; i < tags.length; i++) {
        let s = tags[i].position.start;
        if (tagsMeta[i] && tagsMeta[i] == `${tags[i].tag}-${s.line}-${s.col}-${s.offset}`)
          continue;
        tagsMeta.splice(i, 0, `${s.line}-${s.col}-${s.offset}`);
        TagDetailUtils.fileTagDetail.kvss.splice(i, 0, null);
        _FileTagDetail.shadowText.splice(i, 0, ["", ""]);
        j--;
        if (j == 0)
          break;
      }
    } else {
      let j = tagsMeta.length - tags.length;
      for (let i = 0, k = 0; i < tagsMeta.length; i++, k++) {
        if (i < tags.length) {
          let s = tags[i].position.start;
          if (tagsMeta[i] && tagsMeta[i] == `${tags[i].tag}-${s.line}-${s.col}-${s.offset}`)
            continue;
        }
        tagsMeta.splice(k, 1);
        TagDetailUtils.fileTagDetail.kvss.splice(k, 1);
        _FileTagDetail.shadowText.splice(k, 1);
        k--;
        j--;
        if (j == 0)
          break;
      }
    }
    if (tagsMeta.length != tags.length) {
      await TagDetailUtils.fileTagDetail.writeFrontmatter();
    }
    metaFileTagDetail.set(file.path, tagsMeta);
    TagDetailUtils.removeListener();
    await TagDetailUtils.hoverTagPopupListener(plugin);
    plugin.settings.MetaFileTagDetails = metaFileTagDetail;
    await plugin.saveSettings();
  }
};
var FileTagDetail = _FileTagDetail;
FileTagDetail.shadowText = new Array();

// src/plugin/shadowTextPlugin.ts
var ShadowTextWidget = class extends import_view2.WidgetType {
  constructor(text, start) {
    super();
    this.text = text;
    this.start = start;
  }
  eq(other) {
    return other.text == this.text;
  }
  toDOM() {
    let wrap = document.createElement("span");
    wrap.setAttribute("aria-hidden", "true");
    wrap.className = "colorful-tag-shadow-text";
    wrap.setText(this.text);
    if (this.start) {
      wrap.addClass("shadow-text-start");
    } else {
      wrap.addClass("shadow-text-end");
    }
    return wrap;
  }
  ignoreEvent() {
    return false;
  }
};
function shadowText(view) {
  let widgets = [];
  let i = 0;
  for (let { from, to } of view.visibleRanges) {
    (0, import_language.syntaxTree)(view.state).iterate({
      from,
      to,
      enter: (node) => {
        let shadowText2 = FileTagDetail.shadowText[i] || "";
        if (node.name.startsWith("formatting_formatting-hashtag_hashtag_hashtag-begin")) {
          if (shadowText2 && shadowText2[0] != "") {
            let deco = import_view.Decoration.widget({
              widget: new ShadowTextWidget(shadowText2[0], true),
              side: 0
            });
            widgets.push(deco.range(node.from));
          }
        }
        if (node.name.startsWith("hashtag_hashtag-end")) {
          if (shadowText2 && shadowText2[1] != "") {
            let deco = import_view.Decoration.widget({
              widget: new ShadowTextWidget(shadowText2[1], false),
              side: 1
            });
            widgets.push(deco.range(node.to));
          }
          i++;
        }
      }
    });
  }
  return import_view.Decoration.set(widgets);
}
var shadowTextPlugin = import_view3.ViewPlugin.fromClass(class {
  constructor(view) {
    this.decorations = shadowText(view);
  }
  update(update) {
    if (!(update.docChanged || update.focusChanged))
      return;
    this.decorations = shadowText(update.view);
  }
}, {
  decorations: (v) => v.decorations,
  eventHandlers: {}
});

// src/setting/perTagSetting.ts
var import_obsidian6 = require("obsidian");

// src/utils/attribute.ts
var _Attribute = class {
  constructor(name, type, cssName, displayName, description = null, important = false) {
    this.name = name;
    this.displayName = displayName;
    this.description = description;
    this.type = type;
    this.cssName = cssName;
    this.important = important;
  }
};
var Attribute = _Attribute;
Attribute.AttributeList = /* @__PURE__ */ new Map([
  ["prefix", new _Attribute("prefix", "Text" /* Text */, "content", "Prefix")],
  ["suffix", new _Attribute("suffix", "Text" /* Text */, "content", "Suffix")],
  ["background-color", new _Attribute("background-color", "Color" /* Color */, "background-color", "Background Color")],
  ["text-color", new _Attribute("text-color", "Color" /* Color */, "color", "Text Color")],
  ["text-size", new _Attribute("text-size", "Size" /* Size */, "font-size", "Text Size")],
  ["font-weight", new _Attribute("font-weight", "Number" /* Number */, "font-weight", "Font Weight")],
  ["border", new _Attribute("border", "Any" /* Any */, "border", "Border")],
  ["radius", new _Attribute("radius", "Size" /* Size */, "radius", "Radius")],
  ["nest-tag", new _Attribute("nest-tag", "Boolean" /* Boolean */, null, "Enable Nest Tag")],
  ["remove-hash", new _Attribute("remove-hash", "Boolean" /* Boolean */, null, "Remove Hash", "Set true to remove '#' of the tag.\nFor example: '\u{1F60E}#Nice' => '\u{1F60E}Nice'")],
  ["remove-tag-name", new _Attribute("remove-tag-name", "Boolean" /* Boolean */, null, "Remove Tag Name", "Set true to remove the 'tag name'.\nFor example: '\u{1F60E}#Nice' => '\u{1F60E}#'")]
]);

// src/setting/tagDetailSetting.ts
var import_crypto = require("crypto");
var import_obsidian4 = require("obsidian");

// src/setting/baseTagSetting.ts
var import_obsidian3 = require("obsidian");
var BaseTagSetting = class {
  constructor() {
    this.attributes = /* @__PURE__ */ new Map();
    this.opened = false;
  }
  generateTitle(header, setting, child = false) {
    let title = new import_obsidian3.Setting(header);
    let title_ctl = title.nameEl.createEl("span", "colorful-tag-collapse-indicator is-collapsed");
    (0, import_obsidian3.setIcon)(title_ctl, "right-arrow");
    if (this.opened && !child) {
      setting.removeClass("is-collapsed");
      title_ctl.removeClass("is-collapsed");
    }
    header.onClickEvent(() => {
      setting.classList.toggle("is-collapsed");
      title_ctl.classList.toggle("is-collapsed");
      if (!child) {
        this.opened = !this.opened;
      }
    });
    return title;
  }
  addComponent(name, attributeType, settingItem, save, dropdownOptions = "") {
    let attr = this.attributes;
    let value = attr.get(name);
    switch (attributeType) {
      case "Boolean" /* Boolean */: {
        let dropdown = settingItem.addDropdown((cp) => {
          cp.addOption("True" /* True */, "True").addOption("False" /* False */, "False").setValue(value || "").onChange((v) => {
            attr.set(name, v);
            this.attributes = attr;
            save();
          });
        });
        settingItem.addButton((cp) => {
          cp.setIcon("reset").setClass("small-button").onClick(() => {
            let dropdownComponent = dropdown.components[0];
            dropdownComponent.setValue("");
            attr.set(name, null);
            this.attributes = attr;
            save();
          });
        });
        break;
      }
      case "Dropdown" /* Dropdown */: {
        let options = dropdownOptions.split(",");
        let dropdown = settingItem.addDropdown((cp) => {
          options.forEach((v) => {
            cp.addOption(v, v);
          });
          cp.setValue(value || "").onChange((v) => {
            attr.set(name, v);
            this.attributes = attr;
            save();
          });
        });
        settingItem.addButton((cp) => {
          cp.setIcon("reset").setClass("small-button").onClick(() => {
            let dropdownComponent = dropdown.components[0];
            dropdownComponent.setValue("");
            attr.set(name, null);
            this.attributes = attr;
            save();
          });
        });
        break;
      }
      case "Color" /* Color */: {
        let colorPicker = settingItem.addColorPicker((cp) => {
          cp.setValue(value || "#000000").onChange((v) => {
            attr.set(name, v);
            this.attributes = attr;
            save();
          });
        });
        settingItem.addButton((cp) => {
          cp.setIcon("reset").setClass("small-button").onClick(() => {
            let colorComponent = colorPicker.components[0];
            colorComponent.setValue("#000000");
            attr.set(name, null);
            this.attributes = attr;
            save();
          });
        });
        break;
      }
      case "Size" /* Size */: {
        let regex = /([\d.]+)(.*)/gm.exec(value || "");
        let text = "";
        let unit = "px";
        if (regex != null) {
          text = regex[1];
          unit = regex[2];
        }
        settingItem.addText((cp) => {
          cp.setValue(text).onChange((v) => {
            let res = `${v}${unit}`;
            if (res == "")
              res = null;
            text = v;
            attr.set(name, res);
            this.attributes = attr;
            save();
          });
        }).setClass("small-input");
        settingItem.addDropdown((cp) => {
          for (let [_, v] of Object.entries(SizeType)) {
            cp.addOption(v, v);
          }
          cp.setValue(unit).onChange((v) => {
            unit = v;
            attr.set(name, `${text}${unit}`);
            this.attributes = attr;
            save();
          });
        });
        break;
      }
      default: {
        settingItem.addText((cp) => {
          cp.setValue(value || "").onChange((v) => {
            let res = v;
            if (v == "")
              res = null;
            attr.set(name, res);
            this.attributes = attr;
            save();
          });
        });
      }
    }
  }
};

// src/utils/utils.ts
var crypto = __toESM(require("crypto"));
function insertCss(css2) {
  let head = document.querySelector("head");
  let del = head.querySelectorAll(`[colorful-tag-style]`);
  del.forEach((d) => {
    d.remove();
  });
  head.createEl("style", { "type": "text/css", "attr": { "colorful-tag-style": "" } }).setText(css2);
}
function convertTag(tag1) {
  let tag2 = tag1;
  tag1 = tag1.replace(/\//g, "\\/");
  tag2 = tag2.replace(/\//g, "");
  return [tag1, tag2];
}
function stringToAttributeType(name) {
  for (let [s, t] of Object.entries(AttributeType)) {
    if (name == s) {
      return t;
    }
  }
  return null;
}
function isBefore(el1, el2) {
  if (el2.parentNode == el1.parentNode) {
    for (let cur = el1.previousSibling; cur && cur.nodeType !== 9; cur = cur.previousSibling) {
      if (cur == el2) {
        return true;
      }
    }
  }
  return false;
}

// src/setting/tagDetailSetting.ts
var typeSelect = [
  "Text" /* Text */,
  "Boolean" /* Boolean */,
  "Color" /* Color */,
  "Number" /* Number */,
  "Date" /* Date */,
  "Dropdown" /* Dropdown */,
  "ReadOnly" /* ReadOnly */
];
var TagDetailSetting = class extends BaseTagSetting {
  constructor(tagIndex) {
    super();
    this.itemType = /* @__PURE__ */ new Map();
    this.tagIndex = tagIndex;
  }
  addComponent2(value, name, settingItem, plugin, refresh) {
    let itemType = this.itemType;
    let components = settingItem.controlEl.childNodes;
    let deleted = [];
    for (let i = 0; i < components.length; i++) {
      if (i < 2)
        continue;
      deleted.push(components[i]);
    }
    deleted.forEach((v) => v.remove());
    let dropdownOption = "";
    if (value[1] == "Dropdown" /* Dropdown */) {
      settingItem.addText((cp) => {
        cp.setValue(value[2] || "").setPlaceholder("Dropdown Items(split by ',')").onChange((v) => {
          value[2] = v;
          itemType.set(name, value);
          this.itemType = itemType;
          plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
          plugin.saveSettings();
          let dropdownComponent = settingItem.components[3];
          let deleted2 = [];
          let selectEl = dropdownComponent.selectEl;
          if (!selectEl) {
            selectEl = settingItem.controlEl.childNodes[3];
          }
          selectEl.childNodes.forEach((v2) => deleted2.push(v2));
          deleted2.forEach((v2) => v2.remove());
          let options = v.split(",");
          options.forEach((v2) => {
            selectEl.createEl("option", { value: v2 }).setText(v2);
          });
          selectEl.createEl("option").setAttrs({ selected: "", disabled: "", hidden: "" });
        });
        cp.inputEl.style.marginRight = "auto";
      });
      dropdownOption = value[2] || "";
    }
    this.addComponent(name, value[1] || "Any" /* Any */, settingItem, () => {
      plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
      plugin.saveSettings();
    }, dropdownOption);
    settingItem.addButton((cp) => {
      cp.setIcon("trash").setClass("small-button").setWarning().onClick(() => {
        itemType.delete(name);
        plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
        plugin.saveSettings();
        refresh();
      });
    });
  }
  generateItem(body, k, value, plugin) {
    let itemType = this.itemType;
    let settingItem = new import_obsidian4.Setting(body);
    settingItem.infoEl.remove();
    settingItem.controlEl.style.justifyContent = "flex-start";
    settingItem.addText((cp) => {
      cp.setValue(value[0] || "").setPlaceholder("Item Name").onChange((v) => {
        let res = v;
        if (v == "")
          res = null;
        value[0] = res;
        itemType.set(k, value);
        this.itemType = itemType;
        plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
        plugin.saveSettings();
      }).inputEl.style.width = "100px";
    });
    settingItem.addDropdown((cp) => {
      typeSelect.forEach((v) => {
        cp.addOption(v, v);
      });
      cp.setValue(value[1] || "");
      cp.onChange((v) => {
        value[1] = stringToAttributeType(v);
        this.addComponent2(value, k, settingItem, plugin, () => {
          settingItem.setClass("deleted");
          document.querySelectorAll(".deleted").forEach((v2) => v2.remove());
        });
        itemType.set(k, value);
        this.itemType = itemType;
        plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
        plugin.saveSettings();
      });
      if (value[1] != "Dropdown" /* Dropdown */) {
        cp.selectEl.style.marginRight = "auto";
      }
    });
    this.addComponent2(value, k, settingItem, plugin, () => {
      settingItem.setClass("deleted");
      document.querySelectorAll(".deleted").forEach((v) => v.remove());
    });
  }
  generateDOM(parent, plugin) {
    let setting = parent.createDiv("colorful-tag-setting-header is-collapsed");
    let header = setting.createDiv();
    let title = this.generateTitle(header, setting, true);
    title.nameEl.createSpan().setText("Tag Detail Setting");
    let body = setting.createDiv("colorful-tag-setting-body");
    let tagItems = body.createDiv();
    let itemType = this.itemType;
    itemType.forEach((value, k) => {
      this.generateItem(tagItems, k, value, plugin);
    });
    let tagTemplate = body.createDiv();
    new import_obsidian4.Setting(tagTemplate).setName("Shadow Text Template").addTextArea((cp) => {
      cp.setValue(this.shadowTextTemplate).onChange((v) => {
        this.shadowTextTemplate = v;
        plugin.settings.TagSettings[this.tagIndex].tagDetail = this;
        plugin.saveSettings();
      });
    });
    new import_obsidian4.Setting(body).addButton((cp) => {
      cp.setButtonText("Add Item").onClick(() => {
        let key = (0, import_crypto.randomUUID)().substring(0, 6);
        itemType.set(key, [null, null, null]);
        this.generateItem(tagItems, key, [null, null, null], plugin);
      });
    });
  }
};

// src/setting/globalTagSetting.ts
var import_obsidian5 = require("obsidian");
var GlobalTagSetting = class extends BaseTagSetting {
  constructor() {
    super(...arguments);
    this.enableList_ = /* @__PURE__ */ new Map();
  }
  generateDOM(parent, plugin) {
    let setting = parent.createDiv("colorful-tag-setting-header is-collapsed");
    let header = setting.createDiv();
    let title = this.generateTitle(header, setting);
    title.nameEl.createSpan().setText("Global Setting");
    let body = setting.createDiv("colorful-tag-setting-body");
    let enableList = this.enableList_;
    let attr = this.attributes;
    Attribute.AttributeList.forEach((attribute, name) => {
      let settingItem = new import_obsidian5.Setting(body);
      settingItem.setName(attribute.displayName);
      if (attribute.description != null)
        settingItem.setDesc(attribute.description);
      this.addComponent(name, attribute.type, settingItem, async () => {
        plugin.settings.GlobalTagSetting = this;
        plugin.saveSettings();
        await plugin.refresh();
      });
      settingItem.addToggle((cp) => {
        cp.setValue(enableList.get(name) || false).onChange((v) => {
          enableList.set(name, v);
          this.enableList_ = enableList;
          if (!v)
            attr.set(name, null);
          plugin.settings.GlobalTagSetting = this;
          plugin.saveSettings();
          plugin.settingTab.display();
        });
      });
    });
    parent.appendChild(setting);
  }
};
GlobalTagSetting.from = null;

// src/setting/perTagSetting.ts
var PerTagSetting = class extends BaseTagSetting {
  constructor() {
    super(...arguments);
    this.enable = true;
    this.tagDetail = new TagDetailSetting(-1);
  }
  get name() {
    if (this.name_ == null) {
      return "";
    }
    return this.name_;
  }
  set name(name) {
    this.name_ = name;
  }
  attrCss(name, plugin) {
    let global = plugin.settings.GlobalTagSetting.attributes;
    let local = this.attributes;
    let value = local.get(name) || global.get(name) || "";
    let attribute = Attribute.AttributeList.get(name);
    let cssName = attribute.cssName;
    let important = attribute.important;
    if (value == null) {
      return "";
    }
    if (important) {
      return `${cssName}: ${value} !important;`;
    }
    return `${cssName}: ${value};`;
  }
  generateCss(plugin) {
    let global = plugin.settings.GlobalTagSetting.attributes;
    let local = this.attributes;
    let background_color = local.get("background-color") || global.get("background-color") || "";
    let text_color = local.get("text-color") || global.get("text-color") || "";
    let prefix = local.get("prefix") || global.get("prefix") || "";
    let suffix = local.get("suffix") || global.get("suffix") || "";
    let radius = local.get("radius") || global.get("radius") || "";
    let text_size = local.get("text-size") || global.get("text-size") || "";
    let border = local.get("border") || global.get("border") || "";
    let font_weight = local.get("font-weight") || global.get("font-weight") || "";
    let nest_tag = local.get("nest-tag") || global.get("nest-tag") || "";
    let remove_hash = local.get("remove-hash") || global.get("remove-hash") || "";
    let remove_tag_name = local.get("remove-tag-name") || global.get("remove-tag-name") || "";
    let padding_size = "";
    let [tag1, tag2] = convertTag(this.name);
    let reading_selector = `href="#${tag1}"`;
    let editing_selector = `span.cm-tag-${tag2}`;
    if (nest_tag.toLowerCase() == "true") {
      reading_selector = `href^="#${tag1}"`;
      editing_selector = `span[class*="cm-tag-${tag2}"]`;
    }
    let style1 = `font-weight: ${font_weight}; background-color: ${background_color}; color: ${text_color}; font-size: ${text_size}; white-space: nowrap; border: ${border}; vertical-align: baseline;`;
    let style2 = `border-radius: ${radius}; padding-left: ${padding_size}; padding-right: ${padding_size};`;
    let style3 = `border-top-right-radius: 0; border-bottom-right-radius: 0; padding-right: 0px; border-top-left-radius: ${radius}; border-bottom-left-radius: ${radius}; padding-left: ${padding_size};`;
    let style4 = `border-bottom-left-radius: 0; border-top-left-radius: 0; padding-left: 0px; border-top-right-radius: ${radius}; border-bottom-right-radius: ${radius}; padding-right: ${padding_size};`;
    let css2 = "";
    if (!this.enable)
      return css2;
    css2 += `[class*="popup-${tag2}"] > .colorful-tag-popup-header { display: flex; padding: 5px 10px; background-color: ${background_color}; color: ${text_color}; font-size: ${text_size}; font-weight: ${font_weight}; border-radius: 10px 10px 0 0; }`;
    css2 += `[class*="popup-${tag2}"] > .colorful-tag-popup-body { padding: 0 10px; border: 4px solid ${background_color}; border-radius: 0 0 10px 10px; border-top: none;}`;
    css2 += `body a.tag[${reading_selector}], body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag { ${style1} }`;
    css2 += `body a.tag[${reading_selector}] { ${style2} }`;
    css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin { ${style3} }`;
    css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end { ${style4} }`;
    if (remove_hash.toLowerCase() == "true" && remove_tag_name.toLowerCase() == "true") {
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin { font-size: 0px; background-color: revert; }`;
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end { font-size: 0px; background-color: revert; }`;
      if (suffix == "" && prefix != "") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin::before { padding-right: var(--tag-padding-x) !important; border-top-right-radius: ${radius} !important; border-bottom-right-radius: ${radius} !important; }`;
      } else if (prefix == "" && suffix != "") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end::after { padding-left: var(--tag-padding-x) !important; border-top-left-radius: ${radius} !important; border-bottom-left-radius: ${radius} !important; }`;
      }
    } else if (remove_hash.toLowerCase() == "true") {
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin { font-size: 0px; }`;
      if (prefix == "") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end { padding-left: var(--tag-padding-x); border-top-left-radius: ${radius} !important; border-bottom-left-radius: ${radius} !important; }`;
      } else {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin { padding-left: 0; }`;
      }
    } else if (remove_tag_name.toLowerCase() == "true") {
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end { font-size: 0px; }`;
      if (suffix == "") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin { padding-right: var(--tag-padding-x); border-top-right-radius: ${radius} !important; border-bottom-right-radius: ${radius} !important; }`;
      } else {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end { padding-right: 0; }`;
      }
    }
    if (prefix != "") {
      css2 += `body a.tag[${reading_selector}]::before { content: "${prefix} "; }`;
      css2 += `[class*="popup-${tag2}"] > .colorful-tag-popup-header:before { content: "${prefix}"; }`;
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin::before { content: "${prefix} "; ${style1} }`;
      css2 += `body a.tag[${reading_selector}]::before { ${style2}; }`;
      if (remove_hash.toLowerCase() == "true") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-begin::before { ${style3}; padding-top: var(--tag-padding-y); padding-bottom: var(--tag-padding-y); padding-left: var(--tag-padding-x); }`;
      }
    }
    if (suffix != "") {
      css2 += `body a.tag[${reading_selector}]::after { content: " ${suffix}"; }`;
      css2 += `[class*="popup-${tag2}"] > .colorful-tag-popup-header:after { content: "${suffix}"; }`;
      css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end::after { content: " ${suffix}"; ${style1} }`;
      css2 += `body a.tag[${reading_selector}]::after { ${style2}; }`;
      if (remove_tag_name.toLowerCase() == "true") {
        css2 += `body .cm-s-obsidian .cm-line ${editing_selector}.cm-hashtag.cm-hashtag-end::after { ${style4}; padding-top: var(--tag-padding-y); padding-bottom: var(--tag-padding-y); padding-right: var(--tag-padding-x); }`;
      }
    }
    return css2;
  }
  refreshHeader(name, nameEl) {
    let [tag1, tag2] = convertTag(name || "");
    if (nameEl.querySelectorAll(`.cm-tag-${tag2}`).length > 0)
      return;
    let hashtag = nameEl.createSpan(`cm-hashtag cm-hashtag-begin cm-tag-${tag2}`);
    hashtag.setText("#");
    let content = nameEl.createSpan(`cm-hashtag cm-hashtag-end cm-tag-${tag2}`);
    content.setText(tag1);
    let old = nameEl.querySelectorAll(`:not(.cm-tag-${tag2})`);
    old.forEach((o) => o.remove());
  }
  drag(title, setting, index, plugin) {
    let dragHandle = title.controlEl.createEl("span");
    dragHandle.addClass("colorful-tag-handler");
    (0, import_obsidian6.setIcon)(dragHandle, "align-justify");
    setting.setAttr("index", index);
    dragHandle.draggable = true;
    dragHandle.ondragover = (e) => {
      var _a, _b;
      let to = e.target;
      to = to.closest(".colorful-tag-setting-outer");
      if (GlobalTagSetting.from == null)
        return;
      if (to == GlobalTagSetting.from)
        return;
      if (isBefore(GlobalTagSetting.from, to))
        (_a = to.parentNode) == null ? void 0 : _a.insertBefore(GlobalTagSetting.from, to);
      else
        (_b = to.parentNode) == null ? void 0 : _b.insertBefore(GlobalTagSetting.from, to.nextSibling);
      let idx = GlobalTagSetting.from.getAttr("index");
      GlobalTagSetting.from.setAttr("index", to.getAttr("index"));
      to.setAttr("index", idx);
      let tmpSetting = plugin.settings.TagSettings[parseInt(GlobalTagSetting.from.getAttr("index"))];
      plugin.settings.TagSettings[parseInt(GlobalTagSetting.from.getAttr("index"))] = plugin.settings.TagSettings[parseInt(to.getAttr("index"))];
      plugin.settings.TagSettings[parseInt(to.getAttr("index"))] = tmpSetting;
    };
    dragHandle.ondragend = () => {
      GlobalTagSetting.from = null;
      plugin.saveSettings();
    };
    dragHandle.ondragstart = (e) => {
      let from = e.target;
      from = from.closest(".colorful-tag-setting-outer");
      GlobalTagSetting.from = from;
    };
  }
  generateDOM(parent, plugin, index) {
    let setting = parent.createDiv("colorful-tag-setting-header is-collapsed colorful-tag-setting-outer");
    let inner = setting.createDiv("cm-s-obsidian");
    let header = inner.createDiv("cm-line");
    let body = setting.createDiv("colorful-tag-setting-body");
    let normal = body.createDiv();
    let override = body.createDiv("colorful-tag-setting-header is-collapsed");
    let overrideHeader = override.createDiv();
    let overrideTitle = this.generateTitle(overrideHeader, override, true);
    overrideTitle.nameEl.createSpan().setText("Override Global Setting");
    let overrideBody = override.createDiv("colorful-tag-setting-body");
    let title = this.generateTitle(header, setting).addToggle((cp) => {
      cp.setValue(this.enable).onChange((v) => {
        this.enable = v;
        plugin.settings.TagSettings[index] = this;
        plugin.saveSettings();
        plugin.refresh();
        setting.classList.toggle("is-collapsed", v);
        header.querySelector(".colorful-tag-collapse-indicator").classList.toggle("is-collapsed", v);
      });
    });
    let title_text = title.nameEl.createEl("span");
    this.refreshHeader(this.name_, title_text);
    this.drag(title, setting, index, plugin);
    let attr = this.attributes;
    let globalEnable = plugin.settings.GlobalTagSetting.enableList_;
    new import_obsidian6.Setting(normal).setName("Tag Name").addText((cp) => {
      cp.setValue(this.name_ || "");
      cp.setPlaceholder("Colorful-Tag");
      cp.onChange((v) => {
        let res = v;
        if (v == "")
          res = null;
        else
          res.replace(" ", "");
        this.name_ = res;
        plugin.settings.TagSettings[index] = this;
        plugin.saveSettings();
        plugin.refresh();
        this.refreshHeader(this.name_, title_text);
      });
    }).setDesc("Enter the tag name without '#'.");
    Attribute.AttributeList.forEach((attribute, name) => {
      let value = attr.get(name);
      let globalValue = globalEnable.get(name);
      let node = normal;
      if (!value && globalValue) {
        node = overrideBody;
      }
      let settingItem = new import_obsidian6.Setting(node);
      settingItem.setName(attribute.displayName);
      if (attribute.description != null)
        settingItem.setDesc(attribute.description);
      this.addComponent(name, attribute.type, settingItem, () => {
        plugin.settings.TagSettings[index] = this;
        plugin.saveSettings();
        if (attribute.type == "Boolean" /* Boolean */ || attribute.type == "Color" /* Color */) {
          plugin.settingTab.display();
        } else {
          plugin.refresh();
        }
      });
    });
    if (this.tagDetail == null) {
      this.tagDetail = new TagDetailSetting(index);
    }
    this.tagDetail.tagIndex = index;
    if (plugin.settings.UseTagDetail) {
      this.tagDetail.generateDOM(body, plugin);
    }
    new import_obsidian6.Setting(body).addButton((cp) => {
      cp.setIcon("trash").setButtonText("Remove").setWarning().onClick(() => {
        plugin.settings.TagSettings.splice(index, 1);
        plugin.saveSettings();
        plugin.settingTab.display();
      });
    });
    parent.appendChild(setting);
  }
};

// src/utils/dataConvert.ts
var import_obsidian7 = require("obsidian");
var DEFAULT_SETTINGS_OLD = {
  firstTime: true,
  global_enable: /* @__PURE__ */ new Map(),
  global: /* @__PURE__ */ new Map(),
  attrList: ["nest tag", "remove hash", "remove tag name", "radius", "prefix", "suffix", "background color", "text color", "text size", "border", "font weight"],
  defaultStyle: /* @__PURE__ */ new Map([["nest-tag", "false"], ["remove-hash", "false"], ["remove-tag-name", "false"], ["radius", "4px"], ["prefix", ""], ["suffix", ""], ["background-color", "#fff"], ["text-color", "#000"], ["text-size", "12px"], ["border", "none"], ["font-weight", "900"]]),
  defaultGlobal: /* @__PURE__ */ new Map([["nest-tag", false], ["remove-hash", false], ["remove-tag-name", false], ["radius", false], ["prefix", false], ["suffix", false], ["background-color", false], ["text-color", false], ["text-size", false], ["border", true], ["font-weight", true]]),
  styleList: new Array(),
  useTagDetail: false,
  tagDetail: /* @__PURE__ */ new Map(),
  tagItem: /* @__PURE__ */ new Map()
};
var Convert = class {
  constructor(plugin) {
    this.plugin = plugin;
  }
  async backup() {
    let config = this.plugin.app.vault.configDir;
    let dataJson = config + "/plugins/obsidian-colorful-tag/data.json";
    if (await this.plugin.app.vault.adapter.exists(dataJson + ".bak")) {
      await this.plugin.app.vault.adapter.remove(dataJson + ".bak");
    }
    await this.plugin.app.vault.adapter.copy(dataJson, dataJson + ".bak");
    console.log("backup done");
  }
  async convert() {
    let oldSetting = Object.assign({}, DEFAULT_SETTINGS_OLD, await this.plugin.loadData());
    let newSetting = Object.assign({}, DEFAULT_SETTINGS);
    newSetting.TagSettings = [];
    let enableList = /* @__PURE__ */ new Map();
    for (let [attr, _] of Object.entries(oldSetting.global_enable)) {
      enableList.set(attr, oldSetting.global_enable[attr]);
    }
    newSetting.GlobalTagSetting.enableList_ = enableList;
    let global = /* @__PURE__ */ new Map();
    for (let [attr, _] of Object.entries(oldSetting.global)) {
      global.set(attr, oldSetting.global[attr]);
    }
    newSetting.GlobalTagSetting.attributes = global;
    for (let style of oldSetting.styleList) {
      let tag = new PerTagSetting();
      tag.name = style.tag;
      tag.enable = style.enable;
      let attributes = /* @__PURE__ */ new Map();
      for (let [attr, _] of Object.entries(style)) {
        if (attr != "tag" && attr != "enable") {
          attributes.set(attr, style[attr]);
        }
      }
      tag.attributes = attributes;
      let tagItem = oldSetting.tagItem["#" + style.tag];
      if (tagItem) {
        let tagDetail = /* @__PURE__ */ new Map();
        let defaultMap = /* @__PURE__ */ new Map();
        for (let [detail, _] of Object.entries(tagItem)) {
          if (detail.startsWith("default")) {
            let key = detail.substring(7);
            defaultMap.set(key, tagItem[detail]);
          }
          ;
          let arr = [tagItem[detail], "Text", null];
          tagDetail.set(detail, arr);
        }
        tag.tagDetail.attributes = defaultMap;
        tag.tagDetail.itemType = tagDetail;
      }
      newSetting.TagSettings.push(tag);
    }
    for (let [path] of Object.entries(oldSetting.tagDetail)) {
      let value = oldSetting.tagDetail[path];
      let content = await this.plugin.app.vault.adapter.read(path);
      let frontmatterMap = /* @__PURE__ */ new Map();
      let tagList = new Array();
      let i = 0;
      for (let [tag, _] of Object.entries(value)) {
        let m = /* @__PURE__ */ new Map();
        if (value[tag]["_i"] != i) {
          i++;
          tagList.push(m);
          continue;
        }
        i++;
        for (let [item, _2] of Object.entries(value[tag])) {
          if (item.startsWith("_"))
            continue;
          m.set(item, value[tag][item]);
        }
        tagList.push(m);
      }
      frontmatterMap.set("colorful-tag", tagList);
      const match = content.match(/^---\s+([\w\W]+?)\s+---/);
      if (match) {
        let yaml = match[1] + "\n" + (0, import_obsidian7.stringifyYaml)(frontmatterMap);
        content = content.replace(/^---\s+([\w\W]+?)\s+---/, `---
${yaml}---`);
      } else {
        let yaml = (0, import_obsidian7.stringifyYaml)(frontmatterMap);
        content = `---
${yaml}---
${content}`;
      }
      await this.plugin.app.vault.adapter.write(path, content);
    }
    this.plugin.settings = newSetting;
    this.plugin.saveSettings();
    console.log("convert done");
  }
  async check() {
    let oldSetting = Object.assign({}, await this.plugin.loadData());
    if (oldSetting.global_enable) {
      return true;
    }
    return false;
  }
};

// main.ts
var DEFAULT_SETTINGS = {
  TagSettings: new Array(),
  GlobalTagSetting: new GlobalTagSetting(),
  UseTagDetail: false,
  StoreTagDetailInYaml: "plugin",
  TagDetailData: /* @__PURE__ */ new Map(),
  MetaFileTagDetails: /* @__PURE__ */ new Map()
};
var ColorfulTag2 = class extends import_obsidian8.Plugin {
  async onload() {
    let convert = new Convert(this);
    if (await convert.check()) {
      await convert.backup();
      await convert.convert();
    } else {
      await this.loadSettings();
    }
    let settingTab = new ColorfulTagSettingTab(this.app, this);
    this.settingTab = settingTab;
    this.addSettingTab(settingTab);
    this.app.workspace.on("active-leaf-change", async () => {
      await TagDetailUtils.hoverTagPopupListener(this);
    });
    this.app.metadataCache.on("changed", async (file, data, cache) => {
      await FileTagDetail.handleMetadataChange(file, data, cache, this);
    });
    this.settings.TagSettings.forEach((tag, i) => {
      tag.opened = false;
    });
    await this.refresh();
    await TagDetailUtils.hoverTagPopupListener(this);
    this.registerEditorExtension(shadowTextPlugin);
  }
  onunload() {
    this.app.workspace.off("active-leaf-change", () => {
      TagDetailUtils.hoverTagPopupListener(this);
    });
    TagDetailUtils.removeListener();
  }
  async refresh() {
    let tags = this.settings.TagSettings;
    let cssTotal = css.defaultCss;
    tags.forEach((tag_) => {
      let tag = new PerTagSetting();
      Object.assign(tag, tag_);
      cssTotal += tag.generateCss(this);
    });
    insertCss(cssTotal);
  }
  async loadSettings() {
    this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    for (let i = 0; i < this.settings.TagSettings.length; i++) {
      let tmp2 = new PerTagSetting();
      Object.assign(tmp2, this.settings.TagSettings[i]);
      tmp2.opened = false;
      let map2 = new Map(Object.entries(tmp2.attributes));
      tmp2.attributes = map2;
      let tmpTagDetail = new TagDetailSetting(i);
      Object.assign(tmpTagDetail, this.settings.TagSettings[i].tagDetail);
      let mapTagDetailAttr = new Map(Object.entries(tmpTagDetail.attributes));
      tmpTagDetail.attributes = mapTagDetailAttr;
      let mapTagDetailType = new Map(Object.entries(tmpTagDetail.itemType));
      tmpTagDetail.itemType = mapTagDetailType;
      tmp2.tagDetail = tmpTagDetail;
      this.settings.TagSettings[i] = tmp2;
    }
    let tmp = new GlobalTagSetting();
    Object.assign(tmp, this.settings.GlobalTagSetting);
    tmp.opened = false;
    let map = new Map(Object.entries(tmp.attributes));
    let bmap = new Map(Object.entries(tmp.enableList_));
    tmp.attributes = map;
    tmp.enableList_ = bmap;
    this.settings.GlobalTagSetting = tmp;
    let ttmpMap = new Map(Object.entries(this.settings.MetaFileTagDetails));
    this.settings.MetaFileTagDetails = ttmpMap;
    let tttmpMap = new Map(Object.entries(this.settings.TagDetailData));
    for (let [path, tagDetail] of tttmpMap) {
      let tmpTagDetail = new Array();
      for (let i = 0; i < tagDetail.length; i++) {
        let tmp2 = new Map(Object.entries(tagDetail[i]));
        tmpTagDetail.push(tmp2);
      }
      tttmpMap.set(path, tmpTagDetail);
    }
    this.settings.TagDetailData = tttmpMap;
  }
  saveSettings() {
    let tmp = [];
    let tagDetailAttr = [];
    let tagDetailType = [];
    let globalTmp = null;
    for (let i = 0; i < this.settings.TagSettings.length; i++) {
      tmp.push(this.settings.TagSettings[i].attributes);
      tagDetailAttr.push(this.settings.TagSettings[i].tagDetail.attributes);
      tagDetailType.push(this.settings.TagSettings[i].tagDetail.itemType);
      let obj2 = /* @__PURE__ */ Object.create(null);
      let attr2 = this.settings.TagSettings[i].attributes;
      for (let [k, v] of attr2) {
        obj2[k] = v;
      }
      let objTagDetailAttr = /* @__PURE__ */ Object.create(null);
      let attrTagDetail = this.settings.TagSettings[i].tagDetail.attributes;
      for (let [k, v] of attrTagDetail) {
        objTagDetailAttr[k] = v;
      }
      let objTagDetailType = /* @__PURE__ */ Object.create(null);
      let typeTagDetail = this.settings.TagSettings[i].tagDetail.itemType;
      for (let [k, v] of typeTagDetail) {
        objTagDetailType[k] = v;
      }
      this.settings.TagSettings[i].attributes = obj2;
      this.settings.TagSettings[i].tagDetail.attributes = objTagDetailAttr;
      this.settings.TagSettings[i].tagDetail.itemType = objTagDetailType;
    }
    globalTmp = this.settings.GlobalTagSetting.attributes;
    let globalBTmp = this.settings.GlobalTagSetting.enableList_;
    let obj = /* @__PURE__ */ Object.create(null);
    let attr = this.settings.GlobalTagSetting.attributes;
    for (let [k, v] of attr) {
      obj[k] = v;
    }
    let bobj = /* @__PURE__ */ Object.create(null);
    let enableList_ = this.settings.GlobalTagSetting.enableList_;
    for (let [k, v] of enableList_) {
      bobj[k] = v;
    }
    this.settings.GlobalTagSetting.attributes = obj;
    this.settings.GlobalTagSetting.enableList_ = bobj;
    let ttmp = this.settings.MetaFileTagDetails;
    let ttmpMapObj = /* @__PURE__ */ Object.create(null);
    let ttmpMap = this.settings.MetaFileTagDetails;
    for (let [k, v] of ttmpMap) {
      ttmpMapObj[k] = v;
    }
    this.settings.MetaFileTagDetails = ttmpMapObj;
    let tttmp = this.settings.TagDetailData;
    let tttmpMapObj = /* @__PURE__ */ Object.create(null);
    let tttmpMap = this.settings.TagDetailData;
    for (let [path, tagDetailData] of tttmpMap) {
      let ttttArray = [];
      for (let i = 0; i < tagDetailData.length; i++) {
        let ttttobj = /* @__PURE__ */ Object.create(null);
        let attr2 = tagDetailData[i];
        for (let [k1, v1] of attr2) {
          ttttobj[k1] = v1;
        }
        ttttArray.push(ttttobj);
      }
      tttmpMapObj[path] = ttttArray;
    }
    this.settings.TagDetailData = tttmpMapObj;
    this.saveData(this.settings);
    for (let i = 0; i < this.settings.TagSettings.length; i++) {
      this.settings.TagSettings[i].attributes = tmp[i];
      this.settings.TagSettings[i].tagDetail.attributes = tagDetailAttr[i];
      this.settings.TagSettings[i].tagDetail.itemType = tagDetailType[i];
    }
    this.settings.GlobalTagSetting.attributes = globalTmp;
    this.settings.GlobalTagSetting.enableList_ = globalBTmp;
    this.settings.MetaFileTagDetails = ttmp;
    this.settings.TagDetailData = tttmp;
  }
};
var ColorfulTagSettingTab = class extends import_obsidian8.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
  }
  display() {
    const { containerEl } = this;
    containerEl.empty();
    let addBtn = containerEl.createEl("button", { text: "Add" });
    addBtn.onClickEvent(() => {
      let newTag = new PerTagSetting();
      newTag.opened = true;
      this.plugin.settings.TagSettings.push(newTag);
      this.plugin.saveSettings();
      newTag.generateDOM(containerEl, this.plugin, this.plugin.settings.TagSettings.length - 1);
    });
    let sup = new BaseTagSetting();
    let support = containerEl.createDiv("colorful-tag-setting-header is-collapsed");
    let support_header = support.createDiv();
    let support_title = sup.generateTitle(support_header, support, false);
    support_title.nameEl.createSpan().setText("Support Colorful Tag!");
    let supportBody = support.createDiv("colorful-tag-setting-body");
    supportBody.createSpan().setText("Your support will be my motivation to improve Colorful Tag. If you like this plugin, please consider to buy me a coffee. Thank you!");
    let link = supportBody.createEl("a");
    link.setAttrs({ href: "https://ko-fi.com/V7V2G2MOF", target: "_blank" });
    link.createEl("img").setAttrs({
      height: "32",
      style: "border:0px;height:32px;display:block;margin:10px auto;",
      src: "https://storage.ko-fi.com/cdn/kofi2.png?v=3",
      border: "0",
      alt: "Buy Me a Coffee at ko-fi.com"
    });
    let general = containerEl.createDiv("colorful-tag-setting-header is-collapsed");
    let generalHeader = general.createDiv();
    let generalTitle = this.plugin.settings.GlobalTagSetting.generateTitle(generalHeader, general, false);
    generalTitle.nameEl.createSpan().setText("General Setting");
    let generalBody = general.createDiv("colorful-tag-setting-body");
    new import_obsidian8.Setting(generalBody).setName("Enable Tag Detail(Beta)").addToggle((cp) => {
      cp.setValue(this.plugin.settings.UseTagDetail || false).onChange((v) => {
        this.plugin.settings.UseTagDetail = v;
        this.plugin.saveSettings();
        this.display();
      });
    });
    new import_obsidian8.Setting(generalBody).setName("Store Tag Detail in").addDropdown((cp) => {
      cp.addOption("yaml", "Frontmatter");
      cp.addOption("plugin", "Plugin");
      cp.setValue(this.plugin.settings.StoreTagDetailInYaml).onChange((v) => {
        this.plugin.settings.StoreTagDetailInYaml = v;
        this.plugin.saveSettings();
      });
    });
    this.plugin.settings.GlobalTagSetting.generateDOM(containerEl, this.plugin);
    this.plugin.settings.TagSettings.forEach((tag, i) => {
      tag.generateDOM(containerEl, this.plugin, i);
    });
    this.plugin.refresh();
  }
};
