diff --git a/src/components/EditorView.tsx b/src/components/EditorView.tsx index 634e3d1..0ce14c2 100644 --- a/src/components/EditorView.tsx +++ b/src/components/EditorView.tsx @@ -263,6 +263,7 @@ export function EditorView() { )} (null); const editor = useEditor({ extensions: editorExtensions, @@ -28,6 +28,7 @@ export function Editor({ bookId, chapterId, content, onChange, onReady }: Editor useEffect(() => { onReady(editor); + return () => onReady(null); }, [editor, onReady]); useEffect(() => { @@ -35,15 +36,6 @@ export function Editor({ bookId, chapterId, content, onChange, onReady }: Editor let active = true; const scroller = editor.view.dom.closest(".editor-pane") as HTMLElement | null; - const previous = openChapter.current; - if (previous !== chapterId) { - const { from, to } = editor.state.selection; - savePosition(bookId, previous, { from, to, scroll: scroller?.scrollTop ?? 0 }); - } - openChapter.current = chapterId; - - editor.commands.setContent(content, { emitUpdate: false }); - const saved = loadPosition(bookId, chapterId); const size = editor.state.doc.content.size; const selection = saved ? { from: Math.min(saved.from, size), to: Math.min(saved.to, size) } : 0; @@ -63,18 +55,20 @@ export function Editor({ bookId, chapterId, content, onChange, onReady }: Editor active = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [chapterId, editor, bookId]); + }, [editor]); useEffect(() => { if (!editor) return; const scroller = editor.view.dom.closest(".editor-pane") as HTMLElement | null; let timer: ReturnType; + const capture = () => { + const { from, to } = editor.state.selection; + latest.current = { from, to, scroll: scroller?.scrollTop ?? 0 }; + }; const persist = () => { + capture(); clearTimeout(timer); - timer = setTimeout(() => { - const { from, to } = editor.state.selection; - savePosition(bookId, openChapter.current, { from, to, scroll: scroller?.scrollTop ?? 0 }); - }, 400); + timer = setTimeout(() => savePosition(bookId, chapterId, latest.current!), 400); }; editor.on("selectionUpdate", persist); scroller?.addEventListener("scroll", persist, { passive: true }); @@ -82,8 +76,9 @@ export function Editor({ bookId, chapterId, content, onChange, onReady }: Editor clearTimeout(timer); editor.off("selectionUpdate", persist); scroller?.removeEventListener("scroll", persist); + if (latest.current) savePosition(bookId, chapterId, latest.current); }; - }, [editor, bookId]); + }, [editor, bookId, chapterId]); return ; }