mirror of
https://github.com/lordmathis/lemma.git
synced 2025-11-06 16:04:23 +00:00
Initial frontend implementation
This commit is contained in:
50
frontend/src/components/Editor.js
Normal file
50
frontend/src/components/Editor.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { basicSetup } from "codemirror";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView, keymap } from "@codemirror/view";
|
||||
import { markdown } from "@codemirror/lang-markdown";
|
||||
import { defaultKeymap } from "@codemirror/commands";
|
||||
|
||||
const Editor = ({ content, onChange }) => {
|
||||
const editorRef = useRef();
|
||||
const viewRef = useRef();
|
||||
|
||||
useEffect(() => {
|
||||
const state = EditorState.create({
|
||||
doc: content,
|
||||
extensions: [
|
||||
basicSetup,
|
||||
markdown(),
|
||||
keymap.of(defaultKeymap),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
onChange(update.state.doc.toString());
|
||||
}
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const view = new EditorView({
|
||||
state,
|
||||
parent: editorRef.current,
|
||||
});
|
||||
|
||||
viewRef.current = view;
|
||||
|
||||
return () => {
|
||||
view.destroy();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (viewRef.current && content !== viewRef.current.state.doc.toString()) {
|
||||
viewRef.current.dispatch({
|
||||
changes: { from: 0, to: viewRef.current.state.doc.length, insert: content }
|
||||
});
|
||||
}
|
||||
}, [content]);
|
||||
|
||||
return <div ref={editorRef} />;
|
||||
};
|
||||
|
||||
export default Editor;
|
||||
Reference in New Issue
Block a user