import { AuthoringToolbar } from "./AuthoringToolbar"; import { useEffect, useRef } from "react"; import { EditorView } from "@codemirror/view"; import { basicSetup } from "codemirror"; import { markdown } from "@codemirror/lang-markdown"; export function Editor({ source, onChange, }: { source: string; onChange(source: string): void; }) { const editor = useRef(); const root = useRef(null); const change = useRef(onChange); change.current = onChange; useEffect(() => { const view = new EditorView({ doc: source, parent: root.current!, extensions: [ basicSetup, markdown(), EditorView.lineWrapping, EditorView.contentAttributes.of({ "aria-label": "Notebook Markdown" }), EditorView.updateListener.of((update) => { if (update.docChanged) change.current(update.state.doc.toString()); }), ], }); editor.current = view; return () => { editor.current = undefined; view.destroy(); }; // Editor lifetime matches edit mode. Parent remounts after reload. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <> { const view = editor.current; if (!view) return; view.dispatch(view.state.replaceSelection(text)); view.focus(); }} replace={(text) => { const view = editor.current; if (!view) return; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, }); }} />
); }