fix: reduce pageMeta instance (#2222)

This commit is contained in:
Himself65 2023-05-03 22:09:43 -05:00 committed by GitHub
parent b3a3911cea
commit 1e84ad1484
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 20 deletions

View File

@ -19,9 +19,9 @@ beforeEach(() => {
}) })
.register(AffineSchemas) .register(AffineSchemas)
.register(__unstableSchemas); .register(__unstableSchemas);
initPage(blockSuiteWorkspace.createPage('page0')); initPage(blockSuiteWorkspace.createPage({ id: 'page0' }));
initPage(blockSuiteWorkspace.createPage('page1')); initPage(blockSuiteWorkspace.createPage({ id: 'page1' }));
initPage(blockSuiteWorkspace.createPage('page2')); initPage(blockSuiteWorkspace.createPage({ id: 'page2' }));
}); });
describe('useBlockSuiteWorkspaceHelper', () => { describe('useBlockSuiteWorkspaceHelper', () => {

View File

@ -1,7 +1,9 @@
import type { PageBlockModel } from '@blocksuite/blocks'; import type { PageBlockModel } from '@blocksuite/blocks';
import type { PageMeta, Workspace } from '@blocksuite/store'; import type { PageMeta, Workspace } from '@blocksuite/store';
import { assertExists } from '@blocksuite/store'; import { assertExists } from '@blocksuite/store';
import { useEffect, useMemo, useState } from 'react'; import type { Atom } from 'jotai';
import { atom, useAtomValue } from 'jotai';
import { useMemo } from 'react';
declare module '@blocksuite/store' { declare module '@blocksuite/store' {
interface PageMeta { interface PageMeta {
@ -19,30 +21,24 @@ declare module '@blocksuite/store' {
} }
} }
const weakMap = new WeakMap<Workspace, Atom<PageMeta[]>>();
export function useBlockSuitePageMeta( export function useBlockSuitePageMeta(
blockSuiteWorkspace: Workspace blockSuiteWorkspace: Workspace
): PageMeta[] { ): PageMeta[] {
const [pageMeta, setPageMeta] = useState<PageMeta[]>( if (!weakMap.has(blockSuiteWorkspace)) {
() => blockSuiteWorkspace?.meta.pageMetas ?? [] const baseAtom = atom<PageMeta[]>(blockSuiteWorkspace.meta.pageMetas);
); weakMap.set(blockSuiteWorkspace, baseAtom);
const [prev, setPrev] = useState(() => blockSuiteWorkspace); baseAtom.onMount = set => {
if (prev !== blockSuiteWorkspace) {
setPrev(blockSuiteWorkspace);
if (blockSuiteWorkspace) {
setPageMeta(blockSuiteWorkspace.meta.pageMetas);
}
}
useEffect(() => {
if (blockSuiteWorkspace) {
const dispose = blockSuiteWorkspace.meta.pageMetasUpdated.on(() => { const dispose = blockSuiteWorkspace.meta.pageMetasUpdated.on(() => {
setPageMeta(blockSuiteWorkspace.meta.pageMetas); set(blockSuiteWorkspace.meta.pageMetas);
}); });
return () => { return () => {
dispose.dispose(); dispose.dispose();
}; };
} };
}, [blockSuiteWorkspace]); }
return pageMeta; return useAtomValue(weakMap.get(blockSuiteWorkspace) as Atom<PageMeta[]>);
} }
export function usePageMetaHelper(blockSuiteWorkspace: Workspace) { export function usePageMetaHelper(blockSuiteWorkspace: Workspace) {