"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var link_exports = {};
__export(link_exports, {
  link: () => link
});
module.exports = __toCommonJS(link_exports);
var import_classnames = __toESM(require("classnames"));
var import_linkifyjs = require("linkifyjs");
var import_v1 = require("./../../ricos-schema/legacy/wix/rich_content/v1/index.js");
var import_next_schema = require("./../../ricos-schema/next-schema/index.js");
var import_create_ricos_extension = require("../create-ricos-extension/index.js");
var import_click_handler = require("../link/helpers/click-handler.js");
var import_styles_scss = __toESM(require("../statics/styles-scss.js"));
var import_data_hooks = require("./data-hooks.js");
var import_paste_handler = require("./helpers/paste-handler.js");
var import_link_parse_html_tag = require("./link-parse-html-tag.js");
var import_models = require("./models.js");
var import_utils = require("./utils.js");
const link = (0, import_create_ricos_extension.createRicosMarkExtension)({
  type: "mark",
  groups: [],
  name: import_v1.Decoration_Type.LINK,
  reconfigure: (config, _extensions, props, _settings, services) => {
    const { rel, relValue, anchorTarget = import_next_schema.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: import_models.RicosLink.of("", anchorTarget, relValue, actualRel),
        autoUnderline
      })
    };
  },
  createExtensionConfig({ markPasteRule }) {
    return {
      name: this.name,
      keepOnSplit: false,
      priority: 1e3,
      inclusive() {
        return this.options.inclusive;
      },
      addAttributes() {
        return import_models.RicosLink.getLinkDefaults();
      },
      parseHTML() {
        return [
          {
            tag: import_link_parse_html_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: import_models.RicosLink.of(url, target, rel).toLink() };
            },
            priority: 51
          }
        ];
      },
      renderHTML({ HTMLAttributes }) {
        const { link: link2, linkInViewer } = import_styles_scss.default;
        const classes = (0, import_classnames.default)(link2, linkInViewer);
        let {
          url: href,
          rel,
          target
        } = HTMLAttributes.link ? import_models.RicosLink.fromLink(HTMLAttributes.link).toHtmlAttributes() : this.options.defaultLink.toHtmlAttributes();
        return [
          "a",
          { href, rel: rel += " noopener", target, class: classes, "data-hook": import_data_hooks.WEB_LINK },
          0
        ];
      },
      addCommands() {
        return {
          setLink: (link2) => ({ commands, tr, state, chain }) => {
            (0, import_utils.cleanAndSetSelection)(
              this.name,
              import_v1.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 } = (0, import_utils.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 (0, import_linkifyjs.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(
            (0, import_click_handler.clickHandler)({
              type: this.type
            })
          );
        }
        if (this.options.linkOnPaste) {
          plugins.push(
            (0, import_paste_handler.pasteHandler)({
              editor: this.editor,
              type: this.type,
              defaultLink: this.options.defaultLink
            })
          );
        }
        return plugins;
      }
    };
  }
});
//# sourceMappingURL=link.js.map
