import { nodeViewProps as $, NodeViewWrapper as R, VueRenderer as v, VueNodeViewRenderer as I, BubbleMenu as G, EditorContent as Q, Editor as Z } from "../../node_modules/@tiptap/vue-3.js";
import { Node as ee, nodePasteRule as A, InputRule as te, mergeAttributes as b, getMarksBetween as ne, combineTransactionSteps as oe, getChangedRanges as re, findChildrenInRange as se, Mark as ie, nodeInputRule as ae, Extension as ce } from "@tiptap/core";
import de from "@tiptap/extension-blockquote";
import le from "@tiptap/extension-code-block";
import ue from "@tiptap/extension-code";
import me from "@tiptap/extension-document";
import he from "@tiptap/extension-hard-break";
import U from "@tiptap/extension-paragraph";
import pe from "@tiptap/extension-placeholder";
import fe from "@tiptap/extension-bold";
import ge from "@tiptap/extension-bullet-list";
import _e from "@tiptap/extension-italic";
import ke from "@tiptap/extension-link";
import ye from "@tiptap/extension-list-item";
import we from "@tiptap/extension-ordered-list";
import Ce from "@tiptap/extension-strike";
import be from "@tiptap/extension-underline";
import xe from "@tiptap/extension-text";
import Te from "@tiptap/extension-text-align";
import Ee from "@tiptap/extension-history";
import Se from "@tiptap/extension-text-style";
import Le from "@tiptap/extension-color";
import $e from "@tiptap/extension-font-family";
import { PluginKey as T, Plugin as Re } from "@tiptap/pm/state";
import ve from "@tiptap/suggestion";
import { emojiPattern as W } from "regex-combined-emojis";
import { resolveComponent as l, createBlock as m, openBlock as d, withCtx as u, createVNode as f, createElementBlock as _, withDirectives as Ie, createElementVNode as k, Fragment as Me, renderList as Be, withModifiers as Ne, normalizeClass as z, resolveDynamicComponent as Oe, vShow as De, createTextVNode as C, toDisplayString as h, markRaw as M, createCommentVNode as w, mergeProps as Ae } from "vue";
import { _ as g } from "../../_plugin-vue_export-helper-CHgC5LLL.js";
import X from "../emoji/emoji.js";
import { getEmojiData as Pe, emojiRegex as je, stringToUnicode as He, codeToEmojiData as j, emojiShortCodeRegex as Ke } from "../../common/emoji/index.js";
import Fe from "../list-item/list-item.js";
import E from "../stack/stack.js";
import B from "tippy.js";
import { getPhoneNumberRegex as Ve, linkRegex as qe, warnIfUnmounted as Ue, returnFirstEl as K } from "../../common/utils/index.js";
import We from "@tiptap/extension-image";
import H from "@tiptap/extension-mention";
import J from "../link/link.js";
import { DtIconLock as ze } from "@dialpad/dialtone-icons/vue3";
import { RICH_TEXT_EDITOR_SUPPORTED_LINK_PROTOCOLS as F, RICH_TEXT_EDITOR_OUTPUT_FORMATS as Xe, RICH_TEXT_EDITOR_AUTOFOCUS_TYPES as Je } from "./rich-text-editor-constants.js";
import Ye from "../avatar/avatar.js";
import Ge from "@dialpad/dialtone-icons/vue3/hash";
import Qe from "@dialpad/dialtone-icons/vue3/lock";
import Ze from "deep-equal";
import { DialtoneLocalization as et } from "../../localization/index.js";
import tt from "../button/button.js";
const nt = {
  compatConfig: { MODE: 3 },
  name: "EmojiComponent",
  components: {
    NodeViewWrapper: R,
    DtEmoji: X
  },
  props: $
};
function ot(e, t, o, n, r, s) {
  const i = l("dt-emoji"), a = l("node-view-wrapper");
  return d(), m(a, { class: "d-d-inline-block d-va-bottom d-lh0" }, {
    default: u(() => [
      f(i, {
        size: "500",
        code: e.node.attrs.code
      }, null, 8, ["code"])
    ]),
    _: 1
  });
}
const rt = /* @__PURE__ */ g(nt, [["render", ot]]), st = {
  compatConfig: { MODE: 3 },
  name: "SuggestionList",
  components: {
    DtListItem: Fe
  },
  props: {
    items: {
      type: Array,
      required: !0
    },
    command: {
      type: Function,
      required: !0
    },
    itemComponent: {
      type: Object,
      required: !0
    },
    itemType: {
      type: String,
      required: !0
    }
  },
  data() {
    return {
      selectedIndex: 0
    };
  },
  watch: {
    items() {
      this.selectedIndex = 0;
    }
  },
  methods: {
    onKeyDown({ event: e }) {
      return e.key === "ArrowUp" ? (this.upHandler(), !0) : e.key === "ArrowDown" ? (this.downHandler(), !0) : e.key === "Enter" || e.key === "Tab" ? (this.selectHandler(), !0) : !1;
    },
    upHandler() {
      this.selectedIndex = (this.selectedIndex + this.items.length - 1) % this.items.length, this.scrollActiveElementIntoView();
    },
    downHandler() {
      this.selectedIndex = (this.selectedIndex + 1) % this.items.length, this.scrollActiveElementIntoView();
    },
    async scrollActiveElementIntoView() {
      await this.$nextTick();
      const e = this.$refs.suggestionList.querySelector(".d-list-item--highlighted");
      e && e.scrollIntoView({
        behaviour: "smooth",
        block: "center"
      });
    },
    selectHandler() {
      this.selectItem(this.selectedIndex);
    },
    selectItem(e) {
      const t = this.items[e];
      switch (this.itemType) {
        case "emoji":
          this.command(t);
          return;
        case "mention":
          this.command({ name: t.name, id: t.id, avatarSrc: t.avatarSrc });
          break;
        case "channel":
          this.command({ name: t.name, id: t.id, locked: t.locked });
          break;
        case "slash-command":
          this.command({ command: t.command });
          break;
      }
    }
  }
}, it = { class: "d-popover__dialog d-suggestion-list__container" }, at = {
  ref: "suggestionList",
  class: "d-suggestion-list"
};
function ct(e, t, o, n, r, s) {
  const i = l("dt-list-item");
  return d(), _("div", it, [
    Ie(k("ul", at, [
      (d(!0), _(Me, null, Be(o.items, (a, c) => (d(), m(i, {
        key: a.id,
        class: z([
          "d-suggestion-list__item",
          { "d-list-item--highlighted": c === r.selectedIndex }
        ]),
        "navigation-type": "arrow-keys",
        onClick: (p) => s.selectItem(c),
        onKeydown: Ne(s.onKeyDown, ["prevent"])
      }, {
        default: u(() => [
          (d(), m(Oe(o.itemComponent), { item: a }, null, 8, ["item"]))
        ]),
        _: 2
      }, 1032, ["class", "onClick", "onKeydown"]))), 128))
    ], 512), [
      [De, o.items.length]
    ])
  ]);
}
const N = /* @__PURE__ */ g(st, [["render", ct]]), dt = {
  compatConfig: { MODE: 3 },
  name: "EmojiSuggestion",
  components: {
    DtEmoji: X,
    DtStack: E
  },
  props: {
    item: {
      type: Object,
      required: !0
    }
  }
};
function lt(e, t, o, n, r, s) {
  const i = l("dt-emoji"), a = l("dt-stack");
  return d(), m(a, {
    direction: "row",
    gap: "400"
  }, {
    default: u(() => [
      f(i, {
        size: "200",
        code: o.item.code
      }, null, 8, ["code"]),
      C(" " + h(o.item.code), 1)
    ]),
    _: 1
  });
}
const ut = /* @__PURE__ */ g(dt, [["render", lt]]), O = {
  name: "hideOnEsc",
  defaultValue: !0,
  fn({ hide: e }) {
    function t(o) {
      o.keyCode === 27 && e();
    }
    return {
      onShow() {
        document.addEventListener("keydown", t);
      },
      onHide() {
        document.removeEventListener("keydown", t);
      }
    };
  }
}, mt = 20, ht = (e, t, o) => {
  var a, c;
  const n = (a = e.shortname) == null ? void 0 : a.replaceAll(":", ""), r = (c = t.shortname) == null ? void 0 : c.replaceAll(":", ""), s = n.startsWith(o), i = r.startsWith(o);
  return s && !i ? -1 : !s && i ? 1 : n.localeCompare(r);
}, pt = {
  items: ({ query: e }) => {
    if (e.length < 2)
      return [];
    const t = Object.values(Pe());
    return e = e.toLowerCase(), t.filter(
      (n) => {
        var r;
        return [
          n.name,
          (r = n.shortname) == null ? void 0 : r.replaceAll(":", ""),
          ...n.keywords || []
        ].some((s) => s && s.startsWith(e));
      }
    ).splice(0, mt).sort((n, r) => ht(n, r, e)).map((n) => ({ code: n.shortname }));
  },
  command: ({ editor: e, range: t, props: o }) => {
    var s, i;
    const n = e.view.state.selection.$to.nodeAfter;
    ((s = n == null ? void 0 : n.text) == null ? void 0 : s.startsWith(" ")) && (t.to += 1), e.chain().focus().insertContentAt(t, [
      {
        type: "emoji",
        attrs: o
      }
    ]).run(), (i = window.getSelection()) == null || i.collapseToEnd();
  },
  render: () => {
    let e, t, o = !1;
    return {
      onStart: (n) => {
        e = new v(N, {
          props: {
            itemComponent: M(ut),
            itemType: "emoji",
            ...n
          },
          editor: n.editor
        }), n.clientRect && (t = B("body", {
          getReferenceClientRect: n.clientRect,
          appendTo: () => document.body,
          content: e.element,
          showOnCreate: !1,
          onShow: () => {
            o = !0;
          },
          onHidden: () => {
            o = !1;
          },
          interactive: !0,
          trigger: "manual",
          placement: "top-start",
          zIndex: 650,
          plugins: [O]
        }), n.items.length > 0 && (t == null || t[0].show()));
      },
      onUpdate(n) {
        e == null || e.updateProps(n), n.items.length > 0 ? t == null || t[0].show() : t == null || t[0].hide(), t == null || t[0].setProps({
          getReferenceClientRect: n.clientRect
        });
      },
      onKeyDown(n) {
        var r;
        if (o)
          return (r = e == null ? void 0 : e.ref) == null ? void 0 : r.onKeyDown(n);
      },
      onExit() {
        t == null || t[0].destroy(), t = null, e == null || e.destroy(), e = null;
      }
    };
  }
}, ft = /(:\w+:)$/, gt = new RegExp(W + "$"), _t = (e) => {
  if (e && j(e[0]))
    return { text: e[2] || e[0] };
}, kt = (e) => [...e.matchAll(Ke)].filter((o) => j(o[0])).map((o) => ({
  index: o.index,
  text: o[0],
  match: o
})), yt = ee.create({
  name: "emoji",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  group: "inline",
  inline: !0,
  selectable: !1,
  atom: !0,
  addNodeView() {
    return I(rt);
  },
  addAttributes() {
    return {
      code: {
        default: null
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "emoji-component"
      }
    ];
  },
  renderText({ node: e }) {
    return He(j(e.attrs.code).unicode_output);
  },
  renderHTML({ HTMLAttributes: e }) {
    return ["emoji-component", b(this.options.HTMLAttributes, e)];
  },
  addInputRules() {
    return [
      new te({
        find: (e) => {
          const t = e.match(ft) || e.match(gt);
          if (t)
            return _t(t);
        },
        handler: ({ state: e, range: t, match: o }) => {
          const { tr: n } = e, r = t.from, s = t.to;
          n.replaceWith(r, s, this.type.create({ code: o[0] }));
        }
      })
    ];
  },
  addPasteRules() {
    return [
      A({
        find: kt,
        type: this.type,
        getAttributes(e) {
          return {
            code: e[0]
          };
        }
      }),
      A({
        find: je,
        type: this.type,
        getAttributes(e) {
          return {
            code: e[0]
          };
        }
      })
    ];
  },
  addProseMirrorPlugins() {
    return [
      ve({
        char: ":",
        pluginKey: new T("emoji"),
        editor: this.editor,
        ...this.options.suggestion,
        ...pt
      })
    ];
  },
  addKeyboardShortcuts() {
    return {
      Backspace: () => this.editor.commands.command(({ tr: e, state: t }) => {
        let o = !1;
        const { selection: n } = t, { empty: r, anchor: s } = n;
        return r ? (t.doc.nodesBetween(s - 1, s, (i, a) => {
          if (i.type.name === this.name)
            return o = !0, e.insertText("", a, a + i.nodeSize), !1;
        }), o) : !1;
      })
    };
  }
});
function wt(e, t, o = () => !0) {
  const n = [];
  t.lastIndex = 0;
  let r;
  for (; r = t.exec(e); )
    o(e, r) && n.push(r);
  return n;
}
function Ct(e, t) {
  return !["#", "@"].includes(e.charAt(t.index)) && !["#", "@"].includes(e.charAt(t.index - 1));
}
function bt(e) {
  const t = new RegExp(
    "(?:" + [
      `[!?.,:;'"]`,
      "(?:&|&amp;)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)+$"
    ].join("|"),
    "g"
  );
  return e.replace(t, "");
}
function xt(e, t) {
  const o = e.slice(0, t + 1).search(/\S+\s*$/), n = e.slice(t).search(/\s/);
  if (n < 0) {
    const r = e.slice(o);
    return {
      text: r,
      from: o,
      to: o + r.length
    };
  }
  return {
    text: e.slice(o, n + t),
    from: o,
    to: n + t
  };
}
function P(e, t, o, n) {
  const r = xt(e, t);
  if (n.lastIndex = 0, !n.test(r.text))
    return r;
  const s = o === "left" ? r.from - 1 : r.to + 1;
  return s <= 0 || s >= e.length || s === t ? r : P(e, s, o, n);
}
function Tt(e, t, o, n) {
  const r = Math.max(e.from - 1, 0), s = Math.min(e.to + 1, t.content.size), i = ne(r, s, t);
  for (const a of i)
    a.mark.type === n && o.removeMark(a.from, a.to, n);
}
const V = Ve(1, 15);
function q(e, t, o, n, r, s) {
  if (!e)
    return;
  let i = o - t - 1;
  i = i < 0 ? 0 : i;
  const a = n - t, c = P(
    e,
    i,
    "left",
    V
  ), p = P(
    e,
    a,
    "right",
    V
  ), y = e.slice(c.from, p.to);
  wt(y, qe, Ct).forEach((D) => {
    const x = bt(D[0]), L = t + c.from + D.index + 1, Y = L + x.length;
    r.addMark(L, Y, s.create());
  });
}
function Et(e) {
  let t = !1;
  return new Re({
    key: new T("autolink"),
    appendTransaction: (o, n, r) => {
      const s = o.some((y) => y.docChanged) && !n.doc.eq(r.doc);
      if (t && !s)
        return;
      const { tr: i } = r, { textContent: a } = r.doc;
      t || q(a, 0, 0, a.length, i, e.type), t = !0;
      const c = oe(
        n.doc,
        [...o]
      );
      return re(c).forEach(({ oldRange: y, newRange: S }) => {
        Tt(S, r.doc, i, e.type), se(
          r.doc,
          S,
          (x) => x.isTextblock
        ).forEach(({ node: x, pos: L }) => {
          q(
            x.textContent,
            L,
            y.from,
            S.to,
            i,
            e.type
          );
        });
      }), i;
    }
  });
}
const St = {
  class: "d-link d-c-text d-d-inline-block d-wb-break-all",
  rel: "noopener noreferrer nofollow"
}, Lt = ie.create({
  name: "CustomLink",
  renderHTML({ HTMLAttributes: e }) {
    return [
      "a",
      b(
        this.options.HTMLAttributes,
        e,
        St
      )
    ];
  },
  renderText({ node: e }) {
    return e.attrs.text;
  },
  addProseMirrorPlugins() {
    return [
      Et({ type: this.type })
    ];
  }
}), $t = We.extend({
  name: "ConfigurableImage",
  addAttributes() {
    return {
      src: {
        default: ""
      },
      alt: {
        default: void 0
      },
      title: {
        default: void 0
      },
      width: {
        default: void 0
      },
      height: {
        default: void 0
      },
      style: {
        default: void 0
      }
    };
  }
}).configure({ inline: !0, allowBase64: !0 }), Rt = U.extend({
  parseHTML() {
    return [{ tag: "div" }];
  },
  renderHTML({ HTMLAttributes: e }) {
    return ["div", b(this.options.HTMLAttributes, e), 0];
  }
}), vt = {
  compatConfig: { MODE: 3 },
  name: "MentionComponent",
  components: {
    NodeViewWrapper: R,
    DtLink: J
  },
  props: $,
  computed: {
    text() {
      return "@" + this.$props.node.attrs.name;
    }
  }
};
function It(e, t, o, n, r, s) {
  const i = l("dt-link"), a = l("node-view-wrapper");
  return d(), m(a, { class: "d-d-inline-block" }, {
    default: u(() => [
      f(i, { kind: "mention" }, {
        default: u(() => [
          C(h(s.text), 1)
        ]),
        _: 1
      })
    ]),
    _: 1
  });
}
const Mt = /* @__PURE__ */ g(vt, [["render", It]]), Bt = H.extend({
  addNodeView() {
    return I(Mt);
  },
  parseHTML() {
    return [
      {
        tag: "mention-component"
      }
    ];
  },
  addAttributes() {
    return {
      name: {
        default: ""
      },
      avatarSrc: {
        default: ""
      },
      id: {
        default: ""
      },
      contactKey: {
        default: ""
      }
    };
  },
  renderText({ node: e }) {
    return `@${e.attrs.id}`;
  },
  renderHTML({ HTMLAttributes: e }) {
    return ["mention-component", b(this.options.HTMLAttributes, e)];
  }
}).configure({
  suggestion: {
    char: "@",
    pluginKey: new T("mentionSuggestion")
  }
}), Nt = {
  compatConfig: { MODE: 3 },
  name: "ChannelComponent",
  components: {
    NodeViewWrapper: R,
    DtLink: J,
    DtIconLock: ze,
    DtStack: E
  },
  props: $,
  computed: {
    text() {
      return this.$props.node.attrs.locked ? this.$props.node.attrs.name : "#" + this.$props.node.attrs.name;
    }
  }
};
function Ot(e, t, o, n, r, s) {
  const i = l("dt-icon-lock"), a = l("dt-stack"), c = l("dt-link"), p = l("node-view-wrapper");
  return d(), m(p, { class: "d-d-inline-block" }, {
    default: u(() => [
      f(c, { kind: "mention" }, {
        default: u(() => [
          f(a, {
            direction: "row",
            gap: "0"
          }, {
            default: u(() => [
              e.$props.node.attrs.locked ? (d(), m(i, {
                key: 0,
                size: "200"
              })) : w("", !0),
              k("span", null, h(s.text), 1)
            ]),
            _: 1
          })
        ]),
        _: 1
      })
    ]),
    _: 1
  });
}
const Dt = /* @__PURE__ */ g(Nt, [["render", Ot]]), At = H.extend({
  name: "channel",
  addNodeView() {
    return I(Dt);
  },
  parseHTML() {
    return [
      {
        tag: "channel-component"
      }
    ];
  },
  addAttributes() {
    return {
      name: {
        default: ""
      },
      id: {
        default: ""
      },
      locked: {
        default: !1
      }
    };
  },
  renderText({ node: e }) {
    return `#${e.attrs.id}`;
  },
  renderHTML({ HTMLAttributes: e }) {
    return ["channel-component", b(this.options.HTMLAttributes, e)];
  }
}).configure({
  suggestion: {
    char: "#",
    pluginKey: new T("channelSuggestion")
  }
}), Pt = {
  compatConfig: { MODE: 3 },
  name: "SlashCommandsComponent",
  components: {
    NodeViewWrapper: R
  },
  props: {
    ...$
  },
  emits: ["selected-command"],
  computed: {
    text() {
      return "/" + this.$props.node.attrs.command;
    }
  },
  created() {
    var o, n, r;
    const e = this.$props.node.attrs.command;
    this.$emit("selected-command", e);
    const t = (r = (n = (o = this.editor) == null ? void 0 : o.storage) == null ? void 0 : n["slash-commands"]) == null ? void 0 : r.onSelectedCommand;
    t && typeof t == "function" && t(e);
  }
};
function jt(e, t, o, n, r, s) {
  const i = l("node-view-wrapper");
  return d(), m(i, { class: "d-d-inline-block" }, {
    default: u(() => [
      C(h(s.text), 1)
    ]),
    _: 1
  });
}
const Ht = /* @__PURE__ */ g(Pt, [["render", jt]]), Kt = (e, t) => [...e.matchAll(t)].map((n) => {
  let r = n[2];
  return r.endsWith(" ") || (r += " "), {
    index: n.index,
    text: r,
    match: n
  };
}), Ft = H.extend({
  name: "slash-commands",
  group: "inline",
  inline: !0,
  addOptions() {
    var e;
    return {
      ...(e = this.parent) == null ? void 0 : e.call(this),
      onSelectedCommand: null
    };
  },
  addStorage() {
    return {
      onSelectedCommand: this.options.onSelectedCommand
    };
  },
  addNodeView() {
    return I(Ht);
  },
  parseHTML() {
    return [
      {
        tag: "command-component"
      }
    ];
  },
  addAttributes() {
    return {
      command: {
        default: ""
      },
      parametersExample: {
        default: ""
      },
      description: {
        default: ""
      }
    };
  },
  renderText({ node: e }) {
    return `/${e.attrs.command}`;
  },
  renderHTML({ HTMLAttributes: e }) {
    return ["command-component", b(this.options.HTMLAttributes, e)];
  },
  addInputRules() {
    var o;
    const e = (o = this.options.suggestion) == null ? void 0 : o.items({ query: "" }).map((n) => n.command), t = new RegExp(`^((?:\\/)(${e.join("|")})) $`);
    return [
      ae({
        find: t,
        type: this.type,
        getAttributes(n) {
          return { command: n[2] };
        }
      })
    ];
  },
  addPasteRules() {
    var o;
    const e = (o = this.options.suggestion) == null ? void 0 : o.items({ query: "" }).map((n) => n.command), t = new RegExp(`^((?:\\/)(${e.join("|")})) ?$`, "g");
    return [
      A({
        find: (n) => Kt(n, t),
        type: this.type,
        getAttributes(n) {
          return { command: n[0].trim() };
        }
      })
    ];
  }
}).configure({
  suggestion: {
    char: "/",
    pluginKey: new T("slashCommandSuggestion")
  }
}), Vt = {
  compatConfig: { MODE: 3 },
  name: "MentionSuggestion",
  components: {
    DtAvatar: Ye,
    DtStack: E
  },
  props: {
    item: {
      type: Object,
      required: !0
    }
  },
  computed: {
    name() {
      return this.item.name;
    },
    avatarSrc() {
      return this.item.avatarSrc;
    },
    presence() {
      return this.item.presence;
    },
    status() {
      return this.item.status;
    },
    presenceText() {
      return this.item.presenceText;
    },
    presenceFontColorClass() {
      return {
        active: "d-recipe-contact-row--active",
        busy: "d-recipe-contact-row--busy",
        away: "d-recipe-contact-row--away",
        offline: "d-recipe-contact-row--busy"
      }[this.presence];
    },
    showDetails() {
      return this.item.showDetails;
    }
  }
}, qt = { class: "d-mention-suggestion__name" }, Ut = {
  key: 1,
  class: "d-mention-suggestion__divider"
}, Wt = {
  key: 2,
  class: "d-mention-suggestion__status"
};
function zt(e, t, o, n, r, s) {
  const i = l("dt-avatar"), a = l("dt-stack");
  return d(), m(a, {
    direction: "row",
    class: "d-mention-suggestion__container",
    gap: "400"
  }, {
    default: u(() => [
      f(i, {
        "full-name": s.name,
        "image-src": s.avatarSrc,
        "image-alt": s.name,
        "show-presence": s.showDetails,
        presence: s.presence,
        size: "sm"
      }, null, 8, ["full-name", "image-src", "image-alt", "show-presence", "presence"]),
      f(a, {
        class: "d-mention-suggestion__details-container",
        gap: "100"
      }, {
        default: u(() => [
          k("span", qt, h(s.name), 1),
          s.showDetails ? (d(), m(a, {
            key: 0,
            direction: "row",
            gap: "300",
            class: "d-label--sm-plain"
          }, {
            default: u(() => [
              s.presenceText ? (d(), _("span", {
                key: 0,
                class: z(["d-mention-suggestion__presence", [s.presenceFontColorClass]])
              }, h(s.presenceText), 3)) : w("", !0),
              s.status && s.presenceText ? (d(), _("div", Ut, " • ")) : w("", !0),
              s.status ? (d(), _("div", Wt, h(s.status), 1)) : w("", !0)
            ]),
            _: 1
          })) : w("", !0)
        ]),
        _: 1
      })
    ]),
    _: 1
  });
}
const Xt = /* @__PURE__ */ g(Vt, [["render", zt]]), Jt = {
  // This function comes from the user and passed to the editor directly.
  // This will also activate the mention plugin on the editor
  // items: ({ query }) => { return [] },
  allowSpaces: !0,
  render: () => {
    let e, t, o = !1;
    return {
      onStart: (n) => {
        e = new v(N, {
          props: {
            itemComponent: M(Xt),
            itemType: "mention",
            ...n
          },
          editor: n.editor
        }), n.clientRect && (t = B("body", {
          getReferenceClientRect: n.clientRect,
          appendTo: () => document.body,
          content: e.element,
          showOnCreate: !1,
          onShow: () => {
            o = !0;
          },
          onHidden: () => {
            o = !1;
          },
          interactive: !0,
          trigger: "manual",
          placement: "top-start",
          zIndex: 650,
          plugins: [O]
        }), n.items.length > 0 && (t == null || t[0].show()));
      },
      onUpdate(n) {
        e == null || e.updateProps(n), n.items.length > 0 ? t == null || t[0].show() : t == null || t[0].hide(), n.clientRect && (t == null || t[0].setProps({
          getReferenceClientRect: n.clientRect
        }));
      },
      onKeyDown(n) {
        var r;
        if (o)
          return (r = e == null ? void 0 : e.ref) == null ? void 0 : r.onKeyDown(n);
      },
      onExit() {
        t == null || t[0].destroy(), t = null, e == null || e.destroy(), e = null;
      }
    };
  }
}, Yt = {
  compatConfig: { MODE: 3 },
  name: "ChannelSuggestion",
  components: {
    DtStack: E,
    DtIconHash: Ge,
    DtIconLock: Qe
  },
  props: {
    item: {
      type: Object,
      required: !0
    }
  },
  computed: {
    name() {
      return this.item.name;
    }
  }
};
function Gt(e, t, o, n, r, s) {
  const i = l("dt-icon-hash"), a = l("dt-icon-lock"), c = l("dt-stack");
  return d(), m(c, {
    direction: "row",
    gap: "400"
  }, {
    default: u(() => [
      o.item.locked ? (d(), m(a, {
        key: 1,
        size: "300"
      })) : (d(), m(i, {
        key: 0,
        size: "300"
      })),
      k("span", null, h(s.name), 1)
    ]),
    _: 1
  });
}
const Qt = /* @__PURE__ */ g(Yt, [["render", Gt]]), Zt = {
  // This function comes from the user and passed to the editor directly.
  // This will also activate the mention plugin on the editor
  // items: ({ query }) => { return [] },
  allowSpaces: !0,
  render: () => {
    let e, t, o = !1;
    return {
      onStart: (n) => {
        e = new v(N, {
          props: {
            itemComponent: M(Qt),
            itemType: "channel",
            ...n
          },
          editor: n.editor
        }), n.clientRect && (t = B("body", {
          getReferenceClientRect: n.clientRect,
          appendTo: () => document.body,
          content: e.element,
          showOnCreate: !1,
          onShow: () => {
            o = !0;
          },
          onHidden: () => {
            o = !1;
          },
          interactive: !0,
          trigger: "manual",
          placement: "top-start",
          zIndex: 650,
          plugins: [O]
        }), n.items.length > 0 && (t == null || t[0].show()));
      },
      onUpdate(n) {
        e == null || e.updateProps(n), n.items.length > 0 ? t == null || t[0].show() : t == null || t[0].hide(), n.clientRect && (t == null || t[0].setProps({
          getReferenceClientRect: n.clientRect
        }));
      },
      onKeyDown(n) {
        var r;
        if (o)
          return (r = e == null ? void 0 : e.ref) == null ? void 0 : r.onKeyDown(n);
      },
      onExit() {
        t == null || t[0].destroy(), t = null, e == null || e.destroy(), e = null;
      }
    };
  }
}, en = {
  compatConfig: { MODE: 3 },
  name: "SlashCommandSuggestion",
  props: {
    item: {
      type: Object,
      required: !0
    }
  },
  computed: {
    command() {
      return this.item.command;
    },
    description() {
      return this.item.description;
    },
    parametersExample() {
      return this.item.parametersExample;
    }
  }
}, tn = { class: "d-body--md-compact" }, nn = { key: 0 }, on = { class: "d-body--sm d-fc-tertiary" };
function rn(e, t, o, n, r, s) {
  return d(), _("div", null, [
    k("div", tn, [
      k("span", null, "/" + h(s.command), 1),
      s.parametersExample ? (d(), _("span", nn, h(s.parametersExample), 1)) : w("", !0)
    ]),
    k("div", on, h(s.description), 1)
  ]);
}
const sn = /* @__PURE__ */ g(en, [["render", rn]]), an = {
  // This function comes from the user and passed to the editor directly.
  // This will also activate the mention plugin on the editor
  // items: ({ query }) => { return [] },
  allowSpaces: !0,
  startOfLine: !0,
  render: () => {
    let e, t, o = !1;
    return {
      onStart: (n) => {
        e = new v(N, {
          parent: void 0,
          props: {
            itemComponent: M(sn),
            itemType: "slash-command",
            ...n
          },
          editor: n.editor
        }), n.clientRect && (t = B("body", {
          getReferenceClientRect: n.clientRect,
          appendTo: () => document.body,
          content: e.element,
          showOnCreate: !1,
          onShow: () => {
            o = !0;
          },
          onHidden: () => {
            o = !1;
          },
          interactive: !0,
          trigger: "manual",
          placement: "top-start",
          zIndex: 650,
          plugins: [O]
        }), n.items.length > 0 && (t == null || t[0].show()));
      },
      onUpdate(n) {
        e == null || e.updateProps(n), n.items.length > 0 ? t == null || t[0].show() : t == null || t[0].hide(), n.clientRect && (t == null || t[0].setProps({
          getReferenceClientRect: n.clientRect
        }));
      },
      onKeyDown(n) {
        var r;
        if (o)
          return (r = e == null ? void 0 : e.ref) == null ? void 0 : r.onKeyDown(n);
      },
      onExit() {
        t == null || t[0].destroy(), t = null, e == null || e.destroy(), e = null;
      }
    };
  }
}, cn = {
  compatConfig: { MODE: 3 },
  name: "DtRichTextEditor",
  components: {
    EditorContent: Q,
    BubbleMenu: G,
    DtButton: tt,
    DtStack: E
  },
  props: {
    /**
     * Value of the input. The object format should match TipTap's JSON
     * document structure: https://tiptap.dev/guide/output#option-1-json
     */
    modelValue: {
      type: [Object, String],
      default: ""
    },
    /**
     * Whether the input is editable
     */
    editable: {
      type: Boolean,
      default: !0
    },
    /**
     * Prevents the user from typing any further. Deleting text will still work.
     */
    preventTyping: {
      type: Boolean,
      default: !1
    },
    /**
     * When this option is false the editor will only ever paste plain text, no rich text formatting will be applied,
     * and any HTML will be rendered as text.
     */
    pasteRichText: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for line breaks to be introduced in the text by pressing enter. If this is disabled,
     * line breaks can still be entered by pressing shift+enter.
     */
    allowLineBreaks: {
      type: Boolean,
      default: !1
    },
    /**
     * Descriptive label for the input element
     */
    inputAriaLabel: {
      type: String,
      required: !0
    },
    /**
     * Additional class name for the input element. Only accepts a String value
     * because this is passed to the editor via options. For multiple classes,
     * join them into one string, e.g. "d-p8 d-hmx96"
     */
    inputClass: {
      type: String,
      default: ""
    },
    /**
     * Whether the input should receive focus after the component has been
     * mounted. Either one of `start`, `end`, `all` or a Boolean or a Number.
     * - `start`  Sets the focus to the beginning of the input
     * - `end`    Sets the focus to the end of the input
     * - `all`    Selects the whole contents of the input
     * - `Number` Sets the focus to a specific position in the input
     * - `true`   Defaults to `start`
     * - `false`  Disables autofocus
     * @values true, false, start, end, all, number
     */
    autoFocus: {
      type: [Boolean, String, Number],
      default: !1,
      validator(e) {
        return typeof e == "string" ? Je.includes(e) : !0;
      }
    },
    /**
     * The output format that the editor uses when emitting the "@input" event.
     * One of `text`, `json`, `html`, `markdown`. See https://tiptap.dev/guide/output for
     * examples.
     * @values text, json, html, markdown
     */
    outputFormat: {
      type: String,
      default: "html",
      validator(e) {
        return Xe.includes(e);
      }
    },
    /**
     * Placeholder text
     */
    placeholder: {
      type: String,
      default: ""
    },
    /**
     * Enables the TipTap Link extension and optionally passes configurations to it
     *
     * It is not recommended to use this and the custom link extension at the same time.
     */
    link: {
      type: [Boolean, Object],
      default: !1
    },
    /**
     * Enables the Custom Link extension and optionally passes configurations to it
     *
     * It is not recommended to use this and the built in TipTap link extension at the same time.
     *
     * The custom link does some additional things on top of the built in TipTap link
     * extension such as styling phone numbers and IP adresses as links, and allows you
     * to linkify text without having to type a space after the link. Currently it is missing some
     * functionality such as editing links and will likely require more work to be fully usable,
     * so it is recommended to use the built in TipTap link for now.
     */
    customLink: {
      type: [Boolean, Object],
      default: !1
    },
    /**
     * suggestion object containing the items query function.
     * The valid keys passed into this object can be found here: https://tiptap.dev/api/utilities/suggestion
     *
     * The only required key is the items function which is used to query the contacts for suggestion.
     * items({ query }) => { return [ContactObject]; }
     * ContactObject format:
     * { name: string, avatarSrc: string, id: string }
     *
     * When null, it does not add the plugin.
     */
    mentionSuggestion: {
      type: Object,
      default: null
    },
    /**
     * suggestion object containing the items query function.
     * The valid keys passed into this object can be found here: https://tiptap.dev/api/utilities/suggestion
     *
     * The only required key is the items function which is used to query the channels for suggestion.
     * items({ query }) => { return [ChannelObject]; }
     * ChannelObject format:
     * { name: string, id: string, locked: boolean }
     *
     * When null, it does not add the plugin. Setting locked to true will display a lock rather than hash.
     */
    channelSuggestion: {
      type: Object,
      default: null
    },
    /**
     * suggestion object containing the items query function.
     * The valid keys passed into this object can be found here: https://tiptap.dev/api/utilities/suggestion
     *
     * The only required key is the items function which is used to query the slash commands for suggestion.
     * items({ query }) => { return [SlashCommandObject]; }
     * SlashCommandObject format:
     * { command: string, description: string, parametersExample?: string }
     * The "parametersExample" parameter is optional, and describes an example
     * of the parameters that command can take.
     *
     * When null, it does not add the plugin.
     * Note that slash commands only work when they are the first word in the input.
     */
    slashCommandSuggestion: {
      type: Object,
      default: null
    },
    /**
     * Whether the input allows for block quote.
     */
    allowBlockquote: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for bold to be introduced in the text.
     */
    allowBold: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for bullet list to be introduced in the text.
     */
    allowBulletList: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for italic to be introduced in the text.
     */
    allowItalic: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for strike to be introduced in the text.
     */
    allowStrike: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows for underline to be introduced in the text.
     */
    allowUnderline: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows inline code (wrapped in backticks).
     */
    allowCode: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows codeblock to be introduced in the text.
     */
    allowCodeblock: {
      type: Boolean,
      default: !0
    },
    /**
     * Whether the input allows inline images to be rendered.
     */
    allowInlineImages: {
      type: Boolean,
      default: !1
    },
    /**
     * Whether the input allows color to be introduced in the text.
     */
    allowFontColor: {
      type: Boolean,
      default: !1
    },
    /**
     * Whether the input allows different font-families to be introduced in the text.
     */
    allowFontFamily: {
      type: Boolean,
      default: !1
    },
    /**
     * Additional TipTap extensions to be added to the editor.
     */
    additionalExtensions: {
      type: Array,
      default: () => []
    },
    /**
     * Manually hide the link bubble menu. The link bubble menu is shown when a link is selected via the cursor.
     * There are some cases when you may want the link to remain selected but hide the bubble menu such as when You
     * are showing a custom link editor popup.
     */
    hideLinkBubbleMenu: {
      type: Boolean,
      default: !1
    },
    /**
     * Show text in HTML div tags instead of paragraph tags
     */
    useDivTags: {
      type: Boolean,
      default: !1
    }
  },
  emits: [
    /**
     * Editor input event
     * @event input
     * @type {String|JSON}
     */
    "input",
    /**
     * Input event always in JSON format.
     * @event input
     * @type {JSON}
     */
    "json-input",
    /**
     * Input event always in HTML format.
     * @event input
     * @type {HTML}
     */
    "html-input",
    /**
     * Input event always in text format.
     * @event input
     * @type {String}
     */
    "text-input",
    /**
     * Input event always in markdown format.
     * @event input
     * @type {String}
     */
    "markdown-input",
    /**
     * Event to sync the value with the parent
     * @event update:value
     * @type {String|JSON}
     */
    "update:modelValue",
    /**
     * Editor blur event
     * @event blur
     * @type {FocusEvent}
     */
    "blur",
    /**
     * Editor focus event
     * @event focus
     * @type {FocusEvent}
     */
    "focus",
    /**
     * Enter was pressed. Note that shift enter must be pressed to line break the input.
     * @event enter
     * @type {String}
     */
    "enter",
    /**
     * "Edit link" button was clicked. Fires an event for the consuming component to handle the editing of the link.
     * event contains the link object with two properties href and text.
     * @event edit-link
     * @type {Object}
     */
    "edit-link",
    /**
     * "Selected" event is fired when the user selects text in the editor. returns the currently selected text.
     * If the selected text is partially a link, the full link text is returned.
     * @event selected
     * @type {String}
     */
    "selected",
    /**
     * Event fired when a slash command is selected
     * @event selected-command
     * @type {String}
     */
    "selected-command"
  ],
  data() {
    return {
      editor: null,
      tippyOptions: {
        appendTo: () => {
          var e;
          return (e = K(this.$refs.editor.$el).getRootNode()) == null ? void 0 : e.querySelector("body");
        },
        placement: "top-start"
      },
      i18n: new et(),
      // JSON-to-markdown converter
      jsonToMarkdownConverter: {
        convertToMarkdown(e) {
          return this.processNode(e);
        },
        processNodeContent(e) {
          return e.content ? e.content.map((t) => this.processNode(t)).join("") : "";
        },
        processNode(e) {
          if (!e) return "";
          const o = {
            doc: (n) => this.processDocNode(n),
            paragraph: (n) => this.processParagraphNode(n),
            text: (n) => this.processTextNode(n),
            hardBreak: () => this.processHardBreakNode(),
            blockquote: (n) => this.processBlockquoteNode(n),
            bulletList: (n) => this.processBulletListNode(n),
            orderedList: (n) => this.processOrderedListNode(n),
            listItem: (n) => this.processListItemNode(n),
            codeBlock: (n) => this.processCodeBlockNode(n),
            mention: (n) => this.processMentionNode(n),
            channel: (n) => this.processChannelNode(n),
            "slash-commands": (n) => this.processSlashCommandsNode(n),
            emoji: (n) => this.processEmojiNode(n)
          }[e.type];
          return o ? o(e) : this.processUnknownNode(e);
        },
        processDocNode(e) {
          return this.processNodeContent(e);
        },
        processParagraphNode(e) {
          const t = this.processNodeContent(e);
          return t ? t + `
` : `
`;
        },
        processTextNode(e) {
          let t = e.text || "";
          return e.marks && (t = this.applyMarks(t, e.marks)), t;
        },
        processHardBreakNode() {
          return `
`;
        },
        processBlockquoteNode(e) {
          return this.processNodeContent(e).split(`
`).map((o) => o ? `> ${o}` : ">").join(`
`) + `
`;
        },
        processBulletListNode(e) {
          return this.processNodeContent(e);
        },
        processOrderedListNode(e) {
          return e.content ? e.content.map((t, o) => this.processNode(t).replace(/^- /, `${o + 1}. `)).join("") : "";
        },
        processListItemNode(e) {
          const t = this.processNodeContent(e);
          return t ? `- ${t.replace(/\n$/, "")}
` : "";
        },
        processCodeBlockNode(e) {
          return `\`\`\`
${this.processNodeContent(e)}
\`\`\``;
        },
        processMentionNode(e) {
          var r, s, i;
          const t = ((r = e.attrs) == null ? void 0 : r.name) || "", o = ((s = e.attrs) == null ? void 0 : s.id) || "", n = ((i = e.attrs) == null ? void 0 : i.contactKey) || "";
          return `<!-- @mention: {"id": "${o}", "contactKey": "${n}", "name": "${t}"} -->`;
        },
        processChannelNode(e) {
          var r, s, i;
          const t = ((r = e.attrs) == null ? void 0 : r.name) || "", o = ((s = e.attrs) == null ? void 0 : s.id) || "", n = ((i = e.attrs) == null ? void 0 : i.locked.toString()) || "";
          return `<!-- @channel: {"id": "${o}", "name": "${t}", "locked": "${n}"} -->`;
        },
        processSlashCommandsNode(e) {
          var n, r;
          const t = ((n = e.attrs) == null ? void 0 : n.command) || "", o = ((r = e.attrs) == null ? void 0 : r.parameters) || "";
          return `/${t}${o ? ` ${o}` : ""}`;
        },
        processEmojiNode(e) {
          var t;
          return ((t = e.attrs) == null ? void 0 : t.code) || "";
        },
        processUnknownNode(e) {
          return this.processNodeContent(e);
        },
        applyMarks(e, t) {
          let o = e;
          return [...t].sort((r, s) => {
            const i = { link: 0, bold: 1, italic: 2, strike: 3, code: 4 };
            return (i[r.type] || 5) - (i[s.type] || 5);
          }).forEach((r) => {
            var s;
            switch (r.type) {
              case "bold":
                o = `**${o}**`;
                break;
              case "italic":
                o = `*${o}*`;
                break;
              case "strike":
                o = `~~${o}~~`;
                break;
              case "code":
                o = `\`${o}\``;
                break;
              case "link": {
                const i = ((s = r.attrs) == null ? void 0 : s.href) || "";
                o = `[${o}](${i})`;
                break;
              }
            }
          }), o;
        }
      }
    };
  },
  computed: {
    attrs() {
      return {
        ...this.$attrs,
        onInput: () => {
        },
        onFocus: () => {
        },
        onBlur: () => {
        }
      };
    },
    // eslint-disable-next-line complexity
    extensions() {
      const e = [me, xe, Ee, he];
      e.push(this.useDivTags ? Rt : U), this.allowBold && e.push(fe), this.allowBlockquote && e.push(de), this.allowBulletList && (e.push(ge), e.push(ye.extend({
        renderText({ node: n }) {
          return n.textContent;
        }
      })), e.push(we)), this.allowItalic && e.push(_e), this.allowStrike && e.push(Ce), this.allowUnderline && e.push(be), this.placeholder && e.push(
        pe.configure({ placeholder: this.placeholder })
      );
      const t = this, o = ce.create({
        addKeyboardShortcuts() {
          return {
            "Shift-Enter": ({ editor: n }) => t.allowLineBreaks ? !1 : (n.commands.first(({ commands: r }) => [
              () => r.newlineInCode(),
              () => t.allowBulletList && r.splitListItem("listItem"),
              () => r.createParagraphNear(),
              () => r.liftEmptyBlock(),
              () => r.splitBlock()
            ]), !0),
            Enter: () => t.allowLineBreaks ? !1 : (t.$emit("enter"), !0)
          };
        }
      });
      if (e.push(o), this.link && e.push(ke.extend({
        inclusive: !1,
        addKeyboardShortcuts() {
          return {
            "Mod-k": () => (t.$emit("edit-link"), !0)
          };
        }
      }).configure({
        HTMLAttributes: {
          class: "d-link d-wb-break-all"
        },
        openOnClick: !1,
        autolink: !0,
        protocols: F
      })), this.customLink && e.push(this.getExtension(Lt, this.customLink)), this.mentionSuggestion) {
        const n = { ...this.mentionSuggestion, ...Jt };
        e.push(Bt.configure({ suggestion: n }));
      }
      if (this.channelSuggestion) {
        const n = { ...this.channelSuggestion, ...Zt };
        e.push(At.configure({ suggestion: n }));
      }
      if (this.slashCommandSuggestion) {
        const n = { ...this.slashCommandSuggestion, ...an };
        e.push(Ft.configure({
          suggestion: n,
          onSelectedCommand: (r) => {
            this.$emit("selected-command", r);
          }
        }));
      }
      return e.push(yt), e.push(Te.configure({
        types: ["paragraph"]
      })), this.allowCode && e.push(ue), this.allowCodeblock && e.push(le.extend({
        renderText({ node: n }) {
          return `\`\`\`
${n.textContent}
\`\`\``;
        }
      }).configure({
        HTMLAttributes: {
          class: "d-rich-text-editor__code-block"
        }
      })), this.allowInlineImages && e.push($t), (this.allowFontFamily || this.allowFontColor) && (e.push(Se), this.allowFontColor && e.push(Le), this.allowFontFamily && e.push($e)), this.additionalExtensions.length && e.push(...this.additionalExtensions), e;
    },
    inputAttrs() {
      const e = {
        "aria-label": this.inputAriaLabel,
        "aria-multiline": !0,
        role: "textbox"
      };
      return this.editable || (e["aria-readonly"] = !0), e;
    }
  },
  /**
   * Because the Editor instance is initialized when mounted it does not get
   * updated props automatically, so the ones that can change after mount have
   * to be hooked up to the Editor's own API.
   */
  watch: {
    editable(e) {
      this.editor.setEditable(e), this.updateEditorAttributes({ "aria-readonly": !e });
    },
    inputClass(e) {
      this.updateEditorAttributes({ class: e });
    },
    inputAriaLabel(e) {
      this.updateEditorAttributes({ "aria-label": e });
    },
    extensions() {
      this.destroyEditor(), this.createEditor();
    },
    modelValue(e) {
      this.processValue(e);
    }
  },
  created() {
    this.createEditor();
  },
  beforeUnmount() {
    this.destroyEditor();
  },
  mounted() {
    Ue(K(this.$el), this.$options.name), this.processValue(this.modelValue, !1);
  },
  methods: {
    createEditor() {
      this.editor = new Z({
        autofocus: this.autoFocus,
        content: this.modelValue,
        editable: this.editable,
        extensions: this.extensions,
        parseOptions: {
          preserveWhitespace: "full"
        },
        editorProps: {
          attributes: {
            ...this.inputAttrs,
            class: this.inputClass
          },
          handleKeyDown: (e, t) => {
            if (!this.preventTyping) return !1;
            const o = ["Backspace"];
            return !this.allowLineBreaks && !t.shiftKey && o.push("Enter"), !o.includes(t.key);
          },
          handlePaste: (e, t) => {
            const o = t.clipboardData || window.clipboardData, n = o.getData("text/plain"), r = o.getData("text/html");
            return this.processPasteData(e, n, r);
          },
          // Moves the <br /> tags inside the previous closing tag to avoid
          // Prosemirror wrapping them within another </p> tag.
          transformPastedHTML(e) {
            return e.replace(/(<\/\w+>)((<br \/>)+)/g, "$2$3$1");
          }
        }
      }), this.addEditorListeners();
    },
    bubbleMenuShouldShow({ editor: e }) {
      return e.isActive("link");
    },
    /**
     * If the selection contains a link, return the existing link text.
     * Otherwise, use just the selected text.
     * @param editor the editor instance.
     */
    getSelectedLinkText(e) {
      var a, c, p;
      const { view: t, state: o } = e, { from: n, to: r } = t.state.selection, s = o.doc.textBetween(n, r, ""), i = this.editor.state.doc.nodeAt(n);
      return i && ((p = (c = (a = i.marks) == null ? void 0 : a.at(0)) == null ? void 0 : c.type) == null ? void 0 : p.name) === "link" ? i.textContent : s;
    },
    editLink() {
      const e = this.getSelectedLinkText(this.editor), t = {
        href: this.editor.getAttributes("link").href,
        text: e
      };
      this.$emit("edit-link", t);
    },
    removeLink() {
      var e, t, o, n;
      (n = (o = (t = (e = this.editor) == null ? void 0 : e.chain()) == null ? void 0 : t.focus()) == null ? void 0 : o.unsetLink()) == null || n.run();
    },
    openLink() {
      var t, o;
      (o = (t = this.editor) == null ? void 0 : t.chain()) == null || o.focus();
      const e = this.editor.getAttributes("link").href;
      window.open(e, "_blank");
    },
    setLink(e, t, o, n = F, r) {
      var a, c, p;
      if (!e) {
        this.removeLink();
        return;
      }
      n.find((y) => y.test(e)) || (e = `${r}${e}`), this.editor.chain().focus().extendMarkRange("link").run();
      const i = (p = (c = (a = this.editor) == null ? void 0 : a.view) == null ? void 0 : c.state) == null ? void 0 : p.selection;
      this.editor.chain().focus().insertContent(t).setTextSelection({ from: i.from, to: i.from + t.length }).setLink({ href: e, class: o.class }).run();
    },
    processValue(e, t = !0) {
      const o = this.getOutput();
      if (!(t && Ze(e, o))) {
        if (typeof e == "string" && this.outputFormat === "text") {
          const n = new RegExp(`(${W})`, "g");
          e = e == null ? void 0 : e.replace(n, '<emoji-component code="$1"></emoji-component>');
        }
        this.editor.commands.setContent(e, !1, { preserveWhitespace: "full" });
      }
    },
    destroyEditor() {
      this.editor.destroy();
    },
    insertPlainTextWithHardBreaks(e, t) {
      const { tr: o } = e.state, { from: n, to: r } = e.state.selection;
      o.deleteRange(n, r);
      const s = t.split(/\r?\n/);
      let i = n;
      for (let a = 0; a < s.length; a++)
        a > 0 && (o.insert(i, e.state.schema.nodes.hardBreak.create()), i++), o.insertText(s[a], i), i += s[a].length;
      e.dispatch(o);
    },
    shouldPreserveLineBreaks(e, t) {
      return this.pasteRichText ? !t && e && this.hasBlankLines(e) : !!e;
    },
    processPasteData(e, t, o) {
      if (this.shouldPreserveLineBreaks(t, o))
        return this.insertPlainTextWithHardBreaks(e, t), !0;
      if (this.shouldHandlePreformattedHTML(o)) {
        const n = this.extractPreformattedText(o);
        if (n && n.includes(`
`))
          return this.insertPlainTextWithHardBreaks(e, n), !0;
      }
      return !1;
    },
    shouldHandlePreformattedHTML(e) {
      return this.pasteRichText && e && this.containsPreformattedContent(e);
    },
    containsPreformattedContent(e) {
      const t = document.createElement("div");
      t.innerHTML = e;
      const o = t.querySelectorAll("*");
      for (const n of o)
        if (this.hasPreWhitespace(n) && this.hasLineBreaks(n))
          return !0;
      return !1;
    },
    hasPreWhitespace(e) {
      const t = e.getAttribute("style") || "", o = e.style.whiteSpace || "", n = o === "pre" || o === "pre-wrap", r = t.includes("white-space: pre");
      return n || r;
    },
    hasLineBreaks(e) {
      return e.textContent && e.textContent.includes(`
`);
    },
    hasBlankLines(e) {
      return e.includes(`

`) || /\n\s*\n/.test(e);
    },
    extractPreformattedText(e) {
      const t = document.createElement("div");
      return t.innerHTML = e, this.walkAndExtractText(t);
    },
    walkAndExtractText(e) {
      let t = "";
      if (e.nodeType === Node.TEXT_NODE)
        t += e.textContent;
      else if (e.nodeType === Node.ELEMENT_NODE)
        if (this.hasPreWhitespace(e))
          t += e.textContent;
        else
          for (const o of e.childNodes)
            t += this.walkAndExtractText(o);
      return t;
    },
    triggerInputChangeEvents() {
      const e = this.getOutput();
      this.$emit("input", e), this.$emit("update:modelValue", e);
      const t = this.editor.getJSON();
      this.$emit("json-input", t);
      const o = this.editor.getHTML();
      this.$emit("html-input", o);
      const n = this.editor.getText({ blockSeparator: `
` });
      this.$emit("text-input", n);
      const r = this.jsonToMarkdownConverter.convertToMarkdown(t);
      this.$emit("markdown-input", r);
    },
    /**
     * The Editor exposes event hooks that we have to map our emits into. See
     * https://tiptap.dev/api/events for all events.
     */
    addEditorListeners() {
      this.editor.on("create", () => {
        this.triggerInputChangeEvents();
      }), this.editor.on("update", () => {
        this.triggerInputChangeEvents();
      }), this.editor.on("selectionUpdate", ({ editor: e }) => {
        this.$emit("selected", this.getSelectedLinkText(e));
      }), this.editor.on("focus", ({ event: e }) => {
        this.$emit("focus", e);
      }), this.editor.on("blur", ({ event: e }) => {
        this.$emit("blur", e);
      });
    },
    getOutput() {
      switch (this.outputFormat) {
        case "json":
          return this.editor.getJSON();
        case "html":
          return this.editor.getHTML();
        case "markdown":
          return this.jsonToMarkdownConverter.convertToMarkdown(this.editor.getJSON());
        case "text":
        default:
          return this.editor.getText({ blockSeparator: `
` });
      }
    },
    getExtension(e, t) {
      var o;
      return typeof t == "boolean" ? e : (o = e.configure) == null ? void 0 : o.call(e, t);
    },
    updateEditorAttributes(e) {
      this.editor.setOptions({
        editorProps: {
          attributes: {
            ...this.inputAttrs,
            class: this.inputClass,
            ...e
          }
        }
      });
    },
    focusEditor() {
      this.editor.commands.focus();
    }
  }
}, dn = { class: "d-popover__dialog" };
function ln(e, t, o, n, r, s) {
  const i = l("dt-button"), a = l("dt-stack"), c = l("bubble-menu"), p = l("editor-content");
  return d(), _("div", null, [
    r.editor && o.link && !o.hideLinkBubbleMenu ? (d(), m(c, {
      key: 0,
      editor: r.editor,
      "should-show": s.bubbleMenuShouldShow,
      "tippy-options": r.tippyOptions,
      style: { visibility: "visible" }
    }, {
      default: u(() => [
        k("div", dn, [
          f(a, {
            direction: "row",
            class: "d-rich-text-editor-bubble-menu__button-stack",
            gap: "0"
          }, {
            default: u(() => [
              f(i, {
                kind: "muted",
                importance: "clear",
                onClick: s.editLink
              }, {
                default: u(() => [
                  C(h(r.i18n.$t("DIALTONE_RICH_TEXT_EDITOR_EDIT_BUTTON_LABEL")), 1)
                ]),
                _: 1
              }, 8, ["onClick"]),
              f(i, {
                kind: "muted",
                importance: "clear",
                onClick: s.openLink
              }, {
                default: u(() => [
                  C(h(r.i18n.$t("DIALTONE_RICH_TEXT_EDITOR_OPEN_LINK_BUTTON_LABEL")), 1)
                ]),
                _: 1
              }, 8, ["onClick"]),
              f(i, {
                kind: "danger",
                importance: "clear",
                onClick: s.removeLink
              }, {
                default: u(() => [
                  C(h(r.i18n.$t("DIALTONE_RICH_TEXT_EDITOR_REMOVE_BUTTON_LABEL")), 1)
                ]),
                _: 1
              }, 8, ["onClick"])
            ]),
            _: 1
          })
        ])
      ]),
      _: 1
    }, 8, ["editor", "should-show", "tippy-options"])) : w("", !0),
    f(p, Ae({
      ref: "editor",
      editor: r.editor,
      class: "d-rich-text-editor",
      "data-qa": "dt-rich-text-editor"
    }, s.attrs), null, 16, ["editor"])
  ]);
}
const no = /* @__PURE__ */ g(cn, [["render", ln]]);
export {
  no as default
};
//# sourceMappingURL=rich-text-editor.js.map
