Files
notesnook/packages/editor/src/hooks/use-editor.ts

69 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-07-01 18:02:53 +05:00
import { EditorOptions, Editor } from "@tiptap/core";
2022-07-02 11:57:52 +05:00
import { DependencyList, useEffect, useRef, useState } from "react";
2022-07-01 18:02:53 +05:00
import { Editor as EditorType } from "../types";
function useForceUpdate() {
const [, setValue] = useState(0);
return () => setValue((value) => value + 1);
}
export const useEditor = (
options: Partial<EditorOptions> = {},
deps: DependencyList = []
) => {
2022-07-02 11:57:52 +05:00
const [editor, setEditor] = useState<EditorType | null>(null);
2022-07-01 18:02:53 +05:00
const forceUpdate = useForceUpdate();
2022-07-02 11:57:52 +05:00
const editorRef = useRef<EditorType | null>(editor);
2022-07-01 18:02:53 +05:00
useEffect(() => {
let isMounted = true;
const instance = new Editor(options);
setEditor(instance);
instance.on("transaction", () => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (isMounted) {
forceUpdate();
}
});
});
});
return () => {
instance.destroy();
isMounted = false;
};
}, deps);
2022-07-02 11:57:52 +05:00
useEffect(() => {
editorRef.current = editor;
if (editor && !editor.current)
Object.defineProperty(editor, "current", {
get: () => editorRef.current,
});
}, [editor]);
useEffect(() => {
// this is required for the drag/drop to work properly
// in the editor.
function onDragEnter(event: DragEvent) {
if (!!editor?.view.dragging) {
event.preventDefault();
return true;
}
}
editor?.view.dom.addEventListener("dragenter", onDragEnter);
return () => {
editor?.view.dom.removeEventListener("dragenter", onDragEnter);
};
}, [editor?.view.dom]);
return editor;
2022-07-01 18:02:53 +05:00
};