Files
notesnook/packages/editor/dist/cjs/hooks/useEditor.js

67 lines
2.3 KiB
JavaScript
Raw Normal View History

2022-07-01 18:02:53 +05:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useEditor = void 0;
const react_1 = require("react");
2022-07-04 13:00:13 +05:00
const types_1 = require("../types");
2022-07-01 18:02:53 +05:00
function useForceUpdate() {
const [, setValue] = (0, react_1.useState)(0);
return () => setValue((value) => value + 1);
}
const useEditor = (options = {}, deps = []) => {
const [editor, setEditor] = (0, react_1.useState)(null);
const forceUpdate = useForceUpdate();
const editorRef = (0, react_1.useRef)(editor);
2022-07-01 18:02:53 +05:00
(0, react_1.useEffect)(() => {
let isMounted = true;
2022-07-04 13:00:13 +05:00
const instance = new types_1.Editor(options);
2022-07-01 18:02:53 +05:00
setEditor(instance);
instance.on("transaction", () => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (isMounted) {
forceUpdate();
}
});
});
});
return () => {
instance.destroy();
isMounted = false;
};
}, deps);
(0, react_1.useEffect)(() => {
editorRef.current = editor;
2022-07-04 13:00:13 +05:00
if (!editor)
return;
if (!editor.current) {
Object.defineProperty(editor, "current", {
get: () => editorRef.current,
});
2022-07-04 13:00:13 +05:00
}
// if (!editor.executor) {
// Object.defineProperty(editor, "executor", {
// get: () => (id?: string) => {
// console.log(id);
// return editorRef.current;
// },
// });
// }
}, [editor]);
(0, react_1.useEffect)(() => {
// this is required for the drag/drop to work properly
// in the editor.
function onDragEnter(event) {
if (!!(editor === null || editor === void 0 ? void 0 : editor.view.dragging)) {
event.preventDefault();
return true;
}
}
editor === null || editor === void 0 ? void 0 : editor.view.dom.addEventListener("dragenter", onDragEnter);
return () => {
editor === null || editor === void 0 ? void 0 : editor.view.dom.removeEventListener("dragenter", onDragEnter);
};
}, [editor === null || editor === void 0 ? void 0 : editor.view.dom]);
2022-07-01 18:02:53 +05:00
return editor;
};
exports.useEditor = useEditor;