/*
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[Object.keys(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  __markAsModule(target);
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = (target, module2, desc) => {
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
    for (let key of __getOwnPropNames(module2))
      if (!__hasOwnProp.call(target, key) && key !== "default")
        __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
  }
  return target;
};
var __toModule = (module2) => {
  return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
};
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};

// node_modules/math-expression-evaluator/src/math_function.js
var require_math_function = __commonJS({
  "node_modules/math-expression-evaluator/src/math_function.js"(exports, module2) {
    "use strict";
    var Mexp = function(parsed) {
      this.value = parsed;
    };
    Mexp.math = {
      isDegree: true,
      acos: function(x) {
        return Mexp.math.isDegree ? 180 / Math.PI * Math.acos(x) : Math.acos(x);
      },
      add: function(a, b) {
        return a + b;
      },
      asin: function(x) {
        return Mexp.math.isDegree ? 180 / Math.PI * Math.asin(x) : Math.asin(x);
      },
      atan: function(x) {
        return Mexp.math.isDegree ? 180 / Math.PI * Math.atan(x) : Math.atan(x);
      },
      acosh: function(x) {
        return Math.log(x + Math.sqrt(x * x - 1));
      },
      asinh: function(x) {
        return Math.log(x + Math.sqrt(x * x + 1));
      },
      atanh: function(x) {
        return Math.log((1 + x) / (1 - x));
      },
      C: function(n, r) {
        var pro = 1;
        var other = n - r;
        var choice = r;
        if (choice < other) {
          choice = other;
          other = r;
        }
        for (var i = choice + 1; i <= n; i++) {
          pro *= i;
        }
        return pro / Mexp.math.fact(other);
      },
      changeSign: function(x) {
        return -x;
      },
      cos: function(x) {
        if (Mexp.math.isDegree)
          x = Mexp.math.toRadian(x);
        return Math.cos(x);
      },
      cosh: function(x) {
        return (Math.pow(Math.E, x) + Math.pow(Math.E, -1 * x)) / 2;
      },
      div: function(a, b) {
        return a / b;
      },
      fact: function(n) {
        if (n % 1 !== 0)
          return "NaN";
        var pro = 1;
        for (var i = 2; i <= n; i++) {
          pro *= i;
        }
        return pro;
      },
      inverse: function(x) {
        return 1 / x;
      },
      log: function(i) {
        return Math.log(i) / Math.log(10);
      },
      mod: function(a, b) {
        return a % b;
      },
      mul: function(a, b) {
        return a * b;
      },
      P: function(n, r) {
        var pro = 1;
        for (var i = Math.floor(n) - Math.floor(r) + 1; i <= Math.floor(n); i++) {
          pro *= i;
        }
        return pro;
      },
      Pi: function(low, high, ex) {
        var pro = 1;
        for (var i = low; i <= high; i++) {
          pro *= Number(ex.postfixEval({
            n: i
          }));
        }
        return pro;
      },
      pow10x: function(e) {
        var x = 1;
        while (e--) {
          x *= 10;
        }
        return x;
      },
      sigma: function(low, high, ex) {
        var sum = 0;
        for (var i = low; i <= high; i++) {
          sum += Number(ex.postfixEval({
            n: i
          }));
        }
        return sum;
      },
      sin: function(x) {
        if (Mexp.math.isDegree)
          x = Mexp.math.toRadian(x);
        return Math.sin(x);
      },
      sinh: function(x) {
        return (Math.pow(Math.E, x) - Math.pow(Math.E, -1 * x)) / 2;
      },
      sub: function(a, b) {
        return a - b;
      },
      tan: function(x) {
        if (Mexp.math.isDegree)
          x = Mexp.math.toRadian(x);
        return Math.tan(x);
      },
      tanh: function(x) {
        return Mexp.sinha(x) / Mexp.cosha(x);
      },
      toRadian: function(x) {
        return x * Math.PI / 180;
      }
    };
    Mexp.Exception = function(message) {
      this.message = message;
    };
    module2.exports = Mexp;
  }
});

// node_modules/math-expression-evaluator/src/lexer.js
var require_lexer = __commonJS({
  "node_modules/math-expression-evaluator/src/lexer.js"(exports, module2) {
    "use strict";
    var Mexp = require_math_function();
    function inc(arr, val) {
      for (var i = 0; i < arr.length; i++) {
        arr[i] += val;
      }
      return arr;
    }
    var token = [
      "sin",
      "cos",
      "tan",
      "pi",
      "(",
      ")",
      "P",
      "C",
      " ",
      "asin",
      "acos",
      "atan",
      "7",
      "8",
      "9",
      "int",
      "cosh",
      "acosh",
      "ln",
      "^",
      "root",
      "4",
      "5",
      "6",
      "/",
      "!",
      "tanh",
      "atanh",
      "Mod",
      "1",
      "2",
      "3",
      "*",
      "sinh",
      "asinh",
      "e",
      "log",
      "0",
      ".",
      "+",
      "-",
      ",",
      "Sigma",
      "n",
      "Pi",
      "pow"
    ];
    var show = [
      "sin",
      "cos",
      "tan",
      "&pi;",
      "(",
      ")",
      "P",
      "C",
      " ",
      "asin",
      "acos",
      "atan",
      "7",
      "8",
      "9",
      "Int",
      "cosh",
      "acosh",
      " ln",
      "^",
      "root",
      "4",
      "5",
      "6",
      "&divide;",
      "!",
      "tanh",
      "atanh",
      " Mod ",
      "1",
      "2",
      "3",
      "&times;",
      "sinh",
      "asinh",
      "e",
      " log",
      "0",
      ".",
      "+",
      "-",
      ",",
      "&Sigma;",
      "n",
      "&Pi;",
      "pow"
    ];
    var eva = [
      Mexp.math.sin,
      Mexp.math.cos,
      Mexp.math.tan,
      "PI",
      "(",
      ")",
      Mexp.math.P,
      Mexp.math.C,
      " ".anchor,
      Mexp.math.asin,
      Mexp.math.acos,
      Mexp.math.atan,
      "7",
      "8",
      "9",
      Math.floor,
      Mexp.math.cosh,
      Mexp.math.acosh,
      Math.log,
      Math.pow,
      Math.sqrt,
      "4",
      "5",
      "6",
      Mexp.math.div,
      Mexp.math.fact,
      Mexp.math.tanh,
      Mexp.math.atanh,
      Mexp.math.mod,
      "1",
      "2",
      "3",
      Mexp.math.mul,
      Mexp.math.sinh,
      Mexp.math.asinh,
      "E",
      Mexp.math.log,
      "0",
      ".",
      Mexp.math.add,
      Mexp.math.sub,
      ",",
      Mexp.math.sigma,
      "n",
      Mexp.math.Pi,
      Math.pow
    ];
    var preced = {
      0: 11,
      1: 0,
      2: 3,
      3: 0,
      4: 0,
      5: 0,
      6: 0,
      7: 11,
      8: 11,
      9: 1,
      10: 10,
      11: 0,
      12: 11,
      13: 0,
      14: -1
    };
    var type = [
      0,
      0,
      0,
      3,
      4,
      5,
      10,
      10,
      14,
      0,
      0,
      0,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      10,
      0,
      1,
      1,
      1,
      2,
      7,
      0,
      0,
      2,
      1,
      1,
      1,
      2,
      0,
      0,
      3,
      0,
      1,
      6,
      9,
      9,
      11,
      12,
      13,
      12,
      8
    ];
    var type0 = {
      0: true,
      1: true,
      3: true,
      4: true,
      6: true,
      8: true,
      9: true,
      12: true,
      13: true,
      14: true
    };
    var type1 = {
      0: true,
      1: true,
      2: true,
      3: true,
      4: true,
      5: true,
      6: true,
      7: true,
      8: true,
      9: true,
      10: true,
      11: true,
      12: true,
      13: true
    };
    var type1Asterick = {
      0: true,
      3: true,
      4: true,
      8: true,
      12: true,
      13: true
    };
    var empty = {};
    var type3Asterick = {
      0: true,
      1: true,
      3: true,
      4: true,
      6: true,
      8: true,
      12: true,
      13: true
    };
    var type6 = {
      1: true
    };
    var newAr = [
      [],
      ["1", "2", "3", "7", "8", "9", "4", "5", "6", "+", "-", "*", "/", "(", ")", "^", "!", "P", "C", "e", "0", ".", ",", "n", " "],
      ["pi", "ln", "Pi"],
      ["sin", "cos", "tan", "Del", "int", "Mod", "log", "pow"],
      ["asin", "acos", "atan", "cosh", "root", "tanh", "sinh"],
      ["acosh", "atanh", "asinh", "Sigma"]
    ];
    function match(str1, str2, i, x) {
      for (var f = 0; f < x; f++) {
        if (str1[i + f] !== str2[f]) {
          return false;
        }
      }
      return true;
    }
    Mexp.addToken = function(tokens) {
      for (var i = 0; i < tokens.length; i++) {
        var x = tokens[i].token.length;
        var temp = -1;
        newAr[x] = newAr[x] || [];
        for (var y = 0; y < newAr[x].length; y++) {
          if (tokens[i].token === newAr[x][y]) {
            temp = token.indexOf(newAr[x][y]);
            break;
          }
        }
        if (temp === -1) {
          token.push(tokens[i].token);
          type.push(tokens[i].type);
          if (newAr.length <= tokens[i].token.length) {
            newAr[tokens[i].token.length] = [];
          }
          newAr[tokens[i].token.length].push(tokens[i].token);
          eva.push(tokens[i].value);
          show.push(tokens[i].show);
        } else {
          token[temp] = tokens[i].token;
          type[temp] = tokens[i].type;
          eva[temp] = tokens[i].value;
          show[temp] = tokens[i].show;
        }
      }
    };
    function tokenize(string) {
      var nodes = [];
      var length = string.length;
      var key, x, y;
      for (var i = 0; i < length; i++) {
        if (i < length - 1 && string[i] === " " && string[i + 1] === " ") {
          continue;
        }
        key = "";
        for (x = string.length - i > newAr.length - 2 ? newAr.length - 1 : string.length - i; x > 0; x--) {
          if (newAr[x] === void 0)
            continue;
          for (y = 0; y < newAr[x].length; y++) {
            if (match(string, newAr[x][y], i, x)) {
              key = newAr[x][y];
              y = newAr[x].length;
              x = 0;
            }
          }
        }
        i += key.length - 1;
        if (key === "") {
          throw new Mexp.Exception("Can't understand after " + string.slice(i));
        }
        var index = token.indexOf(key);
        nodes.push({
          index,
          token: key,
          type: type[index],
          eval: eva[index],
          precedence: preced[type[index]],
          show: show[index]
        });
      }
      return nodes;
    }
    Mexp.lex = function(inp, tokens) {
      "use strict";
      var changeSignObj = {
        value: Mexp.math.changeSign,
        type: 0,
        pre: 21,
        show: "-"
      };
      var closingParObj = {
        value: ")",
        show: ")",
        type: 5,
        pre: 0
      };
      var openingParObj = {
        value: "(",
        type: 4,
        pre: 0,
        show: "("
      };
      var str = [openingParObj];
      var ptc = [];
      var inpStr = inp;
      var allowed = type0;
      var bracToClose = 0;
      var asterick = empty;
      var prevKey = "";
      var i;
      if (typeof tokens !== "undefined") {
        Mexp.addToken(tokens);
      }
      var obj = {};
      var nodes = tokenize(inpStr);
      for (i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (node.type === 14) {
          if (i > 0 && i < nodes.length - 1 && nodes[i + 1].type === 1 && (nodes[i - 1].type === 1 || nodes[i - 1].type === 6))
            throw new Mexp.Exception("Unexpected Space");
          continue;
        }
        var index = node.index;
        var cToken = node.token;
        var cType = node.type;
        var cEv = node.eval;
        var cPre = node.precedence;
        var cShow = node.show;
        var pre = str[str.length - 1];
        var j;
        for (j = ptc.length; j--; ) {
          if (ptc[j] === 0) {
            if ([0, 2, 3, 4, 5, 9, 11, 12, 13].indexOf(cType) !== -1) {
              if (allowed[cType] !== true) {
                console.log(inp, node, nodes, allowed);
                throw new Mexp.Exception(cToken + " is not allowed after " + prevKey);
              }
              str.push(closingParObj);
              allowed = type1;
              asterick = type3Asterick;
              inc(ptc, -1).pop();
            }
          } else
            break;
        }
        if (allowed[cType] !== true) {
          throw new Mexp.Exception(cToken + " is not allowed after " + prevKey);
        }
        if (asterick[cType] === true) {
          cType = 2;
          cEv = Mexp.math.mul;
          cShow = "&times;";
          cPre = 3;
          i = i - cToken.length;
        }
        obj = {
          value: cEv,
          type: cType,
          pre: cPre,
          show: cShow
        };
        if (cType === 0) {
          allowed = type0;
          asterick = empty;
          inc(ptc, 2).push(2);
          str.push(obj);
          str.push(openingParObj);
        } else if (cType === 1) {
          if (pre.type === 1) {
            pre.value += cEv;
            inc(ptc, 1);
          } else {
            str.push(obj);
          }
          allowed = type1;
          asterick = type1Asterick;
        } else if (cType === 2) {
          allowed = type0;
          asterick = empty;
          inc(ptc, 2);
          str.push(obj);
        } else if (cType === 3) {
          str.push(obj);
          allowed = type1;
          asterick = type3Asterick;
        } else if (cType === 4) {
          inc(ptc, 1);
          bracToClose++;
          allowed = type0;
          asterick = empty;
          str.push(obj);
        } else if (cType === 5) {
          if (!bracToClose) {
            throw new Mexp.Exception("Closing parenthesis are more than opening one, wait What!!!");
          }
          bracToClose--;
          allowed = type1;
          asterick = type3Asterick;
          str.push(obj);
          inc(ptc, 1);
        } else if (cType === 6) {
          if (pre.hasDec) {
            throw new Mexp.Exception("Two decimals are not allowed in one number");
          }
          if (pre.type !== 1) {
            pre = {
              value: 0,
              type: 1,
              pre: 0
            };
            str.push(pre);
            inc(ptc, -1);
          }
          allowed = type6;
          inc(ptc, 1);
          asterick = empty;
          pre.value += cEv;
          pre.hasDec = true;
        } else if (cType === 7) {
          allowed = type1;
          asterick = type3Asterick;
          inc(ptc, 1);
          str.push(obj);
        }
        if (cType === 8) {
          allowed = type0;
          asterick = empty;
          inc(ptc, 4).push(4);
          str.push(obj);
          str.push(openingParObj);
        } else if (cType === 9) {
          if (pre.type === 9) {
            if (pre.value === Mexp.math.add) {
              pre.value = cEv;
              pre.show = cShow;
              inc(ptc, 1);
            } else if (pre.value === Mexp.math.sub && cShow === "-") {
              pre.value = Mexp.math.add;
              pre.show = "+";
              inc(ptc, 1);
            }
          } else if (pre.type !== 5 && pre.type !== 7 && pre.type !== 1 && pre.type !== 3 && pre.type !== 13) {
            if (cToken === "-") {
              allowed = type0;
              asterick = empty;
              inc(ptc, 2).push(2);
              str.push(changeSignObj);
              str.push(openingParObj);
            }
          } else {
            str.push(obj);
            inc(ptc, 2);
          }
          allowed = type0;
          asterick = empty;
        } else if (cType === 10) {
          allowed = type0;
          asterick = empty;
          inc(ptc, 2);
          str.push(obj);
        } else if (cType === 11) {
          allowed = type0;
          asterick = empty;
          str.push(obj);
        } else if (cType === 12) {
          allowed = type0;
          asterick = empty;
          inc(ptc, 6).push(6);
          str.push(obj);
          str.push(openingParObj);
        } else if (cType === 13) {
          allowed = type1;
          asterick = type3Asterick;
          str.push(obj);
        }
        inc(ptc, -1);
        prevKey = cToken;
      }
      for (j = ptc.length; j--; ) {
        if (ptc[j] === 0) {
          str.push(closingParObj);
          inc(ptc, -1).pop();
        } else
          break;
      }
      if (allowed[5] !== true) {
        throw new Mexp.Exception("complete the expression");
      }
      while (bracToClose--) {
        str.push(closingParObj);
      }
      str.push(closingParObj);
      return new Mexp(str);
    };
    module2.exports = Mexp;
  }
});

// node_modules/math-expression-evaluator/src/postfix.js
var require_postfix = __commonJS({
  "node_modules/math-expression-evaluator/src/postfix.js"(exports, module2) {
    var Mexp = require_lexer();
    Mexp.prototype.toPostfix = function() {
      "use strict";
      var post = [], elem, popped, prep, pre, ele;
      var stack = [{ value: "(", type: 4, pre: 0 }];
      var arr = this.value;
      for (var i = 1; i < arr.length; i++) {
        if (arr[i].type === 1 || arr[i].type === 3 || arr[i].type === 13) {
          if (arr[i].type === 1)
            arr[i].value = Number(arr[i].value);
          post.push(arr[i]);
        } else if (arr[i].type === 4) {
          stack.push(arr[i]);
        } else if (arr[i].type === 5) {
          while ((popped = stack.pop()).type !== 4) {
            post.push(popped);
          }
        } else if (arr[i].type === 11) {
          while ((popped = stack.pop()).type !== 4) {
            post.push(popped);
          }
          stack.push(popped);
        } else {
          elem = arr[i];
          pre = elem.pre;
          ele = stack[stack.length - 1];
          prep = ele.pre;
          var flag = ele.value == "Math.pow" && elem.value == "Math.pow";
          if (pre > prep)
            stack.push(elem);
          else {
            while (prep >= pre && !flag || flag && pre < prep) {
              popped = stack.pop();
              ele = stack[stack.length - 1];
              post.push(popped);
              prep = ele.pre;
              flag = elem.value == "Math.pow" && ele.value == "Math.pow";
            }
            stack.push(elem);
          }
        }
      }
      return new Mexp(post);
    };
    module2.exports = Mexp;
  }
});

// node_modules/math-expression-evaluator/src/postfix_evaluator.js
var require_postfix_evaluator = __commonJS({
  "node_modules/math-expression-evaluator/src/postfix_evaluator.js"(exports, module2) {
    var Mexp = require_postfix();
    Mexp.prototype.postfixEval = function(UserDefined) {
      "use strict";
      UserDefined = UserDefined || {};
      UserDefined.PI = Math.PI;
      UserDefined.E = Math.E;
      var stack = [], pop1, pop2, pop3;
      var disp = [];
      var temp = "";
      var arr = this.value;
      var bool = typeof UserDefined.n !== "undefined";
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].type === 1) {
          stack.push({ value: arr[i].value, type: 1 });
        } else if (arr[i].type === 3) {
          stack.push({ value: UserDefined[arr[i].value], type: 1 });
        } else if (arr[i].type === 0) {
          if (typeof stack[stack.length - 1].type === "undefined") {
            stack[stack.length - 1].value.push(arr[i]);
          } else
            stack[stack.length - 1].value = arr[i].value(stack[stack.length - 1].value);
        } else if (arr[i].type === 7) {
          if (typeof stack[stack.length - 1].type === "undefined") {
            stack[stack.length - 1].value.push(arr[i]);
          } else
            stack[stack.length - 1].value = arr[i].value(stack[stack.length - 1].value);
        } else if (arr[i].type === 8) {
          pop1 = stack.pop();
          pop2 = stack.pop();
          stack.push({ type: 1, value: arr[i].value(pop2.value, pop1.value) });
        } else if (arr[i].type === 10) {
          pop1 = stack.pop();
          pop2 = stack.pop();
          if (typeof pop2.type === "undefined") {
            pop2.value = pop2.concat(pop1);
            pop2.value.push(arr[i]);
            stack.push(pop2);
          } else if (typeof pop1.type === "undefined") {
            pop1.unshift(pop2);
            pop1.push(arr[i]);
            stack.push(pop1);
          } else {
            stack.push({ type: 1, value: arr[i].value(pop2.value, pop1.value) });
          }
        } else if (arr[i].type === 2 || arr[i].type === 9) {
          pop1 = stack.pop();
          pop2 = stack.pop();
          if (typeof pop2.type === "undefined") {
            pop2 = pop2.concat(pop1);
            pop2.push(arr[i]);
            stack.push(pop2);
          } else if (typeof pop1.type === "undefined") {
            pop1.unshift(pop2);
            pop1.push(arr[i]);
            stack.push(pop1);
          } else {
            stack.push({ type: 1, value: arr[i].value(pop2.value, pop1.value) });
          }
        } else if (arr[i].type === 12) {
          pop1 = stack.pop();
          if (typeof pop1.type !== "undefined") {
            pop1 = [pop1];
          }
          pop2 = stack.pop();
          pop3 = stack.pop();
          stack.push({ type: 1, value: arr[i].value(pop3.value, pop2.value, new Mexp(pop1)) });
        } else if (arr[i].type === 13) {
          if (bool) {
            stack.push({ value: UserDefined[arr[i].value], type: 3 });
          } else
            stack.push([arr[i]]);
        }
      }
      if (stack.length > 1) {
        throw new Mexp.Exception("Uncaught Syntax error");
      }
      return stack[0].value > 1e15 ? "Infinity" : parseFloat(stack[0].value.toFixed(15));
    };
    Mexp.eval = function(str, tokens, obj) {
      if (typeof tokens === "undefined") {
        return this.lex(str).toPostfix().postfixEval();
      } else if (typeof obj === "undefined") {
        if (typeof tokens.length !== "undefined")
          return this.lex(str, tokens).toPostfix().postfixEval();
        else
          return this.lex(str).toPostfix().postfixEval(tokens);
      } else
        return this.lex(str, tokens).toPostfix().postfixEval(obj);
    };
    module2.exports = Mexp;
  }
});

// node_modules/math-expression-evaluator/src/formula_evaluator.js
var require_formula_evaluator = __commonJS({
  "node_modules/math-expression-evaluator/src/formula_evaluator.js"(exports, module2) {
    var Mexp = require_postfix_evaluator();
    Mexp.prototype.formulaEval = function() {
      "use strict";
      var stack = [], pop1, pop2, pop3;
      var disp = [];
      var temp = "";
      var arr = this.value;
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].type === 1 || arr[i].type === 3) {
          disp.push({ value: arr[i].type === 3 ? arr[i].show : arr[i].value, type: 1 });
        } else if (arr[i].type === 13) {
          disp.push({ value: arr[i].show, type: 1 });
        } else if (arr[i].type === 0) {
          disp[disp.length - 1] = { value: arr[i].show + (arr[i].show != "-" ? "(" : "") + disp[disp.length - 1].value + (arr[i].show != "-" ? ")" : ""), type: 0 };
        } else if (arr[i].type === 7) {
          disp[disp.length - 1] = { value: (disp[disp.length - 1].type != 1 ? "(" : "") + disp[disp.length - 1].value + (disp[disp.length - 1].type != 1 ? ")" : "") + arr[i].show, type: 7 };
        } else if (arr[i].type === 10) {
          pop1 = disp.pop();
          pop2 = disp.pop();
          if (arr[i].show === "P" || arr[i].show === "C")
            disp.push({ value: "<sup>" + pop2.value + "</sup>" + arr[i].show + "<sub>" + pop1.value + "</sub>", type: 10 });
          else
            disp.push({ value: (pop2.type != 1 ? "(" : "") + pop2.value + (pop2.type != 1 ? ")" : "") + "<sup>" + pop1.value + "</sup>", type: 1 });
        } else if (arr[i].type === 2 || arr[i].type === 9) {
          pop1 = disp.pop();
          pop2 = disp.pop();
          disp.push({ value: (pop2.type != 1 ? "(" : "") + pop2.value + (pop2.type != 1 ? ")" : "") + arr[i].show + (pop1.type != 1 ? "(" : "") + pop1.value + (pop1.type != 1 ? ")" : ""), type: arr[i].type });
        } else if (arr[i].type === 12) {
          pop1 = disp.pop();
          pop2 = disp.pop();
          pop3 = disp.pop();
          disp.push({ value: arr[i].show + "(" + pop3.value + "," + pop2.value + "," + pop1.value + ")", type: 12 });
        }
      }
      return disp[0].value;
    };
    module2.exports = Mexp;
  }
});

// src/index.ts
__export(exports, {
  default: () => ButtonsPlugin
});
var import_obsidian20 = __toModule(require("obsidian"));

// src/utils.ts
var import_obsidian = __toModule(require("obsidian"));

// src/buttonStore.ts
var buttonStore;
var getStore = (isMobile) => isMobile ? buttonStore : JSON.parse(localStorage.getItem("buttons"));
var initializeButtonStore = (app, storeEvents) => {
  const files = app.vault.getMarkdownFiles();
  const blocksArr = files.map((file) => {
    const cache = app.metadataCache.getFileCache(file);
    return buildButtonArray(cache, file);
  }).filter((arr) => arr !== void 0).flat();
  localStorage.setItem("buttons", JSON.stringify(blocksArr));
  buttonStore = blocksArr;
  storeEvents.trigger("index-complete");
};
var addButtonToStore = (app, file) => {
  const cache = app.metadataCache.getFileCache(file);
  const buttons = buildButtonArray(cache, file);
  const store = getStore(app.isMobile);
  const newStore = buttons && store ? removeDuplicates([...buttons, ...store]) : store ? removeDuplicates(store) : buttons ? removeDuplicates(buttons) : [];
  localStorage.setItem("buttons", JSON.stringify(newStore));
  buttonStore = newStore;
};
var getButtonFromStore = async (app, args) => {
  const store = getStore(app.isMobile);
  args.id;
  if (args.id) {
    const storedButton = store && store.filter((item) => `button-${args.id}` === item.id)[0];
    if (storedButton) {
      const file = app.vault.getAbstractFileByPath(storedButton.path);
      const content = await app.vault.cachedRead(file);
      const contentArray = content.split("\n");
      const button = contentArray.slice(storedButton.position.start.line + 1, storedButton.position.end.line).join("\n");
      const storedArgs = createArgumentObject(button);
      return {
        args: { ...storedArgs, ...args },
        id: storedButton.id.split("button-")[1]
      };
    }
  }
};
var getButtonById = async (app, id) => {
  const store = getStore(app.isMobile);
  const readArgsByBlockId = async (blockId) => {
    const btn = (store || []).find((item) => `button-${blockId}` === item.id);
    if (!btn)
      return void 0;
    const file = app.vault.getAbstractFileByPath(btn.path);
    const content = await app.vault.cachedRead(file);
    const contentArray = content.split("\n");
    const button = contentArray.slice(btn.position.start.line + 1, btn.position.end.line).join("\n");
    return createArgumentObject(button);
  };
  const resolveInheritedArgs = async (startId, visited = new Set(), depth = 0) => {
    if (depth > 3)
      return void 0;
    if (visited.has(startId))
      return void 0;
    visited.add(startId);
    const childArgs = await readArgsByBlockId(startId);
    if (!childArgs)
      return void 0;
    const parentId = typeof childArgs.id === "string" ? childArgs.id.trim() : "";
    if (!parentId)
      return childArgs;
    const parentArgs = await resolveInheritedArgs(parentId, visited, depth + 1);
    if (!parentArgs)
      return childArgs;
    return { ...parentArgs, ...childArgs };
  };
  const merged = await resolveInheritedArgs(id);
  if (merged)
    return merged;
};
var getButtonSwapById = async (app, id) => {
  const store = getStore(app.isMobile);
  const storedButton = store.filter((item) => `button-${id}` === item.id)[0];
  if (storedButton) {
    return storedButton.swap;
  }
};
var setButtonSwapById = async (app, id, newSwap) => {
  const store = getStore(app.isMobile);
  const storedButton = store.filter((item) => `button-${id}` === item.id)[0];
  if (storedButton) {
    storedButton.swap = newSwap;
    const newStore = removeDuplicates([...store, storedButton]);
    localStorage.setItem("buttons", JSON.stringify(newStore));
    buttonStore = newStore;
  }
};
var buildButtonArray = (cache, file) => {
  const blocks = cache && cache.blocks;
  if (blocks) {
    const blockKeys = Array.from(Object.keys(blocks));
    const blockArray = blockKeys.map((key) => blocks[key]).map((obj) => {
      obj["path"] = file.path;
      obj["swap"] = 0;
      return obj;
    }).filter((block) => block.id.includes("button"));
    return blockArray;
  }
};
function removeDuplicates(arr) {
  return arr && arr[0] ? arr.filter((v, i, a) => a.findIndex((t) => t.id === v.id || t.path === v.path && t.position.start.line === v.position.start.line && t.position.end.line === v.position.end.line) === i) : arr;
}

// src/utils.ts
function nanoid(num) {
  let result = "";
  const characters = "abcdefghijklmnopqrstuvwxyz0123456789";
  const charactersLength = characters.length;
  for (let i = 0; i < num; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
var insertButton = (app, outputObject) => {
  const buttonArr = [];
  buttonArr.push("```button");
  outputObject.name && buttonArr.push(`name ${outputObject.name}`);
  if (outputObject.type && outputObject.type.includes("note") && outputObject.noteTitle && outputObject.openMethod) {
    const noteType = `note(${outputObject.noteTitle}, ${outputObject.openMethod}) ${outputObject.type.replace("note ", "")}`;
    buttonArr.push(`type ${noteType}`);
    outputObject.action && buttonArr.push(`action ${outputObject.action}`);
  } else {
    outputObject.type && buttonArr.push(`type ${outputObject.type}`);
    outputObject.action && buttonArr.push(`action ${outputObject.action}`);
  }
  outputObject.id && buttonArr.push(`id ${outputObject.id}`);
  outputObject.swap && buttonArr.push(`swap ${outputObject.swap}`);
  outputObject.remove && buttonArr.push(`remove ${outputObject.remove}`);
  outputObject.replace && buttonArr.push(`replace ${outputObject.replace}`);
  outputObject.templater === true && buttonArr.push(`templater ${outputObject.templater}`);
  outputObject.color && buttonArr.push(`color ${outputObject.color}`);
  outputObject.customColor && buttonArr.push(`customColor ${outputObject.customColor}`);
  outputObject.customTextColor && buttonArr.push(`customTextColor ${outputObject.customTextColor}`);
  outputObject.class && buttonArr.push(`class ${outputObject.class}`);
  outputObject.folder && buttonArr.push(`folder ${outputObject.folder}`);
  outputObject.prompt && buttonArr.push(`prompt ${outputObject.prompt}`);
  if (outputObject.actions && Array.isArray(outputObject.actions) && outputObject.actions.length > 0) {
    buttonArr.push(`actions ${JSON.stringify(outputObject.actions)}`);
  }
  buttonArr.push("```");
  outputObject.blockId ? buttonArr.push(`^button-${outputObject.blockId}`) : buttonArr.push(`^button-${nanoid(4)}`);
  const page = app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
  const editor = page.editor;
  editor.replaceSelection(buttonArr.join("\n"));
  addButtonToStore(app, page.file);
};
var insertInlineButton = (app, id) => {
  const page = app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
  const editor = page.editor;
  editor.replaceSelection(`\`button-${id}\``);
};
var createArgumentObject = (source) => {
  const lines = source.split("\n");
  const acc = {};
  const knownArguments = new Set([
    "name",
    "type",
    "action",
    "id",
    "swap",
    "remove",
    "replace",
    "templater",
    "color",
    "customcolor",
    "customtextcolor",
    "class",
    "folder",
    "prompt",
    "actions",
    "width",
    "height",
    "align"
  ]);
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const split = line.split(" ");
    const key = split[0]?.toLowerCase();
    if (!key)
      continue;
    if (key === "name") {
      const parseLines = [line.replace(/^name\s*/, "")];
      let destructor = parseMultiLine(lines, i, parseLines);
      if (destructor.parseValue[0] == "{") {
        acc[key] = destructor.parseValue.slice(1, -1).trim();
      } else {
        acc[key] = destructor.parseValue.trim();
      }
      i = destructor.i;
    } else if (key === "actions") {
      const jsonLines = [line.replace(/^actions\s*/, "")];
      let destructor = parseMultiLine(lines, i, jsonLines);
      try {
        acc[key] = JSON.parse(destructor.parseValue);
      } catch (e) {
        acc[key] = [];
        new import_obsidian.Notice(`Error: Malformed JSON in actions field. Please check your chain button syntax.`, 4e3);
      }
      i = destructor.i;
    } else if (key === "action") {
      const actionLines = [line.replace(/^action\s*/, "")];
      while (i + 1 < lines.length) {
        const nextLine = lines[i + 1];
        if (nextLine.startsWith("```")) {
          break;
        }
        if (nextLine.trim() !== "" && !nextLine.startsWith(" ") && !nextLine.startsWith("	")) {
          const potentialKey = nextLine.split(" ")[0]?.toLowerCase();
          if (knownArguments.has(potentialKey)) {
            break;
          }
        }
        i++;
        actionLines.push(nextLine);
      }
      const actionContent = actionLines.join("\n").replace(/\s+$/, "");
      acc[key] = actionContent;
    } else {
      const value = split.slice(1).join(" ").trim();
      acc[key] = value;
    }
  }
  return acc;
};
var createContentArray = async (app) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
  if (activeView) {
    const file = activeView.file;
    const content = await app.vault.read(file);
    return { contentArray: content.split("\n"), file };
  }
  new import_obsidian.Notice("Could not get Active View", 1e3);
  console.error("could not get active view");
};
var handleValueArray = (value, callback) => {
  if (value.includes("[") && value.includes("]")) {
    const args = value.match(/\[(.*)\]/);
    if (args[1]) {
      const argArray = args[1].split(/,\s?/);
      if (argArray[0]) {
        callback(argArray);
      }
    }
  }
};
async function getNewArgs(app, position) {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian.MarkdownView);
  const newContent = await app.vault.cachedRead(activeView.file).then((content) => content.split("\n"));
  const newButton = newContent.splice(position.lineStart, position.lineEnd - position.lineStart).join("\n").replace("```button", "").replace("```", "");
  return { args: createArgumentObject(newButton) };
}
var wrapAround = (value, size) => {
  return (value % size + size) % size;
};
var parseMultiLine = (lines, iStart, parseLinesStart) => {
  let i = iStart;
  let parseLines = parseLinesStart;
  let bracketCount = 0;
  let braceCount = 0;
  let inString = false;
  let escaped = false;
  let parseValue;
  for (const char of parseLines[0]) {
    if (escaped) {
      escaped = false;
      continue;
    }
    if (char === "\\") {
      escaped = true;
      continue;
    }
    if (char === '"' && !escaped) {
      inString = !inString;
      continue;
    }
    if (!inString) {
      if (char === "[")
        bracketCount++;
      else if (char === "]")
        bracketCount--;
      else if (char === "{")
        braceCount++;
      else if (char === "}")
        braceCount--;
    }
  }
  while ((bracketCount > 0 || braceCount > 0) && i + 1 < lines.length) {
    i++;
    const nextLine = lines[i];
    parseLines.push(nextLine);
    for (const char of nextLine) {
      if (escaped) {
        escaped = false;
        continue;
      }
      if (char === "\\") {
        escaped = true;
        continue;
      }
      if (char === '"' && !escaped) {
        inString = !inString;
        continue;
      }
      if (!inString) {
        if (char === "[")
          bracketCount++;
        else if (char === "]")
          bracketCount--;
        else if (char === "{")
          braceCount++;
        else if (char === "}")
          braceCount--;
      }
    }
  }
  const parseString = parseLines.join("\n").trim();
  parseValue = parseString;
  return { parseValue, i };
};

// src/events.ts
var buttonEventListener = (app, callback) => {
  return app.metadataCache.on("changed", (file) => {
    callback(app, file);
  });
};
var openFileListener = (app, storeEvents, callback) => {
  return app.workspace.on("file-open", () => {
    callback(app, storeEvents);
  });
};

// src/modal.ts
var import_obsidian18 = __toModule(require("obsidian"));

// src/button.ts
var import_obsidian16 = __toModule(require("obsidian"));

// src/buttonTypes/calculate.ts
var import_obsidian9 = __toModule(require("obsidian"));
var import_math_expression_evaluator = __toModule(require_formula_evaluator());

// src/handlers/removeButton.ts
var removeButton = async (app, remove2, lineStart, lineEnd) => {
  const { contentArray, file } = await createContentArray(app);
  const store = getStore(app.isMobile);
  if (remove2 === "true") {
    const numberOfItems = lineEnd - lineStart;
    contentArray.splice(lineStart, numberOfItems + 1);
    if (contentArray[lineStart] && contentArray[lineStart].includes("^button-")) {
      contentArray.splice(lineStart, 1);
    }
    const content = contentArray.join("\n");
    await app.vault.modify(file, content);
    return;
  }
  if (lineStart === lineEnd) {
    contentArray.splice(lineStart, 1);
    const content = contentArray.join("\n");
    await app.vault.modify(file, content);
    return;
  }
  handleValueArray(remove2, async (argArray) => {
    if (!store) {
      return;
    }
    const buttons = store.filter((item) => {
      let exists = false;
      argArray.forEach((arg) => {
        if (item.id === `button-${arg}` && item.path === file.path) {
          exists = true;
        }
      });
      return exists;
    });
    if (buttons && buttons.length > 0) {
      let offset2 = 0;
      buttons.forEach((button) => {
        const start2 = button.position.start.line - offset2;
        const numLines = button.position.end.line - button.position.start.line;
        contentArray.splice(start2, numLines + 2);
        offset2 += numLines + 2;
      });
      const content = contentArray.join("\n");
      await app.vault.modify(file, content);
    }
  });
};

// src/handlers/removeSection.ts
var removeSection = async (app, section, buttonPosition, preCapturedCursorLine) => {
  const { contentArray, file } = await createContentArray(app);
  if (section.includes("[") && section.includes("]")) {
    const args = section.match(/\[(.*)\]/);
    if (args && args[1]) {
      if (args[1].trim().toLowerCase() === "cursor") {
        if (preCapturedCursorLine !== void 0) {
          if (preCapturedCursorLine >= 0 && preCapturedCursorLine < contentArray.length) {
            contentArray.splice(preCapturedCursorLine, 1);
            const content = contentArray.join("\n");
            await app.vault.modify(file, content);
          }
        }
        return;
      }
      const argArray = args[1].split(/,\s?/);
      if (argArray[0]) {
        let startLine;
        const firstArgRelative = argArray[0].match(/^([+-])(\d+)$/);
        if (firstArgRelative && buttonPosition) {
          const operator = firstArgRelative[1];
          const offset2 = parseInt(firstArgRelative[2]);
          if (operator === "+") {
            startLine = buttonPosition.lineEnd + 1 + offset2;
          } else {
            startLine = buttonPosition.lineStart + 1 - offset2;
            if (startLine < 1) {
              startLine = 1;
            }
          }
        } else {
          startLine = parseInt(argArray[0]);
        }
        const start2 = startLine - 1;
        if (argArray.length === 1) {
          contentArray.splice(start2, 1);
        } else {
          let endLine;
          const secondArgRelative = argArray[1].match(/^([+-])(\d+)$/);
          if (secondArgRelative && buttonPosition) {
            const operator = secondArgRelative[1];
            const offset2 = parseInt(secondArgRelative[2]);
            if (operator === "+") {
              endLine = buttonPosition.lineEnd + 1 + offset2;
            } else {
              endLine = buttonPosition.lineStart + 1 - offset2;
              if (endLine < 1) {
                endLine = 1;
              }
            }
          } else {
            endLine = parseInt(argArray[1]);
          }
          if (!isNaN(endLine)) {
            const numLines = endLine - start2;
            if (numLines > 0) {
              contentArray.splice(start2, numLines);
            }
          }
        }
        const content = contentArray.join("\n");
        await app.vault.modify(file, content);
      }
    }
  }
};

// src/handlers/prependContent.ts
var import_obsidian3 = __toModule(require("obsidian"));

// src/templater.ts
var import_obsidian2 = __toModule(require("obsidian"));
async function templater(app, template2, _target) {
  const activeFile = template2 || app.workspace.getActiveFile();
  const targetFile = _target || activeFile;
  if (!activeFile) {
    new import_obsidian2.Notice("No active file found for templater processing.");
    return;
  }
  const config = {
    template_file: template2,
    active_file: activeFile,
    target_file: targetFile,
    run_mode: "DynamicProcessor"
  };
  const plugins = app.plugins.plugins;
  const exists = plugins["templater-obsidian"];
  if (!exists) {
    new import_obsidian2.Notice("Templater is not installed. Please install it.");
    return;
  }
  try {
    const { templater: templater3 } = plugins["templater-obsidian"];
    const functions = await templater3.functions_generator.internal_functions.generate_object(config);
    functions.user = {};
    const userScriptFunctions = await templater3.functions_generator.user_functions.user_script_functions.generate_user_script_functions(config);
    userScriptFunctions.forEach((value, key) => {
      functions.user[key] = value;
    });
    if (activeFile) {
      const userSystemFunctions = await templater3.functions_generator.user_functions.user_system_functions.generate_system_functions(config);
      userSystemFunctions.forEach((value, key) => {
        functions.user[key] = value;
      });
    }
    return async (command2) => {
      return await templater3.parser.parse_commands(command2, functions);
    };
  } catch (error) {
    console.error("Error setting up templater functions:", error);
    new import_obsidian2.Notice("Error setting up templater functions. Check console for details.");
    return;
  }
}
async function processTemplate(app, file) {
  try {
    const content = await app.vault.read(file);
    const runTemplater = await templater(app, file, file);
    if (runTemplater) {
      const processed = await runTemplater(content);
      return processed;
    }
  } catch (e) {
    new import_obsidian2.Notice(`There was an error processing the template!`, 2e3);
  }
}
var templater_default = templater;

// src/handlers/prependContent.ts
var prependContent = async (app, insert, lineStart, isTemplater) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian3.MarkdownView);
  if (activeView) {
    const file = activeView.file;
    let content = await app.vault.read(file);
    const contentArray = content.split("\n");
    if (typeof insert === "string") {
      const lines = insert.split("\n");
      contentArray.splice(lineStart, 0, ...lines);
    } else {
      if (isTemplater) {
        const runTemplater = await templater_default(app, insert, file);
        const templateContent = await app.vault.read(insert);
        const processed = await runTemplater(templateContent);
        const lines = processed.split("\n");
        contentArray.splice(lineStart, 0, ...lines);
      } else {
        activeView.editor.setCursor(lineStart);
        await app.internalPlugins?.plugins["templates"].instance.insertTemplate(insert);
        return;
      }
    }
    content = contentArray.join("\n");
    await app.vault.modify(file, content);
  } else {
    new import_obsidian3.Notice("There was an issue prepending content, please try again", 2e3);
  }
};

// src/handlers/appendContent.ts
var import_obsidian4 = __toModule(require("obsidian"));
var appendContent = async (app, insert, lineEnd, isTemplater) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian4.MarkdownView);
  if (activeView) {
    const file = activeView.file;
    let content = await app.vault.read(file);
    const contentArray = content.split("\n");
    let insertionPoint;
    if (contentArray[lineEnd + 1] && contentArray[lineEnd + 1].includes("^button")) {
      insertionPoint = lineEnd + 2;
    } else {
      insertionPoint = lineEnd + 1;
    }
    if (typeof insert === "string") {
      const lines = insert.split("\n");
      contentArray.splice(insertionPoint, 0, ...lines);
    } else {
      if (isTemplater) {
        const runTemplater = await templater_default(app, insert, file);
        const content2 = await app.vault.read(insert);
        const processed = await runTemplater(content2);
        const lines = processed.split("\n");
        contentArray.splice(insertionPoint, 0, ...lines);
      } else {
        activeView.editor.setCursor(insertionPoint);
        await app.internalPlugins?.plugins["templates"].instance.insertTemplate(insert);
        return;
      }
    }
    content = contentArray.join("\n");
    await app.vault.modify(file, content);
  } else {
    new import_obsidian4.Notice("There was an issue appending content, please try again", 2e3);
  }
};

// src/handlers/addContentAtLine.ts
var import_obsidian5 = __toModule(require("obsidian"));
var addContentAtLine = async (app, insert, type, isTemplater, buttonPosition) => {
  let insertionPoint;
  const relativeMatch = type.match(/line\(([+-])(\d+)\)/);
  if (relativeMatch && buttonPosition) {
    const operator = relativeMatch[1];
    const offset2 = parseInt(relativeMatch[2]);
    if (operator === "+") {
      insertionPoint = buttonPosition.lineEnd + offset2;
    } else {
      insertionPoint = buttonPosition.lineStart - offset2;
      if (insertionPoint < 0) {
        insertionPoint = 0;
      }
    }
  } else {
    const lineNumber = type.match(/(\d+)/g);
    if (lineNumber && lineNumber[0]) {
      insertionPoint = parseInt(lineNumber[0]) - 1;
    } else {
      new import_obsidian5.Notice("There was an issue parsing the line number, please try again", 2e3);
      return;
    }
  }
  const activeView = app.workspace.getActiveViewOfType(import_obsidian5.MarkdownView);
  if (activeView) {
    const file = activeView.file;
    let content = await app.vault.read(file);
    const contentArray = content.split("\n");
    if (typeof insert === "string") {
      const lines = insert.split("\n");
      contentArray.splice(insertionPoint, 0, ...lines);
    } else {
      if (isTemplater) {
        const runTemplater = await templater_default(app, insert, file);
        const content2 = await app.vault.read(insert);
        const processed = await runTemplater(content2);
        const lines = processed.split("\n");
        contentArray.splice(insertionPoint, 0, ...lines);
      } else {
        activeView.editor.setCursor(insertionPoint);
        await app.internalPlugins?.plugins["templates"].instance.insertTemplate(insert);
        return;
      }
    }
    content = contentArray.join("\n");
    await app.vault.modify(file, content);
  }
};

// src/handlers/addContentAtCursor.ts
var import_obsidian6 = __toModule(require("obsidian"));
var addContentAtCursor = async (app, insert, isTemplater) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian6.MarkdownView);
  if (activeView) {
    const editor = activeView.editor;
    const cursor = editor.getCursor();
    if (typeof insert === "string") {
      editor.replaceRange(insert, cursor);
      const lines = insert.split("\n");
      if (lines.length === 1) {
        editor.setCursor({
          line: cursor.line,
          ch: cursor.ch + insert.length
        });
      } else {
        editor.setCursor({
          line: cursor.line + lines.length - 1,
          ch: lines[lines.length - 1].length
        });
      }
    } else {
      if (isTemplater) {
        const file = activeView.file;
        const runTemplater = await templater_default(app, insert, file);
        if (runTemplater) {
          const templateContent = await app.vault.read(insert);
          const processed = await runTemplater(templateContent);
          editor.replaceRange(processed, cursor);
          const lines = processed.split("\n");
          if (lines.length === 1) {
            editor.setCursor({
              line: cursor.line,
              ch: cursor.ch + processed.length
            });
          } else {
            editor.setCursor({
              line: cursor.line + lines.length - 1,
              ch: lines[lines.length - 1].length
            });
          }
        } else {
          new import_obsidian6.Notice("Failed to initialize Templater processor", 2e3);
          return;
        }
      } else {
        await app.internalPlugins?.plugins["templates"].instance.insertTemplate(insert);
      }
    }
  } else {
    new import_obsidian6.Notice("There was an issue inserting content at cursor, please try again", 2e3);
  }
};

// src/handlers/createNote.ts
var import_obsidian8 = __toModule(require("obsidian"));

// src/nameModal.ts
var import_obsidian7 = __toModule(require("obsidian"));
var nameModal = class extends import_obsidian7.Modal {
  constructor(app, onSubmit, defaultName) {
    super(app);
    __publicField(this, "result");
    __publicField(this, "defaultName");
    __publicField(this, "onSubmit");
    this.onSubmit = onSubmit;
    this.defaultName = defaultName;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.createEl("h1", { text: "Name of new note" });
    new import_obsidian7.Setting(contentEl).setName("Name").addText((text2) => {
      text2.setPlaceholder(this.defaultName);
      text2.onChange((value) => {
        this.result = value;
      });
    });
    new import_obsidian7.Setting(contentEl).addButton((btn) => btn.setButtonText("Create Note").setCta().onClick(() => {
      this.close();
      this.onSubmit(this.result);
    }));
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/handlers/createNote.ts
var createNote = async (app, type, folder, prompt, filePath, isTemplater) => {
  const path = type.match(/\(([\s\S]*?),?\s?(vsplit|hsplit|split|tab|same|false)?\)/);
  if (path) {
    let fullPath = `${path[1]}.md`;
    const fileName = fullPath.substring(fullPath.lastIndexOf("/"));
    fullPath = folder ? `${folder}/${fullPath}` : fullPath;
    const directoryPath = fullPath.substring(0, fullPath.lastIndexOf("/"));
    if (directoryPath && !app.vault.getAbstractFileByPath(directoryPath)) {
      console.log("trying to create folder at: ", directoryPath);
      await app.vault.createFolder(directoryPath);
    }
    try {
      if (prompt === "true") {
        const promptedName = await new Promise((res) => new nameModal(app, res, fileName).open());
        fullPath = promptedName ? `${directoryPath}/${promptedName}.md` : fullPath;
      }
      const originalActiveView = app.workspace.getActiveViewOfType(import_obsidian8.MarkdownView);
      const originalActiveLeaf = originalActiveView?.leaf;
      let file;
      if (typeof filePath === "string") {
        file = await app.vault.create(fullPath, filePath);
      } else {
        if (isTemplater) {
          const templateContent = await app.vault.read(filePath);
          file = await app.vault.create(fullPath, templateContent);
          const runTemplater = await templater_default(app, filePath, file);
          const content = await app.vault.read(filePath);
          const processed = await runTemplater(content);
          await app.vault.modify(file, processed);
        } else {
          file = await app.vault.create(fullPath, "");
          const tempLeaf = app.workspace.getLeaf("tab");
          try {
            await tempLeaf.openFile(file);
            await app.internalPlugins?.plugins["templates"].instance.insertTemplate(filePath);
          } finally {
            tempLeaf.detach();
          }
        }
      }
      const openOption = path[2];
      if (openOption === "false") {
        return;
      } else if (openOption === "vsplit") {
        const leaf = app.workspace.getLeaf("split", "vertical");
        await leaf.openFile(file);
      } else if (openOption === "hsplit") {
        const leaf = app.workspace.getLeaf("split", "horizontal");
        await leaf.openFile(file);
      } else if (openOption === "split") {
        const leaf = app.workspace.getLeaf("split", "vertical");
        await leaf.openFile(file);
      } else if (openOption === "tab") {
        const leaf = app.workspace.getLeaf("tab");
        await leaf.openFile(file);
      } else if (openOption === "same") {
        if (originalActiveLeaf && originalActiveLeaf.view) {
          await originalActiveLeaf.openFile(file);
        } else {
          const currentActiveView = app.workspace.getActiveViewOfType(import_obsidian8.MarkdownView);
          if (currentActiveView?.leaf) {
            await currentActiveView.leaf.openFile(file);
          } else {
            await app.workspace.getLeaf().openFile(file);
          }
        }
      } else {
        await app.workspace.getLeaf().openFile(file);
      }
    } catch (e) {
      console.error("Error in Buttons: ", e);
      new import_obsidian8.Notice("There was an error! Maybe the file already exists?", 2e3);
    }
  } else {
    new import_obsidian8.Notice(`couldn't parse the path!`, 2e3);
  }
};

// src/parser.ts
var getButtonPosition = (content, args) => {
  let finalPosition;
  const possiblePositions = [];
  let possiblePosition = { lineStart: 0, lineEnd: 0 };
  const contentArray = content.split("\n");
  let open = false;
  contentArray.forEach((item, index) => {
    if (item.includes("```")) {
      if (open === false) {
        possiblePosition.lineStart = index;
        open = true;
      } else {
        possiblePosition.lineEnd = index;
        possiblePositions.push(possiblePosition);
        possiblePosition = { lineStart: 0, lineEnd: 0 };
        open = false;
      }
    }
  });
  possiblePositions.forEach((position) => {
    const codeblock = contentArray.slice(position.lineStart, position.lineEnd + 1).join("\n");
    if (codeblock.includes("button") && codeblock.includes(args.name)) {
      finalPosition = position;
    }
  });
  return finalPosition;
};
var getInlineButtonPosition = async (app, id) => {
  const content = await createContentArray(app);
  const position = { lineStart: 0, lineEnd: 0 };
  content.contentArray.map((line) => line.split(" ")).forEach((words, index) => {
    words.forEach((word) => {
      if (word.startsWith("`button")) {
        if (word === `\`button-${id}\``) {
          position.lineStart = index;
          position.lineEnd = index;
        }
      }
    });
  });
  return position;
};
var getBlockButtonPositionById = async (app, id) => {
  const store = getStore(app.isMobile);
  if (!store || !id)
    return void 0;
  const activeFile = app.workspace.getActiveFile();
  if (!activeFile)
    return void 0;
  const button = store.find((item) => item.id === `button-${id}` && item.path === activeFile.path);
  if (!button)
    return void 0;
  return {
    lineStart: button.position.start.line,
    lineEnd: button.position.end.line
  };
};
var findNumber = async (app, lineNumber) => {
  const content = await createContentArray(app);
  const value = [];
  content.contentArray.forEach((line, index) => {
    if (index === lineNumber - 1) {
      value.push(line);
    }
  });
  const convertWords = value.join("").replace("plus", "+").replace("minus", "-").replace("times", "*").replace(/divide(d)?(\sby)?/g, "/");
  const numbers = convertWords.replace(/\s/g, "").match(/[^\w:]*?\d+?/g);
  return numbers;
};

// src/buttonTypes/calculate.ts
var calculate = async (app, { action }, position) => {
  let equation = action;
  const variables = action.match(/\$[0-9]*/g);
  if (variables) {
    const output = variables.map(async (value) => {
      const activeView = app.workspace.getActiveViewOfType(import_obsidian9.MarkdownView);
      if (activeView) {
        const lineNumber = parseInt(value.substring(1));
        const numbers = await findNumber(app, lineNumber);
        return { variable: value, numbers };
      } else {
        new import_obsidian9.Notice(`couldn't read file`, 2e3);
      }
    });
    const resolved = await Promise.all(output);
    resolved.forEach((term) => {
      if (term.numbers) {
        equation = equation.replace(term.variable, term.numbers.join(""));
      } else {
        new import_obsidian9.Notice("Check the line number in your calculate button", 3e3);
        equation = void 0;
      }
    });
  }
  const fun = equation && import_math_expression_evaluator.default.eval(equation);
  if (fun !== null && fun !== void 0) {
    appendContent(app, `Result: ${fun}`, position.lineEnd, false);
  }
};

// src/buttonTypes/remove.ts
var remove = async (app, { remove: remove2 }, { lineStart, lineEnd }) => {
  await removeButton(app, remove2, lineStart, lineEnd);
};

// src/buttonTypes/replace.ts
var import_obsidian10 = __toModule(require("obsidian"));
var replace = async (app, { replace: replace2 }, position) => {
  let cursorPosition;
  if (replace2.includes("[cursor]")) {
    const activeView = app.workspace.getActiveViewOfType(import_obsidian10.MarkdownView);
    if (activeView) {
      const editor = activeView.editor;
      const cursor = editor.getCursor();
      cursorPosition = cursor.line;
    }
  }
  await removeSection(app, replace2, position, cursorPosition);
};

// src/buttonTypes/text.ts
var text = async (app, args, position) => {
  if (args.type.includes("prepend")) {
    await prependContent(app, args.action, position.lineStart, false);
  }
  if (args.type.includes("append")) {
    await appendContent(app, args.action, position.lineEnd, false);
  }
  if (args.type.includes("note")) {
    createNote(app, args.type, args.folder, args.prompt, args.action, false);
  }
  if (args.type.includes("line")) {
    await addContentAtLine(app, args.action, args.type, false, position);
  }
  if (args.type.includes("cursor")) {
    await addContentAtCursor(app, args.action, false);
  }
};

// src/buttonTypes/template.ts
var import_obsidian11 = __toModule(require("obsidian"));
var findTemplate = (app, templateFile, templatesEnabled, templaterPluginEnabled) => {
  const allFiles = app.vault.getFiles();
  const results = [];
  if (templatesEnabled) {
    const folder = app.internalPlugins.plugins.templates.instance.options.folder;
    if (folder) {
      const folderLower = folder.toLowerCase();
      const coreTemplateFile = allFiles.find((file) => file.path.toLowerCase() === `${folderLower}/${templateFile}.md`);
      if (coreTemplateFile) {
        results.push({
          file: coreTemplateFile,
          source: "core",
          isTemplater: false
        });
      }
    }
  }
  if (templaterPluginEnabled) {
    const templaterPlugin = app.plugins?.plugins["templater-obsidian"];
    const folder = templaterPlugin?.settings?.templates_folder;
    if (folder) {
      const folderLower = folder.toLowerCase();
      const templaterFile = allFiles.find((file) => file.path.toLowerCase() === `${folderLower}/${templateFile}.md`);
      if (templaterFile) {
        results.push({
          file: templaterFile,
          source: "templater",
          isTemplater: true
        });
      }
    }
  }
  if (results.length === 0) {
    return { file: null, isTemplater: false, source: "none" };
  } else if (results.length === 1) {
    const result = results[0];
    return {
      file: result.file,
      isTemplater: result.isTemplater,
      source: result.source
    };
  } else {
    const templaterResult = results.find((r) => r.source === "templater");
    const coreResult = results.find((r) => r.source === "core");
    if (templaterResult && coreResult) {
      new import_obsidian11.Notice(`Found template "${templateFile}" in both Core Templates and Templater folders. Using Templater version.`, 3e3);
      return {
        file: templaterResult.file,
        isTemplater: templaterResult.isTemplater,
        source: templaterResult.source
      };
    }
    const result = results[0];
    return {
      file: result.file,
      isTemplater: result.isTemplater,
      source: result.source
    };
  }
};
var template = async (app, args, position) => {
  const templatesEnabled = app.internalPlugins.plugins.templates.enabled;
  const templaterPluginEnabled = !!app.plugins.plugins["templater-obsidian"];
  const templateFile = args.action.toLowerCase();
  if (!templatesEnabled && !templaterPluginEnabled) {
    new import_obsidian11.Notice("You need to have the Templates or Templater plugin enabled and Template folder defined", 2e3);
    return;
  }
  const searchResult = findTemplate(app, templateFile, templatesEnabled, templaterPluginEnabled);
  if (!searchResult.file) {
    const availableFolders = [];
    if (templatesEnabled) {
      const coreFolder = app.internalPlugins.plugins.templates.instance.options.folder;
      if (coreFolder)
        availableFolders.push(`Core Templates: ${coreFolder}`);
    }
    if (templaterPluginEnabled) {
      const templaterPlugin = app.plugins?.plugins["templater-obsidian"];
      const templaterFolder = templaterPlugin?.settings?.templates_folder;
      if (templaterFolder)
        availableFolders.push(`Templater: ${templaterFolder}`);
    }
    const folderList = availableFolders.length > 0 ? `

Searched in: ${availableFolders.join(", ")}` : "";
    new import_obsidian11.Notice(`Couldn't find template "${templateFile}.md" in any configured template folder.${folderList}`, 4e3);
    return;
  }
  const { file, isTemplater } = searchResult;
  try {
    if (args.type.includes("prepend")) {
      await prependContent(app, file, position.lineStart, isTemplater);
    }
    if (args.type.includes("append")) {
      await appendContent(app, file, position.lineEnd, isTemplater);
    }
    if (args.type.includes("note")) {
      createNote(app, args.type, args.folder, args.prompt, file, isTemplater);
    }
    if (args.type.includes("line")) {
      await addContentAtLine(app, file, args.type, isTemplater, position);
    }
    if (args.type.includes("cursor")) {
      await addContentAtCursor(app, file, isTemplater);
    }
  } catch (error) {
    console.error("Error executing template action:", error);
    new import_obsidian11.Notice(`Error executing template "${templateFile}". Check console for details.`, 3e3);
  }
};

// src/buttonTypes/link.ts
var link = ({ action }) => {
  const link2 = action.trim();
  window.open(link2);
};

// src/buttonTypes/copy.ts
var copy = ({ action }) => {
  navigator.clipboard.writeText(action);
};

// src/buttonTypes/command.ts
var import_obsidian12 = __toModule(require("obsidian"));
var command = (app, args, buttonStart) => {
  const allCommands = app.commands.listCommands();
  const action = args.action;
  const command2 = allCommands.filter((command3) => command3.name.toUpperCase() === action.toUpperCase().trim())[0];
  if (!command2) {
    new import_obsidian12.Notice(`Command "${action}" not found. Available commands can be found in the Command Palette.`);
    console.error(`Button command error: Command "${action}" not found.`);
    console.log("Available commands:", allCommands.map((cmd) => cmd.name));
    return;
  }
  try {
    if (args.type.includes("prepend")) {
      app.workspace.getActiveViewOfType(import_obsidian12.MarkdownView).editor.setCursor(buttonStart.lineStart, 0);
      app.commands.executeCommandById(command2.id);
    }
    if (args.type.includes("append")) {
      app.workspace.getActiveViewOfType(import_obsidian12.MarkdownView).editor.setCursor(buttonStart.lineEnd + 2, 0);
      app.commands.executeCommandById(command2.id);
    }
    if (args.type === "command") {
      app.commands.executeCommandById(command2.id);
    }
  } catch (error) {
    new import_obsidian12.Notice(`Failed to execute command "${action}": ${error.message}`);
    console.error(`Button command execution error:`, error);
  }
};

// src/buttonTypes/swap.ts
var import_obsidian14 = __toModule(require("obsidian"));

// src/buttonTypes/templater.ts
var import_obsidian13 = __toModule(require("obsidian"));
var templater2 = async (app, position) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian13.MarkdownView);
  if (activeView) {
    await activeView.save();
    const file = activeView.file;
    const content = await processTemplate(app, file);
    const { args } = await getNewArgs(app, position);
    const cachedData = [];
    const cacheChange = app.vault.on("modify", (file2) => {
      cachedData.push(file2.unsafeCachedData);
    });
    setTimeout(async () => {
      const button = content.split("\n").splice(position.lineStart, position.lineEnd - position.lineStart + 2).join("\n");
      let finalContent;
      if (cachedData[0]) {
        const cachedContent = cachedData[cachedData.length - 1].split("\n");
        let addOne = false;
        if (args.type.includes("prepend")) {
          addOne = true;
        } else if (args.type.includes("line")) {
          const lineNumber = args.type.match(/(\d+)/g);
          if (lineNumber[0]) {
            const line = parseInt(lineNumber[0]) - 1;
            if (line < position.lineStart && !args.replace) {
              addOne = true;
            }
          }
        }
        if (addOne) {
          cachedContent.splice(position.lineStart + 1, position.lineEnd - position.lineStart + 2, button);
        } else {
          cachedContent.splice(position.lineStart, position.lineEnd - position.lineStart + 2, button);
        }
        finalContent = cachedContent.join("\n");
      } else {
        finalContent = content;
      }
      await app.vault.modify(file, finalContent);
      app.metadataCache.offref(cacheChange);
    }, 200);
    return args;
  }
};

// src/buttonTypes/swap.ts
var swap = async (app, swap2, id, inline, file, buttonStart) => {
  handleValueArray(swap2, async (argArray) => {
    const swap3 = await getButtonSwapById(app, id);
    const newSwap = swap3 + 1 > argArray.length - 1 ? 0 : swap3 + 1;
    setButtonSwapById(app, id, newSwap);
    let args = await getButtonById(app, argArray[swap3]);
    let position;
    let content;
    if (args) {
      if (args.templater) {
        args = await templater2(app, position);
        if (inline) {
          new import_obsidian14.Notice("templater args don't work with inline buttons yet", 2e3);
        }
      }
      if (args.type === "command") {
        command(app, args, buttonStart);
      }
      if (args.type === "link") {
        link(args);
      }
      if (args.type && args.type.includes("template")) {
        content = await app.vault.read(file);
        position = inline ? await getInlineButtonPosition(app, id) : getButtonPosition(content, args);
        await template(app, args, position);
      }
      if (args.type === "calculate") {
        await calculate(app, args, position);
      }
      if (args.type && args.type.includes("text")) {
        content = await app.vault.read(file);
        position = inline ? await getInlineButtonPosition(app, id) : getButtonPosition(content, args);
        await text(app, args, position);
      }
      if (args.remove) {
        content = await app.vault.read(file);
        position = inline ? await getInlineButtonPosition(app, id) : getButtonPosition(content, args);
        await remove(app, args, position);
      }
      if (args.replace) {
        content = await app.vault.read(file);
        position = inline ? await getInlineButtonPosition(app, id) : getButtonPosition(content, args);
        await replace(app, args, position);
      }
    }
  });
};

// src/buttonTypes/chain.ts
var import_obsidian15 = __toModule(require("obsidian"));
var chain = async (app, args, position, inline, id, file) => {
  if (!Array.isArray(args.actions)) {
    new import_obsidian15.Notice("No actions array found for chain button.");
    return;
  }
  for (const actionObj of args.actions) {
    try {
      const actionArgs = { ...args, ...actionObj };
      let processedAction = actionArgs.action;
      let processedType = actionArgs.type;
      let processedFolder = actionArgs.folder;
      if (args.templater) {
        try {
          const activeFile = file || app.workspace.getActiveFile();
          if (activeFile) {
            const runTemplater = await templater_default(app, activeFile, activeFile);
            if (runTemplater) {
              if (actionArgs.action && actionArgs.action.includes("<%")) {
                processedAction = await runTemplater(actionArgs.action);
              }
              if (actionArgs.type && actionArgs.type.includes("<%")) {
                processedType = await runTemplater(actionArgs.type);
              }
              if (actionArgs.folder && actionArgs.folder.includes("<%")) {
                processedFolder = await runTemplater(actionArgs.folder);
              }
            }
          }
        } catch (error) {
          console.error("Error processing templater in chain action:", error);
          new import_obsidian15.Notice("Error processing templater in chain action. Check console for details.", 2e3);
        }
      }
      actionArgs.action = processedAction;
      actionArgs.type = processedType;
      actionArgs.folder = processedFolder;
      let currentPosition = position;
      if (actionArgs.type && (actionArgs.type.includes("text") || actionArgs.type.includes("template"))) {
        if (file) {
          const content = await app.vault.read(file);
          currentPosition = inline && id ? await getInlineButtonPosition(app, id) : getButtonPosition(content, actionArgs);
        }
      }
      if (actionArgs.type && actionArgs.type.includes("command")) {
        command(app, actionArgs, currentPosition);
      } else if (actionArgs.type === "copy") {
        copy(actionArgs);
      } else if (actionArgs.type === "link") {
        link(actionArgs);
      } else if (actionArgs.type && actionArgs.type.includes("template")) {
        await template(app, actionArgs, currentPosition);
      } else if (actionArgs.type === "calculate") {
        await calculate(app, actionArgs, currentPosition);
      } else if (actionArgs.type && actionArgs.type.includes("text")) {
        await text(app, actionArgs, currentPosition);
      } else if (actionArgs.type === "chain") {
        await chain(app, actionArgs, currentPosition, inline, id, file);
      } else {
        new import_obsidian15.Notice(`Unsupported action type in chain: ${actionArgs.type}`);
      }
    } catch (e) {
      console.error("Error executing chain action:", actionObj, e);
      new import_obsidian15.Notice(`Error executing chain action: ${actionObj.type}`);
    }
  }
};

// src/button.ts
var createButton = ({
  app,
  el,
  args,
  inline,
  id,
  component,
  clickOverride
}) => {
  const button = el.createEl("button", {
    cls: [
      args.class ? `${args.class} ${args.color}` : `button-default ${args.color ? args.color : ""}`,
      inline ? "button-inline" : ""
    ]
  });
  if (args.customcolor) {
    button.style.backgroundColor = args.customcolor;
  }
  if (args.customtextcolor) {
    button.style.color = args.customtextcolor;
  }
  import_obsidian16.MarkdownRenderer.render(app, args.name, button, app.workspace.getActiveFile()?.path || "", component);
  const numberOfLines = args.name.split("\n").length;
  let paddingTop = "auto";
  let paddingBottom = "auto";
  let alignment = args.align?.split(" ") || ["center", "middle"];
  if (args.height) {
    if (alignment.includes("top")) {
      alignment = alignment.filter((a) => a !== "top");
      paddingBottom = parseFloat(args.height) - 1.2 * numberOfLines + "em";
    } else if (alignment.includes("bottom")) {
      alignment = alignment.filter((a) => a !== "bottom");
      paddingTop = parseFloat(args.height) - 1.2 * numberOfLines + "em";
    } else {
      alignment = alignment.filter((a) => a !== "middle");
      paddingTop = (parseFloat(args.height) - 1.2 * numberOfLines) / 2 + "em";
      paddingBottom = (parseFloat(args.height) - 1.2 * numberOfLines) / 2 + "em";
    }
  }
  if (args.width) {
    args.width += "em";
  } else {
    args.width = "auto";
  }
  button.innerHTML = `<div style='width: ${args.width};padding-top: ${paddingTop};padding-bottom: ${paddingBottom};text-align: ${alignment[0] || "center"};line-height: 1.2em;'>${button.innerHTML.slice(14, -4)}</div>`;
  args.id ? button.setAttribute("id", args.id) : "";
  button.on("click", "button", () => {
    clickOverride ? clickOverride.click(...clickOverride.params) : clickHandler(app, args, inline, id);
  });
  return button;
};
var clickHandler = async (app, args, inline, id) => {
  const activeView = app.workspace.getActiveViewOfType(import_obsidian16.MarkdownView);
  const activeFile = activeView?.file || app.workspace.getActiveFile();
  if (!activeFile) {
    new import_obsidian16.Notice("No active file found. Buttons can only be used with files.");
    return;
  }
  let content = await app.vault.read(activeFile);
  const idFirstPosition = !inline && id ? await getBlockButtonPositionById(app, id) : void 0;
  const buttonStart = idFirstPosition ?? getButtonPosition(content, args);
  let position = inline ? await getInlineButtonPosition(app, id) : idFirstPosition ?? getButtonPosition(content, args);
  let processedAction = args.action;
  let processedType = args.type;
  let processedFolder = args.folder;
  if (args.templater) {
    try {
      const runTemplater = await templater_default(app, activeFile, activeFile);
      if (runTemplater) {
        if (args.action && args.action.includes("<%")) {
          processedAction = await runTemplater(args.action);
        }
        if (args.type && args.type.includes("<%")) {
          processedType = await runTemplater(args.type);
        }
        if (args.folder && args.folder.includes("<%")) {
          processedFolder = await runTemplater(args.folder);
        }
      }
    } catch (error) {
      console.error("Error processing templater in button:", error);
      new import_obsidian16.Notice("Error processing templater in button. Check console for details.", 2e3);
    }
  }
  const processedArgs = { ...args, action: processedAction, type: processedType, folder: processedFolder };
  if (args.replace) {
    replace(app, processedArgs, position);
  }
  if (processedArgs.type && processedArgs.type.includes("command")) {
    command(app, processedArgs, buttonStart);
  }
  if (processedArgs.type === "copy") {
    copy(processedArgs);
  }
  if (processedArgs.type === "link") {
    link(processedArgs);
  }
  if (processedArgs.type && processedArgs.type.includes("template")) {
    content = await app.vault.read(activeFile);
    position = inline ? await getInlineButtonPosition(app, id) : await getBlockButtonPositionById(app, id) ?? getButtonPosition(content, args);
    await template(app, processedArgs, position);
  }
  if (processedArgs.type === "calculate") {
    await calculate(app, processedArgs, position);
  }
  if (processedArgs.type && processedArgs.type.includes("text")) {
    content = await app.vault.read(activeFile);
    position = inline ? await getInlineButtonPosition(app, id) : await getBlockButtonPositionById(app, id) ?? getButtonPosition(content, args);
    await text(app, processedArgs, position);
  }
  if (args.swap) {
    if (!inline) {
      new import_obsidian16.Notice("swap args only work in inline buttons for now", 2e3);
    } else {
      await swap(app, args.swap, id, inline, activeFile, buttonStart);
    }
  }
  if (args.remove) {
    content = await app.vault.read(activeFile);
    await remove(app, processedArgs, position);
  }
  if (processedArgs.type === "chain") {
    await chain(app, processedArgs, position, inline, id, activeFile);
    return;
  }
};

// src/suggest.ts
var import_obsidian17 = __toModule(require("obsidian"));

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

// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js
function getNodeName(element) {
  return element ? (element.nodeName || "").toLowerCase() : null;
}

// node_modules/@popperjs/core/lib/dom-utils/getWindow.js
function getWindow(node) {
  if (node == null) {
    return window;
  }
  if (node.toString() !== "[object Window]") {
    var ownerDocument = node.ownerDocument;
    return ownerDocument ? ownerDocument.defaultView || window : window;
  }
  return node;
}

// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js
function isElement(node) {
  var OwnElement = getWindow(node).Element;
  return node instanceof OwnElement || node instanceof Element;
}
function isHTMLElement(node) {
  var OwnElement = getWindow(node).HTMLElement;
  return node instanceof OwnElement || node instanceof HTMLElement;
}
function isShadowRoot(node) {
  if (typeof ShadowRoot === "undefined") {
    return false;
  }
  var OwnElement = getWindow(node).ShadowRoot;
  return node instanceof OwnElement || node instanceof ShadowRoot;
}

// node_modules/@popperjs/core/lib/modifiers/applyStyles.js
function applyStyles(_ref) {
  var state = _ref.state;
  Object.keys(state.elements).forEach(function(name) {
    var style = state.styles[name] || {};
    var attributes = state.attributes[name] || {};
    var element = state.elements[name];
    if (!isHTMLElement(element) || !getNodeName(element)) {
      return;
    }
    Object.assign(element.style, style);
    Object.keys(attributes).forEach(function(name2) {
      var value = attributes[name2];
      if (value === false) {
        element.removeAttribute(name2);
      } else {
        element.setAttribute(name2, value === true ? "" : value);
      }
    });
  });
}
function effect(_ref2) {
  var state = _ref2.state;
  var initialStyles = {
    popper: {
      position: state.options.strategy,
      left: "0",
      top: "0",
      margin: "0"
    },
    arrow: {
      position: "absolute"
    },
    reference: {}
  };
  Object.assign(state.elements.popper.style, initialStyles.popper);
  state.styles = initialStyles;
  if (state.elements.arrow) {
    Object.assign(state.elements.arrow.style, initialStyles.arrow);
  }
  return function() {
    Object.keys(state.elements).forEach(function(name) {
      var element = state.elements[name];
      var attributes = state.attributes[name] || {};
      var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]);
      var style = styleProperties.reduce(function(style2, property) {
        style2[property] = "";
        return style2;
      }, {});
      if (!isHTMLElement(element) || !getNodeName(element)) {
        return;
      }
      Object.assign(element.style, style);
      Object.keys(attributes).forEach(function(attribute) {
        element.removeAttribute(attribute);
      });
    });
  };
}
var applyStyles_default = {
  name: "applyStyles",
  enabled: true,
  phase: "write",
  fn: applyStyles,
  effect,
  requires: ["computeStyles"]
};

// node_modules/@popperjs/core/lib/utils/getBasePlacement.js
function getBasePlacement(placement) {
  return placement.split("-")[0];
}

// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js
function getBoundingClientRect(element) {
  var rect = element.getBoundingClientRect();
  return {
    width: rect.width,
    height: rect.height,
    top: rect.top,
    right: rect.right,
    bottom: rect.bottom,
    left: rect.left,
    x: rect.left,
    y: rect.top
  };
}

// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js
function getLayoutRect(element) {
  var clientRect = getBoundingClientRect(element);
  var width = element.offsetWidth;
  var height = element.offsetHeight;
  if (Math.abs(clientRect.width - width) <= 1) {
    width = clientRect.width;
  }
  if (Math.abs(clientRect.height - height) <= 1) {
    height = clientRect.height;
  }
  return {
    x: element.offsetLeft,
    y: element.offsetTop,
    width,
    height
  };
}

// node_modules/@popperjs/core/lib/dom-utils/contains.js
function contains(parent, child) {
  var rootNode = child.getRootNode && child.getRootNode();
  if (parent.contains(child)) {
    return true;
  } else if (rootNode && isShadowRoot(rootNode)) {
    var next = child;
    do {
      if (next && parent.isSameNode(next)) {
        return true;
      }
      next = next.parentNode || next.host;
    } while (next);
  }
  return false;
}

// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js
function getComputedStyle(element) {
  return getWindow(element).getComputedStyle(element);
}

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

// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js
function getDocumentElement(element) {
  return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement;
}

// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js
function getParentNode(element) {
  if (getNodeName(element) === "html") {
    return element;
  }
  return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element);
}

// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js
function getTrueOffsetParent(element) {
  if (!isHTMLElement(element) || getComputedStyle(element).position === "fixed") {
    return null;
  }
  return element.offsetParent;
}
function getContainingBlock(element) {
  var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") !== -1;
  var isIE = navigator.userAgent.indexOf("Trident") !== -1;
  if (isIE && isHTMLElement(element)) {
    var elementCss = getComputedStyle(element);
    if (elementCss.position === "fixed") {
      return null;
    }
  }
  var currentNode = getParentNode(element);
  while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) {
    var css = getComputedStyle(currentNode);
    if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") {
      return currentNode;
    } else {
      currentNode = currentNode.parentNode;
    }
  }
  return null;
}
function getOffsetParent(element) {
  var window2 = getWindow(element);
  var offsetParent = getTrueOffsetParent(element);
  while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") {
    offsetParent = getTrueOffsetParent(offsetParent);
  }
  if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) {
    return window2;
  }
  return offsetParent || getContainingBlock(element) || window2;
}

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

// node_modules/@popperjs/core/lib/utils/math.js
var max = Math.max;
var min = Math.min;
var round = Math.round;

// node_modules/@popperjs/core/lib/utils/within.js
function within(min2, value, max2) {
  return max(min2, min(value, max2));
}

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

// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js
function mergePaddingObject(paddingObject) {
  return Object.assign({}, getFreshSideObject(), paddingObject);
}

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

// node_modules/@popperjs/core/lib/modifiers/arrow.js
var toPaddingObject = function toPaddingObject2(padding, state) {
  padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, {
    placement: state.placement
  })) : padding;
  return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
};
function arrow(_ref) {
  var _state$modifiersData$;
  var state = _ref.state, name = _ref.name, options = _ref.options;
  var arrowElement = state.elements.arrow;
  var popperOffsets2 = state.modifiersData.popperOffsets;
  var basePlacement = getBasePlacement(state.placement);
  var axis = getMainAxisFromPlacement(basePlacement);
  var isVertical = [left, right].indexOf(basePlacement) >= 0;
  var len = isVertical ? "height" : "width";
  if (!arrowElement || !popperOffsets2) {
    return;
  }
  var paddingObject = toPaddingObject(options.padding, state);
  var arrowRect = getLayoutRect(arrowElement);
  var minProp = axis === "y" ? top : left;
  var maxProp = axis === "y" ? bottom : right;
  var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len];
  var startDiff = popperOffsets2[axis] - state.rects.reference[axis];
  var arrowOffsetParent = getOffsetParent(arrowElement);
  var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0;
  var centerToReference = endDiff / 2 - startDiff / 2;
  var min2 = paddingObject[minProp];
  var max2 = clientSize - arrowRect[len] - paddingObject[maxProp];
  var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference;
  var offset2 = within(min2, center, max2);
  var axisProp = axis;
  state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset2, _state$modifiersData$.centerOffset = offset2 - center, _state$modifiersData$);
}
function effect2(_ref2) {
  var state = _ref2.state, options = _ref2.options;
  var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element;
  if (arrowElement == null) {
    return;
  }
  if (typeof arrowElement === "string") {
    arrowElement = state.elements.popper.querySelector(arrowElement);
    if (!arrowElement) {
      return;
    }
  }
  if (true) {
    if (!isHTMLElement(arrowElement)) {
      console.error(['Popper: "arrow" element must be an HTMLElement (not an SVGElement).', "To use an SVG arrow, wrap it in an HTMLElement that will be used as", "the arrow."].join(" "));
    }
  }
  if (!contains(state.elements.popper, arrowElement)) {
    if (true) {
      console.error(['Popper: "arrow" modifier\'s `element` must be a child of the popper', "element."].join(" "));
    }
    return;
  }
  state.elements.arrow = arrowElement;
}
var arrow_default = {
  name: "arrow",
  enabled: true,
  phase: "main",
  fn: arrow,
  effect: effect2,
  requires: ["popperOffsets"],
  requiresIfExists: ["preventOverflow"]
};

// node_modules/@popperjs/core/lib/modifiers/computeStyles.js
var unsetSides = {
  top: "auto",
  right: "auto",
  bottom: "auto",
  left: "auto"
};
function roundOffsetsByDPR(_ref) {
  var x = _ref.x, y = _ref.y;
  var win = window;
  var dpr = win.devicePixelRatio || 1;
  return {
    x: round(round(x * dpr) / dpr) || 0,
    y: round(round(y * dpr) / dpr) || 0
  };
}
function mapToStyles(_ref2) {
  var _Object$assign2;
  var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets;
  var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === "function" ? roundOffsets(offsets) : offsets, _ref3$x = _ref3.x, x = _ref3$x === void 0 ? 0 : _ref3$x, _ref3$y = _ref3.y, y = _ref3$y === void 0 ? 0 : _ref3$y;
  var hasX = offsets.hasOwnProperty("x");
  var hasY = offsets.hasOwnProperty("y");
  var sideX = left;
  var sideY = top;
  var win = window;
  if (adaptive) {
    var offsetParent = getOffsetParent(popper2);
    var heightProp = "clientHeight";
    var widthProp = "clientWidth";
    if (offsetParent === getWindow(popper2)) {
      offsetParent = getDocumentElement(popper2);
      if (getComputedStyle(offsetParent).position !== "static") {
        heightProp = "scrollHeight";
        widthProp = "scrollWidth";
      }
    }
    offsetParent = offsetParent;
    if (placement === top) {
      sideY = bottom;
      y -= offsetParent[heightProp] - popperRect.height;
      y *= gpuAcceleration ? 1 : -1;
    }
    if (placement === left) {
      sideX = right;
      x -= offsetParent[widthProp] - popperRect.width;
      x *= gpuAcceleration ? 1 : -1;
    }
  }
  var commonStyles = Object.assign({
    position
  }, adaptive && unsetSides);
  if (gpuAcceleration) {
    var _Object$assign;
    return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign));
  }
  return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2));
}
function computeStyles(_ref4) {
  var state = _ref4.state, options = _ref4.options;
  var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets;
  if (true) {
    var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || "";
    if (adaptive && ["transform", "top", "right", "bottom", "left"].some(function(property) {
      return transitionProperty.indexOf(property) >= 0;
    })) {
      console.warn(["Popper: Detected CSS transitions on at least one of the following", 'CSS properties: "transform", "top", "right", "bottom", "left".', "\n\n", 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', "for smooth transitions, or remove these properties from the CSS", "transition declaration on the popper element if only transitioning", "opacity or background-color for example.", "\n\n", "We recommend using the popper element as a wrapper around an inner", "element that can have any CSS property transitioned for animations."].join(" "));
    }
  }
  var commonStyles = {
    placement: getBasePlacement(state.placement),
    popper: state.elements.popper,
    popperRect: state.rects.popper,
    gpuAcceleration
  };
  if (state.modifiersData.popperOffsets != null) {
    state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.popperOffsets,
      position: state.options.strategy,
      adaptive,
      roundOffsets
    })));
  }
  if (state.modifiersData.arrow != null) {
    state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, {
      offsets: state.modifiersData.arrow,
      position: "absolute",
      adaptive: false,
      roundOffsets
    })));
  }
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    "data-popper-placement": state.placement
  });
}
var computeStyles_default = {
  name: "computeStyles",
  enabled: true,
  phase: "beforeWrite",
  fn: computeStyles,
  data: {}
};

// node_modules/@popperjs/core/lib/modifiers/eventListeners.js
var passive = {
  passive: true
};
function effect3(_ref) {
  var state = _ref.state, instance = _ref.instance, options = _ref.options;
  var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize;
  var window2 = getWindow(state.elements.popper);
  var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper);
  if (scroll) {
    scrollParents.forEach(function(scrollParent) {
      scrollParent.addEventListener("scroll", instance.update, passive);
    });
  }
  if (resize) {
    window2.addEventListener("resize", instance.update, passive);
  }
  return function() {
    if (scroll) {
      scrollParents.forEach(function(scrollParent) {
        scrollParent.removeEventListener("scroll", instance.update, passive);
      });
    }
    if (resize) {
      window2.removeEventListener("resize", instance.update, passive);
    }
  };
}
var eventListeners_default = {
  name: "eventListeners",
  enabled: true,
  phase: "write",
  fn: function fn() {
  },
  effect: effect3,
  data: {}
};

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

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

// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js
function getWindowScroll(node) {
  var win = getWindow(node);
  var scrollLeft = win.pageXOffset;
  var scrollTop = win.pageYOffset;
  return {
    scrollLeft,
    scrollTop
  };
}

// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js
function getWindowScrollBarX(element) {
  return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft;
}

// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js
function getViewportRect(element) {
  var win = getWindow(element);
  var html = getDocumentElement(element);
  var visualViewport = win.visualViewport;
  var width = html.clientWidth;
  var height = html.clientHeight;
  var x = 0;
  var y = 0;
  if (visualViewport) {
    width = visualViewport.width;
    height = visualViewport.height;
    if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
      x = visualViewport.offsetLeft;
      y = visualViewport.offsetTop;
    }
  }
  return {
    width,
    height,
    x: x + getWindowScrollBarX(element),
    y
  };
}

// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js
function getDocumentRect(element) {
  var _element$ownerDocumen;
  var html = getDocumentElement(element);
  var winScroll = getWindowScroll(element);
  var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body;
  var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0);
  var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0);
  var x = -winScroll.scrollLeft + getWindowScrollBarX(element);
  var y = -winScroll.scrollTop;
  if (getComputedStyle(body || html).direction === "rtl") {
    x += max(html.clientWidth, body ? body.clientWidth : 0) - width;
  }
  return {
    width,
    height,
    x,
    y
  };
}

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

// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js
function getScrollParent(node) {
  if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) {
    return node.ownerDocument.body;
  }
  if (isHTMLElement(node) && isScrollParent(node)) {
    return node;
  }
  return getScrollParent(getParentNode(node));
}

// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js
function listScrollParents(element, list) {
  var _element$ownerDocumen;
  if (list === void 0) {
    list = [];
  }
  var scrollParent = getScrollParent(element);
  var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body);
  var win = getWindow(scrollParent);
  var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent;
  var updatedList = list.concat(target);
  return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target)));
}

// node_modules/@popperjs/core/lib/utils/rectToClientRect.js
function rectToClientRect(rect) {
  return Object.assign({}, rect, {
    left: rect.x,
    top: rect.y,
    right: rect.x + rect.width,
    bottom: rect.y + rect.height
  });
}

// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js
function getInnerBoundingClientRect(element) {
  var rect = getBoundingClientRect(element);
  rect.top = rect.top + element.clientTop;
  rect.left = rect.left + element.clientLeft;
  rect.bottom = rect.top + element.clientHeight;
  rect.right = rect.left + element.clientWidth;
  rect.width = element.clientWidth;
  rect.height = element.clientHeight;
  rect.x = rect.left;
  rect.y = rect.top;
  return rect;
}
function getClientRectFromMixedType(element, clippingParent) {
  return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element)));
}
function getClippingParents(element) {
  var clippingParents2 = listScrollParents(getParentNode(element));
  var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0;
  var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element;
  if (!isElement(clipperElement)) {
    return [];
  }
  return clippingParents2.filter(function(clippingParent) {
    return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body";
  });
}
function getClippingRect(element, boundary, rootBoundary) {
  var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary);
  var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]);
  var firstClippingParent = clippingParents2[0];
  var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) {
    var rect = getClientRectFromMixedType(element, clippingParent);
    accRect.top = max(rect.top, accRect.top);
    accRect.right = min(rect.right, accRect.right);
    accRect.bottom = min(rect.bottom, accRect.bottom);
    accRect.left = max(rect.left, accRect.left);
    return accRect;
  }, getClientRectFromMixedType(element, firstClippingParent));
  clippingRect.width = clippingRect.right - clippingRect.left;
  clippingRect.height = clippingRect.bottom - clippingRect.top;
  clippingRect.x = clippingRect.left;
  clippingRect.y = clippingRect.top;
  return clippingRect;
}

// node_modules/@popperjs/core/lib/utils/getVariation.js
function getVariation(placement) {
  return placement.split("-")[1];
}

// node_modules/@popperjs/core/lib/utils/computeOffsets.js
function computeOffsets(_ref) {
  var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement;
  var basePlacement = placement ? getBasePlacement(placement) : null;
  var variation = placement ? getVariation(placement) : null;
  var commonX = reference2.x + reference2.width / 2 - element.width / 2;
  var commonY = reference2.y + reference2.height / 2 - element.height / 2;
  var offsets;
  switch (basePlacement) {
    case top:
      offsets = {
        x: commonX,
        y: reference2.y - element.height
      };
      break;
    case bottom:
      offsets = {
        x: commonX,
        y: reference2.y + reference2.height
      };
      break;
    case right:
      offsets = {
        x: reference2.x + reference2.width,
        y: commonY
      };
      break;
    case left:
      offsets = {
        x: reference2.x - element.width,
        y: commonY
      };
      break;
    default:
      offsets = {
        x: reference2.x,
        y: reference2.y
      };
  }
  var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null;
  if (mainAxis != null) {
    var len = mainAxis === "y" ? "height" : "width";
    switch (variation) {
      case start:
        offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2);
        break;
      case end:
        offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2);
        break;
      default:
    }
  }
  return offsets;
}

// node_modules/@popperjs/core/lib/utils/detectOverflow.js
function detectOverflow(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding;
  var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements));
  var altContext = elementContext === popper ? reference : popper;
  var referenceElement = state.elements.reference;
  var popperRect = state.rects.popper;
  var element = state.elements[altBoundary ? altContext : elementContext];
  var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary);
  var referenceClientRect = getBoundingClientRect(referenceElement);
  var popperOffsets2 = computeOffsets({
    reference: referenceClientRect,
    element: popperRect,
    strategy: "absolute",
    placement
  });
  var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2));
  var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect;
  var overflowOffsets = {
    top: clippingClientRect.top - elementClientRect.top + paddingObject.top,
    bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom,
    left: clippingClientRect.left - elementClientRect.left + paddingObject.left,
    right: elementClientRect.right - clippingClientRect.right + paddingObject.right
  };
  var offsetData = state.modifiersData.offset;
  if (elementContext === popper && offsetData) {
    var offset2 = offsetData[placement];
    Object.keys(overflowOffsets).forEach(function(key) {
      var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1;
      var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x";
      overflowOffsets[key] += offset2[axis] * multiply;
    });
  }
  return overflowOffsets;
}

// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js
function computeAutoPlacement(state, options) {
  if (options === void 0) {
    options = {};
  }
  var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP;
  var variation = getVariation(placement);
  var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) {
    return getVariation(placement2) === variation;
  }) : basePlacements;
  var allowedPlacements = placements2.filter(function(placement2) {
    return allowedAutoPlacements.indexOf(placement2) >= 0;
  });
  if (allowedPlacements.length === 0) {
    allowedPlacements = placements2;
    if (true) {
      console.error(["Popper: The `allowedAutoPlacements` option did not allow any", "placements. Ensure the `placement` option matches the variation", "of the allowed placements.", 'For example, "auto" cannot be used to allow "bottom-start".', 'Use "auto-start" instead.'].join(" "));
    }
  }
  var overflows = allowedPlacements.reduce(function(acc, placement2) {
    acc[placement2] = detectOverflow(state, {
      placement: placement2,
      boundary,
      rootBoundary,
      padding
    })[getBasePlacement(placement2)];
    return acc;
  }, {});
  return Object.keys(overflows).sort(function(a, b) {
    return overflows[a] - overflows[b];
  });
}

// node_modules/@popperjs/core/lib/modifiers/flip.js
function getExpandedFallbackPlacements(placement) {
  if (getBasePlacement(placement) === auto) {
    return [];
  }
  var oppositePlacement = getOppositePlacement(placement);
  return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)];
}
function flip(_ref) {
  var state = _ref.state, options = _ref.options, name = _ref.name;
  if (state.modifiersData[name]._skip) {
    return;
  }
  var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements;
  var preferredPlacement = state.options.placement;
  var basePlacement = getBasePlacement(preferredPlacement);
  var isBasePlacement = basePlacement === preferredPlacement;
  var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement));
  var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) {
    return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, {
      placement: placement2,
      boundary,
      rootBoundary,
      padding,
      flipVariations,
      allowedAutoPlacements
    }) : placement2);
  }, []);
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var checksMap = new Map();
  var makeFallbackChecks = true;
  var firstFittingPlacement = placements2[0];
  for (var i = 0; i < placements2.length; i++) {
    var placement = placements2[i];
    var _basePlacement = getBasePlacement(placement);
    var isStartVariation = getVariation(placement) === start;
    var isVertical = [top, bottom].indexOf(_basePlacement) >= 0;
    var len = isVertical ? "width" : "height";
    var overflow = detectOverflow(state, {
      placement,
      boundary,
      rootBoundary,
      altBoundary,
      padding
    });
    var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top;
    if (referenceRect[len] > popperRect[len]) {
      mainVariationSide = getOppositePlacement(mainVariationSide);
    }
    var altVariationSide = getOppositePlacement(mainVariationSide);
    var checks = [];
    if (checkMainAxis) {
      checks.push(overflow[_basePlacement] <= 0);
    }
    if (checkAltAxis) {
      checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0);
    }
    if (checks.every(function(check) {
      return check;
    })) {
      firstFittingPlacement = placement;
      makeFallbackChecks = false;
      break;
    }
    checksMap.set(placement, checks);
  }
  if (makeFallbackChecks) {
    var numberOfChecks = flipVariations ? 3 : 1;
    var _loop = function _loop2(_i2) {
      var fittingPlacement = placements2.find(function(placement2) {
        var checks2 = checksMap.get(placement2);
        if (checks2) {
          return checks2.slice(0, _i2).every(function(check) {
            return check;
          });
        }
      });
      if (fittingPlacement) {
        firstFittingPlacement = fittingPlacement;
        return "break";
      }
    };
    for (var _i = numberOfChecks; _i > 0; _i--) {
      var _ret = _loop(_i);
      if (_ret === "break")
        break;
    }
  }
  if (state.placement !== firstFittingPlacement) {
    state.modifiersData[name]._skip = true;
    state.placement = firstFittingPlacement;
    state.reset = true;
  }
}
var flip_default = {
  name: "flip",
  enabled: true,
  phase: "main",
  fn: flip,
  requiresIfExists: ["offset"],
  data: {
    _skip: false
  }
};

// node_modules/@popperjs/core/lib/modifiers/hide.js
function getSideOffsets(overflow, rect, preventedOffsets) {
  if (preventedOffsets === void 0) {
    preventedOffsets = {
      x: 0,
      y: 0
    };
  }
  return {
    top: overflow.top - rect.height - preventedOffsets.y,
    right: overflow.right - rect.width + preventedOffsets.x,
    bottom: overflow.bottom - rect.height + preventedOffsets.y,
    left: overflow.left - rect.width - preventedOffsets.x
  };
}
function isAnySideFullyClipped(overflow) {
  return [top, right, bottom, left].some(function(side) {
    return overflow[side] >= 0;
  });
}
function hide(_ref) {
  var state = _ref.state, name = _ref.name;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var preventedOffsets = state.modifiersData.preventOverflow;
  var referenceOverflow = detectOverflow(state, {
    elementContext: "reference"
  });
  var popperAltOverflow = detectOverflow(state, {
    altBoundary: true
  });
  var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect);
  var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets);
  var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets);
  var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets);
  state.modifiersData[name] = {
    referenceClippingOffsets,
    popperEscapeOffsets,
    isReferenceHidden,
    hasPopperEscaped
  };
  state.attributes.popper = Object.assign({}, state.attributes.popper, {
    "data-popper-reference-hidden": isReferenceHidden,
    "data-popper-escaped": hasPopperEscaped
  });
}
var hide_default = {
  name: "hide",
  enabled: true,
  phase: "main",
  requiresIfExists: ["preventOverflow"],
  fn: hide
};

// node_modules/@popperjs/core/lib/modifiers/offset.js
function distanceAndSkiddingToXY(placement, rects, offset2) {
  var basePlacement = getBasePlacement(placement);
  var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1;
  var _ref = typeof offset2 === "function" ? offset2(Object.assign({}, rects, {
    placement
  })) : offset2, skidding = _ref[0], distance = _ref[1];
  skidding = skidding || 0;
  distance = (distance || 0) * invertDistance;
  return [left, right].indexOf(basePlacement) >= 0 ? {
    x: distance,
    y: skidding
  } : {
    x: skidding,
    y: distance
  };
}
function offset(_ref2) {
  var state = _ref2.state, options = _ref2.options, name = _ref2.name;
  var _options$offset = options.offset, offset2 = _options$offset === void 0 ? [0, 0] : _options$offset;
  var data = placements.reduce(function(acc, placement) {
    acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset2);
    return acc;
  }, {});
  var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y;
  if (state.modifiersData.popperOffsets != null) {
    state.modifiersData.popperOffsets.x += x;
    state.modifiersData.popperOffsets.y += y;
  }
  state.modifiersData[name] = data;
}
var offset_default = {
  name: "offset",
  enabled: true,
  phase: "main",
  requires: ["popperOffsets"],
  fn: offset
};

// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js
function popperOffsets(_ref) {
  var state = _ref.state, name = _ref.name;
  state.modifiersData[name] = computeOffsets({
    reference: state.rects.reference,
    element: state.rects.popper,
    strategy: "absolute",
    placement: state.placement
  });
}
var popperOffsets_default = {
  name: "popperOffsets",
  enabled: true,
  phase: "read",
  fn: popperOffsets,
  data: {}
};

// node_modules/@popperjs/core/lib/utils/getAltAxis.js
function getAltAxis(axis) {
  return axis === "x" ? "y" : "x";
}

// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js
function preventOverflow(_ref) {
  var state = _ref.state, options = _ref.options, name = _ref.name;
  var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset;
  var overflow = detectOverflow(state, {
    boundary,
    rootBoundary,
    padding,
    altBoundary
  });
  var basePlacement = getBasePlacement(state.placement);
  var variation = getVariation(state.placement);
  var isBasePlacement = !variation;
  var mainAxis = getMainAxisFromPlacement(basePlacement);
  var altAxis = getAltAxis(mainAxis);
  var popperOffsets2 = state.modifiersData.popperOffsets;
  var referenceRect = state.rects.reference;
  var popperRect = state.rects.popper;
  var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, {
    placement: state.placement
  })) : tetherOffset;
  var data = {
    x: 0,
    y: 0
  };
  if (!popperOffsets2) {
    return;
  }
  if (checkMainAxis || checkAltAxis) {
    var mainSide = mainAxis === "y" ? top : left;
    var altSide = mainAxis === "y" ? bottom : right;
    var len = mainAxis === "y" ? "height" : "width";
    var offset2 = popperOffsets2[mainAxis];
    var min2 = popperOffsets2[mainAxis] + overflow[mainSide];
    var max2 = popperOffsets2[mainAxis] - overflow[altSide];
    var additive = tether ? -popperRect[len] / 2 : 0;
    var minLen = variation === start ? referenceRect[len] : popperRect[len];
    var maxLen = variation === start ? -popperRect[len] : -referenceRect[len];
    var arrowElement = state.elements.arrow;
    var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : {
      width: 0,
      height: 0
    };
    var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject();
    var arrowPaddingMin = arrowPaddingObject[mainSide];
    var arrowPaddingMax = arrowPaddingObject[altSide];
    var arrowLen = within(0, referenceRect[len], arrowRect[len]);
    var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue;
    var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue;
    var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow);
    var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0;
    var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0;
    var tetherMin = popperOffsets2[mainAxis] + minOffset - offsetModifierValue - clientOffset;
    var tetherMax = popperOffsets2[mainAxis] + maxOffset - offsetModifierValue;
    if (checkMainAxis) {
      var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset2, tether ? max(max2, tetherMax) : max2);
      popperOffsets2[mainAxis] = preventedOffset;
      data[mainAxis] = preventedOffset - offset2;
    }
    if (checkAltAxis) {
      var _mainSide = mainAxis === "x" ? top : left;
      var _altSide = mainAxis === "x" ? bottom : right;
      var _offset = popperOffsets2[altAxis];
      var _min = _offset + overflow[_mainSide];
      var _max = _offset - overflow[_altSide];
      var _preventedOffset = within(tether ? min(_min, tetherMin) : _min, _offset, tether ? max(_max, tetherMax) : _max);
      popperOffsets2[altAxis] = _preventedOffset;
      data[altAxis] = _preventedOffset - _offset;
    }
  }
  state.modifiersData[name] = data;
}
var preventOverflow_default = {
  name: "preventOverflow",
  enabled: true,
  phase: "main",
  fn: preventOverflow,
  requiresIfExists: ["offset"]
};

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

// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js
function getNodeScroll(node) {
  if (node === getWindow(node) || !isHTMLElement(node)) {
    return getWindowScroll(node);
  } else {
    return getHTMLElementScroll(node);
  }
}

// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js
function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) {
  if (isFixed === void 0) {
    isFixed = false;
  }
  var documentElement = getDocumentElement(offsetParent);
  var rect = getBoundingClientRect(elementOrVirtualElement);
  var isOffsetParentAnElement = isHTMLElement(offsetParent);
  var scroll = {
    scrollLeft: 0,
    scrollTop: 0
  };
  var offsets = {
    x: 0,
    y: 0
  };
  if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
    if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) {
      scroll = getNodeScroll(offsetParent);
    }
    if (isHTMLElement(offsetParent)) {
      offsets = getBoundingClientRect(offsetParent);
      offsets.x += offsetParent.clientLeft;
      offsets.y += offsetParent.clientTop;
    } else if (documentElement) {
      offsets.x = getWindowScrollBarX(documentElement);
    }
  }
  return {
    x: rect.left + scroll.scrollLeft - offsets.x,
    y: rect.top + scroll.scrollTop - offsets.y,
    width: rect.width,
    height: rect.height
  };
}

// node_modules/@popperjs/core/lib/utils/orderModifiers.js
function order(modifiers) {
  var map = new Map();
  var visited = new Set();
  var result = [];
  modifiers.forEach(function(modifier) {
    map.set(modifier.name, modifier);
  });
  function sort(modifier) {
    visited.add(modifier.name);
    var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []);
    requires.forEach(function(dep) {
      if (!visited.has(dep)) {
        var depModifier = map.get(dep);
        if (depModifier) {
          sort(depModifier);
        }
      }
    });
    result.push(modifier);
  }
  modifiers.forEach(function(modifier) {
    if (!visited.has(modifier.name)) {
      sort(modifier);
    }
  });
  return result;
}
function orderModifiers(modifiers) {
  var orderedModifiers = order(modifiers);
  return modifierPhases.reduce(function(acc, phase) {
    return acc.concat(orderedModifiers.filter(function(modifier) {
      return modifier.phase === phase;
    }));
  }, []);
}

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

// node_modules/@popperjs/core/lib/utils/format.js
function format(str) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  return [].concat(args).reduce(function(p, c) {
    return p.replace(/%s/, c);
  }, str);
}

// node_modules/@popperjs/core/lib/utils/validateModifiers.js
var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s';
var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available';
var VALID_PROPERTIES = ["name", "enabled", "phase", "fn", "effect", "requires", "options"];
function validateModifiers(modifiers) {
  modifiers.forEach(function(modifier) {
    Object.keys(modifier).forEach(function(key) {
      switch (key) {
        case "name":
          if (typeof modifier.name !== "string") {
            console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', '"' + String(modifier.name) + '"'));
          }
          break;
        case "enabled":
          if (typeof modifier.enabled !== "boolean") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', '"' + String(modifier.enabled) + '"'));
          }
        case "phase":
          if (modifierPhases.indexOf(modifier.phase) < 0) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(", "), '"' + String(modifier.phase) + '"'));
          }
          break;
        case "fn":
          if (typeof modifier.fn !== "function") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', '"' + String(modifier.fn) + '"'));
          }
          break;
        case "effect":
          if (typeof modifier.effect !== "function") {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', '"' + String(modifier.fn) + '"'));
          }
          break;
        case "requires":
          if (!Array.isArray(modifier.requires)) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', '"' + String(modifier.requires) + '"'));
          }
          break;
        case "requiresIfExists":
          if (!Array.isArray(modifier.requiresIfExists)) {
            console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', '"' + String(modifier.requiresIfExists) + '"'));
          }
          break;
        case "options":
        case "data":
          break;
        default:
          console.error('PopperJS: an invalid property has been provided to the "' + modifier.name + '" modifier, valid properties are ' + VALID_PROPERTIES.map(function(s) {
            return '"' + s + '"';
          }).join(", ") + '; but "' + key + '" was provided.');
      }
      modifier.requires && modifier.requires.forEach(function(requirement) {
        if (modifiers.find(function(mod) {
          return mod.name === requirement;
        }) == null) {
          console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement));
        }
      });
    });
  });
}

// node_modules/@popperjs/core/lib/utils/uniqueBy.js
function uniqueBy(arr, fn2) {
  var identifiers = new Set();
  return arr.filter(function(item) {
    var identifier = fn2(item);
    if (!identifiers.has(identifier)) {
      identifiers.add(identifier);
      return true;
    }
  });
}

// node_modules/@popperjs/core/lib/utils/mergeByName.js
function mergeByName(modifiers) {
  var merged = modifiers.reduce(function(merged2, current) {
    var existing = merged2[current.name];
    merged2[current.name] = existing ? Object.assign({}, existing, current, {
      options: Object.assign({}, existing.options, current.options),
      data: Object.assign({}, existing.data, current.data)
    }) : current;
    return merged2;
  }, {});
  return Object.keys(merged).map(function(key) {
    return merged[key];
  });
}

// node_modules/@popperjs/core/lib/createPopper.js
var INVALID_ELEMENT_ERROR = "Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.";
var INFINITE_LOOP_ERROR = "Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.";
var DEFAULT_OPTIONS = {
  placement: "bottom",
  modifiers: [],
  strategy: "absolute"
};
function areValidElements() {
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
    args[_key] = arguments[_key];
  }
  return !args.some(function(element) {
    return !(element && typeof element.getBoundingClientRect === "function");
  });
}
function popperGenerator(generatorOptions) {
  if (generatorOptions === void 0) {
    generatorOptions = {};
  }
  var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2;
  return function createPopper2(reference2, popper2, options) {
    if (options === void 0) {
      options = defaultOptions;
    }
    var state = {
      placement: "bottom",
      orderedModifiers: [],
      options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions),
      modifiersData: {},
      elements: {
        reference: reference2,
        popper: popper2
      },
      attributes: {},
      styles: {}
    };
    var effectCleanupFns = [];
    var isDestroyed = false;
    var instance = {
      state,
      setOptions: function setOptions(options2) {
        cleanupModifierEffects();
        state.options = Object.assign({}, defaultOptions, state.options, options2);
        state.scrollParents = {
          reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [],
          popper: listScrollParents(popper2)
        };
        var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers)));
        state.orderedModifiers = orderedModifiers.filter(function(m) {
          return m.enabled;
        });
        if (true) {
          var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function(_ref) {
            var name = _ref.name;
            return name;
          });
          validateModifiers(modifiers);
          if (getBasePlacement(state.options.placement) === auto) {
            var flipModifier = state.orderedModifiers.find(function(_ref2) {
              var name = _ref2.name;
              return name === "flip";
            });
            if (!flipModifier) {
              console.error(['Popper: "auto" placements require the "flip" modifier be', "present and enabled to work."].join(" "));
            }
          }
          var _getComputedStyle = getComputedStyle(popper2), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft;
          if ([marginTop, marginRight, marginBottom, marginLeft].some(function(margin) {
            return parseFloat(margin);
          })) {
            console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', "between the popper and its reference element or boundary.", "To replicate margin, use the `offset` modifier, as well as", "the `padding` option in the `preventOverflow` and `flip`", "modifiers."].join(" "));
          }
        }
        runModifierEffects();
        return instance.update();
      },
      forceUpdate: function forceUpdate() {
        if (isDestroyed) {
          return;
        }
        var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper;
        if (!areValidElements(reference3, popper3)) {
          if (true) {
            console.error(INVALID_ELEMENT_ERROR);
          }
          return;
        }
        state.rects = {
          reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"),
          popper: getLayoutRect(popper3)
        };
        state.reset = false;
        state.placement = state.options.placement;
        state.orderedModifiers.forEach(function(modifier) {
          return state.modifiersData[modifier.name] = Object.assign({}, modifier.data);
        });
        var __debug_loops__ = 0;
        for (var index = 0; index < state.orderedModifiers.length; index++) {
          if (true) {
            __debug_loops__ += 1;
            if (__debug_loops__ > 100) {
              console.error(INFINITE_LOOP_ERROR);
              break;
            }
          }
          if (state.reset === true) {
            state.reset = false;
            index = -1;
            continue;
          }
          var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name;
          if (typeof fn2 === "function") {
            state = fn2({
              state,
              options: _options,
              name,
              instance
            }) || state;
          }
        }
      },
      update: debounce(function() {
        return new Promise(function(resolve) {
          instance.forceUpdate();
          resolve(state);
        });
      }),
      destroy: function destroy() {
        cleanupModifierEffects();
        isDestroyed = true;
      }
    };
    if (!areValidElements(reference2, popper2)) {
      if (true) {
        console.error(INVALID_ELEMENT_ERROR);
      }
      return instance;
    }
    instance.setOptions(options).then(function(state2) {
      if (!isDestroyed && options.onFirstUpdate) {
        options.onFirstUpdate(state2);
      }
    });
    function runModifierEffects() {
      state.orderedModifiers.forEach(function(_ref3) {
        var name = _ref3.name, _ref3$options = _ref3.options, options2 = _ref3$options === void 0 ? {} : _ref3$options, effect4 = _ref3.effect;
        if (typeof effect4 === "function") {
          var cleanupFn = effect4({
            state,
            name,
            instance,
            options: options2
          });
          var noopFn = function noopFn2() {
          };
          effectCleanupFns.push(cleanupFn || noopFn);
        }
      });
    }
    function cleanupModifierEffects() {
      effectCleanupFns.forEach(function(fn2) {
        return fn2();
      });
      effectCleanupFns = [];
    }
    return instance;
  };
}

// node_modules/@popperjs/core/lib/popper.js
var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default];
var createPopper = /* @__PURE__ */ popperGenerator({
  defaultModifiers
});

// src/suggest.ts
var Suggest = class {
  constructor(owner, containerEl, scope) {
    __publicField(this, "owner");
    __publicField(this, "values");
    __publicField(this, "suggestions");
    __publicField(this, "selectedItem");
    __publicField(this, "containerEl");
    this.owner = owner;
    this.containerEl = containerEl;
    containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this));
    containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this));
    scope.register([], "ArrowUp", (event) => {
      if (!event.isComposing) {
        this.setSelectedItem(this.selectedItem - 1, true);
        return false;
      }
    });
    scope.register([], "ArrowDown", (event) => {
      if (!event.isComposing) {
        this.setSelectedItem(this.selectedItem + 1, true);
        return false;
      }
    });
    scope.register([], "Enter", (event) => {
      if (!event.isComposing) {
        this.useSelectedItem(event);
        return false;
      }
    });
  }
  onSuggestionClick(event, el) {
    event.preventDefault();
    const item = this.suggestions.indexOf(el);
    this.setSelectedItem(item, false);
    this.useSelectedItem(event);
  }
  onSuggestionMouseover(_event, el) {
    const item = this.suggestions.indexOf(el);
    this.setSelectedItem(item, false);
  }
  setSuggestions(values) {
    this.containerEl.empty();
    const suggestionEls = [];
    values.forEach((value) => {
      const suggestionEl = this.containerEl.createDiv("suggestion-item");
      this.owner.renderSuggestion(value, suggestionEl);
      suggestionEls.push(suggestionEl);
    });
    this.values = values;
    this.suggestions = suggestionEls;
    this.setSelectedItem(0, false);
  }
  useSelectedItem(event) {
    const currentValue = this.values[this.selectedItem];
    if (currentValue) {
      this.owner.selectSuggestion(currentValue, event);
    }
  }
  setSelectedItem(selectedIndex, scrollIntoView) {
    const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length);
    const prevSelectedSuggestion = this.suggestions[this.selectedItem];
    const selectedSuggestion = this.suggestions[normalizedIndex];
    prevSelectedSuggestion?.removeClass("is-selected");
    selectedSuggestion?.addClass("is-selected");
    this.selectedItem = normalizedIndex;
    if (scrollIntoView) {
      selectedSuggestion.scrollIntoView(false);
    }
  }
};
var TextInputSuggest = class {
  constructor(app, inputEl) {
    __publicField(this, "app");
    __publicField(this, "inputEl");
    __publicField(this, "popper");
    __publicField(this, "scope");
    __publicField(this, "suggestEl");
    __publicField(this, "suggest");
    this.app = app;
    this.inputEl = inputEl;
    this.scope = new import_obsidian17.Scope();
    this.suggestEl = createDiv("suggestion-container");
    const suggestion = this.suggestEl.createDiv("suggestion");
    this.suggest = new Suggest(this, suggestion, this.scope);
    this.scope.register([], "Escape", this.close.bind(this));
    this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
    this.inputEl.addEventListener("focus", this.onInputChanged.bind(this));
    this.inputEl.addEventListener("blur", this.close.bind(this));
    this.suggestEl.on("mousedown", ".suggestion-container", (event) => {
      event.preventDefault();
    });
  }
  onInputChanged() {
    const inputStr = this.inputEl.value;
    const suggestions = this.getSuggestions(inputStr);
    if (suggestions.length > 0) {
      this.suggest.setSuggestions(suggestions);
      this.open(this.app.dom.appContainerEl, this.inputEl);
    }
  }
  open(container, inputEl) {
    this.app.keymap.pushScope(this.scope);
    container.appendChild(this.suggestEl);
    this.popper = createPopper(inputEl, this.suggestEl, {
      placement: "bottom-start",
      modifiers: [
        {
          name: "sameWidth",
          enabled: true,
          fn: ({ state, instance }) => {
            const targetWidth = `${state.rects.reference.width}px`;
            if (state.styles.popper.width === targetWidth) {
              return;
            }
            state.styles.popper.width = targetWidth;
            instance.update();
          },
          phase: "beforeWrite",
          requires: ["computeStyles"]
        }
      ]
    });
  }
  close() {
    this.app.keymap.popScope(this.scope);
    this.suggest.setSuggestions([]);
    this.popper && this.popper.destroy();
    this.suggestEl.detach();
  }
};
var CommandSuggest = class extends TextInputSuggest {
  getSuggestions(inputStr) {
    const commands = this.app.commands.commands;
    const commandNames = [];
    const inputLowerCase = inputStr.toLowerCase();
    for (const command2 in commands) {
      const commandObj = commands[command2];
      if (commandObj.name.toLowerCase().contains(inputLowerCase)) {
        commandNames.push(commandObj);
      }
    }
    return commandNames;
  }
  renderSuggestion(command2, el) {
    el.setText(command2.name);
  }
  selectSuggestion(command2) {
    this.inputEl.value = command2.name;
    this.inputEl.trigger("input");
    this.close();
  }
};
var TemplateSuggest = class extends TextInputSuggest {
  constructor() {
    super(...arguments);
    __publicField(this, "templatesEnabled", this.app.internalPlugins.plugins.templates.enabled);
    __publicField(this, "templaterPluginEnabled", !!this.app.plugins.plugins["templater-obsidian"]);
    __publicField(this, "getTemplateFolders", () => {
      const folders = [];
      if (this.templatesEnabled) {
        const coreFolder = this.app.internalPlugins.plugins.templates.instance.options.folder;
        if (coreFolder) {
          folders.push(coreFolder.toLowerCase());
        }
      }
      if (this.templaterPluginEnabled) {
        const templaterPlugin = this.app.plugins.plugins["templater-obsidian"];
        const templaterFolder = templaterPlugin?.settings?.templates_folder;
        if (templaterFolder) {
          folders.push(templaterFolder.toLowerCase());
        }
      }
      return folders;
    });
  }
  getSuggestions(inputStr) {
    const abstractFiles = this.app.vault.getAllLoadedFiles();
    const files = [];
    const lowerCaseInputStr = inputStr.toLowerCase();
    const folders = this.getTemplateFolders();
    if (folders.length === 0) {
      return files;
    }
    abstractFiles.forEach((file) => {
      let exists = false;
      folders.forEach((folder) => {
        if (file.path.toLowerCase().contains(`${folder}/`)) {
          exists = true;
        }
      });
      if (file instanceof import_obsidian17.TFile && file.extension === "md" && exists && file.path.toLowerCase().contains(lowerCaseInputStr)) {
        files.push(file);
      }
    });
    return files;
  }
  renderSuggestion(file, el) {
    const fileName = file.name.split(".")[0];
    const folders = this.getTemplateFolders();
    let source = "";
    for (const folder of folders) {
      if (file.path.toLowerCase().contains(`${folder}/`)) {
        if (this.templatesEnabled) {
          const coreFolder = this.app.internalPlugins.plugins.templates.instance.options.folder?.toLowerCase();
          if (coreFolder === folder) {
            source = " (Core)";
            break;
          }
        }
        if (this.templaterPluginEnabled) {
          const templaterPlugin = this.app.plugins.plugins["templater-obsidian"];
          const templaterFolder = templaterPlugin?.settings?.templates_folder?.toLowerCase();
          if (templaterFolder === folder) {
            source = " (Templater)";
            break;
          }
        }
      }
    }
    el.setText(fileName + source);
  }
  selectSuggestion(file) {
    this.inputEl.value = file.name.split(".")[0];
    this.inputEl.trigger("input");
    this.close();
  }
};
var ButtonSuggest = class extends TextInputSuggest {
  getSuggestions() {
    const buttonStore2 = getStore(this.app.isMobile);
    const buttons = [];
    buttonStore2.forEach((button) => {
      const trimmed = button.id.split("-")[1];
      buttons.push(trimmed);
    });
    return buttons;
  }
  renderSuggestion(button, el) {
    el.setText(button);
  }
  selectSuggestion(button) {
    this.inputEl.value = this.inputEl.value + button;
    this.inputEl.trigger("input");
    this.close();
  }
};

// src/modal.ts
var ButtonModal = class extends import_obsidian18.Modal {
  constructor(app) {
    super(app);
    __publicField(this, "activeView");
    __publicField(this, "activeEditor");
    __publicField(this, "activeCursor");
    __publicField(this, "buttonPreviewEl", createEl("p"));
    __publicField(this, "previewComponent", null);
    __publicField(this, "commandSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "fileSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "removeSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "swapSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "idSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "removeSuggest");
    __publicField(this, "swapSuggest");
    __publicField(this, "idSuggest");
    __publicField(this, "commandSuggest");
    __publicField(this, "fileSuggest");
    __publicField(this, "handleCommandChange");
    __publicField(this, "handleCommandBlur");
    __publicField(this, "handleFileChange");
    __publicField(this, "handleFileBlur");
    __publicField(this, "outputObject", {
      name: "My Awesome Button",
      type: "",
      action: "",
      swap: "",
      remove: "",
      replace: "",
      id: "",
      templater: false,
      class: "",
      color: "",
      customColor: "",
      customTextColor: "",
      blockId: "",
      folder: "",
      prompt: false,
      openMethod: "",
      noteTitle: "My New Note",
      actions: []
    });
    this.commandSuggest = new CommandSuggest(this.app, this.commandSuggestEl);
    this.commandSuggestEl.placeholder = "Toggle Pin";
    this.commandSuggestEl.addEventListener("change", (e) => {
      this.outputObject.action = e.target.value;
    });
    this.commandSuggestEl.addEventListener("blur", (e) => {
      this.outputObject.action = e.target.value;
    });
    this.fileSuggest = new TemplateSuggest(this.app, this.fileSuggestEl);
    this.fileSuggestEl.placeholder = "My Template";
    this.fileSuggestEl.addEventListener("change", (e) => {
      this.outputObject.action = e.target.value;
    });
    this.fileSuggestEl.addEventListener("blur", (e) => {
      this.outputObject.action = e.target.value;
    });
    this.removeSuggest = new ButtonSuggest(this.app, this.removeSuggestEl);
    this.removeSuggestEl.value = "true";
    this.removeSuggestEl.addEventListener("change", (e) => {
      this.outputObject.remove = e.target.value;
    });
    this.removeSuggestEl.addEventListener("blur", (e) => {
      this.outputObject.remove = e.target.value;
    });
    this.swapSuggest = new ButtonSuggest(this.app, this.swapSuggestEl);
    this.swapSuggestEl.addEventListener("change", (e) => {
      this.outputObject.swap = e.target.value;
    });
    this.swapSuggestEl.addEventListener("blur", (e) => {
      this.outputObject.swap = e.target.value;
    });
    this.idSuggest = new ButtonSuggest(this.app, this.idSuggestEl);
    this.idSuggestEl.addEventListener("change", (e) => {
      this.outputObject.id = e.target.value;
    });
    this.idSuggestEl.addEventListener("blur", (e) => {
      this.outputObject.id = e.target.value;
    });
    this.swapSuggestEl.placeholder = "[idOne, idTwo]";
  }
  onOpen() {
    const { titleEl, contentEl } = this;
    titleEl.setText("Button Maker");
    titleEl.addClass("button-maker-title");
    contentEl.addClass("button-maker");
    const mainContainer = contentEl.createEl("div", { cls: "button-maker-container" });
    mainContainer.createEl("form", { cls: "button-maker-form" }, (formEl) => {
      const basicSection = formEl.createEl("div", { cls: "form-section" });
      basicSection.createEl("h3", { cls: "section-title", text: "Basic Settings" });
      const nameContainer = basicSection.createEl("div", { cls: "form-field" });
      nameContainer.createEl("label", { cls: "field-label", text: "Button Name" });
      nameContainer.createEl("div", { cls: "field-description", text: "What would you like to call this button?" });
      const nameInput = nameContainer.createEl("input", {
        type: "text",
        cls: "field-input",
        attr: { placeholder: "My Awesome Button" }
      });
      nameInput.addEventListener("input", (e) => {
        const value = e.target.value;
        this.buttonPreviewEl.setText(value);
        this.outputObject.name = value;
      });
      window.setTimeout(() => nameInput.focus(), 10);
      const typeContainer = basicSection.createEl("div", { cls: "form-field" });
      typeContainer.createEl("label", { cls: "field-label", text: "Button Type" });
      typeContainer.createEl("div", { cls: "field-description", text: "What type of button are you making?" });
      const typeSelect = typeContainer.createEl("select", { cls: "dropdown" });
      const typeOptions = [
        { value: "pre", text: "Select a Button Type" },
        { value: "command", text: "Command - Run a command prompt command" },
        { value: "link", text: "Link - Open a URL or URI" },
        { value: "template", text: "Template - Insert or create notes from templates" },
        { value: "text", text: "Text - Insert or create notes with text" },
        { value: "calculate", text: "Calculate - Run a mathematical calculation" },
        { value: "swap", text: "Swap - Create a multi-purpose Inline Button from other Buttons" },
        { value: "copy", text: "Copy - Copy text to clipboard" },
        { value: "chain", text: "Chain - Run multiple actions in sequence" }
      ];
      typeOptions.forEach((option, index) => {
        const optionEl = typeSelect.createEl("option");
        optionEl.value = option.value;
        optionEl.textContent = option.text;
        if (index === 0) {
          optionEl.selected = true;
          this.outputObject.type = option.value;
        }
      });
      const actionContainer = formEl.createEl("div", { cls: "action-container" });
      typeSelect.addEventListener("change", (e) => {
        const value = e.target.value;
        this.outputObject.type = value;
        actionContainer.empty();
        if (value === "pre") {
          return;
        } else if (value === "chain") {
          this.renderChainActions(actionContainer);
        } else if (value === "link") {
          this.renderLinkAction(actionContainer);
        } else if (value === "command") {
          this.renderCommandAction(actionContainer);
        } else if (value.includes("template")) {
          this.renderTemplateAction(actionContainer);
        } else if (value === "text") {
          this.renderTextAction(actionContainer);
        } else if (value === "calculate") {
          this.renderCalculateAction(actionContainer);
        } else if (value === "swap") {
          this.renderSwapAction(actionContainer);
        } else if (value === "copy") {
          this.renderCopyAction(actionContainer);
        }
      });
      const advancedSection = formEl.createEl("div", { cls: "form-section" });
      advancedSection.createEl("h3", { cls: "section-title", text: "Advanced Settings" });
      const blockIdContainer = advancedSection.createEl("div", { cls: "form-field" });
      blockIdContainer.createEl("label", { cls: "field-label", text: "Button Block ID" });
      blockIdContainer.createEl("div", { cls: "field-description", text: "Provide a custom button-block-id" });
      const blockIdInput = blockIdContainer.createEl("input", {
        type: "text",
        cls: "field-input",
        attr: { placeholder: "buttonId" }
      });
      blockIdInput.addEventListener("input", (e) => {
        this.outputObject.blockId = e.target.value;
      });
      const toggleSettings = advancedSection.createEl("div", { cls: "toggle-settings" });
      const removeContainer = toggleSettings.createEl("div", { cls: "toggle-field" });
      const removeToggleRow = removeContainer.createEl("div", { cls: "toggle-row" });
      removeToggleRow.createEl("label", { cls: "toggle-label" });
      const removeToggle = removeToggleRow.createEl("input", { type: "checkbox", cls: "toggle-input" });
      removeToggleRow.createEl("span", { cls: "toggle-text", text: "Remove after click" });
      removeToggleRow.createEl("div", { cls: "toggle-description", text: "Remove this button (or other buttons) after clicking?" });
      removeToggle.addEventListener("change", (e) => {
        const checked = e.target.checked;
        if (checked) {
          this.renderRemoveSettings(removeContainer);
          this.outputObject.remove = "true";
        } else {
          this.outputObject.remove = "";
          const removeSettings = removeContainer.querySelector(".remove-settings");
          if (removeSettings)
            removeSettings.remove();
        }
      });
      const replaceContainer = toggleSettings.createEl("div", { cls: "toggle-field" });
      const replaceToggleRow = replaceContainer.createEl("div", { cls: "toggle-row" });
      replaceToggleRow.createEl("label", { cls: "toggle-label" });
      const replaceToggle = replaceToggleRow.createEl("input", { type: "checkbox", cls: "toggle-input" });
      replaceToggleRow.createEl("span", { cls: "toggle-text", text: "Replace content" });
      replaceToggleRow.createEl("div", { cls: "toggle-description", text: "Replace lines in the note after clicking?" });
      replaceToggle.addEventListener("change", (e) => {
        const checked = e.target.checked;
        if (checked) {
          this.renderReplaceSettings(replaceContainer);
        } else {
          const replaceSettings = replaceContainer.querySelector(".replace-settings");
          if (replaceSettings)
            replaceSettings.remove();
        }
      });
      const inheritContainer = toggleSettings.createEl("div", { cls: "toggle-field" });
      const inheritToggleRow = inheritContainer.createEl("div", { cls: "toggle-row" });
      inheritToggleRow.createEl("label", { cls: "toggle-label" });
      const inheritToggle = inheritToggleRow.createEl("input", { type: "checkbox", cls: "toggle-input" });
      inheritToggleRow.createEl("span", { cls: "toggle-text", text: "Inherit from other button" });
      inheritToggleRow.createEl("div", { cls: "toggle-description", text: "Inherit args by adding an existing button block-id?" });
      inheritToggle.addEventListener("change", (e) => {
        const checked = e.target.checked;
        if (checked) {
          this.renderInheritSettings(inheritContainer);
        } else {
          this.outputObject.id = "";
          const inheritSettings = inheritContainer.querySelector(".inherit-settings");
          if (inheritSettings)
            inheritSettings.remove();
        }
      });
      const templaterContainer = toggleSettings.createEl("div", { cls: "toggle-field" });
      const templaterToggleRow = templaterContainer.createEl("div", { cls: "toggle-row" });
      templaterToggleRow.createEl("label", { cls: "toggle-label" });
      const templaterToggle = templaterToggleRow.createEl("input", { type: "checkbox", cls: "toggle-input" });
      templaterToggleRow.createEl("span", { cls: "toggle-text", text: "Enable Templater" });
      templaterToggleRow.createEl("div", { cls: "toggle-description", text: "Convert templater commands inside your button on each click?" });
      templaterToggle.addEventListener("change", (e) => {
        this.outputObject.templater = e.target.checked;
      });
      const stylingSection = formEl.createEl("div", { cls: "form-section" });
      stylingSection.createEl("h3", { cls: "section-title", text: "Styling" });
      const classContainer = stylingSection.createEl("div", { cls: "form-field" });
      classContainer.createEl("label", { cls: "field-label", text: "Custom Class" });
      classContainer.createEl("div", { cls: "field-description", text: "Add a custom class for button styling" });
      const classInput = classContainer.createEl("input", {
        type: "text",
        cls: "field-input"
      });
      classInput.addEventListener("input", (e) => {
        const value = e.target.value;
        this.buttonPreviewEl.setAttribute("class", value);
        this.outputObject.class = value;
        if (value === "") {
          this.buttonPreviewEl.setAttribute("class", "button-default");
        }
      });
      const colorContainer = stylingSection.createEl("div", { cls: "form-field" });
      colorContainer.createEl("label", { cls: "field-label", text: "Color" });
      colorContainer.createEl("div", { cls: "field-description", text: "What color would you like your button to be?" });
      const colorSelect = colorContainer.createEl("select", { cls: "dropdown" });
      const colorOptions = [
        { value: "default", text: "Default Color" },
        { value: "blue", text: "Blue" },
        { value: "red", text: "Red" },
        { value: "green", text: "Green" },
        { value: "yellow", text: "Yellow" },
        { value: "purple", text: "Purple" },
        { value: "custom", text: "Custom" }
      ];
      colorOptions.forEach((option) => {
        const optionEl = colorSelect.createEl("option");
        optionEl.value = option.value;
        optionEl.textContent = option.text;
        if (option.value === "default") {
          optionEl.selected = true;
        }
      });
      colorSelect.addEventListener("change", (e) => {
        const value = e.target.value;
        if (value === "custom") {
          this.renderCustomColorSettings(colorContainer);
        } else {
          this.outputObject.color = value;
          this.updateButtonPreview();
        }
      });
      const buttonContainer = formEl.createEl("div", { cls: "form-actions" });
      const cancelBtn = buttonContainer.createEl("button", {
        type: "button",
        cls: "btn btn-secondary",
        text: "Cancel"
      });
      cancelBtn.addEventListener("click", () => this.close());
      buttonContainer.createEl("button", {
        type: "submit",
        cls: "btn btn-primary",
        text: "Insert Button"
      });
      formEl.addEventListener("submit", (e) => {
        e.preventDefault();
        insertButton(this.app, this.outputObject);
        this.close();
      });
    });
    const previewSection = mainContainer.createEl("div", { cls: "preview-section" });
    previewSection.createEl("h3", { cls: "section-title", text: "Button Preview" });
    const previewContainer = previewSection.createEl("div", { cls: "preview-container" });
    this.previewComponent = new import_obsidian18.Component();
    this.buttonPreviewEl = createButton({
      app: this.app,
      el: previewContainer,
      args: { name: "My Awesome Button" },
      component: this.previewComponent
    });
  }
  renderChainActions(container) {
    if (!Array.isArray(this.outputObject.actions)) {
      this.outputObject.actions = [];
    }
    const actionsHeader = container.createEl("div", { cls: "actions-header" });
    actionsHeader.createEl("h4", { text: "Chain Actions" });
    actionsHeader.createEl("p", { text: "Add actions to be executed in sequence" });
    const actionsList = container.createEl("div", { cls: "actions-list" });
    const renderActions = () => {
      actionsList.empty();
      this.outputObject.actions.forEach((act, idx) => {
        const actionCard = actionsList.createEl("div", { cls: "action-card" });
        const actionHeader = actionCard.createEl("div", { cls: "action-header" });
        actionHeader.createEl("span", { cls: "action-number", text: `Action ${idx + 1}` });
        const removeBtn = actionHeader.createEl("button", {
          type: "button",
          cls: "btn-remove",
          text: "\xD7"
        });
        removeBtn.addEventListener("click", (e) => {
          e.preventDefault();
          e.stopPropagation();
          this.outputObject.actions.splice(idx, 1);
          renderActions();
        });
        const typeSelect = actionCard.createEl("select", { cls: "dropdown" });
        const typeOptions = [
          { value: "command", text: "Command" },
          { value: "append text", text: "Append Text" },
          { value: "prepend text", text: "Prepend Text" },
          { value: "line text", text: "Line Text" },
          { value: "note text", text: "Note Text" },
          { value: "append template", text: "Append Template" },
          { value: "prepend template", text: "Prepend Template" },
          { value: "line template", text: "Line Template" },
          { value: "note template", text: "Note Template" },
          { value: "link", text: "Link" },
          { value: "calculate", text: "Calculate" },
          { value: "copy", text: "Copy" }
        ];
        typeOptions.forEach((opt) => {
          const option = typeSelect.createEl("option");
          option.value = opt.value;
          option.textContent = opt.text;
          if (act.type === opt.value)
            option.selected = true;
        });
        const actionInputContainer = actionCard.createEl("div", { cls: "action-input-container" });
        this.renderActionInput(actionInputContainer, idx, act.type);
        typeSelect.addEventListener("change", () => {
          this.outputObject.actions[idx].type = typeSelect.value;
          actionInputContainer.empty();
          this.renderActionInput(actionInputContainer, idx, typeSelect.value);
        });
      });
    };
    const addActionBtn = container.createEl("button", {
      type: "button",
      cls: "btn btn-add-action",
      text: "+ Add Action"
    });
    addActionBtn.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.outputObject.actions.push({ type: "command", action: "" });
      renderActions();
    });
    renderActions();
  }
  renderLinkAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Link" });
    field.createEl("div", { cls: "field-description", text: "Enter a link to open" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "https://obsidian.md" }
    });
    input.addEventListener("input", (e) => {
      this.outputObject.action = e.target.value;
    });
  }
  renderCommandAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Command" });
    field.createEl("div", { cls: "field-description", text: "Select a command to run" });
    const commandTypeSelect = field.createEl("select", { cls: "dropdown" });
    const defaultOption = commandTypeSelect.createEl("option", { value: "command", text: "Default" });
    defaultOption.selected = true;
    commandTypeSelect.createEl("option", { value: "prepend command", text: "Prepend" });
    commandTypeSelect.createEl("option", { value: "append command", text: "Append" });
    const commandInput = field.createEl("input", {
      type: "text",
      cls: "field-input"
    });
    commandInput.replaceWith(this.commandSuggestEl);
    commandTypeSelect.addEventListener("change", (e) => {
      this.outputObject.type = e.target.value;
    });
  }
  renderTemplateAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Template" });
    field.createEl("div", { cls: "field-description", text: "Select a template note and what should happen" });
    const templateTypeSelect = field.createEl("select", { cls: "dropdown" });
    const templateDefaultOption = templateTypeSelect.createEl("option", { value: "template", text: "Do this..." });
    templateDefaultOption.selected = true;
    templateTypeSelect.createEl("option", { value: "prepend template", text: "Prepend" });
    templateTypeSelect.createEl("option", { value: "append template", text: "Append" });
    templateTypeSelect.createEl("option", { value: "line template", text: "Line" });
    templateTypeSelect.createEl("option", { value: "cursor template", text: "Cursor" });
    templateTypeSelect.createEl("option", { value: "note template", text: "Note" });
    const templateInput = field.createEl("input", {
      type: "text",
      cls: "field-input"
    });
    templateInput.replaceWith(this.fileSuggestEl);
    templateTypeSelect.addEventListener("change", (e) => {
      const value = e.target.value;
      if (value && value !== "template") {
        this.outputObject.type = value;
      }
      if (value === "line template") {
        this.renderLineNumberField(container);
      } else if (value === "note template") {
        this.renderNoteTemplateFields(container);
      }
    });
  }
  renderTextAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Text" });
    field.createEl("div", { cls: "field-description", text: "Enter the text content" });
    const textTypeSelect = field.createEl("select", { cls: "dropdown" });
    const textDefaultOption = textTypeSelect.createEl("option", { value: "text", text: "Do this..." });
    textDefaultOption.selected = true;
    textTypeSelect.createEl("option", { value: "append text", text: "Append" });
    textTypeSelect.createEl("option", { value: "prepend text", text: "Prepend" });
    textTypeSelect.createEl("option", { value: "line text", text: "Line" });
    textTypeSelect.createEl("option", { value: "cursor text", text: "Cursor" });
    textTypeSelect.createEl("option", { value: "note text", text: "Note" });
    const textArea = field.createEl("textarea", {
      cls: "field-textarea",
      attr: { placeholder: "Enter your text content here..." }
    });
    textArea.addEventListener("input", (e) => {
      this.outputObject.action = e.target.value;
    });
    textTypeSelect.addEventListener("change", (e) => {
      const value = e.target.value;
      if (value && value !== "text") {
        this.outputObject.type = value;
      }
      if (value === "line text") {
        this.renderLineNumberField(container);
      } else if (value === "note text") {
        this.renderNoteTextFields(container);
      }
    });
  }
  renderCalculateAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Calculate" });
    field.createEl("div", { cls: "field-description", text: "Enter a calculation, you can reference a line number with $LineNumber" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "2+$10" }
    });
    input.addEventListener("input", (e) => {
      this.outputObject.action = e.target.value;
    });
  }
  renderSwapAction(container) {
    this.outputObject.type = "";
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Swap" });
    field.createEl("div", { cls: "field-description", text: "Choose buttons to be included in the Inline Swap Button" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input"
    });
    input.replaceWith(this.swapSuggestEl);
  }
  renderCopyAction(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Text" });
    field.createEl("div", { cls: "field-description", text: "Text to copy for clipboard" });
    const textarea = field.createEl("textarea", {
      cls: "field-textarea",
      attr: {
        placeholder: "Text to copy\nSupports multiple lines",
        rows: "5"
      }
    });
    textarea.addEventListener("input", (e) => {
      this.outputObject.action = e.target.value;
    });
  }
  renderRemoveSettings(container) {
    const removeSettings = container.createEl("div", { cls: "remove-settings" });
    const field = removeSettings.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Select Remove" });
    field.createEl("div", { cls: "field-description", text: "Use true to remove this button, or supply an [array] of button block-ids" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input"
    });
    input.replaceWith(this.removeSuggestEl);
  }
  renderReplaceSettings(container) {
    const replaceSettings = container.createEl("div", { cls: "replace-settings" });
    const field = replaceSettings.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Select Lines" });
    field.createEl("div", { cls: "field-description", text: "Supply an array of [startingLine, endingLine] to be replaced" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { value: "[]" }
    });
    input.addEventListener("input", (e) => {
      this.outputObject.replace = e.target.value;
    });
  }
  renderInheritSettings(container) {
    const inheritSettings = container.createEl("div", { cls: "inherit-settings" });
    const field = inheritSettings.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Button ID" });
    field.createEl("div", { cls: "field-description", text: "Inherit from other buttons by adding their button block-id" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input"
    });
    input.replaceWith(this.idSuggestEl);
  }
  renderCustomColorSettings(container) {
    this.outputObject.color = "";
    const customColorContainer = container.createEl("div", { cls: "custom-color-container" });
    const bgField = customColorContainer.createEl("div", { cls: "form-field" });
    bgField.createEl("label", { cls: "field-label", text: "Background Color" });
    const bgInput = bgField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "#FFFFFF" }
    });
    bgInput.addEventListener("input", (e) => {
      const value = e.target.value;
      this.buttonPreviewEl.style.background = value;
      this.outputObject.customColor = value;
    });
    const textField = customColorContainer.createEl("div", { cls: "form-field" });
    textField.createEl("label", { cls: "field-label", text: "Text Color" });
    const textInput = textField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "#000000" }
    });
    textInput.addEventListener("input", (e) => {
      const value = e.target.value;
      this.buttonPreviewEl.style.color = value;
      this.outputObject.customTextColor = value;
    });
  }
  updateButtonPreview() {
    if (this.outputObject.color && this.outputObject.color !== "default") {
      this.buttonPreviewEl.setAttribute("class", `button-default ${this.outputObject.color}`);
      this.buttonPreviewEl.removeAttribute("style");
    } else {
      this.buttonPreviewEl.setAttribute("class", "button-default");
      this.buttonPreviewEl.removeAttribute("style");
    }
  }
  renderActionInput(container, actionIndex, actionType) {
    if (actionType === "command") {
      const commandInput = createEl("input", { type: "text" });
      new CommandSuggest(this.app, commandInput);
      commandInput.setAttribute("class", "action-input");
      commandInput.setAttribute("placeholder", "Select a command...");
      const currentValue = this.outputObject.actions[actionIndex]?.action || "";
      commandInput.value = currentValue;
      container.appendChild(commandInput);
      commandInput.addEventListener("change", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
      commandInput.addEventListener("blur", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
    } else if (actionType.includes("template")) {
      const templateInput = createEl("input", { type: "text" });
      new TemplateSuggest(this.app, templateInput);
      templateInput.setAttribute("class", "action-input");
      templateInput.setAttribute("placeholder", "Select a template...");
      const currentValue = this.outputObject.actions[actionIndex]?.action || "";
      templateInput.value = currentValue;
      container.appendChild(templateInput);
      templateInput.addEventListener("change", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
      templateInput.addEventListener("blur", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
    } else {
      const input = container.createEl("input", {
        type: "text",
        cls: "action-input",
        attr: { placeholder: "Enter action..." }
      });
      const currentValue = this.outputObject.actions[actionIndex]?.action || "";
      input.value = currentValue;
      input.addEventListener("input", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
      input.addEventListener("blur", (e) => {
        this.outputObject.actions[actionIndex].action = e.target.value;
      });
    }
  }
  renderLineNumberField(container) {
    const field = container.createEl("div", { cls: "form-field" });
    field.createEl("label", { cls: "field-label", text: "Line Number" });
    field.createEl("div", { cls: "field-description", text: "At which line should the content be inserted?" });
    const input = field.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "69" }
    });
    input.addEventListener("input", (e) => {
      const value = e.target.value;
      if (this.outputObject.type.includes("template")) {
        this.outputObject.type = `line(${value}) template`;
      } else if (this.outputObject.type.includes("text")) {
        this.outputObject.type = `line(${value}) text`;
      }
    });
  }
  renderNoteTemplateFields(container) {
    const promptField = container.createEl("div", { cls: "form-field" });
    promptField.createEl("label", { cls: "field-label", text: "Prompt" });
    promptField.createEl("div", { cls: "field-description", text: "Should you be prompted to enter a name for the file on creation?" });
    const promptToggle = promptField.createEl("input", { type: "checkbox", cls: "toggle-input" });
    promptToggle.addEventListener("change", (e) => {
      this.outputObject.prompt = e.target.checked;
    });
    const nameField = container.createEl("div", { cls: "form-field" });
    nameField.createEl("label", { cls: "field-label", text: "Note Name" });
    nameField.createEl("div", { cls: "field-description", text: "What should the new note be named? Note: if prompt is on, this will be the default name" });
    const nameInput = nameField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "My New Note" }
    });
    nameInput.addEventListener("input", (e) => {
      this.outputObject.noteTitle = e.target.value;
    });
    const openMethodField = container.createEl("div", { cls: "form-field" });
    openMethodField.createEl("label", { cls: "field-label", text: "Opening Method" });
    openMethodField.createEl("div", { cls: "field-description", text: "How should the new note be opened?" });
    const openMethodSelect = openMethodField.createEl("select", { cls: "dropdown" });
    const openMethods = [
      { value: "tab", text: "New Tab" },
      { value: "vsplit", text: "Vertical Split" },
      { value: "hsplit", text: "Horizontal Split" },
      { value: "same", text: "Same Window" },
      { value: "false", text: "Don't Open" }
    ];
    openMethods.forEach((method, index) => {
      const option = openMethodSelect.createEl("option");
      option.value = method.value;
      option.textContent = method.text;
      if (index === 0) {
        option.selected = true;
        this.outputObject.openMethod = method.value;
      }
    });
    openMethodSelect.addEventListener("change", (e) => {
      this.outputObject.openMethod = e.target.value;
    });
    const folderField = container.createEl("div", { cls: "form-field" });
    folderField.createEl("label", { cls: "field-label", text: "Default Folder" });
    folderField.createEl("div", { cls: "field-description", text: "Enter a folder path to place the note in. Defaults to root" });
    const folderInput = folderField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "My Folder" }
    });
    folderInput.addEventListener("input", (e) => {
      this.outputObject.folder = e.target.value;
    });
  }
  renderNoteTextFields(container) {
    const promptField = container.createEl("div", { cls: "form-field" });
    promptField.createEl("label", { cls: "field-label", text: "Prompt" });
    promptField.createEl("div", { cls: "field-description", text: "Should you be prompted to enter a name for the file on creation?" });
    const promptToggle = promptField.createEl("input", { type: "checkbox", cls: "toggle-input" });
    promptToggle.addEventListener("change", (e) => {
      this.outputObject.prompt = e.target.checked;
    });
    const nameField = container.createEl("div", { cls: "form-field" });
    nameField.createEl("label", { cls: "field-label", text: "Note Name" });
    nameField.createEl("div", { cls: "field-description", text: "What should the new note be named? Note: if prompt is on, this will be the default name" });
    const nameInput = nameField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "My New Note" }
    });
    nameInput.addEventListener("input", (e) => {
      this.outputObject.noteTitle = e.target.value;
    });
    const openMethodField = container.createEl("div", { cls: "form-field" });
    openMethodField.createEl("label", { cls: "field-label", text: "Opening Method" });
    openMethodField.createEl("div", { cls: "field-description", text: "How should the new note be opened?" });
    const openMethodSelect = openMethodField.createEl("select", { cls: "dropdown" });
    const openMethods = [
      { value: "tab", text: "New Tab" },
      { value: "vsplit", text: "Vertical Split" },
      { value: "hsplit", text: "Horizontal Split" },
      { value: "same", text: "Same Window" },
      { value: "false", text: "Don't Open" }
    ];
    openMethods.forEach((method, index) => {
      const option = openMethodSelect.createEl("option");
      option.value = method.value;
      option.textContent = method.text;
      if (index === 0) {
        option.selected = true;
        this.outputObject.openMethod = method.value;
      }
    });
    openMethodSelect.addEventListener("change", (e) => {
      this.outputObject.openMethod = e.target.value;
    });
    const folderField = container.createEl("div", { cls: "form-field" });
    folderField.createEl("label", { cls: "field-label", text: "Default Folder" });
    folderField.createEl("div", { cls: "field-description", text: "Enter a folder path to place the note in. Defaults to root" });
    const folderInput = folderField.createEl("input", {
      type: "text",
      cls: "field-input",
      attr: { placeholder: "My Folder" }
    });
    folderInput.addEventListener("input", (e) => {
      this.outputObject.folder = e.target.value;
    });
  }
  onClose() {
    const { contentEl } = this;
    if (this.previewComponent) {
      this.previewComponent.unload();
      this.previewComponent = null;
    }
    contentEl.empty();
  }
};
var InlineButtonModal = class extends import_obsidian18.Modal {
  constructor(app) {
    super(app);
    __publicField(this, "buttonSuggestEl", createEl("input", { type: "text" }));
    __publicField(this, "buttonSuggest");
    this.buttonSuggest = new ButtonSuggest(this.app, this.buttonSuggestEl);
    this.buttonSuggestEl.setAttribute("style", "width: 100%; height: 40px");
  }
  onOpen() {
    const { titleEl, contentEl } = this;
    titleEl.setText("Insert Inline Button");
    contentEl.createEl("form", {}, (formEl) => {
      formEl.appendChild(this.buttonSuggestEl);
      formEl.addEventListener("submit", (e) => {
        e.preventDefault();
        insertInlineButton(this.app, this.buttonSuggestEl.value);
        this.close();
      });
    });
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};

// src/livePreview.ts
var import_obsidian19 = __toModule(require("obsidian"));
var import_view = __toModule(require("@codemirror/view"));
var import_language = __toModule(require("@codemirror/language"));
function selectionAndRangeOverlap(selection, rangeFrom, rangeTo) {
  for (const range of selection.ranges) {
    if (range.from <= rangeTo && range.to >= rangeFrom) {
      return true;
    }
  }
  return false;
}
function inlineButtons(view, app) {
  const regex = new RegExp(".*?_?inline-code_?.*");
  const selection = view.state.selection;
  const buttons = [];
  for (const { from, to } of view.visibleRanges) {
    (0, import_language.syntaxTree)(view.state).iterate({
      from,
      to,
      enter: ({ node }) => {
        const content = view.state.doc.sliceString(node.from, node.to);
        if (selectionAndRangeOverlap(selection, node.from - 1, node.to + 1)) {
          return;
        }
        if (node.type.name.includes("formatting"))
          return;
        if (regex.test(node.type.name)) {
          const matches = content.match(/button-([\s\S]*)/);
          const id = matches && matches[1] ? matches[1] : "";
          if (id) {
            const line = view.state.doc.lineAt(node.to).number;
            const el = createEl("button");
            el.addClass("button-default");
            const deco = import_view.Decoration.replace({
              widget: new ButtonWidget(el, id, app, line),
              block: false
            });
            buttons.push(deco.range(node.from, node.to));
          }
        }
      }
    });
  }
  return import_view.Decoration.set(buttons);
}
function buttonPlugin(app) {
  return import_view.ViewPlugin.fromClass(class {
    constructor(view) {
      __publicField(this, "decorations");
      this.decorations = inlineButtons(view, app);
    }
    update(update) {
      this.decorations = inlineButtons(update.view, app);
    }
  }, {
    decorations: (v) => v.decorations
  });
}
var ButtonWidget = class extends import_view.WidgetType {
  constructor(el, id, app, line) {
    super();
    this.el = el;
    this.id = id;
    this.app = app;
    this.line = line;
    __publicField(this, "component");
    this.component = new import_obsidian19.Component();
  }
  eq(other) {
    return other.id === this.id;
  }
  destroy() {
    this.component.unload();
  }
  toDOM() {
    this.el.innerText = "Loading...";
    this.el.addClass("button-default");
    this.loadButtonData();
    return this.el;
  }
  async loadButtonData() {
    try {
      const args = await getButtonById(this.app, this.id);
      if (args) {
        const name = args.name;
        const color = args.color;
        this.el.innerHTML = "";
        import_obsidian19.MarkdownRenderer.render(this.app, name, this.el, this.app.workspace.getActiveFile()?.path || "", this.component);
        let numberOfLines = args.name.split("\n").length;
        let paddingTop = "auto";
        let paddingBottom = "auto";
        let alignment = args.align?.split(" ") || ["center", "middle"];
        if (args.height) {
          if (alignment.includes("top")) {
            alignment = alignment.filter((a) => a !== "top");
            paddingBottom = parseFloat(args.height) - 1.2 * numberOfLines + "em";
          } else if (alignment.includes("bottom")) {
            alignment = alignment.filter((a) => a !== "bottom");
            paddingTop = parseFloat(args.height) - 1.2 * numberOfLines + "em";
          } else {
            alignment = alignment.filter((a) => a !== "middle");
            paddingTop = (parseFloat(args.height) - 1.2 * numberOfLines) / 2 + "em";
            paddingBottom = (parseFloat(args.height) - 1.2 * numberOfLines) / 2 + "em";
          }
        }
        if (args.width) {
          args.width += "em";
        } else {
          args.width = "auto";
        }
        this.el.innerHTML = `<div style='width: ${args.width};padding-top: ${paddingTop};padding-bottom: ${paddingBottom};text-align: ${alignment[0] || "center"};line-height: 1.2em;'>${this.el.innerHTML.slice(14, -4)}</div>`;
        const classNames = args.class ? args.class.split(" ") : [];
        if (classNames.length > 0) {
          this.el.removeClass("button-default");
          classNames.forEach((className) => {
            this.el.addClass(className);
          });
        }
        if (color) {
          this.el.addClass(color);
        }
        this.el.onclick = async () => {
          await this.handleButtonClick(args);
        };
      } else {
        this.el.innerText = "button not found. check button ID";
        this.el.removeClass("button-default");
        this.el.addClass("button-error");
      }
    } catch (error) {
      console.log(error);
      this.el.innerText = "Error loading button";
      this.el.removeClass("button-default");
      this.el.addClass("button-error");
    }
  }
  async handleButtonClick(args) {
    const activeView = this.app.workspace.getActiveViewOfType(import_obsidian19.MarkdownView);
    const activeFile = activeView?.file || this.app.workspace.getActiveFile();
    if (!activeFile) {
      new import_obsidian19.Notice("No active file found. Buttons can only be used with files.");
      return;
    }
    let processedAction = args.action;
    let processedType = args.type;
    let processedFolder = args.folder;
    if (args.templater) {
      try {
        const runTemplater = await templater_default(this.app, activeFile, activeFile);
        if (runTemplater) {
          if (args.action && args.action.includes("<%")) {
            processedAction = await runTemplater(args.action);
          }
          if (args.type && args.type.includes("<%")) {
            processedType = await runTemplater(args.type);
          }
          if (args.folder && args.folder.includes("<%")) {
            processedFolder = await runTemplater(args.folder);
          }
        }
      } catch (error) {
        console.error("Error processing templater in button:", error);
        new import_obsidian19.Notice("Error processing templater in button. Check console for details.", 2e3);
      }
    }
    const processedArgs = { ...args, action: processedAction, type: processedType, folder: processedFolder };
    const buttonStart = await getInlineButtonPosition(this.app, this.id);
    let position = await getInlineButtonPosition(this.app, this.id);
    if (args.replace) {
      await replace(this.app, processedArgs, position);
    }
    if (processedArgs.type && processedArgs.type.includes("command")) {
      command(this.app, processedArgs, buttonStart);
    }
    if (processedArgs.type === "copy") {
      copy(processedArgs);
    }
    if (processedArgs.type === "link") {
      link(processedArgs);
    }
    if (processedArgs.type && processedArgs.type.includes("template")) {
      position = await getInlineButtonPosition(this.app, this.id);
      await template(this.app, processedArgs, position);
    }
    if (processedArgs.type === "calculate") {
      await calculate(this.app, processedArgs, position);
    }
    if (processedArgs.type && processedArgs.type.includes("text")) {
      position = await getInlineButtonPosition(this.app, this.id);
      await text(this.app, processedArgs, position);
    }
    if (args.swap) {
      await swap(this.app, args.swap, this.id, true, activeFile, buttonStart);
    }
    if (args.remove) {
      position = await getInlineButtonPosition(this.app, this.id);
      await remove(this.app, processedArgs, position);
    }
    if (processedArgs.type === "chain") {
      await chain(this.app, processedArgs, position, true, this.id, activeFile);
      return;
    }
  }
};
var livePreview_default = buttonPlugin;

// src/index.ts
var ButtonsPlugin = class extends import_obsidian20.Plugin {
  constructor() {
    super(...arguments);
    __publicField(this, "buttonEvents");
    __publicField(this, "closedFile");
    __publicField(this, "buttonEdit");
    __publicField(this, "createButton");
    __publicField(this, "storeEvents", new import_obsidian20.Events());
    __publicField(this, "indexCount", 0);
    __publicField(this, "storeEventsRef");
  }
  async addButtonInEdit(_app) {
  }
  async onload() {
    this.app.workspace.onLayoutReady(async () => {
    });
    this.registerEditorExtension(livePreview_default(this.app));
    this.buttonEvents = buttonEventListener(this.app, addButtonToStore);
    this.closedFile = openFileListener(this.app, this.storeEvents, initializeButtonStore);
    this.createButton = createButton;
    this.storeEventsRef = this.storeEvents.on("index-complete", () => {
      this.indexCount++;
    });
    initializeButtonStore(this.app, this.storeEvents);
    this.buttonEdit = openFileListener(this.app, this.storeEvents, this.addButtonInEdit.bind(this));
    this.addCommand({
      id: "button-maker",
      name: "Button Maker",
      callback: () => new ButtonModal(this.app).open()
    });
    this.addCommand({
      id: "inline-button",
      name: "Insert Inline Button",
      callback: () => new InlineButtonModal(this.app).open()
    });
    const assignedBlocks = new Set();
    this.registerMarkdownCodeBlockProcessor("button", async (source, el, ctx) => {
      const file = this.app.vault.getFiles().find((f) => f.path === ctx.sourcePath);
      addButtonToStore(this.app, file);
      let args = createArgumentObject(source);
      const storeArgs = await getButtonFromStore(this.app, args);
      args = storeArgs ? storeArgs.args : args;
      let id = storeArgs && storeArgs.id;
      if (!id && file) {
        try {
          const store = getStore(this.app.isMobile);
          const content = await this.app.vault.cachedRead(file);
          const contentArray = content.split("\n");
          const candidates = (store || []).filter((item) => item.path === file.path && item.id?.startsWith("button-"));
          for (const item of candidates) {
            const blockInner = contentArray.slice(item.position.start.line + 1, item.position.end.line).join("\n");
            if (blockInner.trim() === source.trim()) {
              const key = `${item.path}:${item.position.start.line}:${item.position.end.line}`;
              if (!assignedBlocks.has(key)) {
                id = item.id.split("button-")[1];
                assignedBlocks.add(key);
                break;
              }
            }
          }
        } catch (_) {
        }
      }
      if (Boolean(args["hidden"]) !== true) {
        const component = new import_obsidian20.Component();
        createButton({ app: this.app, el, args, inline: false, id, component });
      }
    });
    this.registerMarkdownPostProcessor(async (el, ctx) => {
      const codeblocks = el.querySelectorAll("code");
      for (let index = 0; index < codeblocks.length; index++) {
        const codeblock = codeblocks.item(index);
        const text2 = codeblock.innerText.trim();
        if (text2.startsWith("button")) {
          const id = text2.split("button-")[1].trim();
          if (this.indexCount < 2) {
            this.storeEventsRef = this.storeEvents.on("index-complete", async () => {
              this.indexCount++;
              const args = await getButtonById(this.app, id);
              if (args) {
                ctx.addChild(new InlineButton(codeblock, this.app, args, id));
              }
            });
          } else {
            const args = await getButtonById(this.app, id);
            if (args) {
              ctx.addChild(new InlineButton(codeblock, this.app, args, id));
            }
          }
        }
      }
    });
  }
  onunload() {
    this.app.metadataCache.offref(this.buttonEvents);
    this.app.workspace.offref(this.closedFile);
    this.app.workspace.offref(this.buttonEdit);
    this.storeEvents.offref(this.storeEventsRef);
  }
};
var InlineButton = class extends import_obsidian20.MarkdownRenderChild {
  constructor(el, app, args, id) {
    super(el);
    this.el = el;
    this.app = app;
    this.args = args;
    this.id = id;
  }
  async onload() {
    const button = createButton({
      app: this.app,
      el: this.el,
      args: this.args,
      inline: true,
      id: this.id,
      component: this
    });
    this.el.replaceWith(button);
  }
};

/* nosourcemap */