client: usememo for get ydoc instance

This commit is contained in:
fantasticit 2022-06-17 18:51:01 +08:00
parent a1380bb064
commit 4ad8552925
1 changed files with 8 additions and 16 deletions

View File

@ -1,6 +1,6 @@
import { Toast } from '@douyinfe/semi-ui';
import { safeJSONStringify } from 'helpers/json';
import { useEffect, useRef } from 'react';
import { useEffect, useMemo, useRef } from 'react';
import { useEditor } from 'tiptap/core';
import { AllExtensions } from 'tiptap/core/all-kit';
import { Collaboration } from 'tiptap/core/extensions/collaboration';
@ -8,25 +8,16 @@ import { prosemirrorJSONToYDoc } from 'tiptap/core/thritypart/y-prosemirror/y-pr
import { markdownToProsemirror } from 'tiptap/markdown/markdown-to-prosemirror';
import * as Y from 'yjs';
let ydoc = null;
const getYdoc = () => {
if (!ydoc) {
ydoc = new Y.Doc();
}
return ydoc;
};
export const ImportEditor = ({ content, onChange }) => {
const parsed = useRef(false);
const ydoc = useMemo(() => new Y.Doc(), []);
const editor = useEditor(
{
editable: false,
extensions: AllExtensions.concat(Collaboration.configure({ document: getYdoc() })),
extensions: AllExtensions.concat(Collaboration.configure({ document: ydoc })),
content: '',
},
[]
[ydoc]
);
useEffect(() => {
@ -37,8 +28,8 @@ export const ImportEditor = ({ content, onChange }) => {
const title = prosemirrorNode.content[0].content[0].text;
editor.commands.setContent(prosemirrorNode);
Y.applyUpdate(getYdoc(), Y.encodeStateAsUpdate(prosemirrorJSONToYDoc(editor.schema, prosemirrorNode)));
const state = Y.encodeStateAsUpdate(getYdoc());
Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(prosemirrorJSONToYDoc(editor.schema, prosemirrorNode)));
const state = Y.encodeStateAsUpdate(ydoc);
onChange({
title,
@ -52,9 +43,10 @@ export const ImportEditor = ({ content, onChange }) => {
}
return () => {
ydoc.destroy();
editor.destroy();
};
}, [editor, content, onChange]);
}, [editor, ydoc, content, onChange]);
return null;
};