From 1e84ad1484cfabd64e5c5caed476b4dc18c94168 Mon Sep 17 00:00:00 2001 From: Himself65 Date: Wed, 3 May 2023 22:09:43 -0500 Subject: [PATCH] fix: reduce pageMeta instance (#2222) --- .../use-blocksuite-workspace-helper.spec.ts | 6 ++-- .../hooks/src/use-block-suite-page-meta.ts | 30 ++++++++----------- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/packages/hooks/src/__tests__/use-blocksuite-workspace-helper.spec.ts b/packages/hooks/src/__tests__/use-blocksuite-workspace-helper.spec.ts index 38a1a6c16a..f950277baa 100644 --- a/packages/hooks/src/__tests__/use-blocksuite-workspace-helper.spec.ts +++ b/packages/hooks/src/__tests__/use-blocksuite-workspace-helper.spec.ts @@ -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', () => { diff --git a/packages/hooks/src/use-block-suite-page-meta.ts b/packages/hooks/src/use-block-suite-page-meta.ts index 8fefe393e7..cb7a21695a 100644 --- a/packages/hooks/src/use-block-suite-page-meta.ts +++ b/packages/hooks/src/use-block-suite-page-meta.ts @@ -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>(); + export function useBlockSuitePageMeta( blockSuiteWorkspace: Workspace ): PageMeta[] { - const [pageMeta, setPageMeta] = useState( - () => 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(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); } export function usePageMetaHelper(blockSuiteWorkspace: Workspace) {