π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(page-editor): treat the title and body as one document when editing (#22154)
Patrick Tien1a6ba7ad3853
diff --git a/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.ts b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.tsindex 1747a679bdb..4af87ff02f6 100644--- a/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.ts+++ b/src/features/AgentTasks/CreateTaskModal/useTitleEnterToInstruction.test.ts@@ -45,6 +45,11 @@ const setup = async () => {throw e;},});+ // The instruction editor is mounted while the modal is open.+ const root = document.createElement('div');+ root.contentEditable = 'true';+ document.body.append(root);+ lexical.setRootElement(root);lexical.update(() => {$getRoot().append($createParagraphNode().append($createTextNode('body')));});diff --git a/src/features/EditorCanvas/focusEditorStartLine.test.ts b/src/features/EditorCanvas/focusEditorStartLine.test.tsindex 1a459486243..7f9b84146d1 100644--- a/src/features/EditorCanvas/focusEditorStartLine.test.ts+++ b/src/features/EditorCanvas/focusEditorStartLine.test.ts@@ -1,3 +1,4 @@+import type { IEditor } from '@lobehub/editor';import {$createParagraphNode,$createTextNode,@@ -5,11 +6,18 @@ import {$getSelection,$isRangeSelection,createEditor,+ DecoratorNode,type LexicalEditor,+ type ParagraphNode,} from 'lexical';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { selectEditorStartLineOnLexical } from './focusEditorStartLine';+import {+ focusEditorFirstLine,+ focusEditorStartLine,+ selectEditorFirstLineOnLexical,+ selectEditorStartLineOnLexical,+} from './focusEditorStartLine';const flush = async (editor: LexicalEditor) => {await new Promise<void>((resolve) => {@@ -17,8 +25,39 @@ const flush = async (editor: LexicalEditor) => {});};+class FakeImageNode extends DecoratorNode<null> {+ static getType() {+ return 'fake-image';+ }++ static clone(node: FakeImageNode) {+ return new FakeImageNode(node.__key);+ }++ static importJSON() {+ return new FakeImageNode();+ }++ isInline() {+ return false;+ }++ createDOM() {+ return document.createElement('div');+ }++ updateDOM() {+ return false;+ }++ decorate() {+ return null;+ }+}+const createTestEditor = () =>createEditor({+ nodes: [FakeImageNode],onError: (e) => {throw e;},@@ -27,6 +66,7 @@ const createTestEditor = () =>const readSnapshot = (editor: LexicalEditor) => {let lines: string[] = [];let caretLine: number | undefined;+ let caretOffset: number | undefined;editor.getEditorState().read(() => {lines = $getRoot().getChildren()@@ -34,9 +74,10 @@ const readSnapshot = (editor: LexicalEditor) => {const selection = $getSelection();if ($isRangeSelection(selection)) {caretLine = selection.anchor.getNode().getTopLevelElementOrThrow().getIndexWithinParent();+ caretOffset = selection.anchor.offset;}});- return { caretLine, lines };+ return { caretLine, caretOffset, lines };};describe('selectEditorStartLineOnLexical', () => {@@ -50,7 +91,7 @@ describe('selectEditorStartLineOnLexical', () => {selectEditorStartLineOnLexical(editor);await flush(editor);- expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: ['', 'body'] });+ expect(readSnapshot(editor)).toEqual({ caretLine: 0, caretOffset: 0, lines: ['', 'body'] });});it('reuses an empty first line instead of stacking another one', async () => {@@ -66,7 +107,7 @@ describe('selectEditorStartLineOnLexical', () => {selectEditorStartLineOnLexical(editor);await flush(editor);- expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: ['', 'body'] });+ expect(readSnapshot(editor)).toEqual({ caretLine: 0, caretOffset: 0, lines: ['', 'body'] });});it('gives an empty document a line to type on', async () => {@@ -75,6 +116,157 @@ describe('selectEditorStartLineOnLexical', () => {selectEditorStartLineOnLexical(editor);await flush(editor);- expect(readSnapshot(editor)).toEqual({ caretLine: 0, lines: [''] });+ expect(readSnapshot(editor)).toEqual({ caretLine: 0, caretOffset: 0, lines: [''] });+ });+});++describe('selectEditorStartLineOnLexical with text split off the title', () => {+ it('puts the text on a new first line above the body, caret at its start', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append($createParagraphNode().append($createTextNode('body')));+ });+ await flush(editor);++ selectEditorStartLineOnLexical(editor, ' world');+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({+ caretLine: 0,+ caretOffset: 0,+ lines: [' world', 'body'],+ });+ });++ it('does not write the text into an empty first line that is already there', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append(+ $createParagraphNode(),+ $createParagraphNode().append($createTextNode('body')),+ );+ });+ await flush(editor);++ selectEditorStartLineOnLexical(editor, 'tail');+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({+ caretLine: 0,+ caretOffset: 0,+ lines: ['tail', '', 'body'],+ });+ });+});++describe('selectEditorFirstLineOnLexical', () => {+ it('moves the caret to the start of the first text block without adding a line', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append(+ $createParagraphNode().append($createTextNode('first')),+ $createParagraphNode().append($createTextNode('body')),+ );+ $getRoot().getLastChildOrThrow<ParagraphNode>().selectEnd();+ });+ await flush(editor);++ selectEditorFirstLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({+ caretLine: 0,+ caretOffset: 0,+ lines: ['first', 'body'],+ });+ });++ it('opens a line above a block image the body starts with', async () => {+ const editor = createTestEditor();+ editor.update(() => {+ $getRoot().append(+ new FakeImageNode(),+ $createParagraphNode().append($createTextNode('body')),+ );+ });+ await flush(editor);++ selectEditorFirstLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({ caretLine: 0, caretOffset: 0, lines: ['', '', 'body'] });+ });++ it('gives an empty document a line to stand on', async () => {+ const editor = createTestEditor();++ selectEditorFirstLineOnLexical(editor);+ await flush(editor);++ expect(readSnapshot(editor)).toEqual({ caretLine: 0, caretOffset: 0, lines: [''] });+ });+});++describe('focusEditorStartLine / focusEditorFirstLine', () => {+ const setupKernel = async ({ editable = true, mounted = true } = {}) => {+ const lexical = createTestEditor();+ if (mounted) {+ const root = document.createElement('div');+ root.contentEditable = 'true';+ document.body.append(root);+ lexical.setRootElement(root);+ }+ lexical.update(() => {+ $getRoot().append($createParagraphNode().append($createTextNode('body')));+ });+ await flush(lexical);+ lexical.setEditable(editable);++ const focus = vi.fn();+ const editor = { focus, getLexicalEditor: () => lexical } as unknown as IEditor;+ return { editor, focus, lexical };+ };++ it('writes the split-off title text into a mounted, editable body', async () => {+ const { editor, focus, lexical } = await setupKernel();++ focusEditorStartLine(editor, 'tail');+ await flush(lexical);++ expect(readSnapshot(lexical).lines).toEqual(['tail', 'body']);+ expect(focus).toHaveBeenCalledTimes(1);+ });++ // While the body is loading the kernel can hold a detached editor whose+ // content is about to be replaced: text written there would be lost.+ it('leaves a body that is not mounted yet untouched', async () => {+ const { editor, focus, lexical } = await setupKernel({ mounted: false });++ focusEditorStartLine(editor, 'tail');+ focusEditorFirstLine(editor);+ await flush(lexical);++ expect(readSnapshot(lexical).lines).toEqual(['body']);+ expect(focus).not.toHaveBeenCalled();+ });++ it('leaves a read-only body untouched', async () => {+ const { editor, focus, lexical } = await setupKernel({ editable: false });++ focusEditorStartLine(editor, 'tail');+ await flush(lexical);++ expect(readSnapshot(lexical).lines).toEqual(['body']);+ expect(focus).not.toHaveBeenCalled();+ });++ it('does nothing before the kernel has a Lexical editor', () => {+ const focus = vi.fn();+ const editor = { focus, getLexicalEditor: () => null } as unknown as IEditor;++ focusEditorStartLine(editor, 'tail');+ focusEditorFirstLine(editor);++ expect(focus).not.toHaveBeenCalled();});});diff --git a/src/features/EditorCanvas/focusEditorStartLine.ts b/src/features/EditorCanvas/focusEditorStartLine.tsindex ff824b2aba7..704106f8904 100644--- a/src/features/EditorCanvas/focusEditorStartLine.ts+++ b/src/features/EditorCanvas/focusEditorStartLine.ts@@ -1,24 +1,49 @@import type { IEditor } from '@lobehub/editor';-import { $createParagraphNode, $getRoot, $isParagraphNode, type LexicalEditor } from 'lexical';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isElementNode,+ $isParagraphNode,+ type LexicalEditor,+} from 'lexical';-/** Exported for tests, which drive a bare Lexical editor without the kernel. */-export const selectEditorStartLineOnLexical = (lexicalEditor: LexicalEditor): void => {- lexicalEditor.update(() => {- const root = $getRoot();- const first = root.getFirstChild();+const $selectStartLine = (text: string) => {+ const root = $getRoot();+ const first = root.getFirstChild();- // An empty first line is already the line the caller wants; adding another- // would stack a blank line on every call.- if ($isParagraphNode(first) && first.getChildrenSize() === 0) {- first.selectStart();- return;- }+ // An empty first line is already the line the caller wants; adding another+ // would stack a blank line on every call. Text carried over from the title+ // always gets a line of its own, though, so it is never glued onto whatever+ // the body starts with.+ if (!text && $isParagraphNode(first) && first.getChildrenSize() === 0) {+ first.selectStart();+ return;+ }- const paragraph = $createParagraphNode();- if (first) first.insertBefore(paragraph);- else root.append(paragraph);- paragraph.selectStart();- });+ const paragraph = $createParagraphNode();+ if (text) paragraph.append($createTextNode(text));+ if (first) first.insertBefore(paragraph);+ else root.append(paragraph);+ paragraph.selectStart();+};++/**+ * The editor's Lexical instance, when it can take the caret and text right now:+ * mounted in the page and editable. While the body is still loading (or after+ * a document switch, before the next body mounts) the kernel may hold no+ * Lexical editor, or a detached one whose content is about to be replaced β+ * anything written there would be lost.+ */+export const getWritableLexicalEditor = (editor: IEditor | undefined) => {+ const lexicalEditor = editor?.getLexicalEditor?.();+ if (!lexicalEditor?.getRootElement() || !lexicalEditor.isEditable()) return null;+ return lexicalEditor;+};++/** Exported for tests, which drive a bare Lexical editor without the kernel. */+export const selectEditorStartLineOnLexical = (lexicalEditor: LexicalEditor, text = ''): void => {+ lexicalEditor.update(() => $selectStartLine(text));};/**@@ -29,11 +54,40 @@ export const selectEditorStartLineOnLexical = (lexicalEditor: LexicalEditor): vo* the body read as one document, so Enter at the title continues on a fresh* line instead of landing inside whatever the body already starts with (an* image, a pasted block, β¦).+ *+ * `text` is the part of the title after the caret that Enter splits off: it+ * becomes the body's new first line, with the caret at its start.*/-export const focusEditorStartLine = (editor: IEditor | undefined): void => {- const lexicalEditor = editor?.getLexicalEditor?.();+export const focusEditorStartLine = (editor: IEditor | undefined, text?: string): void => {+ const lexicalEditor = getWritableLexicalEditor(editor);+ if (!editor || !lexicalEditor) return;++ selectEditorStartLineOnLexical(lexicalEditor, text);+ editor.focus();+};++/** Exported for tests, which drive a bare Lexical editor without the kernel. */+export const selectEditorFirstLineOnLexical = (lexicalEditor: LexicalEditor): void => {+ lexicalEditor.update(() => {+ const first = $getRoot().getFirstChild();+ // A text block (paragraph, heading, list, quote, tableβ¦) takes the caret at+ // its start; a block image or divider has no line to stand on, so open one.+ if ($isElementNode(first) && !first.isInline()) {+ first.selectStart();+ return;+ }+ $selectStartLine('');+ });+};++/**+ * Move the caret to the start of the body's first line, opening a line only+ * when the body has none to stand on β ArrowDown out of the title.+ */+export const focusEditorFirstLine = (editor: IEditor | undefined): void => {+ const lexicalEditor = getWritableLexicalEditor(editor);if (!editor || !lexicalEditor) return;- selectEditorStartLineOnLexical(lexicalEditor);+ selectEditorFirstLineOnLexical(lexicalEditor);editor.focus();};diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex 2377ca1cfcd..6270c508f49 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -2,7 +2,7 @@import { DEFAULT_BLOCK_ANCHOR_PADDING, EditorProvider } from '@lobehub/editor/react';import { cssVar, Flexbox } from '@lobehub/ui';-import type { FC, ReactNode, UIEvent } from 'react';+import type { FC, MouseEvent, ReactNode, UIEvent } from 'react';import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';import type { ComposerTarget } from '@/features/Conversation/types';@@ -15,6 +15,7 @@ import { usePermission } from '@/hooks/usePermission';import { pageActions } from '@/store/page';import { StyleSheet } from '@/utils/styles';+import { focusEditorAtBlankPoint } from './blankAreaClick';import { usePageCollabEligible, usePageCollabEnabled } from './collab/usePageCollab';import DocumentComments from './DocumentComments';import BlockCommentMarker from './DocumentComments/BlockCommentMarker';@@ -34,6 +35,7 @@ import RightPanel from './RightPanel';import { usePageEditorStore } from './store';import TableOfContents from './TableOfContents';import TitleSection from './TitleSection';+import { usePageBodyInteractions } from './usePageBodyInteractions';import { usePageEditable } from './usePageEditable';/**@@ -330,6 +332,27 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {// Register Files scope and save document hotkeyuseRegisterFilesHotkeys();+ // ArrowUp / Backspace from the top of the body into the title, and a click+ // below the last block to keep writing.+ usePageBodyInteractions(editor, editorContentRef);++ // A click on the column's blank space (page margins, below the body). Only+ // clicks that land on a layout wrapper of the content count: anything inside+ // it β the title, banners, the line comment marker, likes, comments β is a+ // control of its own and must keep its focus.+ const handleBlankAreaClick = useCallback(+ (event: MouseEvent<HTMLDivElement>) => {+ if (!editable) return;++ const content = editorContentRef.current;+ const target = event.target;+ if (!content || !(target instanceof Node) || !target.contains(content)) return;++ focusEditorAtBlankPoint(editor, event);+ },+ [editable, editor],+ );+const headerSlot = header === undefined ? <Header /> : header;const editorPane = (@@ -369,11 +392,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {<WideScreenContainerwrapperStyle={{ cursor: editable ? 'text' : 'default' }}onChange={notifyEditorLayoutChange}- onClick={() => {- if (!editable) return;-- editor?.focus();- }}+ onClick={handleBlankAreaClick}><Flexboxflex={1}diff --git a/src/features/PageEditor/TitleSection.tsx b/src/features/PageEditor/TitleSection.tsxindex 37835da20c0..67e29a6cdfb 100644--- a/src/features/PageEditor/TitleSection.tsx+++ b/src/features/PageEditor/TitleSection.tsx@@ -2,60 +2,37 @@import { Button, cssVar, Flexbox, Icon, Skeleton, TextArea } from '@lobehub/ui';import { SmilePlus } from 'lucide-react';-import { memo, useState } from 'react';+import { memo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import EmojiPicker from '@/components/EmojiPicker';-import { useDocumentStore } from '@/store/document';-import { editorSelectors } from '@/store/document/slices/editor';import { useGlobalStore } from '@/store/global';import { globalGeneralSelectors } from '@/store/global/selectors';-import { truncateByWeightedLength } from '@/utils/textLength';-import { usePageEditorStore } from './store';-import { usePageEditable } from './usePageEditable';+import { PAGE_TITLE_INPUT_ATTRIBUTE } from './titleBodyNavigation';+import { usePageTitleInteractions } from './usePageTitleInteractions';++export { isTitleSubmitKey } from './usePageTitleInteractions';export const getTitleTextAreaInteractionProps = (canEdit: boolean) => ({readOnly: !canEdit,});-// Enter that confirms an IME candidate (Chinese/Japanese input) must not submit-// the title: moving focus to the body mid-composition commits the text there too.-// Safari reports the confirming keydown with isComposing=false but keyCode 229.-export const isTitleSubmitKey = (e: {- key: string;- keyCode?: number;- nativeEvent?: { isComposing?: boolean };-}) => e.key === 'Enter' && !e.nativeEvent?.isComposing && e.keyCode !== 229;-const TitleSection = memo(() => {const { t } = useTranslation('file');const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);- const documentId = usePageEditorStore((s) => s.documentId);- // Gate the title/emoji on the same state as the body editor: edit permission- // AND not locked by another member (nor pending / save-blocked). The lock makes- // the whole page read-only, so metadata must not stay editable behind it.- // `metaReadOnly` additionally locks just the meta (title + emoji) while leaving- // the body editable β used for managed docs like a skill's `SKILL.md` index,- // whose identity is renamed through skill APIs, never a plain title save.- const isMetaReadOnly = usePageEditorStore((s) => s.metaReadOnly);- const canEdit = usePageEditable() && !isMetaReadOnly;- const emoji = usePageEditorStore((s) => s.emoji);- const title = usePageEditorStore((s) => s.title);- const setEmoji = usePageEditorStore((s) => s.setEmoji);- const setTitle = usePageEditorStore((s) => s.setTitle);- const handleTitleSubmit = usePageEditorStore((s) => s.handleTitleSubmit);- const isDocumentLoading = useDocumentStore(editorSelectors.isDocumentLoading(documentId));- const showTitleSkeleton = isDocumentLoading && !title;+ const containerRef = useRef<HTMLDivElement>(null);+ const { canEdit, emojiPicker, handleTitleChange, handleTitleKeyDown, showTitleSkeleton, title } =+ usePageTitleInteractions(containerRef);const [isHoveringTitle, setIsHoveringTitle] = useState(false);- const [showEmojiPicker, setShowEmojiPicker] = useState(false);return (<Flexboxgap={16}paddingBlock={16}+ ref={containerRef}style={{cursor: 'default',}}@@ -67,37 +44,23 @@ const TitleSection = memo(() => {}}>{/* Emoji picker above Choose Icon button */}- {(emoji || showEmojiPicker) && (+ {emojiPicker.visible && (<EmojiPickerallowDeletelocale={locale}- open={showEmojiPicker}+ open={emojiPicker.open}shape={'square'}size={72}title={t('pageEditor.chooseIcon')}- value={emoji}- onChange={(e) => {- if (!canEdit) return;-- setEmoji(e);- setShowEmojiPicker(false);- }}- onDelete={() => {- if (!canEdit) return;-- setEmoji(undefined);- setShowEmojiPicker(false);- }}- onOpenChange={(open) => {- if (!canEdit) return;-- setShowEmojiPicker(open);- }}+ value={emojiPicker.value}+ onChange={emojiPicker.onChange}+ onDelete={emojiPicker.onDelete}+ onOpenChange={emojiPicker.onOpenChange}/>)}{/* Choose Icon button - only shown when no emoji */}- {!emoji && !showEmojiPicker && (+ {!emojiPicker.visible && (<Buttondisabled={!canEdit}icon={<Icon icon={SmilePlus} />}@@ -108,12 +71,7 @@ const TitleSection = memo(() => {transition: `opacity ${cssVar.motionDurationMid} ${cssVar.motionEaseInOut}`,width: 'fit-content',}}- onClick={() => {- if (!canEdit) return;-- setEmoji('π');- setShowEmojiPicker(true);- }}+ onClick={emojiPicker.onOpen}>{t('pageEditor.chooseIcon')}</Button>@@ -127,6 +85,7 @@ const TitleSection = memo(() => {autoSize={{ minRows: 1 }}placeholder={t('pageEditor.titlePlaceholder')}{...getTitleTextAreaInteractionProps(canEdit)}+ {...{ [PAGE_TITLE_INPUT_ATTRIBUTE]: true }}value={title}variant={'borderless'}style={{@@ -137,20 +96,8 @@ const TitleSection = memo(() => {width: '100%',borderRadius: '0px',}}- onChange={(e) => {- const truncated = truncateByWeightedLength(e.target.value, 100);- if (!canEdit) return;-- setTitle(truncated);- }}- onKeyDown={(e) => {- if (!canEdit) return;-- if (isTitleSubmitKey(e)) {- e.preventDefault();- handleTitleSubmit();- }- }}+ onChange={handleTitleChange}+ onKeyDown={handleTitleKeyDown}/>)}</Flexbox>diff --git a/src/features/PageEditor/blankAreaClick.test.ts b/src/features/PageEditor/blankAreaClick.test.tsnew file mode 100644index 00000000000..6a5ee45aa74--- /dev/null+++ b/src/features/PageEditor/blankAreaClick.test.ts@@ -0,0 +1,298 @@+/**+ * @vitest-environment happy-dom+ */+import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+ DecoratorNode,+ type LexicalEditor,+} from 'lexical';+import { afterEach, describe, expect, it } from 'vitest';++import {+ focusEditorAtBlankPoint,+ getBlankZone,+ registerClickBelowContentOnLexical,+ selectDocumentEndForWritingOnLexical,+} from './blankAreaClick';++class FakeImageNode extends DecoratorNode<null> {+ static getType() {+ return 'fake-image';+ }++ static clone(node: FakeImageNode) {+ return new FakeImageNode(node.__key);+ }++ static importJSON() {+ return new FakeImageNode();+ }++ isInline() {+ return false;+ }++ createDOM() {+ return document.createElement('div');+ }++ updateDOM() {+ return false;+ }++ decorate() {+ return null;+ }+}++const commit = (editor: LexicalEditor, fn: () => void) =>+ new Promise<void>((resolve) => {+ editor.update(fn, { onUpdate: resolve });+ });++const settle = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++const cleanups: (() => void)[] = [];++afterEach(() => {+ while (cleanups.length > 0) cleanups.pop()?.();+ document.body.innerHTML = '';+});++type Line = string | 'image';++const setup = async (lines: Line[]) => {+ const wrapper = document.createElement('div');+ const root = document.createElement('div');+ root.contentEditable = 'true';+ wrapper.append(root);+ document.body.append(wrapper);++ const editor = createEditor({+ nodes: [FakeImageNode],+ onError: (error) => {+ throw error;+ },+ });+ editor.setRootElement(root);+ cleanups.push(() => editor.setRootElement(null));++ await commit(editor, () => {+ $getRoot().append(+ ...lines.map((line) => {+ if (line === 'image') return new FakeImageNode();+ const paragraph = $createParagraphNode();+ if (line) paragraph.append($createTextNode(line));+ return paragraph;+ }),+ );+ });++ // jsdom-like environments have no layout: the body spans x 0β600 and+ // y 100β(100 + 20 per line), one 20px row per block.+ root.getBoundingClientRect = () =>+ ({ bottom: 100 + lines.length * 20, left: 0, right: 600, top: 100, width: 600 }) as DOMRect;+ [...root.children].forEach((child, index) => {+ (child as HTMLElement).getBoundingClientRect = () =>+ ({ bottom: 120 + index * 20, top: 100 + index * 20 }) as DOMRect;+ });++ return { editor, root, wrapper };+};++const readState = (editor: LexicalEditor) =>+ editor.getEditorState().read(() => {+ const selection = $getSelection();+ return {+ caret: $isRangeSelection(selection)+ ? {+ line: selection.anchor.getNode().getTopLevelElementOrThrow().getIndexWithinParent(),+ offset: selection.anchor.offset,+ }+ : null,+ lines: $getRoot()+ .getChildren()+ .map((child) => (child instanceof FakeImageNode ? 'image' : child.getTextContent())),+ };+ });++const asKernel = (editor: LexicalEditor) => ({ getLexicalEditor: () => editor }) as IEditor;++describe('getBlankZone', () => {+ const bounds = { bodyTop: 100, contentBottom: 300 };++ it('tells above, beside and below the body apart', () => {+ expect(getBlankZone(bounds, 50)).toBe('above');+ expect(getBlankZone(bounds, 200)).toBe('beside');+ expect(getBlankZone(bounds, 301)).toBe('below');+ });+});++describe('selectDocumentEndForWritingOnLexical', () => {+ it('puts the caret on a trailing empty line instead of adding another', async () => {+ const { editor } = await setup(['text', '']);++ selectDocumentEndForWritingOnLexical(editor);+ await settle();++ expect(readState(editor)).toEqual({ caret: { line: 1, offset: 0 }, lines: ['text', ''] });+ });++ it('opens a new line after a document that ends in text', async () => {+ const { editor } = await setup(['text']);++ selectDocumentEndForWritingOnLexical(editor);+ await settle();++ expect(readState(editor)).toEqual({ caret: { line: 1, offset: 0 }, lines: ['text', ''] });+ });++ it('opens a new line after a document that ends in a block image', async () => {+ const { editor } = await setup(['text', 'image']);++ selectDocumentEndForWritingOnLexical(editor);+ await settle();++ expect(readState(editor)).toEqual({+ caret: { line: 2, offset: 0 },+ lines: ['text', 'image', ''],+ });+ });+});++describe('registerClickBelowContentOnLexical', () => {+ const pressAt = (target: Element, clientY: number, init: MouseEventInit = {}) => {+ const event = new MouseEvent('mousedown', {+ bubbles: true,+ button: 0,+ cancelable: true,+ clientY,+ ...init,+ });+ target.dispatchEvent(event);+ return event;+ };++ it('continues writing at the end from a press below the last block', async () => {+ const { editor, wrapper } = await setup(['text', 'image']);+ cleanups.push(registerClickBelowContentOnLexical(editor));++ const event = pressAt(wrapper, 200);+ await settle();++ expect(event.defaultPrevented).toBe(true);+ expect(readState(editor)).toEqual({+ caret: { line: 2, offset: 0 },+ lines: ['text', 'image', ''],+ });+ });++ it('also handles a press on the editable root itself below its content', async () => {+ const { editor, root } = await setup(['text']);+ cleanups.push(registerClickBelowContentOnLexical(editor));++ expect(pressAt(root, 200).defaultPrevented).toBe(true);+ await settle();++ expect(readState(editor).lines).toEqual(['text', '']);+ });++ it('leaves presses within the content to the browser', async () => {+ const { editor, root, wrapper } = await setup(['text']);+ cleanups.push(registerClickBelowContentOnLexical(editor));++ expect(pressAt(wrapper, 110).defaultPrevented).toBe(false);+ expect(pressAt(root.firstElementChild!, 200).defaultPrevented).toBe(false);+ expect(pressAt(wrapper, 200, { shiftKey: true }).defaultPrevented).toBe(false);+ await settle();++ expect(readState(editor).lines).toEqual(['text']);+ });++ it('does nothing on a read-only body', async () => {+ const { editor, wrapper } = await setup(['text']);+ cleanups.push(registerClickBelowContentOnLexical(editor));+ editor.setEditable(false);++ expect(pressAt(wrapper, 200).defaultPrevented).toBe(false);+ await settle();++ expect(readState(editor).lines).toEqual(['text']);+ });++ it('stops listening once unregistered', async () => {+ const { editor, wrapper } = await setup(['text']);+ registerClickBelowContentOnLexical(editor)();++ expect(pressAt(wrapper, 200).defaultPrevented).toBe(false);+ });+});++describe('focusEditorAtBlankPoint', () => {+ it('continues writing at the end from a click below the body', async () => {+ const { editor } = await setup(['first', 'second']);++ focusEditorAtBlankPoint(asKernel(editor), { clientX: 300, clientY: 400 });+ await settle();++ expect(readState(editor)).toEqual({+ caret: { line: 2, offset: 0 },+ lines: ['first', 'second', ''],+ });+ });++ it('puts the caret at the start of the line beside a left-margin click', async () => {+ const { editor } = await setup(['first', 'second']);++ focusEditorAtBlankPoint(asKernel(editor), { clientX: -40, clientY: 130 });+ await settle();++ expect(readState(editor)).toEqual({+ caret: { line: 1, offset: 0 },+ lines: ['first', 'second'],+ });+ });++ it('puts the caret at the end of the line beside a right-margin click', async () => {+ const { editor } = await setup(['first', 'second']);++ focusEditorAtBlankPoint(asKernel(editor), { clientX: 640, clientY: 110 });+ await settle();++ expect(readState(editor)).toEqual({+ caret: { line: 0, offset: 5 },+ lines: ['first', 'second'],+ });+ });++ it('ignores clicks above the body, beside the title', async () => {+ const { editor } = await setup(['first']);+ await commit(editor, () => {+ $getRoot().getFirstChildOrThrow().selectEnd();+ });++ focusEditorAtBlankPoint(asKernel(editor), { clientX: -40, clientY: 40 });+ await settle();++ expect(readState(editor)).toEqual({ caret: { line: 0, offset: 5 }, lines: ['first'] });+ });++ it('does nothing on a read-only body', async () => {+ const { editor } = await setup(['first']);+ editor.setEditable(false);++ focusEditorAtBlankPoint(asKernel(editor), { clientX: 300, clientY: 400 });+ await settle();++ expect(readState(editor).lines).toEqual(['first']);+ });+});diff --git a/src/features/PageEditor/blankAreaClick.ts b/src/features/PageEditor/blankAreaClick.tsnew file mode 100644index 00000000000..ca627297432--- /dev/null+++ b/src/features/PageEditor/blankAreaClick.ts@@ -0,0 +1,220 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createNodeSelection,+ $createParagraphNode,+ $getNearestNodeFromDOMNode,+ $getRoot,+ $isDecoratorNode,+ $isElementNode,+ $isParagraphNode,+ $isTextNode,+ $setSelection,+ type LexicalEditor,+} from 'lexical';++/**+ * Clicks on the blank space around the page body, the way AFFiNE's page root+ * handles them:+ * - below the last block: continue writing at the end β on the trailing empty+ * line if there is one, otherwise on a new one, so a document that ends in a+ * table, code block or image can still be written after;+ * - beside a line (the page margins): put the caret at that line's start+ * (left margin) or end (right margin);+ * - above the body (beside the title, on a banner): nothing.+ */++export type BlankZone = 'above' | 'beside' | 'below';++interface ClickPoint {+ clientX: number;+ clientY: number;+}++/** Exported for tests. */+export const getBlankZone = (+ { bodyTop, contentBottom }: { bodyTop: number; contentBottom: number },+ clientY: number,+): BlankZone => {+ if (clientY < bodyTop) return 'above';+ if (clientY > contentBottom) return 'below';+ return 'beside';+};++/**+ * Select the line to write on at the end of the document: the trailing empty+ * paragraph, or a new one appended after whatever the document ends with.+ */+export const $selectDocumentEndForWriting = () => {+ const root = $getRoot();+ const last = root.getLastChild();+ if ($isParagraphNode(last) && last.getChildrenSize() === 0) {+ last.select();+ return;+ }++ const paragraph = $createParagraphNode();+ root.append(paragraph);+ paragraph.select();+};++/** Exported for tests, which drive a bare Lexical editor without the kernel. */+export const selectDocumentEndForWritingOnLexical = (lexicalEditor: LexicalEditor) => {+ lexicalEditor.update($selectDocumentEndForWriting);+};++const getBlockElements = (root: HTMLElement) =>+ [...root.children].filter((child): child is HTMLElement => child instanceof HTMLElement);++const getContentBottom = (root: HTMLElement) => {+ const blocks = getBlockElements(root);+ const last = blocks.at(-1);+ return last ? last.getBoundingClientRect().bottom : root.getBoundingClientRect().top;+};++/** The top-level block whose rows span `clientY`, else the one closest to it. */+const findBlockElementAt = (root: HTMLElement, clientY: number) => {+ let nearest: HTMLElement | undefined;+ let nearestDistance = Number.POSITIVE_INFINITY;++ for (const block of getBlockElements(root)) {+ const { bottom, top } = block.getBoundingClientRect();+ if (clientY >= top && clientY <= bottom) return block;++ const distance = clientY < top ? top - clientY : clientY - bottom;+ if (distance < nearestDistance) {+ nearest = block;+ nearestDistance = distance;+ }+ }++ return nearest;+};++type DocumentWithCaretApi = Document & {+ caretPositionFromPoint?: (x: number, y: number) => { offset: number; offsetNode: Node } | null;+ caretRangeFromPoint?: (x: number, y: number) => Range | null;+};++const getCaretPointFromPoint = (x: number, y: number) => {+ const doc = document as DocumentWithCaretApi;+ if (doc.caretPositionFromPoint) {+ const position = doc.caretPositionFromPoint(x, y);+ return position ? { node: position.offsetNode, offset: position.offset } : null;+ }+ if (doc.caretRangeFromPoint) {+ const range = doc.caretRangeFromPoint(x, y);+ return range ? { node: range.startContainer, offset: range.startOffset } : null;+ }+ return null;+};++/**+ * Put the caret at the start or end of the line beside the click. The text+ * position the browser reports at the body's edge is the start / end of that+ * visual line; when there is none (an image row, a browser without the caret+ * API) the whole block's start / end is used instead.+ */+const selectLineBesidePoint = (+ lexicalEditor: LexicalEditor,+ root: HTMLElement,+ { clientX, clientY }: ClickPoint,+) => {+ const rootRect = root.getBoundingClientRect();+ const side = clientX < rootRect.left + rootRect.width / 2 ? 'start' : 'end';+ const edgeX = side === 'start' ? rootRect.left + 1 : rootRect.right - 1;+ const caretPoint = getCaretPointFromPoint(edgeX, clientY);+ const blockElement = findBlockElementAt(root, clientY);++ lexicalEditor.update(() => {+ if (+ caretPoint &&+ caretPoint.node.nodeType === Node.TEXT_NODE &&+ root.contains(caretPoint.node)+ ) {+ const textNode = $getNearestNodeFromDOMNode(caretPoint.node);+ if ($isTextNode(textNode)) {+ const offset = Math.min(caretPoint.offset, textNode.getTextContentSize());+ textNode.select(offset, offset);+ return;+ }+ }++ if (!blockElement) return;+ const block = $getNearestNodeFromDOMNode(blockElement);+ if ($isElementNode(block)) {+ if (side === 'start') block.selectStart();+ else block.selectEnd();+ return;+ }+ if ($isDecoratorNode(block)) {+ const selection = $createNodeSelection();+ selection.add(block.getKey());+ $setSelection(selection);+ }+ });+};++/**+ * Handle a click on the page's blank layout space at `point`. A no-op unless+ * the body is editable.+ */+export const focusEditorAtBlankPoint = (editor: IEditor | undefined, point: ClickPoint) => {+ const lexicalEditor = editor?.getLexicalEditor?.();+ const root = lexicalEditor?.getRootElement();+ if (!lexicalEditor || !root || !lexicalEditor.isEditable()) return;++ const zone = getBlankZone(+ { bodyTop: root.getBoundingClientRect().top, contentBottom: getContentBottom(root) },+ point.clientY,+ );++ if (zone === 'above') return;++ if (zone === 'below') selectDocumentEndForWritingOnLexical(lexicalEditor);+ else selectLineBesidePoint(lexicalEditor, root, point);++ lexicalEditor.focus();+};++/**+ * Inside the editor itself, a press on the body's own blank area below its+ * last block (the root, or the padded wrapper around it) would leave the caret+ * wherever the browser snaps it β inside a trailing table cell, or nowhere+ * after an image. Continue writing at the end instead.+ */+export const registerClickBelowContentOnLexical = (lexicalEditor: LexicalEditor) => {+ let attached: { host: HTMLElement; root: HTMLElement } | null = null;++ const onMouseDown = (event: MouseEvent) => {+ const root = attached?.root;+ if (!root || !lexicalEditor.isEditable()) return;+ if (event.button !== 0 || event.shiftKey || event.metaKey || event.ctrlKey || event.altKey)+ return;+ if (event.target !== root && event.target !== root.parentElement) return;+ if (event.clientY <= getContentBottom(root)) return;++ // Keep the browser from snapping a caret (or starting a drag selection)+ // from the blank area; the caret goes to the end line instead.+ event.preventDefault();+ selectDocumentEndForWritingOnLexical(lexicalEditor);+ lexicalEditor.focus();+ };++ const detach = () => {+ attached?.host.removeEventListener('mousedown', onMouseDown);+ attached = null;+ };++ const unregisterRootListener = lexicalEditor.registerRootListener((root) => {+ detach();+ const host = root?.parentElement;+ if (!root || !host) return;+ host.addEventListener('mousedown', onMouseDown);+ attached = { host, root };+ });++ return () => {+ unregisterRootListener();+ detach();+ };+};diff --git a/src/features/PageEditor/store/action.ts b/src/features/PageEditor/store/action.tsindex 45920de7508..bb57c3f0238 100644--- a/src/features/PageEditor/store/action.ts+++ b/src/features/PageEditor/store/action.ts@@ -5,6 +5,7 @@ import { debounce } from 'es-toolkit/compat';import { type StateCreator } from 'zustand';import { type EditLockHealth } from '@/features/EditLock';+import { focusEditorStartLine } from '@/features/EditorCanvas/focusEditorStartLine';import { useDocumentStore } from '@/store/document';import { getElectronStoreState } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';@@ -19,7 +20,11 @@ export interface Action {flushMetaSave: () => void;handleCopyLink: (t: (key: string) => string) => void;handleDelete: (t: (key: string) => string, onDeleteCallback?: () => void) => Promise<void>;- handleTitleSubmit: () => Promise<void>;+ /**+ * Enter in the title: save it and continue on the body's first line. `bodyText`+ * is the part of the title after the caret, which becomes that first line.+ */+ handleTitleSubmit: (bodyText?: string) => Promise<void>;initMeta: (title?: string, emoji?: string) => void;performMetaSave: () => Promise<void>;setCommentsPanelOpen: (open: boolean) => void;@@ -135,12 +140,14 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =});},- handleTitleSubmit: async () => {+ handleTitleSubmit: async (bodyText) => {const { editor, flushMetaSave } = get();- // Flush pending save and focus editor+ // Flush the pending title save, then continue on a fresh first line of+ // the body (AFFiNE's doc title does the same). A bare `editor.focus()`+ // would restore the body's last caret β often the end of a long page.flushMetaSave();- editor?.focus();+ focusEditorStartLine(editor, bodyText);},initMeta: (title, emoji) => {diff --git a/src/features/PageEditor/titleBodyNavigation.test.ts b/src/features/PageEditor/titleBodyNavigation.test.tsnew file mode 100644index 00000000000..d79a7ad0154--- /dev/null+++ b/src/features/PageEditor/titleBodyNavigation.test.ts@@ -0,0 +1,414 @@+/**+ * @vitest-environment happy-dom+ */+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_CRITICAL,+ COMMAND_PRIORITY_NORMAL,+ type CommandListener,+ type CommandListenerPriority,+ createEditor,+ KEY_ARROW_UP_COMMAND,+ KEY_BACKSPACE_COMMAND,+ type LexicalCommand,+ type LexicalEditor,+ type ParagraphNode,+} from 'lexical';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ findPageTitleInput,+ flattenTitleLineBreaks,+ PAGE_TITLE_INPUT_ATTRIBUTE,+ registerTitleBodyNavigationOnLexical,+ shouldTitleArrowDownEnterBody,+} from './titleBodyNavigation';++const commit = (editor: LexicalEditor, fn: () => void) =>+ new Promise<void>((resolve) => {+ editor.update(fn, { onUpdate: resolve });+ });++const settle = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++const cleanups: (() => void)[] = [];++afterEach(() => {+ while (cleanups.length > 0) cleanups.pop()?.();+ document.body.innerHTML = '';+});++type HighCommandRegistrar = <P>(+ command: LexicalCommand<P>,+ listener: CommandListener<P>,+ priority: CommandListenerPriority,+) => () => void;++/**+ * The editor kernel's high-command lane: listeners kept in its own priority+ * sets and run, highest priority first, from one Lexical listener registered+ * at CRITICAL β so all of them run before any plain Lexical listener.+ */+const createKernelHighCommands = (editor: LexicalEditor): HighCommandRegistrar => {+ const lanes = new Map<LexicalCommand<unknown>, Set<CommandListener<unknown>>[]>();+ return (command, listener, priority) => {+ const key = command as LexicalCommand<unknown>;+ if (!lanes.has(key)) {+ const sets = [0, 1, 2, 3, 4].map(() => new Set<CommandListener<unknown>>());+ lanes.set(key, sets);+ editor.registerCommand(+ command,+ (payload, lexicalEditor) => {+ for (let i = 4; i >= 0; i--) {+ for (const run of sets[i]) if (run(payload, lexicalEditor)) return true;+ }+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ );+ }+ const set = lanes.get(key)![priority];+ set.add(listener as CommandListener<unknown>);+ return () => set.delete(listener as CommandListener<unknown>);+ };+};++/**+ * Stand-in for @lobehub/editor's virtual-block plugin: ArrowUp anywhere in a+ * non-empty first block opens a temporary empty line above it.+ */+const registerFakeVirtualBlock = (registerHighCommand: HighCommandRegistrar) =>+ registerHighCommand(+ KEY_ARROW_UP_COMMAND,+ (event) => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return false;+ const block = selection.focus.getNode().getTopLevelElement();+ if (!block || !block.is($getRoot().getFirstChild()) || block.getTextContentSize() === 0)+ return false;+ event?.preventDefault();+ const line = $createParagraphNode();+ block.insertBefore(line);+ line.selectStart();+ return true;+ },+ COMMAND_PRIORITY_NORMAL,+ );++interface SetupOptions {+ isCaretOnFirstLine?: (blockElement: HTMLElement | null) => boolean;+ lines: string[];+ titleReadOnly?: boolean;+ /** Register like the page does: through the kernel's high-command lane. */+ withKernel?: boolean;+}++const setup = async ({+ lines,+ titleReadOnly = false,+ isCaretOnFirstLine,+ withKernel = false,+}: SetupOptions) => {+ const host = document.createElement('div');+ const title = document.createElement('textarea');+ title.setAttribute(PAGE_TITLE_INPUT_ATTRIBUTE, 'true');+ title.value = 'My page';+ title.readOnly = titleReadOnly;+ const root = document.createElement('div');+ root.contentEditable = 'true';+ host.append(title, root);+ document.body.append(host);++ const editor = createEditor({+ onError: (error) => {+ throw error;+ },+ });+ editor.setRootElement(root);+ cleanups.push(() => editor.setRootElement(null));++ await commit(editor, () => {+ $getRoot().append(+ ...lines.map((line) => {+ const paragraph = $createParagraphNode();+ if (line) paragraph.append($createTextNode(line));+ return paragraph;+ }),+ );+ });++ const registerHighCommand = withKernel ? createKernelHighCommands(editor) : undefined;+ // Editor plugins register before the page's own interactions do.+ if (registerHighCommand) cleanups.push(registerFakeVirtualBlock(registerHighCommand));++ cleanups.push(+ registerTitleBodyNavigationOnLexical(editor, {+ getTitleInput: () => findPageTitleInput(host),+ isCaretOnFirstLine: isCaretOnFirstLine ?? (() => false),+ registerHighCommand,+ }),+ );++ return { editor, title };+};++const placeCaret = (editor: LexicalEditor, line: number, offset: number) =>+ commit(editor, () => {+ const paragraph = $getRoot().getChildAtIndex<ParagraphNode>(line)!;+ const text = paragraph.getFirstChild();+ if (text) text.select(offset, offset);+ else paragraph.select(0, 0);+ });++const press = (+ editor: LexicalEditor,+ command: 'up' | 'backspace',+ init: KeyboardEventInit = {},+) => {+ const event = new KeyboardEvent('keydown', {+ cancelable: true,+ key: command === 'up' ? 'ArrowUp' : 'Backspace',+ ...init,+ });+ const handled = editor.dispatchCommand(+ command === 'up' ? KEY_ARROW_UP_COMMAND : KEY_BACKSPACE_COMMAND,+ event,+ );+ return { event, handled };+};++const readLines = (editor: LexicalEditor) =>+ editor.getEditorState().read(() =>+ $getRoot()+ .getChildren()+ .map((child) => child.getTextContent()),+ );++const expectCaretAtTitleEnd = (title: HTMLTextAreaElement) => {+ expect(document.activeElement).toBe(title);+ expect(title.selectionStart).toBe(title.value.length);+ expect(title.selectionEnd).toBe(title.value.length);+};++describe('registerTitleBodyNavigationOnLexical β ArrowUp', () => {+ it('moves from the start of the first block to the end of the title', async () => {+ const { editor, title } = await setup({ lines: ['first', 'second'] });+ await placeCaret(editor, 0, 0);++ const { event, handled } = press(editor, 'up');+ await settle();++ expect(handled).toBe(true);+ expect(event.defaultPrevented).toBe(true);+ expectCaretAtTitleEnd(title);+ // The body lets go of its caret so committing it cannot pull focus back.+ expect(editor.getEditorState().read(() => $getSelection())).toBeNull();+ });++ it("gets in before the editor's own ArrowUp handling of the first block", async () => {+ const { editor, title } = await setup({+ isCaretOnFirstLine: () => true,+ lines: ['first line', 'second'],+ withKernel: true,+ });+ await placeCaret(editor, 0, 4);++ expect(press(editor, 'up').handled).toBe(true);+ await settle();++ // No temporary line is opened above the first block, and none is saved.+ expect(readLines(editor)).toEqual(['first line', 'second']);+ expectCaretAtTitleEnd(title);+ });++ it('drops an empty first line it leaves, unless it is the only line', async () => {+ const { editor, title } = await setup({ lines: ['', 'second'], withKernel: true });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'up').handled).toBe(true);+ await settle();++ expect(readLines(editor)).toEqual(['second']);+ expectCaretAtTitleEnd(title);+ });++ it('keeps the only line of the body when leaving it upward', async () => {+ const { editor, title } = await setup({ lines: [''], withKernel: true });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'up').handled).toBe(true);+ await settle();++ expect(readLines(editor)).toEqual(['']);+ expectCaretAtTitleEnd(title);+ });++ it('moves to the title from anywhere on the first visual line', async () => {+ const isCaretOnFirstLine = vi.fn(() => true);+ const { editor, title } = await setup({ isCaretOnFirstLine, lines: ['first line', 'second'] });+ await placeCaret(editor, 0, 4);++ expect(press(editor, 'up').handled).toBe(true);+ expect(isCaretOnFirstLine).toHaveBeenCalledWith(expect.any(HTMLElement));+ expectCaretAtTitleEnd(title);+ });++ it('leaves the browser to move up a line when the caret is below the first line', async () => {+ const { editor, title } = await setup({ lines: ['a long wrapped first paragraph'] });+ await placeCaret(editor, 0, 12);++ const { event, handled } = press(editor, 'up');++ expect(handled).toBe(false);+ expect(event.defaultPrevented).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });++ it('ignores blocks after the first one', async () => {+ const { editor, title } = await setup({+ isCaretOnFirstLine: () => true,+ lines: ['first', 'second'],+ });+ await placeCaret(editor, 1, 0);++ expect(press(editor, 'up').handled).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });++ it('keeps Shift+ArrowUp for extending the selection', async () => {+ const { editor } = await setup({ lines: ['first'] });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'up', { shiftKey: true }).handled).toBe(false);+ });++ it('stays in the body when the title cannot be written', async () => {+ const { editor, title } = await setup({ lines: ['first'], titleReadOnly: true });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'up').handled).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });++ it('does nothing while the body is read-only', async () => {+ const { editor, title } = await setup({ lines: ['first'] });+ await placeCaret(editor, 0, 0);+ editor.setEditable(false);++ expect(press(editor, 'up').handled).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });+});++describe('registerTitleBodyNavigationOnLexical β Backspace', () => {+ it('drops an empty first line and moves to the end of the title', async () => {+ const { editor, title } = await setup({ lines: ['', 'second'] });+ await placeCaret(editor, 0, 0);++ const { event, handled } = press(editor, 'backspace');+ await settle();++ expect(handled).toBe(true);+ expect(event.defaultPrevented).toBe(true);+ expect(readLines(editor)).toEqual(['second']);+ expectCaretAtTitleEnd(title);+ });++ it('keeps the only line of the body so there is still somewhere to type', async () => {+ const { editor, title } = await setup({ lines: [''] });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'backspace').handled).toBe(true);+ await settle();++ expect(readLines(editor)).toEqual(['']);+ expectCaretAtTitleEnd(title);+ });++ it('moves to the title without merging the first line into it', async () => {+ const { editor, title } = await setup({ lines: ['first', 'second'] });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'backspace').handled).toBe(true);+ await settle();++ expect(readLines(editor)).toEqual(['first', 'second']);+ expect(title.value).toBe('My page');+ expectCaretAtTitleEnd(title);+ });++ it('deletes text normally when the caret is not at the start', async () => {+ const { editor, title } = await setup({ lines: ['first'] });+ await placeCaret(editor, 0, 3);++ expect(press(editor, 'backspace').handled).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });++ it('leaves the start of a later line to merge with the line above', async () => {+ const { editor, title } = await setup({ lines: ['first', 'second'] });+ await placeCaret(editor, 1, 0);++ expect(press(editor, 'backspace').handled).toBe(false);+ expect(document.activeElement).not.toBe(title);+ });++ it('outdents an indented first paragraph before leaving it', async () => {+ const { editor } = await setup({ lines: ['first'] });+ await commit(editor, () => {+ $getRoot().getFirstChildOrThrow<ParagraphNode>().setIndent(1);+ });+ await placeCaret(editor, 0, 0);++ expect(press(editor, 'backspace').handled).toBe(false);+ });+});++describe('flattenTitleLineBreaks', () => {+ it('turns each run of line breaks, with the spaces around it, into one space', () => {+ expect(flattenTitleLineBreaks('Line one\nLine two')).toBe('Line one Line two');+ expect(flattenTitleLineBreaks('a \r\n\r\n b')).toBe('a b');+ expect(flattenTitleLineBreaks('a\u2028b')).toBe('a b');+ });++ it('leaves a single-line title untouched', () => {+ expect(flattenTitleLineBreaks(' spaced title ')).toBe(' spaced title ');+ });+});++describe('shouldTitleArrowDownEnterBody', () => {+ const createTitle = (value: string, caret: number, end = caret) => {+ const input = document.createElement('textarea');+ input.value = value;+ document.body.append(input);+ input.setSelectionRange(caret, end);+ return input;+ };++ it('enters the body from the end of the title', () => {+ expect(shouldTitleArrowDownEnterBody(createTitle('Title', 5))).toBe(true);+ });++ it('enters the body from anywhere in a one-line title', () => {+ expect(shouldTitleArrowDownEnterBody(createTitle('Title', 2))).toBe(true);+ });++ it('lets the browser move down a wrapped title until the caret reaches its end', () => {+ const input = createTitle('A title long enough to wrap onto a second line', 3);+ input.style.lineHeight = '40px';+ Object.defineProperty(input, 'scrollHeight', { configurable: true, value: 80 });++ expect(shouldTitleArrowDownEnterBody(input)).toBe(false);+ });++ it('collapses a selection first instead of leaving the title', () => {+ expect(shouldTitleArrowDownEnterBody(createTitle('Title', 0, 5))).toBe(false);+ });+});diff --git a/src/features/PageEditor/titleBodyNavigation.ts b/src/features/PageEditor/titleBodyNavigation.tsnew file mode 100644index 00000000000..7dce916f0f4--- /dev/null+++ b/src/features/PageEditor/titleBodyNavigation.ts@@ -0,0 +1,231 @@+import {+ $getRoot,+ $getSelection,+ $isParagraphNode,+ $isRangeSelection,+ $setSelection,+ COMMAND_PRIORITY_HIGH,+ COMMAND_PRIORITY_LOW,+ type CommandListener,+ type CommandListenerPriority,+ type ElementNode,+ KEY_ARROW_UP_COMMAND,+ KEY_BACKSPACE_COMMAND,+ type LexicalCommand,+ type LexicalEditor,+ mergeRegister,+ type RangeSelection,+} from 'lexical';++/**+ * The page title and its body read as one document (AFFiNE's doc title works+ * the same way): the caret walks between them with the arrow keys, Enter and+ * Backspace. The title is a plain textarea outside the Lexical editor, so the+ * body finds it through this attribute.+ */+export const PAGE_TITLE_INPUT_ATTRIBUTE = 'data-page-title-input';++export const findPageTitleInput = (host: ParentNode | null | undefined) =>+ host?.querySelector<HTMLTextAreaElement>(`textarea[${PAGE_TITLE_INPUT_ATTRIBUTE}]`) ?? null;++const isTitleInputWritable = (input: HTMLTextAreaElement | null): input is HTMLTextAreaElement =>+ !!input && !input.readOnly && !input.disabled;++/** Put the caret at the end of the title, the way AFFiNE's `focusTitle` does. */+export const focusTitleInputEnd = (input: HTMLTextAreaElement) => {+ input.focus();+ const end = input.value.length;+ input.setSelectionRange(end, end);+};++const LINE_BREAKS = /[^\S\n\r\u2028\u2029]*[\n\r\u2028\u2029]+[^\S\n\r\u2028\u2029]*/g;++/**+ * The title is a single line (it is the document's filename too), so line+ * breaks that reach it β a multi-line paste, a dropped selection β become a+ * single space instead of splitting the title.+ */+export const flattenTitleLineBreaks = (value: string) => value.replaceAll(LINE_BREAKS, ' ');++const isSingleLineTextArea = (input: HTMLTextAreaElement) => {+ const lineHeight = Number.parseFloat(getComputedStyle(input).lineHeight);+ // Without a measurable line box (jsdom, `line-height: normal`) treat the+ // title as one line, which is what it is almost always.+ if (!Number.isFinite(lineHeight) || lineHeight <= 0) return true;+ return input.scrollHeight < lineHeight * 1.5;+};++/**+ * ArrowDown leaves the title for the body once there is no title line below+ * the caret: always on a one-line title, and on a wrapped title once the caret+ * is at its end (the browser moves it there from the last line first).+ */+export const shouldTitleArrowDownEnterBody = (input: HTMLTextAreaElement) => {+ const { selectionEnd, selectionStart, value } = input;+ if (selectionStart !== selectionEnd) return false;+ if (selectionEnd === value.length) return true;+ return isSingleLineTextArea(input);+};++const hasModifier = (event: KeyboardEvent) =>+ event.shiftKey || event.altKey || event.metaKey || event.ctrlKey;++/** The collapsed caret, when it sits in the body's first top-level block. */+const $getCaretInFirstBlock = (): { block: ElementNode; selection: RangeSelection } | null => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) return null;++ const block = selection.anchor.getNode().getTopLevelElement();+ const first = $getRoot().getFirstChild();+ if (!block || !first || !block.is(first)) return null;++ return { block, selection };+};++/** True when nothing in `block` comes before the caret. */+const $isCaretAtBlockStart = (block: ElementNode, selection: RangeSelection) => {+ if (selection.anchor.offset !== 0) return false;++ let node = selection.anchor.getNode();+ while (!node.is(block)) {+ if (node.getPreviousSibling()) return false;+ const parent = node.getParent();+ if (!parent) return false;+ node = parent;+ }+ return true;+};++const getCaretRect = (range: Range): DOMRect | null => {+ const rects = range.getClientRects?.();+ if (rects) {+ for (const rect of rects) if (rect.height > 0) return rect;+ }+ const rect = range.getBoundingClientRect?.();+ return rect && rect.height > 0 ? rect : null;+};++/**+ * Whether the DOM caret is on the first visual line of `blockElement`: its+ * top is less than one line below the block's top.+ */+export const isDomCaretOnFirstLine = (blockElement: HTMLElement | null): boolean => {+ if (!blockElement) return false;+ const domSelection = window.getSelection();+ if (!domSelection || domSelection.rangeCount === 0) return false;++ const range = domSelection.getRangeAt(0);+ if (!blockElement.contains(range.startContainer)) return false;++ const caretRect = getCaretRect(range);+ if (!caretRect) return false;++ return caretRect.top - blockElement.getBoundingClientRect().top < caretRect.height;+};++type CommandRegistrar = <P>(+ command: LexicalCommand<P>,+ listener: CommandListener<P>,+ priority: CommandListenerPriority,+) => () => void;++interface TitleBodyNavigationOptions {+ /** The title input, or null when there is none or it cannot be written. */+ getTitleInput: () => HTMLTextAreaElement | null;+ /** Injected by tests; defaults to measuring the DOM caret. */+ isCaretOnFirstLine?: (blockElement: HTMLElement | null) => boolean;+ /**+ * Where ArrowUp registers. The editor kernel's own ArrowUp handlers (the+ * virtual-block plugin opens a temporary line above the first block) run in+ * its high-command lane, ahead of any plain Lexical listener, so the page+ * passes `editor.registerHighCommand` to get in before them. Defaults to the+ * Lexical editor itself (tests).+ */+ registerHighCommand?: CommandRegistrar;+}++/**+ * Body side of the title β body walk:+ * - ArrowUp on the first line of the first block moves to the end of the title.+ * - Backspace at the very start of a plain first paragraph moves to the end of+ * the title. Its text is never merged into the title, which doubles as the+ * filename.+ * Either way, an empty first line is dropped on the way out unless it is the+ * body's only line β nothing is left behind that the user did not write.+ *+ * Exported for tests, which drive a bare Lexical editor without the kernel.+ */+export const registerTitleBodyNavigationOnLexical = (+ lexicalEditor: LexicalEditor,+ {+ getTitleInput,+ isCaretOnFirstLine = isDomCaretOnFirstLine,+ registerHighCommand = (command, listener, priority) =>+ lexicalEditor.registerCommand(command, listener, priority),+ }: TitleBodyNavigationOptions,+) => {+ const takeTitleInput = () => {+ const input = getTitleInput();+ return isTitleInputWritable(input) ? input : null;+ };++ // The caret leaves the editor, so drop its selection: committing a body+ // selection after the title took focus would pull the DOM caret back.+ const $moveCaretToTitle = (+ event: KeyboardEvent | null,+ input: HTMLTextAreaElement,+ block: ElementNode,+ ) => {+ // The last line stays so the body keeps somewhere to click back into.+ if ($isParagraphNode(block) && block.getChildrenSize() === 0 && block.getNextSibling()) {+ block.remove();+ }+ event?.preventDefault();+ $setSelection(null);+ focusTitleInputEnd(input);+ return true;+ };++ return mergeRegister(+ registerHighCommand(+ KEY_ARROW_UP_COMMAND,+ (event) => {+ if (!lexicalEditor.isEditable()) return false;+ if (event && (hasModifier(event) || event.isComposing)) return false;++ const caret = $getCaretInFirstBlock();+ if (!caret) return false;++ const onFirstLine =+ $isCaretAtBlockStart(caret.block, caret.selection) ||+ isCaretOnFirstLine(lexicalEditor.getElementByKey(caret.block.getKey()));+ if (!onFirstLine) return false;++ const input = takeTitleInput();+ if (!input) return false;++ return $moveCaretToTitle(event, input, caret.block);+ },+ COMMAND_PRIORITY_HIGH,+ ),+ lexicalEditor.registerCommand(+ KEY_BACKSPACE_COMMAND,+ (event) => {+ if (!lexicalEditor.isEditable()) return false;+ if (event?.isComposing) return false;++ const caret = $getCaretInFirstBlock();+ // Headings, quotes and lists turn into a plain paragraph first (their+ // own Backspace handling); an indented paragraph outdents first.+ if (!caret || !$isParagraphNode(caret.block) || caret.block.getIndent() > 0) return false;+ if (!$isCaretAtBlockStart(caret.block, caret.selection)) return false;++ const input = takeTitleInput();+ if (!input) return false;++ return $moveCaretToTitle(event, input, caret.block);+ },+ COMMAND_PRIORITY_LOW,+ ),+ );+};diff --git a/src/features/PageEditor/usePageBodyInteractions.ts b/src/features/PageEditor/usePageBodyInteractions.tsnew file mode 100644index 00000000000..e28adc57ac7--- /dev/null+++ b/src/features/PageEditor/usePageBodyInteractions.ts@@ -0,0 +1,54 @@+import type { IEditor } from '@lobehub/editor';+import { mergeRegister } from 'lexical';+import { type RefObject, useEffect } from 'react';++import { registerClickBelowContentOnLexical } from './blankAreaClick';+import { findPageTitleInput, registerTitleBodyNavigationOnLexical } from './titleBodyNavigation';++/**+ * Wire the page body's own interactions into its Lexical editor: walking the+ * caret up into the title, and writing after the last block from a click on+ * the blank space below it. `hostRef` holds both the title and the body.+ *+ * Both check `isEditable()` per event, so a page that gets locked or unlocked+ * needs no re-registration.+ */+export const usePageBodyInteractions = (+ editor: IEditor | undefined,+ hostRef: RefObject<HTMLElement | null>,+) => {+ useEffect(() => {+ if (!editor) return;++ let disposed = false;+ let unregister: (() => void) | undefined;++ const attach = () => {+ const lexicalEditor = editor.getLexicalEditor?.();+ if (disposed || !lexicalEditor) return;++ // A document switch rebuilds the Lexical editor under the same kernel,+ // so drop the previous registrations before taking new ones.+ unregister?.();+ unregister = mergeRegister(+ registerClickBelowContentOnLexical(lexicalEditor),+ registerTitleBodyNavigationOnLexical(lexicalEditor, {+ getTitleInput: () => findPageTitleInput(hostRef.current),+ registerHighCommand: (command, listener, priority) =>+ editor.registerHighCommand(command, listener, priority),+ }),+ );+ };++ // The body only mounts once its content request resolves, so the Lexical+ // editor may not exist yet; wait for the kernel's own signal.+ editor.on('initialized', attach);+ attach();++ return () => {+ disposed = true;+ editor.off('initialized', attach);+ unregister?.();+ };+ }, [editor, hostRef]);+};diff --git a/src/features/PageEditor/usePageTitleInteractions.test.ts b/src/features/PageEditor/usePageTitleInteractions.test.tsnew file mode 100644index 00000000000..d64267e506a--- /dev/null+++ b/src/features/PageEditor/usePageTitleInteractions.test.ts@@ -0,0 +1,398 @@+import type { IEditor } from '@lobehub/editor';+import { act, renderHook } from '@testing-library/react';+import type { ChangeEvent, KeyboardEvent, ReactNode } from 'react';+import { createElement } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ focusEditorFirstLine,+ focusEditorStartLine,+} from '@/features/EditorCanvas/focusEditorStartLine';++import { createStore, Provider } from './store';+import { PAGE_TITLE_INPUT_ATTRIBUTE } from './titleBodyNavigation';+import {+ holdTitleFocus,+ isUnstartedPage,+ splitTitleAtSelection,+ usePageTitleInteractions,+} from './usePageTitleInteractions';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/features/EditorCanvas/focusEditorStartLine', async (importOriginal) => ({+ // Keep the real readiness check; only the caret moves are spied on.+ ...(await importOriginal<Record<string, unknown>>()),+ focusEditorFirstLine: vi.fn(),+ focusEditorStartLine: vi.fn(),+}));++const mockEditable = { current: true };+vi.mock('./usePageEditable', () => ({+ usePageEditable: () => mockEditable.current,+}));++const mockDocumentState: { current: { documents: Record<string, { content: string }> } } = {+ current: { documents: {} },+};+vi.mock('@/store/document', () => ({+ useDocumentStore: Object.assign((selector: any) => selector(mockDocumentState.current), {+ getState: () => ({ performSave: vi.fn() }),+ }),+}));+vi.mock('@/store/document/slices/editor', () => ({+ editorSelectors: {+ content: (id: string) => (s: any) => s.documents[id]?.content ?? '',+ isDocumentLoading: (id: string | undefined) => (s: any) => !id || !s.documents[id],+ },+}));++/** Whether the body editor is mounted and editable (its content request resolved). */+const mockBodyMounted = { current: true };+const editor = {+ focus: vi.fn(),+ getLexicalEditor: () =>+ mockBodyMounted.current+ ? { getRootElement: () => document.body, isEditable: () => true }+ : null,+} as unknown as IEditor;++const setup = ({+ content = 'Some body',+ documentLoaded = true,+ metaReadOnly = false,+ title: titleOption = 'My page',+ titleUnknown = false,+}: {+ content?: string;+ documentLoaded?: boolean;+ metaReadOnly?: boolean;+ title?: string;+ /** The page's title has not arrived yet (store title `undefined`). */+ titleUnknown?: boolean;+} = {}) => {+ const title = titleUnknown ? undefined : titleOption;+ mockDocumentState.current = { documents: documentLoaded ? { 'doc-1': { content } } : {} };++ const container = document.createElement('div');+ const input = document.createElement('textarea');+ input.setAttribute(PAGE_TITLE_INPUT_ATTRIBUTE, 'true');+ input.value = title ?? '';+ container.append(input);+ document.body.append(container);++ const store = createStore({ documentId: 'doc-1', editor, metaReadOnly, title });+ const flushMetaSave = vi.fn();+ store.setState({ flushMetaSave });+ const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(Provider, { createStore: () => store }, children);+ const { rerender, result } = renderHook(() => usePageTitleInteractions({ current: container }), {+ wrapper,+ });++ return { flushMetaSave, input, rerender, result, store };+};++/** Let focus events and the hold's deferred check run. */+const settle = () =>+ act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ });++const createButton = () => {+ const button = document.createElement('button');+ document.body.append(button);+ return button;+};++const keyDown = (+ input: HTMLTextAreaElement,+ init: { isComposing?: boolean; key: string; keyCode?: number; shiftKey?: boolean },+) => {+ const preventDefault = vi.fn();+ const event = {+ altKey: false,+ ctrlKey: false,+ currentTarget: input,+ key: init.key,+ keyCode: init.keyCode ?? 0,+ metaKey: false,+ nativeEvent: { isComposing: init.isComposing ?? false },+ preventDefault,+ shiftKey: init.shiftKey ?? false,+ } as unknown as KeyboardEvent<HTMLTextAreaElement>;+ return { event, preventDefault };+};++beforeEach(() => {+ mockEditable.current = true;+ mockBodyMounted.current = true;+ vi.mocked(focusEditorFirstLine).mockClear();+ vi.mocked(focusEditorStartLine).mockClear();+});++afterEach(() => {+ (document.activeElement as HTMLElement | null)?.blur?.();+ document.body.innerHTML = '';+});++describe('usePageTitleInteractions β Enter', () => {+ it('splits the title at the caret and carries the rest into the body', () => {+ const { input, result, store } = setup({ title: 'Hello world' });+ input.setSelectionRange(5, 5);+ const { event, preventDefault } = keyDown(input, { key: 'Enter', keyCode: 13 });++ act(() => result.current.handleTitleKeyDown(event));++ expect(preventDefault).toHaveBeenCalled();+ expect(store.getState().title).toBe('Hello');+ expect(focusEditorStartLine).toHaveBeenCalledWith(editor, ' world');+ });++ it('opens the first body line from the end of the title, keeping the title', () => {+ const { input, result, store } = setup({ title: 'Hello' });+ input.setSelectionRange(5, 5);++ act(() => result.current.handleTitleKeyDown(keyDown(input, { key: 'Enter' }).event));++ expect(store.getState().title).toBe('Hello');+ expect(focusEditorStartLine).toHaveBeenCalledWith(editor, '');+ });++ it('leaves an Enter that confirms an IME candidate alone', () => {+ const { input, result } = setup({ title: 'Hello' });++ act(() =>+ result.current.handleTitleKeyDown(keyDown(input, { key: 'Enter', keyCode: 229 }).event),+ );++ expect(focusEditorStartLine).not.toHaveBeenCalled();+ });++ it('does not split a title that cannot be edited', () => {+ const { input, result, store } = setup({ metaReadOnly: true, title: 'Hello world' });+ input.setSelectionRange(5, 5);++ act(() => result.current.handleTitleKeyDown(keyDown(input, { key: 'Enter' }).event));++ expect(store.getState().title).toBe('Hello world');+ expect(focusEditorStartLine).not.toHaveBeenCalled();+ });+});++describe('usePageTitleInteractions β Enter before the body is ready', () => {+ it.each([+ ['the body editor is not mounted yet', { bodyMounted: false, documentLoaded: true }],+ ['the document is still loading', { bodyMounted: true, documentLoaded: false }],+ ])('keeps the whole title and only saves it while %s', (_, { bodyMounted, documentLoaded }) => {+ mockBodyMounted.current = bodyMounted;+ const { flushMetaSave, input, result, store } = setup({+ documentLoaded,+ title: 'Hello world',+ });+ input.setSelectionRange(5, 5);+ const { event, preventDefault } = keyDown(input, { key: 'Enter', keyCode: 13 });++ act(() => result.current.handleTitleKeyDown(event));++ // No line break goes into the title, and nothing of it is lost.+ expect(preventDefault).toHaveBeenCalled();+ expect(store.getState().title).toBe('Hello world');+ expect(flushMetaSave).toHaveBeenCalledTimes(1);+ expect(focusEditorStartLine).not.toHaveBeenCalled();+ });++ it('leaves ArrowDown to the browser until the body is mounted', () => {+ mockBodyMounted.current = false;+ const { input, result } = setup({ title: 'Hello' });+ const { event, preventDefault } = keyDown(input, { key: 'ArrowDown' });++ act(() => result.current.handleTitleKeyDown(event));++ expect(preventDefault).not.toHaveBeenCalled();+ expect(focusEditorFirstLine).not.toHaveBeenCalled();+ });+});++describe('usePageTitleInteractions β ArrowDown', () => {+ it('moves into the body from a one-line title', () => {+ const { input, result } = setup({ title: 'Hello' });+ input.setSelectionRange(2, 2);+ const { event, preventDefault } = keyDown(input, { key: 'ArrowDown' });++ act(() => result.current.handleTitleKeyDown(event));++ expect(preventDefault).toHaveBeenCalled();+ expect(focusEditorFirstLine).toHaveBeenCalledWith(editor);+ });++ it('still moves into an editable body when only the title is read-only', () => {+ const { input, result } = setup({ metaReadOnly: true, title: 'SKILL.md' });++ act(() => result.current.handleTitleKeyDown(keyDown(input, { key: 'ArrowDown' }).event));++ expect(focusEditorFirstLine).toHaveBeenCalledWith(editor);+ });++ it('keeps Shift+ArrowDown for selecting', () => {+ const { input, result } = setup({ title: 'Hello' });++ act(() =>+ result.current.handleTitleKeyDown(keyDown(input, { key: 'ArrowDown', shiftKey: true }).event),+ );++ expect(focusEditorFirstLine).not.toHaveBeenCalled();+ });+});++describe('usePageTitleInteractions β line breaks', () => {+ it('turns a pasted line break into a space', () => {+ const { input, result, store } = setup({ title: '' });+ input.value = 'Line one\nLine two';++ act(() =>+ result.current.handleTitleChange({+ target: input,+ } as unknown as ChangeEvent<HTMLTextAreaElement>),+ );++ expect(store.getState().title).toBe('Line one Line two');+ });+});++describe('usePageTitleInteractions β icon', () => {+ it('previews the default icon while picking but saves only a picked one', () => {+ const { result, store } = setup();++ act(() => result.current.emojiPicker.onOpen());+ expect(result.current.emojiPicker).toMatchObject({ open: true, value: 'π', visible: true });+ expect(store.getState().emoji).toBeUndefined();++ act(() => result.current.emojiPicker.onOpenChange(false));+ expect(result.current.emojiPicker).toMatchObject({ open: false, visible: false });+ expect(store.getState().emoji).toBeUndefined();++ act(() => result.current.emojiPicker.onOpen());+ act(() => result.current.emojiPicker.onChange('π'));+ expect(store.getState().emoji).toBe('π');+ expect(result.current.emojiPicker).toMatchObject({ open: false, value: 'π', visible: true });+ });+});++describe('usePageTitleInteractions β opening a new page', () => {+ it('focuses and selects the default title of an unstarted page', () => {+ const { input } = setup({ content: '', title: 'Untitled' });++ expect(document.activeElement).toBe(input);+ expect([input.selectionStart, input.selectionEnd]).toEqual([0, 'Untitled'.length]);+ });++ it('leaves a page that already has a body alone', () => {+ const { input } = setup({ content: 'Started', title: 'Untitled' });++ expect(document.activeElement).not.toBe(input);+ });++ it('leaves a named page alone', () => {+ const { input } = setup({ content: '', title: 'Plans' });++ expect(document.activeElement).not.toBe(input);+ });++ it('does not take the keyboard from another field', () => {+ const other = document.createElement('input');+ document.body.append(other);+ other.focus();++ setup({ content: '', title: 'Untitled' });++ expect(document.activeElement).toBe(other);+ });++ // The sidebar's "New page" entry closes its menu after the page opens, and+ // the menu hands focus back to the button it was opened from.+ it('takes the title back when focus is handed to the button it was opened from', async () => {+ const { input } = setup({ content: '', title: 'Untitled' });++ createButton().focus();+ await settle();++ expect(document.activeElement).toBe(input);+ expect([input.selectionStart, input.selectionEnd]).toEqual([0, 'Untitled'.length]);+ });++ it('lets the user move the focus away', async () => {+ setup({ content: '', title: 'Untitled' });+ const button = createButton();++ button.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ button.focus();+ await settle();++ expect(document.activeElement).toBe(button);+ });++ it('takes the title from a field that focused itself after the page opened', async () => {+ const { input, rerender } = setup({ content: '', documentLoaded: false, title: 'Untitled' });+ // A side panel auto-focuses its input while the page is still loading.+ const panelInput = document.createElement('input');+ document.body.append(panelInput);+ panelInput.focus();++ mockDocumentState.current = { documents: { 'doc-1': { content: '' } } };+ rerender();+ await settle();++ expect(document.activeElement).toBe(input);+ });++ it('decides only once the title has arrived', async () => {+ const { input, store } = setup({ content: '', titleUnknown: true });+ expect(document.activeElement).not.toBe(input);++ input.value = 'Untitled';+ act(() => store.getState().initMeta('Untitled'));+ await settle();++ expect(document.activeElement).toBe(input);+ });+});++describe('holdTitleFocus', () => {+ it('stops holding the title after a moment', async () => {+ const input = document.createElement('textarea');+ document.body.append(input);+ const open = { documentId: 'doc-1', focusedAtOpen: null, interacted: false };++ holdTitleFocus(input, open, 1);+ expect(document.activeElement).toBe(input);+ await settle();++ const button = createButton();+ button.focus();+ await settle();++ expect(document.activeElement).toBe(button);+ });+});++describe('splitTitleAtSelection', () => {+ it('drops the selected text and splits around it', () => {+ expect(splitTitleAtSelection('Hello big world', 6, 9)).toEqual({+ body: ' world',+ title: 'Hello ',+ });+ });+});++describe('isUnstartedPage', () => {+ it('recognises the default title in the current language or English', () => {+ expect(isUnstartedPage('ζ ζ ι’', '', 'ζ ζ ι’')).toBe(true);+ expect(isUnstartedPage('Untitled', ' ', 'ζ ζ ι’')).toBe(true);+ expect(isUnstartedPage('Untitled', 'body', 'ζ ζ ι’')).toBe(false);+ expect(isUnstartedPage('Plans', '', 'ζ ζ ι’')).toBe(false);+ expect(isUnstartedPage(undefined, '', 'ζ ζ ι’')).toBe(false);+ });+});diff --git a/src/features/PageEditor/usePageTitleInteractions.ts b/src/features/PageEditor/usePageTitleInteractions.tsnew file mode 100644index 00000000000..5298f129788--- /dev/null+++ b/src/features/PageEditor/usePageTitleInteractions.ts@@ -0,0 +1,310 @@+'use client';++import {+ type ChangeEvent,+ type KeyboardEvent,+ type RefObject,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from 'react';+import { useTranslation } from 'react-i18next';++import {+ focusEditorFirstLine,+ getWritableLexicalEditor,+} from '@/features/EditorCanvas/focusEditorStartLine';+import { useDocumentStore } from '@/store/document';+import { editorSelectors } from '@/store/document/slices/editor';+import { truncateByWeightedLength } from '@/utils/textLength';++import { usePageEditorStore } from './store';+import {+ findPageTitleInput,+ flattenTitleLineBreaks,+ shouldTitleArrowDownEnterBody,+} from './titleBodyNavigation';+import { usePageEditable } from './usePageEditable';++/** Shown in the icon picker while it is open on a page that has no icon yet. */+export const DEFAULT_PAGE_EMOJI = 'π';++/** Title a new page is created with (see `pageList.untitled`), in any language it was created in. */+const DEFAULT_UNTITLED_TITLE = 'Untitled';++const TITLE_MAX_WEIGHTED_LENGTH = 100;++// Enter that confirms an IME candidate (Chinese/Japanese input) must not submit+// the title: moving focus to the body mid-composition commits the text there too.+// Safari reports the confirming keydown with isComposing=false but keyCode 229.+export const isTitleSubmitKey = (e: {+ key: string;+ keyCode?: number;+ nativeEvent?: { isComposing?: boolean };+}) => e.key === 'Enter' && !e.nativeEvent?.isComposing && e.keyCode !== 229;++const isTitleArrowDownKey = (e: KeyboardEvent<HTMLTextAreaElement>) =>+ e.key === 'ArrowDown' &&+ !e.shiftKey &&+ !e.altKey &&+ !e.metaKey &&+ !e.ctrlKey &&+ !e.nativeEvent.isComposing;++/**+ * Split the title at the caret for Enter: the text before the selection stays+ * the title, the text after it moves to the body (the selection itself is+ * replaced, as Enter would in any text field).+ */+export const splitTitleAtSelection = (+ value: string,+ selectionStart: number,+ selectionEnd: number,+) => ({ body: value.slice(selectionEnd), title: value.slice(0, selectionStart) });++/**+ * A page still carrying the title it was created with and an empty body is a+ * page nobody has started yet.+ */+export const isUnstartedPage = (+ title: string | undefined,+ content: string,+ untitledTitle: string,+) => {+ const trimmed = title?.trim();+ if (!trimmed || content.trim()) return false;+ return trimmed === untitledTitle || trimmed === DEFAULT_UNTITLED_TITLE;+};++const isEditableElement = (element: Element | null): element is HTMLElement =>+ element instanceof HTMLInputElement ||+ element instanceof HTMLTextAreaElement ||+ element instanceof HTMLSelectElement ||+ (element instanceof HTMLElement && element.isContentEditable);++/** What had focus when a page was opened, and whether the user acted since. */+export interface PageOpenState {+ documentId: string;+ focusedAtOpen: Element | null;+ interacted: boolean;+}++/** How long a just-opened page keeps its title focus against programmatic moves. */+export const TITLE_FOCUS_HOLD_MS = 1500;++/**+ * Focus and select the title, and hold that focus for a moment: while the page+ * settles, other code may move focus programmatically β a menu handing focus+ * back to the "New page" button it closed from, a side panel auto-focusing its+ * input. Until the user presses a key or a pointer, such a move is undone.+ * Returns a function that stops holding.+ */+export const holdTitleFocus = (+ input: HTMLTextAreaElement,+ open: PageOpenState,+ durationMs = TITLE_FOCUS_HOLD_MS,+) => {+ let released = false;+ const claim = () => {+ input.focus();+ input.select();+ };++ const onFocusOut = () => {+ // Look once the focus has landed wherever it is going.+ setTimeout(() => {+ if (released || open.interacted || !input.isConnected) return;+ if (document.activeElement !== input) claim();+ }, 0);+ };++ const release = () => {+ released = true;+ input.removeEventListener('focusout', onFocusOut);+ clearTimeout(timer);+ };++ claim();+ input.addEventListener('focusout', onFocusOut);+ const timer = setTimeout(release, durationMs);+ return release;+};++/**+ * Behaviour of the page title and its icon, following AFFiNE's doc title:+ * - Enter splits the title at the caret; the rest continues as the body's first line.+ * - ArrowDown moves into the body once there is no title line below the caret.+ * - The title stays one line: line breaks that reach it become spaces.+ * - A page nobody has started yet opens with its default title selected.+ * - "Choose icon" previews the default icon but saves only a picked one.+ *+ * `containerRef` holds the title input.+ */+export const usePageTitleInteractions = (containerRef: RefObject<HTMLElement | null>) => {+ const { t } = useTranslation('file');++ const documentId = usePageEditorStore((s) => s.documentId);+ // Gate the title/emoji on the same state as the body editor: edit permission+ // AND not locked by another member (nor pending / save-blocked). The lock makes+ // the whole page read-only, so metadata must not stay editable behind it.+ // `metaReadOnly` additionally locks just the meta (title + emoji) while leaving+ // the body editable β used for managed docs like a skill's `SKILL.md` index,+ // whose identity is renamed through skill APIs, never a plain title save.+ const isMetaReadOnly = usePageEditorStore((s) => s.metaReadOnly);+ const bodyEditable = usePageEditable();+ const canEdit = bodyEditable && !isMetaReadOnly;+ const editor = usePageEditorStore((s) => s.editor);+ const emoji = usePageEditorStore((s) => s.emoji);+ const title = usePageEditorStore((s) => s.title);+ const setEmoji = usePageEditorStore((s) => s.setEmoji);+ const setTitle = usePageEditorStore((s) => s.setTitle);+ const handleTitleSubmit = usePageEditorStore((s) => s.handleTitleSubmit);+ const flushMetaSave = usePageEditorStore((s) => s.flushMetaSave);+ const isDocumentLoading = useDocumentStore(editorSelectors.isDocumentLoading(documentId));+ const content = useDocumentStore((s) =>+ documentId ? editorSelectors.content(documentId)(s) : '',+ );++ const [showEmojiPicker, setShowEmojiPicker] = useState(false);++ // Caret to put back after line breaks were flattened out of the typed value:+ // writing the cleaned value into the textarea moves its caret to the end.+ const pendingCaretRef = useRef<number | null>(null);+ const autoFocusCheckedRef = useRef<string | undefined>(undefined);+ const pageOpenRef = useRef<PageOpenState | undefined>(undefined);+ const releaseTitleFocusRef = useRef<(() => void) | undefined>(undefined);++ // Record what had focus when this page was opened, and whether the user has+ // pressed a key or a pointer since: the user's own focus is never taken.+ useEffect(() => {+ if (!documentId) return;++ const open: PageOpenState = {+ documentId,+ focusedAtOpen: document.activeElement,+ interacted: false,+ };+ pageOpenRef.current = open;+ const markInteracted = () => {+ open.interacted = true;+ };+ document.addEventListener('pointerdown', markInteracted, true);+ document.addEventListener('keydown', markInteracted, true);++ return () => {+ document.removeEventListener('pointerdown', markInteracted, true);+ document.removeEventListener('keydown', markInteracted, true);+ releaseTitleFocusRef.current?.();+ releaseTitleFocusRef.current = undefined;+ };+ }, [documentId]);++ useLayoutEffect(() => {+ const caret = pendingCaretRef.current;+ if (caret === null) return;+ pendingCaretRef.current = null;+ findPageTitleInput(containerRef.current)?.setSelectionRange(caret, caret);+ }, [containerRef, title]);++ // A page nobody has started yet (just created: default title, empty body)+ // opens with its title focused and selected, so typing names it straight+ // away instead of first deleting the placeholder title. Decided once, the+ // first moment the page and its title are loaded and writable β never later,+ // when the user may be typing.+ useEffect(() => {+ if (!documentId || isDocumentLoading || !canEdit || title === undefined) return;+ if (autoFocusCheckedRef.current === documentId) return;++ const input = findPageTitleInput(containerRef.current);+ if (!input) return;+ autoFocusCheckedRef.current = documentId;++ if (!isUnstartedPage(title, content, t('pageList.untitled'))) return;++ const open = pageOpenRef.current;+ if (!open || open.documentId !== documentId || open.interacted) return;+ // The user was in another field when they opened the page, and still is.+ const active = document.activeElement;+ if (active !== input && active === open.focusedAtOpen && isEditableElement(active)) return;++ releaseTitleFocusRef.current = holdTitleFocus(input, open);+ }, [canEdit, containerRef, content, documentId, isDocumentLoading, t, title]);++ const handleTitleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {+ if (!canEdit) return;++ const raw = e.target.value;+ const flattened = flattenTitleLineBreaks(raw);+ const truncated = truncateByWeightedLength(flattened, TITLE_MAX_WEIGHTED_LENGTH);+ if (flattened !== raw) {+ const caret = flattenTitleLineBreaks(raw.slice(0, e.target.selectionEnd)).length;+ pendingCaretRef.current = Math.min(caret, truncated.length);+ }++ setTitle(truncated);+ };++ // Read at key time: the body mounts after its content loads, which no render+ // of the title is told about.+ const isBodyReady = () => !isDocumentLoading && !!getWritableLexicalEditor(editor);++ const handleTitleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {+ if (isTitleArrowDownKey(e)) {+ if (!bodyEditable || !isBodyReady()) return;+ if (!shouldTitleArrowDownEnterBody(e.currentTarget)) return;+ e.preventDefault();+ focusEditorFirstLine(editor);+ return;+ }++ if (!canEdit || !isTitleSubmitKey(e)) return;++ e.preventDefault();+ // Splitting moves the text after the caret into the body. Until the body+ // can take it, keep the whole title and only save it.+ if (!isBodyReady()) {+ flushMetaSave();+ return;+ }++ const { selectionEnd, selectionStart, value } = e.currentTarget;+ const split = splitTitleAtSelection(value, selectionStart, selectionEnd);+ if (split.title !== value) setTitle(split.title);+ handleTitleSubmit(split.body);+ };++ const emojiPicker = {+ onChange: (next: string) => {+ if (!canEdit) return;+ setEmoji(next);+ setShowEmojiPicker(false);+ },+ onDelete: () => {+ if (!canEdit) return;+ setEmoji(undefined);+ setShowEmojiPicker(false);+ },+ // Opening it on a page without an icon only previews the default icon.+ onOpen: () => {+ if (!canEdit) return;+ setShowEmojiPicker(true);+ },+ onOpenChange: (open: boolean) => {+ if (!canEdit) return;+ setShowEmojiPicker(open);+ },+ open: showEmojiPicker,+ value: emoji || (showEmojiPicker ? DEFAULT_PAGE_EMOJI : undefined),+ visible: !!emoji || showEmojiPicker,+ };++ return {+ canEdit,+ emojiPicker,+ handleTitleChange,+ handleTitleKeyDown,+ showTitleSkeleton: isDocumentLoading && !title,+ title,+ };+};