fix(plugin): make group menu invisible when leave

This commit is contained in:
austaras
2022-07-28 16:24:46 +08:00
parent 6cd8fe6832
commit e150b7c32a
8 changed files with 69 additions and 59 deletions

View File

@@ -20,46 +20,55 @@ interface AffineEditorProps {
isWhiteboard?: boolean;
}
function useConstant<T>(init: () => T): T {
const ref = useRef<T>(null);
ref.current ??= init();
function _useConstantWithDispose(
workspace: string,
rootBlockId: string,
isWhiteboard: boolean
) {
const ref = useRef<{ data: BlockEditor; onInit: boolean }>(null);
const { setCurrentEditors } = useCurrentEditors();
ref.current ??= {
data: createEditor(workspace, rootBlockId, isWhiteboard),
onInit: true,
};
return ref.current;
useEffect(() => {
if (ref.current.onInit) {
ref.current.onInit = false;
} else {
ref.current.data = createEditor(
workspace,
rootBlockId,
isWhiteboard
);
}
setCurrentEditors(prev => ({
...prev,
[rootBlockId]: ref.current.data,
}));
return () => ref.current.data.dispose();
}, [workspace, rootBlockId, isWhiteboard, setCurrentEditors]);
return ref.current.data;
}
export const AffineEditor = forwardRef<BlockEditor, AffineEditorProps>(
({ workspace, rootBlockId, scrollBlank = true, isWhiteboard }, ref) => {
const { setCurrentEditors } = useCurrentEditors();
const editor = useConstant(() => {
const editor = createEditor(workspace, isWhiteboard);
// @ts-ignore
globalThis.virgo = editor;
return editor;
});
const editor = _useConstantWithDispose(
workspace,
rootBlockId,
isWhiteboard
);
useImperativeHandle(ref, () => editor);
useEffect(() => {
if (rootBlockId) {
editor.setRootBlockId(rootBlockId);
} else {
console.error('rootBlockId for page is required. ');
}
}, [editor, rootBlockId]);
useEffect(() => {
if (!rootBlockId) return;
setCurrentEditors(prev => ({ ...prev, [rootBlockId]: editor }));
}, [editor, rootBlockId, setCurrentEditors]);
return (
<RenderRoot
editor={editor}
editorElement={AffineEditor as any}
scrollBlank={scrollBlank}
>
<RenderBlock blockId={rootBlockId} />
<RenderBlock blockId={editor.getRootBlockId()} />
</RenderRoot>
);
}

View File

@@ -27,9 +27,14 @@ import {
import { Protocol } from '@toeverything/datasource/db-service';
import { plugins } from '@toeverything/components/editor-plugins';
export const createEditor = (workspace: string, isWhiteboard?: boolean) => {
export const createEditor = (
workspace: string,
rootBlockId: string,
isWhiteboard?: boolean
) => {
const blockEditor = new BlockEditor({
workspace,
rootBlockId,
views: {
[Protocol.Block.Type.page]: new PageBlock(),
[Protocol.Block.Type.reference]: new RefLinkBlock(),