Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(md): fix selection after programmatic block node delete (#4284)

Seamus51903fbcfdc8
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/accessory/CodeBoxAccessory.tsx b/js/app/packages/core/component/LexicalMarkdown/component/accessory/CodeBoxAccessory.tsx
index 5939b41f6f..d38dedec6b 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/accessory/CodeBoxAccessory.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/accessory/CodeBoxAccessory.tsx
@@ -44,6 +44,7 @@ import {
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { glueToElement } from '../../directive/glueToElement';
+import { deleteCodeNode } from '../../plugins/code/deleteCodeNode';
import { autoRegister } from '../../plugins/shared/utils';
const LanguageIcons: Record<
@@ -194,11 +195,7 @@ export function CodeBoxAccessory(props: {
};
const deleteCode = () => {
- props.editor.update(() => {
- const node = $getNodeByKey(props.nodeKey);
- if (!$isCodeNode(node)) return;
- node.remove();
- });
+ deleteCodeNode(props.editor, props.nodeKey);
};
const setLanguageOnNode = (language: string) => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
index 46911318ba..ca93577559 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/DocumentCard.tsx
@@ -62,6 +62,7 @@ import { TaskPropertiesPreview } from '../../../DocumentPreview';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { floatWithElement } from '../../directive/floatWithElement';
import { UPDATE_DOCUMENT_NAME_COMMAND } from '../../plugins';
+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';
import { dispatchInternalLayoutShift } from '../../plugins/shared/utils';
import { BlockLink } from '../core/BlockLink';
import { ChannelMessageThreadCard } from './ChannelMessageThreadCard';
@@ -255,12 +256,13 @@ function DocumentCardInner(props: DocumentCardDecoratorProps) {
});
const deleteCard = () => {
- editor()?.update(() => {
- const node = $getNodeByKey(props.key);
- if (!$isDocumentCardNode(node)) return false;
- node.remove();
- return true;
- });
+ const currentEditor = editor();
+ if (!currentEditor) return;
+ removeNodeAndRestoreSelection(
+ currentEditor,
+ props.key,
+ $isDocumentCardNode
+ );
};
const convertToMention = () => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx
index 8960ce8c5c..801eac8ea0 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/HorizontalRule.tsx
@@ -2,14 +2,10 @@ import type { HorizontalRuleDecoratorProps } from '@lexical-core';
import Trash from '@phosphor/x.svg';
import { debounce } from '@solid-primitives/scheduled';
import { Button } from '@ui';
-import {
- $createNodeSelection,
- $getNodeByKey,
- $getRoot,
- $setSelection,
-} from 'lexical';
+import { $createNodeSelection, $setSelection } from 'lexical';
import { createSignal, useContext } from 'solid-js';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';
export function HorizontalRule(props: HorizontalRuleDecoratorProps) {
const lexicalWrapper = useContext(LexicalWrapperContext);
@@ -38,22 +34,7 @@ export function HorizontalRule(props: HorizontalRuleDecoratorProps) {
const deleteRule = () => {
const currentEditor = editor();
if (currentEditor === undefined) return;
- currentEditor.update(() => {
- let node = $getNodeByKey(props.key);
- if (!node) return;
- const nextSibling = node.getNextSibling();
- const prevSibling = node.getPreviousSibling();
- const root = $getRoot();
-
- node.remove();
- if (nextSibling) {
- nextSibling.selectStart();
- } else if (prevSibling) {
- prevSibling.selectEnd();
- } else {
- root.selectEnd();
- }
- });
+ removeNodeAndRestoreSelection(currentEditor, props.key);
};
const debouncedSetHover = debounce((state: boolean) => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
index 2a0866ed1a..21a94653ff 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownImage.tsx
@@ -17,7 +17,6 @@ import { cn, Layer } from '@ui';
import {
$createNodeSelection,
$getNodeByKey,
- $getRoot,
$setSelection,
COMMAND_PRIORITY_LOW,
} from 'lexical';
@@ -41,6 +40,7 @@ import {
UPLOAD_MEDIA_START_COMMAND,
UPLOAD_MEDIA_SUCCESS_COMMAND,
} from '../../plugins/media';
+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';
import { MediaButtons } from './MediaButtons';
import { ResizeHandle } from './ResizeHandle';
@@ -160,22 +160,7 @@ export function MarkdownImage(props: ImageDecoratorProps) {
const deleteImage = () => {
const currentEditor = editor();
if (currentEditor === undefined) return;
- currentEditor.update(() => {
- let node = $getNodeByKey(props.key);
- if (!node) return;
- const nextSibling = node.getNextSibling();
- const prevSibling = node.getPreviousSibling();
- const root = $getRoot();
-
- node.remove();
- if (nextSibling) {
- nextSibling.selectStart();
- } else if (prevSibling) {
- prevSibling.selectEnd();
- } else {
- root.selectEnd();
- }
- });
+ removeNodeAndRestoreSelection(currentEditor, props.key, $isImageNode);
};
const viewFull = () => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
index 1c5c89d89e..69129ff7c1 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/MarkdownVideo.tsx
@@ -12,7 +12,6 @@ import { Button, cn } from '@ui';
import {
$createNodeSelection,
$getNodeByKey,
- $getRoot,
$setSelection,
COMMAND_PRIORITY_LOW,
} from 'lexical';
@@ -35,6 +34,7 @@ import {
UPLOAD_MEDIA_START_COMMAND,
UPLOAD_MEDIA_SUCCESS_COMMAND,
} from '../../plugins';
+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';
import { MediaButtons } from './MediaButtons';
import { ResizeHandle } from './ResizeHandle';
@@ -143,22 +143,7 @@ export function MarkdownVideo(props: VideoDecoratorProps) {
const deleteVideo = () => {
const currentEditor = editor();
if (currentEditor === undefined) return;
- currentEditor.update(() => {
- let node = $getNodeByKey(props.key);
- if (!node) return;
- const nextSibling = node.getNextSibling();
- const prevSibling = node.getPreviousSibling();
- const root = $getRoot();
-
- node.remove();
- if (nextSibling) {
- nextSibling.selectStart();
- } else if (prevSibling) {
- prevSibling.selectEnd();
- } else {
- root.selectEnd();
- }
- });
+ removeNodeAndRestoreSelection(currentEditor, props.key, $isVideoNode);
};
const viewFull = () => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
index 1b55b3a331..a947a22429 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Snapshot.tsx
@@ -16,15 +16,12 @@ import TrashSimple from '@phosphor/trash-simple.svg';
import { isAccessiblePreviewItem, useItemPreview } from '@queries/preview';
import { blockNameToItemType } from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
-import {
- $getNodeByKey,
- COMMAND_PRIORITY_NORMAL,
- KEY_ENTER_COMMAND,
-} from 'lexical';
+import { COMMAND_PRIORITY_NORMAL, KEY_ENTER_COMMAND } from 'lexical';
import type { JSX } from 'solid-js';
import { createMemo, Suspense, useContext } from 'solid-js';
import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
import { autoRegister } from '../../plugins';
+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';
import { openDocument } from '../core/BlockLink';
import { MentionTooltip } from './MentionTooltip';
@@ -108,12 +105,8 @@ function SnapshotInner(props: SnapshotDecoratorProps) {
}
const deleteSnapshot = () => {
- editor?.update(() => {
- const node = $getNodeByKey(props.key);
- if (!$isSnapshotNode(node)) return false;
- node.remove();
- return true;
- });
+ if (!editor) return;
+ removeNodeAndRestoreSelection(editor, props.key, $isSnapshotNode);
};
const navHandlers = useSplitNavigationHandler<HTMLSpanElement>((e) => {
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.test.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.test.ts
new file mode 100644
index 0000000000..b7ae63b063
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.test.ts
@@ -0,0 +1,103 @@
+import { SupportedNodeTypes } from '@lexical-core/node-list';
+import { $createCustomCodeNode } from '@lexical-core/nodes/CustomCodeNode';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $isParagraphNode,
+ $isRangeSelection,
+ createEditor,
+ type LexicalEditor,
+} from 'lexical';
+import { describe, expect, test } from 'vitest';
+import { deleteCodeNode } from './deleteCodeNode';
+
+function createTestEditor(): LexicalEditor {
+ const editor = createEditor({
+ namespace: 'delete-code-node-test',
+ nodes: [...SupportedNodeTypes],
+ onError: (error) => {
+ throw error;
+ },
+ });
+
+ const root = document.createElement('div');
+ root.contentEditable = 'true';
+ document.body.appendChild(root);
+ editor.setRootElement(root);
+
+ return editor;
+}
+
+describe('deleteCodeNode', () => {
+ test('replaces a sole code block with an empty paragraph', () => {
+ const editor = createTestEditor();
+ let codeKey = '';
+
+ editor.update(
+ () => {
+ const code = $createCustomCodeNode();
+ code.append($createTextNode('const value = 1;'));
+ codeKey = code.getKey();
+ $getRoot().clear().append(code);
+ code.selectEnd();
+ },
+ { discrete: true }
+ );
+
+ deleteCodeNode(editor, codeKey);
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(1);
+ expect($isParagraphNode(children[0])).toBe(true);
+ expect(children[0].getTextContent()).toBe('');
+
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.anchor.getNode().getTopLevelElement()?.getKey()).toBe(
+ children[0].getKey()
+ );
+ });
+ });
+
+ test('moves selection to the following block when deleting from the start', () => {
+ const editor = createTestEditor();
+ let codeKey = '';
+ let nextParagraphKey = '';
+
+ editor.update(
+ () => {
+ const code = $createCustomCodeNode();
+ code.append($createTextNode('const value = 1;'));
+ codeKey = code.getKey();
+
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode('after'));
+ nextParagraphKey = paragraph.getKey();
+
+ $getRoot().clear().append(code, paragraph);
+ code.selectEnd();
+ },
+ { discrete: true }
+ );
+
+ deleteCodeNode(editor, codeKey);
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(1);
+ expect(children[0].getKey()).toBe(nextParagraphKey);
+
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.anchor.getNode().getTopLevelElement()?.getKey()).toBe(
+ nextParagraphKey
+ );
+ expect(selection.anchor.offset).toBe(0);
+ });
+ });
+});
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.ts
new file mode 100644
index 0000000000..f75e1a2fd6
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/code/deleteCodeNode.ts
@@ -0,0 +1,17 @@
+import { $isCodeNode } from '@lexical/code';
+import { $isCustomCodeNode } from '@lexical-core';
+import type { LexicalEditor, NodeKey } from 'lexical';
+import { removeNodeAndRestoreSelection } from '../shared/removeNodeAndRestoreSelection';
+
+/**
+ * Removes a code block from the editor and leaves the selection anchored in a
+ * live node. If the code block was the only child, recreate the empty paragraph
+ * shape that the rest of the markdown editor expects.
+ */
+export function deleteCodeNode(editor: LexicalEditor, nodeKey: NodeKey) {
+ removeNodeAndRestoreSelection(
+ editor,
+ nodeKey,
+ (node) => $isCodeNode(node) || $isCustomCodeNode(node)
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.test.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.test.ts
new file mode 100644
index 0000000000..3f0615b155
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.test.ts
@@ -0,0 +1,138 @@
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ $isParagraphNode,
+ $isRangeSelection,
+ createEditor,
+ type LexicalEditor,
+ ParagraphNode,
+ TextNode,
+} from 'lexical';
+import { describe, expect, test } from 'vitest';
+import { removeNodeAndRestoreSelection } from './removeNodeAndRestoreSelection';
+
+function createTestEditor(): LexicalEditor {
+ const editor = createEditor({
+ namespace: 'remove-node-and-restore-selection-test',
+ nodes: [ParagraphNode, TextNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+
+ const root = document.createElement('div');
+ root.contentEditable = 'true';
+ document.body.appendChild(root);
+ editor.setRootElement(root);
+
+ return editor;
+}
+
+describe('removeNodeAndRestoreSelection', () => {
+ test('creates an empty paragraph when the root becomes empty', () => {
+ const editor = createTestEditor();
+ let paragraphKey = '';
+
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode('remove me'));
+ paragraphKey = paragraph.getKey();
+ $getRoot().clear().append(paragraph);
+ },
+ { discrete: true }
+ );
+
+ removeNodeAndRestoreSelection(editor, paragraphKey);
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(1);
+ expect($isParagraphNode(children[0])).toBe(true);
+ expect(children[0].getTextContent()).toBe('');
+
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.anchor.getNode().getTopLevelElement()?.getKey()).toBe(
+ children[0].getKey()
+ );
+ });
+ });
+
+ test('selects an emptied paragraph instead of nesting a paragraph', () => {
+ const editor = createTestEditor();
+ let paragraphKey = '';
+ let textKey = '';
+
+ editor.update(
+ () => {
+ const text = $createTextNode('remove me');
+ textKey = text.getKey();
+
+ const paragraph = $createParagraphNode();
+ paragraphKey = paragraph.getKey();
+ paragraph.append(text);
+
+ $getRoot().clear().append(paragraph);
+ },
+ { discrete: true }
+ );
+
+ removeNodeAndRestoreSelection(editor, textKey);
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(1);
+ expect(children[0].getKey()).toBe(paragraphKey);
+ expect($isParagraphNode(children[0])).toBe(true);
+ if (!$isParagraphNode(children[0])) return;
+ expect(children[0].getChildrenSize()).toBe(0);
+
+ const selection = $getSelection();
+ expect($isRangeSelection(selection)).toBe(true);
+ if (!$isRangeSelection(selection)) return;
+ expect(selection.anchor.getNode().getKey()).toBe(paragraphKey);
+ expect(selection.anchor.offset).toBe(0);
+ });
+ });
+
+ test('does not create a nested update when called inside an update', () => {
+ const editor = createTestEditor();
+ let paragraphKey = '';
+
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode();
+ paragraph.append($createTextNode('remove me'));
+ paragraphKey = paragraph.getKey();
+ $getRoot().clear().append(paragraph);
+ },
+ { discrete: true }
+ );
+
+ const originalUpdate = editor.update.bind(editor);
+ let updateCalls = 0;
+ editor.update = ((...args: Parameters<LexicalEditor['update']>) => {
+ updateCalls++;
+ return originalUpdate(...args);
+ }) as LexicalEditor['update'];
+
+ editor.update(
+ () => {
+ removeNodeAndRestoreSelection(editor, paragraphKey);
+ },
+ { discrete: true }
+ );
+
+ expect(updateCalls).toBe(1);
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(1);
+ expect($isParagraphNode(children[0])).toBe(true);
+ expect(children[0].getTextContent()).toBe('');
+ });
+ });
+});
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.ts
new file mode 100644
index 0000000000..096c2a99d9
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/shared/removeNodeAndRestoreSelection.ts
@@ -0,0 +1,76 @@
+import {
+ $createParagraphNode,
+ $getEditor,
+ $getNodeByKey,
+ $isRootOrShadowRoot,
+ type ElementNode,
+ isCurrentlyReadOnlyMode,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+} from 'lexical';
+
+function $selectNodeBoundary(
+ node: LexicalNode | null | undefined,
+ boundary: 'start' | 'end'
+) {
+ if (!node) return false;
+ if (boundary === 'start') {
+ node.selectStart();
+ } else {
+ node.selectEnd();
+ }
+ return true;
+}
+
+export function $removeNodeAndRestoreSelection(node: LexicalNode) {
+ const parent = node.getParent<ElementNode>();
+ const previousSibling = node.getPreviousSibling();
+ const nextSibling = node.getNextSibling();
+
+ node.remove();
+
+ if ($selectNodeBoundary(nextSibling, 'start')) return;
+ if ($selectNodeBoundary(previousSibling, 'end')) return;
+ if (!parent) return;
+
+ if (parent.getChildrenSize() === 0) {
+ if ($isRootOrShadowRoot(parent)) {
+ const paragraph = $createParagraphNode();
+ parent.append(paragraph);
+ paragraph.selectStart();
+ return;
+ }
+
+ parent.selectStart();
+ return;
+ }
+
+ parent.selectEnd();
+}
+
+function isInWritableUpdate(editor: LexicalEditor) {
+ try {
+ return $getEditor() === editor && !isCurrentlyReadOnlyMode();
+ } catch {
+ return false;
+ }
+}
+
+export function removeNodeAndRestoreSelection(
+ editor: LexicalEditor,
+ nodeKey: NodeKey,
+ canRemove: (node: LexicalNode) => boolean = () => true
+) {
+ const removeNode = () => {
+ const node = $getNodeByKey(nodeKey);
+ if (!node || !canRemove(node)) return;
+ $removeNodeAndRestoreSelection(node);
+ };
+
+ if (isInWritableUpdate(editor)) {
+ removeNode();
+ } else {
+ editor.update(removeNode);
+ }
+}