import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";

const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g;

export const TagDecoration = Extension.create({
  name: "tagDecoration",

  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tagDecoration"),
        props: {
          decorations(state) {
            const decorations: Decoration[] = [];
            state.doc.descendants((node, pos) => {
              if (!node.isText || !node.text) return;
              TAG_RE.lastIndex = 0;
              let match: RegExpExecArray | null;
              while ((match = TAG_RE.exec(node.text)) !== null) {
                const from = pos + match.index;
                const to = from + match[0].length;
                decorations.push(
                  Decoration.inline(from, to, { class: "inline-tag" })
                );
              }
            });
            return DecorationSet.create(state.doc, decorations);
          },
        },
      }),
    ];
  },
});
