import { Mark as b, markPasteRule as C, mergeAttributes as L, combineTransactionSteps as T, getChangedRanges as w, findChildrenInRange as E, getMarksBetween as H, getAttributes as B } from "../../../../../@tiptap_core@2.23.0_@tiptap_pm@2.23.0/node_modules/@tiptap/core/dist/index.js";
import { registerCustomProtocol as y, tokenize as O, find as M, reset as U } from "../../../../../linkifyjs@4.3.1/node_modules/linkifyjs/dist/linkify.js";
import { Plugin as m, PluginKey as A } from "../../../../../prosemirror-state@1.4.3/node_modules/prosemirror-state/dist/index.js";
function V(t) {
  return t.length === 1 ? t[0].isLink : t.length === 3 && t[1].isLink ? ["()", "[]"].includes(t[0].value + t[2].value) : !1;
}
function R(t) {
  return new m({
    key: new A("autolink"),
    appendTransaction: (e, n, o) => {
      const i = e.some((s) => s.docChanged) && !n.doc.eq(o.doc), l = e.some((s) => s.getMeta("preventAutolink"));
      if (!i || l)
        return;
      const { tr: a } = o, d = T(n.doc, [...e]);
      if (w(d).forEach(({ newRange: s }) => {
        const f = E(o.doc, s, (k) => k.isTextblock);
        let u, c;
        if (f.length > 1 ? (u = f[0], c = o.doc.textBetween(u.pos, u.pos + u.node.nodeSize, void 0, " ")) : f.length && o.doc.textBetween(s.from, s.to, " ", " ").endsWith(" ") && (u = f[0], c = o.doc.textBetween(u.pos, s.to, void 0, " ")), u && c) {
          const k = c.split(" ").filter((r) => r !== "");
          if (k.length <= 0)
            return !1;
          const g = k[k.length - 1], P = u.pos + c.lastIndexOf(g);
          if (!g)
            return !1;
          const v = O(g).map((r) => r.toObject(t.defaultProtocol));
          if (!V(v))
            return !1;
          v.filter((r) => r.isLink).map((r) => ({
            ...r,
            from: P + r.start + 1,
            to: P + r.end + 1
          })).filter((r) => o.schema.marks.code ? !o.doc.rangeHasMark(r.from, r.to, o.schema.marks.code) : !0).filter((r) => t.validate(r.value)).filter((r) => t.shouldAutoLink(r.value)).forEach((r) => {
            H(r.from, r.to, o.doc).some((x) => x.mark.type === t.type) || a.addMark(r.from, r.to, t.type.create({
              href: r.href
            }));
          });
        }
      }), !!a.steps.length)
        return a;
    }
  });
}
function W(t) {
  return new m({
    key: new A("handleClickLink"),
    props: {
      handleClick: (e, n, o) => {
        var i, l;
        if (o.button !== 0 || !e.editable)
          return !1;
        let a = o.target;
        const d = [];
        for (; a.nodeName !== "DIV"; )
          d.push(a), a = a.parentNode;
        if (!d.find((c) => c.nodeName === "A"))
          return !1;
        const h = B(e.state, t.type.name), s = o.target, f = (i = s == null ? void 0 : s.href) !== null && i !== void 0 ? i : h.href, u = (l = s == null ? void 0 : s.target) !== null && l !== void 0 ? l : h.target;
        return s && f ? (window.open(f, u), !0) : !1;
      }
    }
  });
}
function z(t) {
  return new m({
    key: new A("handlePasteLink"),
    props: {
      handlePaste: (e, n, o) => {
        const { state: i } = e, { selection: l } = i, { empty: a } = l;
        if (a)
          return !1;
        let d = "";
        o.content.forEach((s) => {
          d += s.textContent;
        });
        const h = M(d, { defaultProtocol: t.defaultProtocol }).find((s) => s.isLink && s.value === d);
        return !d || !h ? !1 : t.editor.commands.setMark(t.type, {
          href: h.href
        });
      }
    }
  });
}
const I = /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g;
function p(t, e) {
  const n = [
    "http",
    "https",
    "ftp",
    "ftps",
    "mailto",
    "tel",
    "callto",
    "sms",
    "cid",
    "xmpp"
  ];
  return e && e.forEach((o) => {
    const i = typeof o == "string" ? o : o.scheme;
    i && n.push(i);
  }), !t || t.replace(I, "").match(new RegExp(
    // eslint-disable-next-line no-useless-escape
    `^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,
    "i"
  ));
}
const D = b.create({
  name: "link",
  priority: 1e3,
  keepOnSplit: !1,
  exitable: !0,
  onCreate() {
    this.options.validate && !this.options.shouldAutoLink && (this.options.shouldAutoLink = this.options.validate, console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")), this.options.protocols.forEach((t) => {
      if (typeof t == "string") {
        y(t);
        return;
      }
      y(t.scheme, t.optionalSlashes);
    });
  },
  onDestroy() {
    U();
  },
  inclusive() {
    return this.options.autolink;
  },
  addOptions() {
    return {
      openOnClick: !0,
      linkOnPaste: !0,
      autolink: !0,
      protocols: [],
      defaultProtocol: "http",
      HTMLAttributes: {
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        class: null
      },
      isAllowedUri: (t, e) => !!p(t, e.protocols),
      validate: (t) => !!t,
      shouldAutoLink: (t) => !!t
    };
  },
  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML(t) {
          return t.getAttribute("href");
        }
      },
      target: {
        default: this.options.HTMLAttributes.target
      },
      rel: {
        default: this.options.HTMLAttributes.rel
      },
      class: {
        default: this.options.HTMLAttributes.class
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "a[href]",
        getAttrs: (t) => {
          const e = t.getAttribute("href");
          return !e || !this.options.isAllowedUri(e, {
            defaultValidate: (n) => !!p(n, this.options.protocols),
            protocols: this.options.protocols,
            defaultProtocol: this.options.defaultProtocol
          }) ? !1 : null;
        }
      }
    ];
  },
  renderHTML({ HTMLAttributes: t }) {
    return this.options.isAllowedUri(t.href, {
      defaultValidate: (e) => !!p(e, this.options.protocols),
      protocols: this.options.protocols,
      defaultProtocol: this.options.defaultProtocol
    }) ? ["a", L(this.options.HTMLAttributes, t), 0] : [
      "a",
      L(this.options.HTMLAttributes, { ...t, href: "" }),
      0
    ];
  },
  addCommands() {
    return {
      setLink: (t) => ({ chain: e }) => {
        const { href: n } = t;
        return this.options.isAllowedUri(n, {
          defaultValidate: (o) => !!p(o, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        }) ? e().setMark(this.name, t).setMeta("preventAutolink", !0).run() : !1;
      },
      toggleLink: (t) => ({ chain: e }) => {
        const { href: n } = t;
        return this.options.isAllowedUri(n, {
          defaultValidate: (o) => !!p(o, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        }) ? e().toggleMark(this.name, t, { extendEmptyMarkRange: !0 }).setMeta("preventAutolink", !0).run() : !1;
      },
      unsetLink: () => ({ chain: t }) => t().unsetMark(this.name, { extendEmptyMarkRange: !0 }).setMeta("preventAutolink", !0).run()
    };
  },
  addPasteRules() {
    return [
      C({
        find: (t) => {
          const e = [];
          if (t) {
            const { protocols: n, defaultProtocol: o } = this.options, i = M(t).filter((l) => l.isLink && this.options.isAllowedUri(l.value, {
              defaultValidate: (a) => !!p(a, n),
              protocols: n,
              defaultProtocol: o
            }));
            i.length && i.forEach((l) => e.push({
              text: l.value,
              data: {
                href: l.href
              },
              index: l.start
            }));
          }
          return e;
        },
        type: this.type,
        getAttributes: (t) => {
          var e;
          return {
            href: (e = t.data) === null || e === void 0 ? void 0 : e.href
          };
        }
      })
    ];
  },
  addProseMirrorPlugins() {
    const t = [], { protocols: e, defaultProtocol: n } = this.options;
    return this.options.autolink && t.push(R({
      type: this.type,
      defaultProtocol: this.options.defaultProtocol,
      validate: (o) => this.options.isAllowedUri(o, {
        defaultValidate: (i) => !!p(i, e),
        protocols: e,
        defaultProtocol: n
      }),
      shouldAutoLink: this.options.shouldAutoLink
    })), this.options.openOnClick === !0 && t.push(W({
      type: this.type
    })), this.options.linkOnPaste && t.push(z({
      editor: this.editor,
      defaultProtocol: this.options.defaultProtocol,
      type: this.type
    })), t;
  }
});
export {
  D as Link,
  D as default,
  p as isAllowedUri
};
//# sourceMappingURL=index.js.map
