import classNames from "classnames";
import { find } from "linkifyjs";
import { Decoration_Type } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { Link_Target } from "./../../ricos-schema/next-schema/index.js";
import { createRicosMarkExtension } from "../create-ricos-extension/index.js";
import { clickHandler } from "../link/helpers/click-handler.js";
import styles from "../statics/styles-scss.js";
import { WEB_LINK } from "./data-hooks.js";
import { pasteHandler } from "./helpers/paste-handler.js";
import { LINK_PARSE_HTML_TAG } from "./link-parse-html-tag.js";
import { RicosLink } from "./models.js";
import { cleanAndSetSelection, getSelectedMarkRangeByTypeNames } from "./utils.js";
const link = createRicosMarkExtension({
  type: "mark",
  groups: [],
  name: Decoration_Type.LINK,
  reconfigure: (config, _extensions, props, _settings, services) => {
    const { rel, relValue, anchorTarget = Link_Target.BLANK } = props;
    const actualRel = {
      noreferrer: rel?.noreferrer ?? true,
      ...[rel?.nofollow ? { nofollow: true } : {}],
      ...[rel?.sponsored ? { sponsored: true } : {}]
    };
    const autoUnderline = services.editorProps.generalLinkSettings?.autoUnderline ?? true;
    return {
      ...config,
      addOptions: () => ({
        inclusive: false,
        openOnClick: false,
        linkOnPaste: true,
        HTMLAttributes: { link: {} },
        defaultLink: RicosLink.of("", anchorTarget, relValue, actualRel),
        autoUnderline
      })
    };
  },
  createExtensionConfig({ markPasteRule }) {
    return {
      name: this.name,
      keepOnSplit: false,
      priority: 1e3,
      inclusive() {
        return this.options.inclusive;
      },
      addAttributes() {
        return RicosLink.getLinkDefaults();
      },
      parseHTML() {
        return [
          {
            tag: LINK_PARSE_HTML_TAG,
            consuming: false,
            getAttrs: (node) => {
              const url = node.getAttribute("href") || "";
              const target = node.getAttribute("target") || "";
              const rel = node.getAttribute("rel") || "";
              return { link: RicosLink.of(url, target, rel).toLink() };
            },
            priority: 51
          }
        ];
      },
      renderHTML({ HTMLAttributes }) {
        const { link: link2, linkInViewer } = styles;
        const classes = classNames(link2, linkInViewer);
        let {
          url: href,
          rel,
          target
        } = HTMLAttributes.link ? RicosLink.fromLink(HTMLAttributes.link).toHtmlAttributes() : this.options.defaultLink.toHtmlAttributes();
        return [
          "a",
          { href, rel: rel += " noopener", target, class: classes, "data-hook": WEB_LINK },
          0
        ];
      },
      addCommands() {
        return {
          setLink: (link2) => ({ commands, tr, state, chain }) => {
            cleanAndSetSelection(
              this.name,
              Decoration_Type.ANCHOR,
              commands.unsetAnchor,
              state.schema,
              tr.selection,
              state.doc,
              commands,
              link2.link?.defaultName || link2.link?.url || ""
            );
            let setLinkChain = chain().setMark(this.name, link2);
            if (this.options.autoUnderline) {
              setLinkChain = setLinkChain.setUnderline();
            }
            return setLinkChain.setMeta("preventAutolink", true).run();
          },
          toggleLink: (link2) => ({ chain }) => {
            return chain().toggleMark(this.name, link2, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
          },
          unsetLink: () => ({ tr, chain, state }) => {
            const { from, to } = getSelectedMarkRangeByTypeNames(
              [this.name],
              state.schema,
              tr.selection
            );
            let unsetLinkChain = chain().setTextSelection({ from, to }).unsetMark(this.name);
            if (this.options.autoUnderline) {
              unsetLinkChain = unsetLinkChain.unsetUnderline();
            }
            return unsetLinkChain.setMeta("preventAutolink", true).run();
          }
        };
      },
      addPasteRules() {
        return [
          markPasteRule({
            find: (text) => {
              return find(text).filter((link2) => {
                if (this.options.validate) {
                  return this.options.validate(link2.value);
                }
                return true;
              }).filter((link2) => link2.isLink).map((link2) => ({
                text: link2.value,
                index: link2.start,
                data: link2
              }));
            },
            type: this.type,
            getAttributes: (match) => {
              return this.options.defaultLink.setUrl(match.data?.href || "");
            }
          })
        ];
      },
      addProseMirrorPlugins() {
        const plugins = [];
        if (this.options.openOnClick) {
          plugins.push(
            clickHandler({
              type: this.type
            })
          );
        }
        if (this.options.linkOnPaste) {
          plugins.push(
            pasteHandler({
              editor: this.editor,
              type: this.type,
              defaultLink: this.options.defaultLink
            })
          );
        }
        return plugins;
      }
    };
  }
});
export {
  link
};
//# sourceMappingURL=link.js.map
