🤯 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
🐛 fix(task): move the caret to the instruction on title Enter (#22118)
Rdmclin2467cfac3bbb2
diff --git a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsxindex 865070315d5..dfe75f8055e 100644--- a/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx+++ b/src/features/AgentTasks/CreateTaskModal/CreateTaskContent.tsx@@ -324,6 +324,7 @@ const CreateTaskContent = memo<CreateTaskContentProps>(<div style={{ minHeight: 0, overflowY: 'auto' }}><div style={{ minHeight: 144, padding: '0 24px' }}><EditorCanvas+ blockImageCaretGuarddisabled={!canCreateTask}editor={editor}floatingToolbar={false}diff --git a/src/features/EditorCanvas/EditorCanvas.tsx b/src/features/EditorCanvas/EditorCanvas.tsxindex 999b5b9e083..5567e47e42d 100644--- a/src/features/EditorCanvas/EditorCanvas.tsx+++ b/src/features/EditorCanvas/EditorCanvas.tsx@@ -52,7 +52,9 @@ export interface EditorCanvasProps {/*** Keep the caret out of Lexical's root node around block images by pushing* an empty paragraph next to the image (otherwise a horizontal root-level- * caret shows above / below it). Off by default; comment editors opt in.+ * caret shows above / below it), and let a click in an image's row or+ * typing with the image selected continue on the line after it. Off by+ * default; comment editors and the create-task modal opt in.*/blockImageCaretGuard?: boolean;diff --git a/src/features/EditorCanvas/InternalEditor.tsx b/src/features/EditorCanvas/InternalEditor.tsxindex b15c95fd918..62e46a5755d 100644--- a/src/features/EditorCanvas/InternalEditor.tsx+++ b/src/features/EditorCanvas/InternalEditor.tsx@@ -30,6 +30,7 @@ import InlineToolbar from './InlineToolbar';import LinearFilePlugin from './LinearFilePlugin';import { registerAttachmentClickOpen } from './registerAttachmentClickOpen';import { registerBlockDecoratorCaretGuard } from './registerBlockDecoratorCaretGuard';+import { registerBlockDecoratorClickToWrite } from './registerBlockDecoratorClickToWrite';import { registerImageFilePastePreference } from './registerImageFilePastePreference';import { needsImageRehost, rehostImage } from './rehostImage';import { useFileUpload, useImageUpload } from './useImageUpload';@@ -296,13 +297,19 @@ const InternalEditor = memo<InternalEditorProps>(return () => unregister?.();}, [editor]);- // Opt-in (comment editors): keep the caret out of the root node around+ // Opt-in (comment / task editors): keep the caret out of the root node around// block images by pushing an empty paragraph next to the image instead of// showing Lexical's horizontal root-level caret.useEffect(() => {if (!editor || !blockImageCaretGuard) return;- const unregister = registerBlockDecoratorCaretGuard(editor);- return () => unregister?.();+ const unregisterGuard = registerBlockDecoratorCaretGuard(editor);+ // A click in a block image's row, or typing with the image selected,+ // continues writing on the line after it.+ const unregisterClick = registerBlockDecoratorClickToWrite(editor);+ return () => {+ unregisterGuard?.();+ unregisterClick?.();+ };}, [blockImageCaretGuard, editor]);const onInitRef = useRef(onInit);diff --git a/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.test.ts b/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.test.tsnew file mode 100644index 00000000000..2acd958bad5--- /dev/null+++ b/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.test.ts@@ -0,0 +1,241 @@+/**+ * @vitest-environment happy-dom+ */+import {+ $createNodeSelection,+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ $setSelection,+ createEditor,+ DecoratorNode,+ type LexicalEditor,+} from 'lexical';+import { afterEach, describe, expect, it } from 'vitest';++import { registerBlockDecoratorClickToWriteOnLexical } from './registerBlockDecoratorClickToWrite';++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() {+ const wrapper = document.createElement('div');+ wrapper.append(document.createElement('img'));+ return wrapper;+ }++ updateDOM() {+ return false;+ }++ decorate() {+ return null;+ }+}++const commit = (editor: LexicalEditor, fn: () => void) =>+ new Promise<void>((resolve) => {+ editor.update(fn, { onUpdate: resolve });+ });++/** Let queued microtasks and follow-up updates settle. */+const settle = () =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, 0);+ });++/**+ * The create-task modal after pasting an image: the body holds only the image+ * (and optionally a line after it), and the user has moved on to the title.+ */+const setup = async ({ lineAfter = false } = {}) => {+ const root = document.createElement('div');+ root.contentEditable = 'true';+ const title = document.createElement('input');+ document.body.append(title, root);++ const editor = createEditor({+ nodes: [FakeImageNode],+ onError: (e) => {+ throw e;+ },+ });+ editor.setRootElement(root);+ registerBlockDecoratorClickToWriteOnLexical(editor);++ let imageKey = '';+ await commit(editor, () => {+ const image = new FakeImageNode();+ imageKey = image.getKey();+ $getRoot().append(image);+ if (lineAfter) $getRoot().append($createParagraphNode().append($createTextNode('after')));+ });++ title.focus();+ title.select();++ const imageWrapper = root.querySelector('[data-lexical-decorator]') as HTMLElement;+ return { editor, imageKey, imageWrapper, root, title };+};++const selectImage = (editor: LexicalEditor, key: string) =>+ commit(editor, () => {+ const selection = $createNodeSelection();+ selection.add(key);+ $setSelection(selection);+ });++const readBody = (editor: LexicalEditor) => {+ let types: string[] = [];+ let caret: { offset: number; text: string; type: string } | undefined;+ let texts: string[] = [];+ editor.getEditorState().read(() => {+ const children = $getRoot().getChildren();+ types = children.map((child) => child.getType());+ texts = children.map((child) => child.getTextContent());+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ const block = selection.anchor.getNode().getTopLevelElementOrThrow();+ caret = {+ offset: selection.anchor.offset,+ text: block.getTextContent(),+ type: block.getType(),+ };+ }+ });+ return { caret, texts, types };+};++afterEach(() => {+ document.body.innerHTML = '';+});++describe('registerBlockDecoratorClickToWriteOnLexical', () => {+ it('a click beside the image opens a line after it and takes focus from the title', async () => {+ const { editor, imageWrapper, root } = await setup();++ imageWrapper.dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ await settle();++ expect(document.activeElement).toBe(root);+ expect(readBody(editor)).toMatchObject({+ caret: { text: '', type: 'paragraph' },+ types: ['fake-image', 'paragraph'],+ });+ });++ it('a click beside the image reuses the line already after it', async () => {+ const { editor, imageWrapper } = await setup({ lineAfter: true });++ imageWrapper.dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ await settle();++ expect(readBody(editor)).toMatchObject({+ caret: { offset: 0, text: 'after' },+ types: ['fake-image', 'paragraph'],+ });+ });++ // The real image stops the click from bubbling, so only a capture listener+ // on the root sees it. Without taking focus, keys kept going to the title.+ it('a click on the image itself still takes focus even when the image stops the click', async () => {+ const { editor, imageWrapper, root } = await setup();+ const img = imageWrapper.querySelector('img')!;+ img.addEventListener('click', (e) => e.stopPropagation());++ img.dispatchEvent(new MouseEvent('click', { bubbles: true, button: 0 }));+ await settle();++ expect(document.activeElement).toBe(root);+ // The image stays the thing selected; no line is opened by the click itself.+ expect(readBody(editor).types).toEqual(['fake-image']);+ });++ it('typing a character while the image is selected continues on the line after it', async () => {+ const { editor, imageKey, root } = await setup();+ await selectImage(editor, imageKey);++ root.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'a' }));+ await settle();++ expect(readBody(editor)).toMatchObject({+ caret: { text: '', type: 'paragraph' },+ types: ['fake-image', 'paragraph'],+ });+ });++ it('starting an IME composition while the image is selected also moves the caret', async () => {+ const { editor, imageKey, root } = await setup();+ await selectImage(editor, imageKey);++ root.dispatchEvent(+ new KeyboardEvent('keydown', { bubbles: true, key: 'Process', keyCode: 229 }),+ );+ await settle();++ expect(readBody(editor).caret?.type).toBe('paragraph');+ });++ it('leaves shortcuts and deletion keys to the editor', async () => {+ const { editor, imageKey, root } = await setup();+ await selectImage(editor, imageKey);++ root.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'c', metaKey: true }));+ root.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Shift' }));+ await settle();++ expect(readBody(editor)).toMatchObject({ caret: undefined, types: ['fake-image'] });+ });++ it('writes inserted text that arrives without a keydown on the line after the image, once', async () => {+ const { editor, imageKey, root } = await setup();+ await selectImage(editor, imageKey);++ const event = new InputEvent('beforeinput', {+ bubbles: true,+ cancelable: true,+ data: '中',+ inputType: 'insertText',+ });+ let reachedLexical = false;+ root.addEventListener('beforeinput', () => (reachedLexical = true));+ root.dispatchEvent(event);+ await settle();++ expect(event.defaultPrevented).toBe(true);+ expect(reachedLexical).toBe(false);+ expect(readBody(editor)).toMatchObject({+ caret: { offset: 1, text: '中' },+ texts: ['', '中'],+ });+ });++ it('does nothing to typing when no image is selected', async () => {+ const { editor, root } = await setup({ lineAfter: true });+ await commit(editor, () => $getRoot().getLastChildOrThrow().selectEnd());++ root.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'a' }));+ await settle();++ expect(readBody(editor)).toMatchObject({+ caret: { offset: 5, text: 'after' },+ types: ['fake-image', 'paragraph'],+ });+ });+});diff --git a/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.ts b/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.tsnew file mode 100644index 00000000000..691a4382e19--- /dev/null+++ b/src/features/EditorCanvas/registerBlockDecoratorClickToWrite.ts@@ -0,0 +1,152 @@+import type { IEditor } from '@lobehub/editor';+import {+ $createParagraphNode,+ $getNearestNodeFromDOMNode,+ $getSelection,+ $isDecoratorNode,+ $isElementNode,+ $isNodeSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_LOW,+ type DecoratorNode,+ KEY_DOWN_COMMAND,+ type LexicalEditor,+ type LexicalNode,+ mergeRegister,+} from 'lexical';++const $isBlockDecorator = (node: LexicalNode | null | undefined): node is DecoratorNode<unknown> =>+ $isDecoratorNode(node) && !node.isInline();++/**+ * Put the caret at the start of the line after a block decorator, opening an+ * empty line there when the next block is not a text line.+ */+export const $selectLineAfterBlockDecorator = (decorator: LexicalNode): void => {+ const next = decorator.getNextSibling();+ if ($isElementNode(next) && !next.isInline()) {+ next.selectStart();+ return;+ }++ const paragraph = $createParagraphNode();+ decorator.insertAfter(paragraph);+ paragraph.selectStart();+};++/** The one block decorator a node selection holds, if that is all it holds. */+const $getSelectedBlockDecorator = (): DecoratorNode<unknown> | null => {+ const selection = $getSelection();+ if (!$isNodeSelection(selection)) return null;+ const nodes = selection.getNodes();+ return nodes.length === 1 && $isBlockDecorator(nodes[0]) ? nodes[0] : null;+};++/** A key that starts writing text: a printable character, or an IME composition. */+const isWritingKey = (event: KeyboardEvent): boolean => {+ if (event.ctrlKey || event.metaKey || event.altKey) return false;+ if (event.isComposing || event.keyCode === 229 || event.key === 'Process') return true;+ return event.key.length === 1;+};++/** Exported for tests, which drive a bare Lexical editor without the kernel. */+export const registerBlockDecoratorClickToWriteOnLexical = (lexicalEditor: LexicalEditor) => {+ const onClick = (event: MouseEvent) => {+ if (!lexicalEditor.isEditable() || event.button !== 0) return;+ const target = event.target;+ if (!(target instanceof Element)) return;+ const decoratorElement = target.closest('[data-lexical-decorator]');+ const rootElement = lexicalEditor.getRootElement();+ if (!decoratorElement || !rootElement || decoratorElement.parentElement !== rootElement) return;++ // The decorator is contenteditable=false, so the click neither focuses the+ // editor nor moves the browser caret: a caret left in another field (the+ // task title) keeps receiving the keys typed next. Take both over here.+ if (document.activeElement !== rootElement) rootElement.focus({ preventScroll: true });+ const domSelection = window.getSelection();+ if (domSelection?.anchorNode && !rootElement.contains(domSelection.anchorNode)) {+ domSelection.removeAllRanges();+ }++ // A click on the block itself (the image) keeps selecting it. A click on+ // the blank part of its row means "write here": continue on the next line.+ if (target !== decoratorElement) return;+ lexicalEditor.update(() => {+ const node = $getNearestNodeFromDOMNode(decoratorElement);+ if ($isBlockDecorator(node)) $selectLineAfterBlockDecorator(node);+ });+ };++ // Text that arrives without a writing keydown first (autofill-like input,+ // some IME paths) would also be dropped on a selected image; write it on+ // the line after the image instead.+ const onBeforeInput = (event: InputEvent) => {+ if (event.inputType !== 'insertText' || !event.data) return;+ const data = event.data;+ // A non-cancelable insert (IME commit) is written by the browser anyway, at+ // the caret we move here; only a cancelable one is ours to write.+ const writeHere = event.cancelable;+ let handled = false;+ lexicalEditor.update(+ () => {+ const decorator = $getSelectedBlockDecorator();+ if (!decorator) return;+ handled = true;+ $selectLineAfterBlockDecorator(decorator);+ const selection = $getSelection();+ if (writeHere && $isRangeSelection(selection)) selection.insertText(data);+ },+ { discrete: true },+ );+ if (!handled || !writeHere) return;+ // Lexical's own before-input handler would queue the same text again.+ event.preventDefault();+ event.stopImmediatePropagation();+ };++ return mergeRegister(+ lexicalEditor.registerRootListener((rootElement, prevRootElement) => {+ // Capture: the image stops the click from bubbling up to the root, and+ // the before-input fallback must run before Lexical's own handler.+ prevRootElement?.removeEventListener('click', onClick, true);+ prevRootElement?.removeEventListener('beforeinput', onBeforeInput, true);+ rootElement?.addEventListener('click', onClick, true);+ rootElement?.addEventListener('beforeinput', onBeforeInput, true);+ }),+ // Typing while a block image is selected would otherwise write nothing:+ // a node selection has no caret. Move the caret to the line after it before+ // the browser turns the key into input, so plain keys and IME input both+ // land there through the editor's normal input path.+ lexicalEditor.registerCommand(+ KEY_DOWN_COMMAND,+ (event) => {+ if (!isWritingKey(event) || !$getSelectedBlockDecorator()) return false;+ queueMicrotask(() => {+ lexicalEditor.update(+ () => {+ const decorator = $getSelectedBlockDecorator();+ if (decorator) $selectLineAfterBlockDecorator(decorator);+ },+ { discrete: true },+ );+ });+ return false;+ },+ COMMAND_PRIORITY_LOW,+ ),+ );+};++/**+ * Let a click anywhere in a block image's row lead to writing:+ *+ * 1. The click takes focus and the browser caret from whatever field had them,+ * so keys no longer go back to e.g. the task title (T-2690).+ * 2. A click beside the image puts the caret on the line after it.+ * 3. Typing while the image itself is selected continues on the line after it.+ */+export const registerBlockDecoratorClickToWrite = (editor: IEditor): (() => void) | undefined => {+ const lexicalEditor = editor.getLexicalEditor?.();+ if (!lexicalEditor) return;+ return registerBlockDecoratorClickToWriteOnLexical(lexicalEditor);+};diff --git a/src/features/EditorCanvas/releaseEditorSelection.test.ts b/src/features/EditorCanvas/releaseEditorSelection.test.tsindex 8fece68a7da..a3f5e4a594b 100644--- a/src/features/EditorCanvas/releaseEditorSelection.test.ts+++ b/src/features/EditorCanvas/releaseEditorSelection.test.ts@@ -11,6 +11,7 @@ import {} from 'lexical';import { afterEach, describe, expect, it } from 'vitest';+import { selectEditorStartLineOnLexical } from './focusEditorStartLine';import { releaseEditorSelectionOnLexical } from './releaseEditorSelection';const commit = (editor: LexicalEditor, fn: () => void) =>@@ -81,4 +82,20 @@ describe('releaseEditorSelectionOnLexical', () => {expect(selectionInside(root)).toBe(true);});++ // Enter in the title hands the caret to the instruction. Releasing must not+ // leave anything behind that stops that later selection from reaching the DOM,+ // or focus stays in the title (T-2690).+ it('lets a later selection reach the DOM after releasing', async () => {+ const { editor, root } = await setup();++ releaseEditorSelectionOnLexical(editor);+ await commit(editor, () => undefined);+ await new Promise<void>((resolve) => {+ selectEditorStartLineOnLexical(editor);+ editor.update(() => undefined, { onUpdate: resolve });+ });++ expect(selectionInside(root)).toBe(true);+ });});diff --git a/src/features/EditorCanvas/releaseEditorSelection.ts b/src/features/EditorCanvas/releaseEditorSelection.tsindex 4570e593e95..ca4581910a0 100644--- a/src/features/EditorCanvas/releaseEditorSelection.ts+++ b/src/features/EditorCanvas/releaseEditorSelection.ts@@ -1,11 +1,15 @@import type { IEditor } from '@lobehub/editor';-import { $setSelection, type LexicalEditor, SKIP_DOM_SELECTION_TAG } from 'lexical';+import { $setSelection, type LexicalEditor } from 'lexical';/** Exported for tests, which drive a bare Lexical editor without the kernel. */export const releaseEditorSelectionOnLexical = (lexicalEditor: LexicalEditor): void => {- // The tag keeps this update from touching the DOM selection, which already- // belongs to the field the user moved to.- lexicalEditor.update(() => $setSelection(null), { tag: SKIP_DOM_SELECTION_TAG });+ // No update tag here. This update changes no nodes, and Lexical only clears an+ // update's tags when nodes changed, so a tag such as `skip-dom-selection` would+ // stick to the next content update instead: Enter in the title would then set+ // a caret Lexical never writes to the DOM, and focus would stay in the title.+ // Untagged is safe: with no selection, Lexical only clears a DOM selection that+ // is still inside the editor, and the field the user moved to already owns it.+ lexicalEditor.update(() => $setSelection(null));};/**