智能选中文字
This commit is contained in:
1 parent
e8a31b5d37
commit
da4a08dfe1
34 files changed
+3208
-541
No files matched your search
@@ -0,0 +1,79 @@
|
||||
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<HighlightRange | null>("aiHighlight");
|
||||
|
||||
// Augment Tiptap's Commands interface so TS knows about our custom commands
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
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<HighlightRange | null>({
|
||||
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" }),
|
||||
]);
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user