63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
import { useEffect, useMemo, 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);
|
|
|
|
// 扩展集合 memo 一次,避免每次渲染生成新数组导致 useEditor 反复重建(v3 下会触发
|
|
// 重复 schema 解析 / "Duplicate extension names" 警告,极端情况引发更新风暴)。
|
|
const extensions = useMemo(() => buildExtensions(placeholder), [placeholder]);
|
|
|
|
// onChange 用 ref 持有最新值,让 onUpdate 闭包保持稳定,不随父组件回调身份变化而重建编辑器。
|
|
const onChangeRef = useRef(onChange);
|
|
useEffect(() => { onChangeRef.current = onChange; }, [onChange]);
|
|
|
|
const editor = useEditor({
|
|
extensions,
|
|
editable,
|
|
content: markdown,
|
|
onUpdate({ editor }) {
|
|
const fn = onChangeRef.current;
|
|
if (!fn) return;
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
const md = (editor as any).storage?.markdown?.getMarkdown?.() ?? editor.getText();
|
|
fn(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;
|
|
}
|