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(__unstableSchemas);
initPage(blockSuiteWorkspace.createPage('page0'));
initPage(blockSuiteWorkspace.createPage('page1'));
initPage(blockSuiteWorkspace.createPage('page2'));
initPage(blockSuiteWorkspace.createPage({ id: 'page0' }));
initPage(blockSuiteWorkspace.createPage({ id: 'page1' }));
initPage(blockSuiteWorkspace.createPage({ id: 'page2' }));
});
describe('useBlockSuiteWorkspaceHelper', () => {

View File

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