智能选中文字
This commit is contained in:
1 parent
e8a31b5d37
commit
da4a08dfe1
34 files changed
+3208
-541
No files matched your search
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useEditor } from "@tiptap/react";
|
||||
import { buildExtensions } from "../editor/TiptapExtensions";
|
||||
|
||||
interface UseWritingEditorOptions {
|
||||
markdown: string;
|
||||
onChange?: (markdown: string) => void;
|
||||
editable?: boolean;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function useWritingEditor({
|
||||
markdown,
|
||||
onChange,
|
||||
editable = true,
|
||||
placeholder,
|
||||
}: UseWritingEditorOptions) {
|
||||
const prevMarkdownRef = useRef<string>(markdown);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: buildExtensions(placeholder),
|
||||
editable,
|
||||
content: markdown,
|
||||
onUpdate({ editor }) {
|
||||
if (!onChange) return;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const md = (editor as any).storage?.markdown?.getMarkdown?.() ?? editor.getText();
|
||||
onChange(md);
|
||||
},
|
||||
});
|
||||
|
||||
// Sync external markdown changes (e.g. after streaming completes)
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
if (markdown === prevMarkdownRef.current) return;
|
||||
prevMarkdownRef.current = markdown;
|
||||
|
||||
const { from, to } = editor.state.selection;
|
||||
editor.commands.setContent(markdown, { emitUpdate: false });
|
||||
const docSize = editor.state.doc.content.size;
|
||||
if (from <= docSize && to <= docSize) {
|
||||
editor.commands.setTextSelection({ from, to });
|
||||
}
|
||||
}, [editor, markdown]);
|
||||
|
||||
// Sync editable flag
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
editor.setEditable(editable);
|
||||
}, [editor, editable]);
|
||||
|
||||
return editor;
|
||||
}
|
||||
Reference in new issue
Block a user