import { Extension } from "@tiptap/core"; import { Plugin, PluginKey } from "@tiptap/pm/state"; import { Decoration, DecorationSet } from "@tiptap/pm/view"; interface HighlightRange { from: number; to: number; } const aiHighlightKey = new PluginKey("aiHighlight"); // Augment Tiptap's Commands interface so TS knows about our custom commands declare module "@tiptap/core" { interface Commands { aiHighlight: { setAiHighlight: (from: number, to: number) => ReturnType; clearAiHighlight: () => ReturnType; }; } } export const AiHighlightExtension = Extension.create({ name: "aiHighlight", addCommands() { return { setAiHighlight: (from: number, to: number) => ({ dispatch, tr }) => { if (dispatch) dispatch(tr.setMeta(aiHighlightKey, { from, to })); return true; }, clearAiHighlight: () => ({ dispatch, tr }) => { if (dispatch) dispatch(tr.setMeta(aiHighlightKey, null)); return true; }, }; }, addProseMirrorPlugins() { return [ new Plugin({ key: aiHighlightKey, state: { init: () => null, apply(tr, prev) { const meta = tr.getMeta(aiHighlightKey); // explicit set / clear via command if (meta !== undefined) return meta as HighlightRange | null; // map positions through doc changes so highlight survives edits if (tr.docChanged && prev) { return { from: tr.mapping.map(prev.from), to: tr.mapping.map(prev.to), }; } return prev; }, }, props: { decorations(state) { const range = aiHighlightKey.getState(state); if (!range) return DecorationSet.empty; const { from, to } = range; const docSize = state.doc.content.size; if (from >= to || from < 0 || to > docSize) return DecorationSet.empty; return DecorationSet.create(state.doc, [ Decoration.inline(from, to, { class: "ai-rewrite-highlight" }), ]); }, }, }), ]; }, });