feat: add hook setPageTitle (#1769)

This commit is contained in:
Himself65 2023-03-31 00:06:56 -05:00 committed by GitHub
parent 5717d126ee
commit b0d13fbabe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -8,6 +8,7 @@ import assert from 'node:assert';
import { jotaiWorkspacesAtom } from '@affine/workspace/atom';
import type { LocalWorkspace } from '@affine/workspace/type';
import { WorkspaceFlavour } from '@affine/workspace/type';
import type { PageBlockModel } from '@blocksuite/blocks';
import { __unstableSchemas, AffineSchemas } from '@blocksuite/blocks/models';
import type { Page } from '@blocksuite/store';
import { assertExists } from '@blocksuite/store';
@ -141,6 +142,26 @@ describe('usePageMetas', async () => {
rerender();
expect(result.current[0].mode).toBe('page');
});
test('update title', () => {
const { result, rerender } = renderHook(() =>
usePageMeta(blockSuiteWorkspace)
);
expect(result.current.length).toBe(3);
expect(result.current[0].mode).not.exist;
const pageMetaHelperHook = renderHook(() =>
usePageMetaHelper(blockSuiteWorkspace)
);
expect(result.current[0].title).toBe('');
pageMetaHelperHook.result.current.setPageTitle('page0', 'test');
rerender();
const page = blockSuiteWorkspace.getPage('page0');
const pageBlocks = page.getBlockByFlavour('affine:page');
expect(pageBlocks.length).toBe(1);
const pageBlock = pageBlocks[0] as PageBlockModel;
expect(pageBlock.title.toString()).toBe('test');
expect(result.current[0].title).toBe('test');
});
});
describe('useWorkspacesHelper', () => {

View File

@ -1,4 +1,6 @@
import type { PageBlockModel } from '@blocksuite/blocks';
import type { PageMeta } from '@blocksuite/store';
import { assertExists } from '@blocksuite/store';
import { useEffect, useMemo, useState } from 'react';
import type { BlockSuiteWorkspace } from '../shared';
@ -45,6 +47,19 @@ export function usePageMeta(
export function usePageMetaHelper(blockSuiteWorkspace: BlockSuiteWorkspace) {
return useMemo(
() => ({
setPageTitle: (pageId: string, newTitle: string) => {
const page = blockSuiteWorkspace.getPage(pageId);
assertExists(page);
const pageBlock = page
.getBlockByFlavour('affine:page')
.at(0) as PageBlockModel;
assertExists(pageBlock);
page.transact(() => {
pageBlock.title.delete(0, pageBlock.title.length);
pageBlock.title.insert(newTitle, 0);
});
blockSuiteWorkspace.meta.setPageMeta(pageId, { title: newTitle });
},
setPageMeta: (pageId: string, pageMeta: Partial<PageMeta>) => {
blockSuiteWorkspace.meta.setPageMeta(pageId, pageMeta);
},