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
fix(md): fix incorrectly nested snippet insertions (#4078)
Seamus96e33a8530ad
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsxindex 0d81269fed..2bc2f45659 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/SnippetsMenu/SnippetsMenu.tsx@@ -4,6 +4,7 @@ import type { EntityItem } from '@core/context/quickAccess';import clickOutside from '@core/directive/clickOutside';import { debouncedDependent } from '@core/util/debounce';import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';+import { fetchSnippetRaw } from '@queries/storage/snippets';import { Surface } from '@ui';import type { LexicalEditor } from 'lexical';import {@@ -112,6 +113,7 @@ function SnippetsMenuInner(props: SnippetsMenuProps) {props.editor.dispatchCommand(INSERT_SNIPPET_COMMAND, {documentId: item.id,sourceDocumentId: props.sourceDocumentId,+ fetchSnippet: () => fetchSnippetRaw({ documentId: item.id }),});};diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetInsertion.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetInsertion.tsnew file mode 100644index 0000000000..0a9826225b--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetInsertion.ts@@ -0,0 +1,101 @@+import { $getRoot, $isParagraphNode, type LexicalNode } from 'lexical';++/**+ * Replace `target` with `replacements`, returning the last inserted node so the+ * caller can place the selection. Assumes `replacements` is non-empty.+ */+function $replaceWithNodes(+ target: LexicalNode,+ replacements: LexicalNode[]+): LexicalNode {+ const first = replacements[0]!;+ target.replace(first);+ let cursor: LexicalNode = first;+ for (let i = 1; i < replacements.length; i++) {+ const next = replacements[i]!;+ cursor.insertAfter(next);+ cursor = next;+ }+ return cursor;+}++/**+ * Insert `nodes` after `target`, returning the last inserted node so the caller+ * can place the selection. Assumes `nodes` is non-empty.+ */+function $insertNodesAfter(+ target: LexicalNode,+ nodes: LexicalNode[]+): LexicalNode {+ let cursor = target;+ for (const node of nodes) {+ cursor.insertAfter(node);+ cursor = node;+ }+ return cursor;+}++/**+ * Remove an inline await placeholder when there is no content to insert,+ * placing the cursor on the nearest sibling.+ */+function $removeAwaitNodePlacingCursor(awaitNode: LexicalNode): void {+ const next = awaitNode.getNextSibling();+ const prev = awaitNode.getPreviousSibling();+ awaitNode.remove();+ if (next) next.selectStart();+ else if (prev) prev.selectEnd();+}++/**+ * Replace an inline await placeholder with parsed snippet content.+ *+ * The placeholder is an inline node living inside a paragraph, while snippet+ * content is a list of block-level nodes. Inserting blocks directly in place of+ * the placeholder nests paragraphs inside a paragraph, producing content that+ * can't be edited or deleted. This unwraps as needed to keep the resulting tree+ * flat:+ *+ * 1. If the placeholder is the only child of its paragraph parent, replace the+ * whole paragraph with the snippet's block nodes.+ * 2. If the snippet is a single paragraph of inline content, unwrap it and+ * splice its children in place of the placeholder so it flows inline.+ * 3. Otherwise, remove the placeholder and insert the snippet's block nodes at+ * the root, after the placeholder's top-level block.+ */+export function $replaceAwaitNodeWithSnippet(+ awaitNode: LexicalNode,+ snippetNodes: LexicalNode[]+): void {+ if (snippetNodes.length === 0) {+ $removeAwaitNodePlacingCursor(awaitNode);+ return;+ }++ // Case 1: placeholder is the only thing on its line.+ const parent = awaitNode.getParent();+ if ($isParagraphNode(parent) && parent.getChildrenSize() === 1) {+ $replaceWithNodes(parent, snippetNodes).selectEnd();+ return;+ }++ // Case 2: single-paragraph snippet — unwrap to inline content.+ const [onlyNode] = snippetNodes;+ if (snippetNodes.length === 1 && $isParagraphNode(onlyNode)) {+ const inlineChildren = onlyNode.getChildren();+ if (inlineChildren.length > 0) {+ $replaceWithNodes(awaitNode, inlineChildren).selectEnd();+ return;+ }+ }++ // Case 3: multi-block snippet alongside other content — insert at root.+ const topLevel = awaitNode.getTopLevelElement();+ awaitNode.remove();+ if (topLevel) {+ $insertNodesAfter(topLevel, snippetNodes).selectEnd();+ } else {+ $getRoot().append(...snippetNodes);+ snippetNodes[snippetNodes.length - 1]!.selectEnd();+ }+}diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.tsindex 1400157f1b..44f894359e 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/snippets/snippetsPlugin.ts@@ -15,7 +15,6 @@ import {InlineSearchNodesType,validTriggerPosition,} from '@lexical-core';-import { fetchSnippetRaw } from '@queries/storage/snippets';import {$getNodeByKey,$insertNodes,@@ -30,6 +29,7 @@ import {type LexicalCommand,type LexicalEditor,type LexicalNode,+ type SerializedEditorState,} from 'lexical';import { nanoid } from 'nanoid';import { createLexicalWrapper } from '../../context/LexicalWrapperContext';@@ -39,6 +39,7 @@ import {initializeEditorWithState,setEditorStateFromMarkdown,} from '../../utils';+import { $replaceAwaitNodeWithSnippet } from './snippetInsertion';const TYPE_SNIPPET_SYMBOL_COMMAND: LexicalCommand<void> = createCommand('SNIPPET_SYMBOL_COMMAND'@@ -51,10 +52,21 @@ export const CLOSE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> = createCommand(export const REMOVE_SNIPPET_SEARCH_COMMAND: LexicalCommand<void> =createCommand('REMOVE_SNIPPET_SEARCH_COMMAND');-export const INSERT_SNIPPET_COMMAND: LexicalCommand<{+/**+ * Payload for inserting a snippet. The plugin owns the markdown conversion and+ * node insertion; the caller stays opinionated about *how* a snippet's content+ * is retrieved by supplying `fetchSnippet` (see SnippetsMenu).+ */+export type InsertSnippetPayload = {+ /** Identifier of the snippet being inserted; guards against self-insertion. */documentId: string;sourceDocumentId?: string;-}> = createCommand('INSERT_SNIPPET_COMMAND');+ /** Resolves the snippet's serialized editor state from wherever it lives. */+ fetchSnippet: () => Promise<SerializedEditorState>;+};++export const INSERT_SNIPPET_COMMAND: LexicalCommand<InsertSnippetPayload> =+ createCommand('INSERT_SNIPPET_COMMAND');type SnippetsPluginProps = {menu: MenuOperations;@@ -82,15 +94,14 @@ function $getActiveSnippetSearchNode(): InlineSearchNode | null {}/**- * Fetch a snippet document's content and render it to internal markdown.- * Content lives in sync-service; a plugin-scoped markdown editor converts the- * serialized state to a markdown string the target editor can ingest.+ * Render a snippet's serialized editor state to internal markdown. A+ * plugin-scoped markdown editor converts the serialized state to a markdown+ * string the target editor can ingest.*/-async function fetchSnippetMarkdown(- documentId: string,+function snippetStateAsMarkdown(+ rawState: SerializedEditorState,extractionEditor: LexicalEditor-): Promise<string> {- const rawState = await fetchSnippetRaw({ documentId });+): string {initializeEditorWithState(extractionEditor, rawState);return editorStateAsMarkdown(extractionEditor, 'internal');}@@ -135,10 +146,7 @@ function registerSnippetsPlugin(isInteractable: () => false,});- function insertSnippet(payload: {- documentId: string;- sourceDocumentId?: string;- }) {+ function insertSnippet(payload: InsertSnippetPayload) {const sourceDocumentId = payload.sourceDocumentId ?? props.sourceDocumentId;if (sourceDocumentId === payload.documentId) {return;@@ -146,7 +154,7 @@ function registerSnippetsPlugin(const replaceAwaitNode = (insertedAwaitNodeKey: string,- $createReplacement?: () => LexicalNode[] | null | undefined+ $createSnippetNodes?: () => LexicalNode[] | null | undefined) => {editor.update(() => {@@ -154,26 +162,7 @@ function registerSnippetsPlugin(if (!$isAwaitNode(target)) {return;}-- const nodes = $createReplacement?.() ?? [];- if (nodes.length === 0) {- const next = target.getNextSibling();- const prev = target.getPreviousSibling();- target.remove();- if (next) next.selectStart();- else if (prev) prev.selectEnd();- return;- }-- const first = nodes[0]!;- target.replace(first);- let cursor = first;- for (let i = 1; i < nodes.length; i++) {- const next = nodes[i]!;- cursor.insertAfter(next);- cursor = next;- }- cursor.selectEnd();+ $replaceAwaitNodeWithSnippet(target, $createSnippetNodes?.() ?? []);},{ tag: HISTORY_MERGE_TAG });@@ -181,10 +170,8 @@ function registerSnippetsPlugin(const fetchAndReplaceSnippet = async (insertedAwaitNodeKey: string) => {try {- const markdown = await fetchSnippetMarkdown(- payload.documentId,- extractionEditor- );+ const rawState = await payload.fetchSnippet();+ const markdown = snippetStateAsMarkdown(rawState, extractionEditor);if (!markdown.trim()) {replaceAwaitNode(insertedAwaitNodeKey);return;