import classNames from "classnames";
import { Decoration_Type } from "./../../ricos-schema/legacy/wix/rich_content/v1/index.js";
import { findChildren, mergeAttributes } from "./../../tiptap/index.js";
import { NodeSelection, TextSelection } from "./../../tiptap/pm/state.js";
import { createRicosMarkExtension } from "../create-ricos-extension/index.js";
import styles from "../statics/styles-scss.js";
import { ANCHOR_LINK } from "./data-hooks.js";
import { cleanAndSetSelection, getSelectedMarkRangeByTypeNames } from "./utils.js";
const scrollIntoViewWithOffset = (element) => {
  element.scrollIntoView({ behavior: "smooth", block: "nearest" });
};
const anchor = createRicosMarkExtension({
  type: "mark",
  groups: [],
  name: Decoration_Type.ANCHOR,
  createExtensionConfig() {
    return {
      name: this.name,
      keepOnSplit: false,
      priority: 1e3,
      addOptions: () => ({
        inclusive: false,
        HTMLAttributes: {}
      }),
      inclusive() {
        return this.options.inclusive;
      },
      addAttributes() {
        return {
          anchor: {
            default: ""
          }
        };
      },
      renderHTML({ HTMLAttributes }) {
        const { link, linkInViewer } = styles;
        const classes = classNames(link, linkInViewer);
        const anchorAttributes = HTMLAttributes.anchor ? {
          "ricos-anchor": HTMLAttributes.anchor,
          href: `#${HTMLAttributes.anchor}`,
          target: "_self"
        } : {};
        return [
          "a",
          mergeAttributes(this.options.HTMLAttributes, {
            ...anchorAttributes,
            class: classes,
            "data-hook": ANCHOR_LINK
          }),
          0
        ];
      },
      parseHTML() {
        return [
          {
            tag: `a[data-hook~=${ANCHOR_LINK}][ricos-anchor]`,
            getAttrs: (node) => {
              const anchor2 = node.getAttribute("ricos-anchor") ?? "";
              return { anchor: anchor2 };
            }
          }
        ];
      },
      addCommands() {
        return {
          setAnchor: (data) => ({ commands, state, tr, chain }) => {
            cleanAndSetSelection(
              this.name,
              Decoration_Type.LINK,
              commands.unsetLink,
              state.schema,
              tr.selection,
              state.doc,
              commands,
              data.defaultName || ""
            );
            const setLinkChain = chain().setMark(this.name, { anchor: data.anchor });
            return setLinkChain.setUnderline().run();
          },
          unsetAnchor: () => ({ tr, state, chain }) => {
            const { from, to } = getSelectedMarkRangeByTypeNames(
              [this.name],
              state.schema,
              tr.selection
            );
            const unsetLinkChain = chain().setTextSelection({ from, to }).unsetMark(this.name);
            return unsetLinkChain.unsetUnderline().run();
          },
          scrollToAnchor: (anchor2) => ({ editor, tr }) => {
            const { view } = editor;
            const foundNodes = findChildren(view.state.doc, (node) => {
              return node?.attrs?.id?.toString() === anchor2;
            });
            if (foundNodes.length === 0) {
              return false;
            }
            const targetNode = foundNodes[0];
            let targetDom = view.nodeDOM(targetNode.pos);
            if (targetDom && targetDom instanceof HTMLElement && !targetDom.scrollIntoView) {
              targetDom = targetDom.parentElement;
            }
            if (targetDom && targetDom instanceof HTMLElement) {
              scrollIntoViewWithOffset(targetDom);
              try {
                if (targetNode.node.isText || targetNode.node.isTextblock) {
                  tr.setSelection(
                    TextSelection.between(
                      tr.doc.resolve(targetNode.pos),
                      tr.doc.resolve(targetNode.pos)
                    )
                  );
                } else {
                  tr.setSelection(NodeSelection.create(tr.doc, targetNode.pos));
                }
              } catch (e) {
                console.error("Failed to set selection on anchor", e);
              }
              return true;
            } else {
              return false;
            }
          }
        };
      }
    };
  }
});
export {
  anchor
};
//# sourceMappingURL=anchor.js.map
