Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chg(mg): normalize enter handling with element and inline styles, improve right arrow escape (#4449)
Seamuscf4a54b61772
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.test.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.test.tsnew file mode 100644index 0000000000..bc6918b87f--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.test.ts@@ -0,0 +1,205 @@+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isRangeSelection,+ createEditor,+ KEY_ARROW_RIGHT_COMMAND,+ type LexicalEditor,+ ParagraphNode,+ TextNode,+} from 'lexical';+import { describe, expect, test } from 'vitest';+import { keyboardShortcutsPlugin } from './keyboardShortcutsPlugin';++function createTestEditor(): LexicalEditor {+ const editor = createEditor({+ namespace: 'keyboard-shortcuts-plugin-test',+ nodes: [ParagraphNode, TextNode],+ onError: (error) => {+ throw error;+ },+ });++ const root = document.createElement('div');+ root.contentEditable = 'true';+ document.body.appendChild(root);+ editor.setRootElement(root);+ keyboardShortcutsPlugin({ shortcuts: [] })(editor);++ return editor;+}++describe('keyboardShortcutsPlugin', () => {+ test('right arrow escapes inline code and inserts a trailing space', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const codeText = $createTextNode('code').setFormat('code');+ paragraph.append(codeText);+ $getRoot().clear().append(paragraph);+ codeText.select(4, 4);++ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.setFormat(codeText.getFormat());+ }+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ARROW_RIGHT_COMMAND,+ new KeyboardEvent('keydown', { key: 'ArrowRight' })+ );++ editor.read(() => {+ expect($getRoot().getTextContent()).toBe('code ');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.hasFormat('code')).toBe(false);+ expect(selection.anchor.getNode().getTextContent()).toBe(' ');+ expect(selection.anchor.offset).toBe(1);+ });+ });++ test('right arrow escapes inline code and moves past an existing trailing space', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const codeText = $createTextNode('code').setFormat('code');+ const spaceText = $createTextNode(' ');+ paragraph.append(codeText, spaceText);+ $getRoot().clear().append(paragraph);+ codeText.select(4, 4);++ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.setFormat(codeText.getFormat());+ }+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ARROW_RIGHT_COMMAND,+ new KeyboardEvent('keydown', { key: 'ArrowRight' })+ );++ editor.read(() => {+ expect($getRoot().getTextContent()).toBe('code ');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.hasFormat('code')).toBe(false);+ expect(selection.anchor.getNode().getTextContent()).toBe(' ');+ expect(selection.anchor.offset).toBe(1);+ });+ });++ test('right arrow inserts a space when the caret is at the start of text after inline code', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const codeText = $createTextNode('code').setFormat('code');+ const nextText = $createTextNode('after');+ paragraph.append(codeText, nextText);+ $getRoot().clear().append(paragraph);+ nextText.select(0, 0);+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ARROW_RIGHT_COMMAND,+ new KeyboardEvent('keydown', { key: 'ArrowRight' })+ );++ editor.read(() => {+ expect($getRoot().getTextContent()).toBe('code after');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.anchor.getNode().getTextContent()).toBe(' after');+ expect(selection.anchor.offset).toBe(1);+ });+ });++ test('right arrow moves past a space from an element boundary after inline code', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const codeText = $createTextNode('code').setFormat('code');+ const spaceText = $createTextNode(' ');+ paragraph.append(codeText, spaceText);+ $getRoot().clear().append(paragraph);+ paragraph.select(1, 1);+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ARROW_RIGHT_COMMAND,+ new KeyboardEvent('keydown', { key: 'ArrowRight' })+ );++ editor.read(() => {+ expect($getRoot().getTextContent()).toBe('code ');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.anchor.getNode().getTextContent()).toBe(' ');+ expect(selection.anchor.offset).toBe(1);+ });+ });++ test('right arrow inserts a space when selection format is clear at the end of inline code', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const codeText = $createTextNode('code').setFormat('code');+ paragraph.append(codeText);+ $getRoot().clear().append(paragraph);+ codeText.select(4, 4);++ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.setFormat(0);+ }+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ARROW_RIGHT_COMMAND,+ new KeyboardEvent('keydown', { key: 'ArrowRight' })+ );++ editor.read(() => {+ expect($getRoot().getTextContent()).toBe('code ');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.hasFormat('code')).toBe(false);+ expect(selection.anchor.getNode().getTextContent()).toBe(' ');+ expect(selection.anchor.offset).toBe(1);+ });+ });+});diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.tsindex 6cf3405644..a22971f669 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/keyboard-shortcuts/keyboardShortcutsPlugin.ts@@ -1,18 +1,21 @@import { IS_MAC } from '@core/constant/isMac';import { mergeRegister } from '@lexical/utils';import {+ $createTextNode,$getSelection,+ $isElementNode,$isRangeSelection,+ $isTextNode,COMMAND_PRIORITY_HIGH,COMMAND_PRIORITY_NORMAL,FORMAT_TEXT_COMMAND,KEY_ARROW_RIGHT_COMMAND,KEY_DOWN_COMMAND,type LexicalEditor,+ type LexicalNode,type RangeSelection,type TextFormatType,} from 'lexical';-import { $isAtEndOfTextNode } from '../../utils';const META_OR_CTRL = IS_MAC ? 'meta' : 'ctrl';@@ -28,6 +31,80 @@ const $shouldEscapeRight = (selection: RangeSelection) => {return escapableInlineFormats.some((format) => selection.hasFormat(format));};+const $hasEscapableInlineFormat = (node: LexicalNode | null | undefined) => {+ return (+ $isTextNode(node) &&+ escapableInlineFormats.some((format) => node.hasFormat(format))+ );+};++const $isAtEndOfTextNode = (selection: RangeSelection) => {+ if (!selection.isCollapsed()) return false;+ const focusNode = selection.focus.getNode();+ return (+ $isTextNode(focusNode) &&+ selection.focus.offset === focusNode.getTextContentSize()+ );+};++const $movePastSpaceOrInsertAfter = (+ leftNode: LexicalNode,+ rightNode: LexicalNode | null | undefined+) => {+ if ($isTextNode(rightNode) && rightNode.getTextContent().startsWith(' ')) {+ rightNode.select(1, 1);+ return;+ }++ const space = $createTextNode(' ');+ space.setFormat(0);+ space.setStyle('');+ leftNode.insertAfter(space);+ space.select(1, 1);+};++const $movePastAdjacentSpaceOrInsertOne = (selection: RangeSelection) => {+ const focusNode = selection.focus.getNode();+ if (!$isTextNode(focusNode)) return;+ $movePastSpaceOrInsertAfter(focusNode, focusNode.getNextSibling());+};++const $handleCaretAfterEscapableInlineFormat = (selection: RangeSelection) => {+ if (!selection.isCollapsed()) return false;++ const focusNode = selection.focus.getNode();+ if ($isTextNode(focusNode) && selection.focus.offset === 0) {+ const prevSibling = focusNode.getPreviousSibling();+ if (prevSibling && $hasEscapableInlineFormat(prevSibling)) {+ $movePastSpaceOrInsertAfter(prevSibling, focusNode);+ return true;+ }+ }++ if (+ selection.focus.type === 'element' &&+ $isElementNode(focusNode) &&+ selection.focus.offset > 0+ ) {+ const prevChild = focusNode.getChildAtIndex(selection.focus.offset - 1);+ const nextChild = focusNode.getChildAtIndex(selection.focus.offset);+ if (prevChild && $hasEscapableInlineFormat(prevChild)) {+ $movePastSpaceOrInsertAfter(prevChild, nextChild);+ return true;+ }+ }++ return false;+};++const $shouldEscapeRightAtEndOfTextNode = (selection: RangeSelection) => {+ if (!$isAtEndOfTextNode(selection)) return false;+ return (+ $shouldEscapeRight(selection) ||+ $hasEscapableInlineFormat(selection.focus.getNode())+ );+};+const metaOrCtrl = (meta: boolean, ctrl: boolean) => {return IS_MAC ? meta : ctrl;};@@ -72,13 +149,17 @@ function registerKeyboardShortcutsPlugin(if (!$isRangeSelection(selection) || !selection.isCollapsed()) {return false;}- if (!$shouldEscapeRight(selection)) return false;- if (!$isAtEndOfTextNode(selection)) return false;+ if ($handleCaretAfterEscapableInlineFormat(selection)) {+ e.preventDefault();+ return true;+ }+ if (!$shouldEscapeRightAtEndOfTextNode(selection)) return false;e.preventDefault();for (const format of escapableInlineFormats) {if (selection.hasFormat(format)) selection.toggleFormat(format);}+ $movePastAdjacentSpaceOrInsertOne(selection);return true;},COMMAND_PRIORITY_HIGHdiff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.test.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.test.tsnew file mode 100644index 0000000000..44c53f9fbf--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.test.ts@@ -0,0 +1,160 @@+import {+ $createHeadingNode,+ $isHeadingNode,+ HeadingNode,+ QuoteNode,+ registerRichText,+} from '@lexical/rich-text';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isParagraphNode,+ $isRangeSelection,+ createEditor,+ KEY_ENTER_COMMAND,+ type LexicalEditor,+ ParagraphNode,+ TextNode,+} from 'lexical';+import { describe, expect, test } from 'vitest';+import { normalizeEnterPlugin } from './normalizeEnterPlugin';++function createTestEditor(): LexicalEditor {+ const editor = createEditor({+ namespace: 'normalize-enter-plugin-test',+ nodes: [HeadingNode, ParagraphNode, QuoteNode, TextNode],+ onError: (error) => {+ throw error;+ },+ });++ const root = document.createElement('div');+ root.contentEditable = 'true';+ document.body.appendChild(root);+ editor.setRootElement(root);+ registerRichText(editor);+ normalizeEnterPlugin()(editor);++ return editor;+}++const waitForStyleCleanup = () =>+ new Promise((resolve) => {+ setTimeout(resolve, 0);+ });++describe('normalizeEnterPlugin', () => {+ test('splits heading text into a following paragraph', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const heading = $createHeadingNode('h2');+ const text = $createTextNode('HelloWorld');+ heading.append(text);+ $getRoot().clear().append(heading);+ text.select(5, 5);+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ENTER_COMMAND,+ new KeyboardEvent('keydown', { key: 'Enter' })+ );++ editor.read(() => {+ const children = $getRoot().getChildren();+ expect(children).toHaveLength(2);+ expect($isHeadingNode(children[0])).toBe(true);+ expect(children[0].getTextContent()).toBe('Hello');+ expect($isParagraphNode(children[1])).toBe(true);+ expect(children[1].getTextContent()).toBe('World');+ });+ });++ test('clears pending inline styles for an empty paragraph after a heading', () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const heading = $createHeadingNode('h2');+ const text = $createTextNode('Hello').setFormat('bold');+ heading.append(text);+ $getRoot().clear().append(heading);+ text.select(5, 5);++ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return;+ selection.setFormat(text.getFormat());+ selection.setStyle('color: red;');+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ENTER_COMMAND,+ new KeyboardEvent('keydown', { key: 'Enter' })+ );++ editor.read(() => {+ const children = $getRoot().getChildren();+ expect(children).toHaveLength(2);+ expect($isParagraphNode(children[1])).toBe(true);+ expect(children[1].getTextContent()).toBe('');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.anchor.getNode().getTopLevelElement()?.getKey()).toBe(+ children[1].getKey()+ );+ expect(selection.format).toBe(0);+ expect(selection.style).toBe('');+ });+ });++ test('clears pending inline styles for an empty paragraph after a paragraph', async () => {+ const editor = createTestEditor();++ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ const text = $createTextNode('Hello').setFormat('bold');+ paragraph.append(text);+ $getRoot().clear().append(paragraph);+ text.select(5, 5);++ const selection = $getSelection();+ if (!$isRangeSelection(selection)) return;+ selection.setFormat(text.getFormat());+ selection.setStyle('color: red;');+ },+ { discrete: true }+ );++ editor.dispatchCommand(+ KEY_ENTER_COMMAND,+ new KeyboardEvent('keydown', { key: 'Enter' })+ );+ await waitForStyleCleanup();++ editor.read(() => {+ const children = $getRoot().getChildren();+ expect(children).toHaveLength(2);+ expect($isParagraphNode(children[1])).toBe(true);+ expect(children[1].getTextContent()).toBe('');++ const selection = $getSelection();+ expect($isRangeSelection(selection)).toBe(true);+ if (!$isRangeSelection(selection)) return;+ expect(selection.anchor.getNode().getTopLevelElement()?.getKey()).toBe(+ children[1].getKey()+ );+ expect(selection.format).toBe(0);+ expect(selection.style).toBe('');+ });+ });+});diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.tsindex 7049fb9681..97431c622e 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/normalize-enter/normalizeEnterPlugin.ts@@ -1,4 +1,8 @@-import { $createQuoteNode, $isQuoteNode } from '@lexical/rich-text';+import {+ $createQuoteNode,+ $isHeadingNode,+ $isQuoteNode,+} from '@lexical/rich-text';import { mergeRegister } from '@lexical/utils';import {$createParagraphNode,@@ -11,12 +15,25 @@ import {COMMAND_PRIORITY_LOW,COMMAND_PRIORITY_NORMAL,type ElementNode,+ INSERT_PARAGRAPH_COMMAND,KEY_ENTER_COMMAND,type LexicalEditor,type RangeSelection,} from 'lexical';-import { isEmptyOrMatches } from '../../utils';+const isEmptyOrMatches = (str: string, regex: RegExp) =>+ str === '' || regex.test(str);++/**+ * Normalizes Enter behavior for the markdown editor:+ * - Enter in a heading creates a paragraph next, including when splitting a+ * heading in the middle.+ * - Enter at the start of a non-empty quote inserts a quote before it.+ * - Enter in an empty quote converts it back to a paragraph.+ * - Enter into an empty paragraph clears pending inline text format and style.+ * - Shift+Enter at the start of an empty paragraph falls back to a normal+ * paragraph split instead of inserting a line break.+ */function $testSelectionPosition(selection: RangeSelection,parent: ElementNode@@ -94,6 +111,74 @@ function $handleEnterAtBlockStart(): boolean {return false;}+function $clearInlineStylesIfEmptyParagraph(node: ElementNode): void {+ if (!$isParagraphNode(node) || node.getTextContent().trim() !== '') {+ return;+ }++ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.setFormat(0);+ selection.setStyle('');+ }+}++function $clearInlineStylesAtEmptyParagraphSelection(): void {+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !selection.isCollapsed()) {+ return;+ }++ const node = selection.anchor.getNode();+ const paragraph = $isParagraphNode(node) ? node : node.getTopLevelElement();+ if ($isElementNode(paragraph)) {+ $clearInlineStylesIfEmptyParagraph(paragraph);+ }+}++function scheduleInlineStyleCleanup(editor: LexicalEditor): void {+ setTimeout(() => {+ editor.update(() => {+ $clearInlineStylesAtEmptyParagraphSelection();+ });+ }, 0);+}++/**+ * Lexical keeps the heading type when a heading is split in the middle. Notion+ * always makes the next block a paragraph, including the split-off text.+ */+function $handleEnterFromHeading(): boolean {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ return false;+ }++ const anchorBlock = selection.anchor.getNode().getTopLevelElement();+ const focusBlock = selection.focus.getNode().getTopLevelElement();+ if (!$isHeadingNode(anchorBlock) || anchorBlock !== focusBlock) {+ return false;+ }++ const nextBlock = selection.insertParagraph();+ if (!$isElementNode(nextBlock)) {+ return false;+ }++ if ($isHeadingNode(nextBlock)) {+ const paragraph = $createParagraphNode();+ paragraph.setDirection(nextBlock.getDirection());+ paragraph.setIndent(nextBlock.getIndent());+ nextBlock.replace(paragraph, true);+ paragraph.selectStart();+ $clearInlineStylesIfEmptyParagraph(paragraph);+ return true;+ }++ $clearInlineStylesIfEmptyParagraph(nextBlock);+ return true;+}+function registerNormalizeEnterPlugin(editor: LexicalEditor) {return mergeRegister(editor.registerCommand(@@ -103,13 +188,27 @@ function registerNormalizeEnterPlugin(editor: LexicalEditor) {if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) {return false;}+ if ($handleEnterFromHeading()) {+ event.preventDefault();+ return true;+ }const res = $handleEnterAtBlockStart();if (res) event.preventDefault();+ else scheduleInlineStyleCleanup(editor);return res;},COMMAND_PRIORITY_NORMAL),+ editor.registerCommand(+ INSERT_PARAGRAPH_COMMAND,+ () => {+ scheduleInlineStyleCleanup(editor);+ return false;+ },+ COMMAND_PRIORITY_NORMAL+ ),+editor.registerCommand(KEY_ENTER_COMMAND,(e) => {