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(editor): keep pasted paragraphs quoted (#9233)
gbirman38826a18046c
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 8a864a1409..00d292fb74 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -161,6 +161,11 @@ Block formatting passes a forward copy of the selection to Lexical's`$setBlocksType` so backward selections include their first paragraph and keepthe editor's actual selection direction. The Markdown core browser suite's`quotes.browser.e2e.ts` checks Quote through the floating toolbar and after saving.+The same suite checks multi-paragraph plain-text, HTML, and Lexical pastes into+empty quotes and selections within a quote on desktop, tablet, and phone.+Selections across adjacent quotes stay quoted; ranges containing unquoted blocks+retain normal paste behavior.+Keep pasted paragraphs quoted through the shared clipboard insertion command.A frontend dev server runs against the **dev** backend, so this needs no local stack, Docker, Rust build, or `sudo`:diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.mdindex 2fc163f430..18f0600ecf 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md@@ -39,5 +39,12 @@ Screenshots: [desktop](proof/autolinks-desktop.png) andthrough the real floating toolbar on desktop/tablet and the composer formatribbon on phones. It checks the first paragraph's quote styling and the savedmessage. Run just this case by adding `quotes.browser.e2e.ts` to the command above.--Screenshots: [desktop](proof/quotes-desktop.png) and [phone](proof/quotes-mobile.png).+It also creates a quote with `> ` and pastes multiple paragraphs from plain text,+HTML, and Lexical clipboards, both into an empty quote and over selected text.+All pasted paragraphs stay quoted, inline formatting and surrounding text survive,+and typing at the paste caret and saving keep the quote formatting.+Replacing adjacent quotes also preserves quoting, while ranges containing+unquoted paragraphs retain normal paste behavior.++Screenshots: [desktop](proof/quotes-desktop.png), [phone](proof/quotes-mobile.png),+and [multi-paragraph paste](proof/quote-paste.png).diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/quote-paste.png b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/quote-paste.pngnew file mode 100644index 0000000000..1630b8f45eBinary files /dev/null and b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/proof/quote-paste.png differdiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.browser.e2e.tsindex 0409215ec9..4ca1044729 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.browser.e2e.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.browser.e2e.ts@@ -1,5 +1,123 @@import { expect, test } from '@playwright/test';+for (const format of ['plain', 'html', 'lexical'] as const) {+ for (const replaceSelection of [false, true]) {+ test(`pasting ${format} paragraphs ${replaceSelection ? 'over selected text' : 'into an empty quote'} keeps them quoted`, async ({+ page,+ context,+ }, testInfo) => {+ await context.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.includes('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({ status: 401, body: '{}' });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(+ '/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.html'+ );+ const editor = page.getByRole('textbox', { name: 'Message' });+ await expect(editor).toBeVisible({ timeout: 60_000 });+ await expect(editor.locator('p')).toHaveCount(3);+ await editor.focus();+ await page.keyboard.press('ControlOrMeta+A');+ const copied = await editor.evaluate((element) => {+ const clipboardData = new DataTransfer();+ element.dispatchEvent(+ new ClipboardEvent('copy', {+ clipboardData,+ bubbles: true,+ cancelable: true,+ })+ );+ return clipboardData.getData('application/x-lexical-editor');+ });+ await page.keyboard.press('Backspace');+ await page.keyboard.type('> ');+ await expect(editor.locator('blockquote')).toHaveCount(1);+ if (replaceSelection) {+ await page.keyboard.type('Prefix replace suffix');+ // Seed the exact range through the fixture so native selectionchange+ // timing cannot race the synthetic clipboard event on touch devices.+ await page+ .getByRole('button', { name: 'Select replacement text' })+ .click();+ expect(+ await page.evaluate(() => window.getSelection()?.toString())+ ).toBe('replace');+ }+ await editor.evaluate(+ (element, { format, copied }) => {+ const clipboardData = new DataTransfer();+ clipboardData.setData(+ 'text/plain',+ 'First paragraph.\n\nSecond paragraph.\n\nThird paragraph.'+ );+ if (format === 'html') {+ clipboardData.setData(+ 'text/html',+ '<p>First <strong>paragraph.</strong></p><p>Second <em>paragraph.</em></p><p>Third paragraph.</p>'+ );+ } else if (format === 'lexical') {+ clipboardData.setData('application/x-lexical-editor', copied);+ }+ element.dispatchEvent(+ new ClipboardEvent('paste', {+ clipboardData,+ bubbles: true,+ cancelable: true,+ })+ );+ },+ { format, copied }+ );+ const expected =+ format === 'lexical'+ ? [+ 'First paragraph with enough words to wrap onto several lines.',+ 'Second paragraph with additional words.',+ 'Third paragraph finishes the message.',+ ]+ : ['First paragraph.', 'Second paragraph.', 'Third paragraph.'];+ if (replaceSelection) {+ expected[0] = `Prefix ${expected[0]}`;+ expected[2] += ' suffix';+ }+ if (format === 'lexical') expect(copied).not.toBe('');+ await expect(editor.locator('blockquote')).toHaveText(expected);+ if (format === 'html') {+ await expect(editor.locator('blockquote strong')).toHaveText(+ 'paragraph.'+ );+ await expect(editor.locator('blockquote em')).toHaveText('paragraph.');+ }+ await page.keyboard.type(' Still quoted.');+ expected[2] = replaceSelection+ ? expected[2].replace(' suffix', ' Still quoted. suffix')+ : `${expected[2]} Still quoted.`;+ await expect(editor.locator('blockquote')).toHaveText(expected);+ await page.getByRole('button', { name: 'Save message' }).click();+ await expect(page.getByTestId('saved').locator('blockquote')).toHaveText(+ expected+ );+ expect(errors).toEqual([]);+ if (format === 'plain' && !replaceSelection) {+ await page.screenshot({+ path: testInfo.outputPath('quote-paste.png'),+ fullPage: true,+ });+ }+ });+ }+}+test('quoting a backward selection includes the first paragraph', async ({page,context,@@ -59,3 +177,72 @@ test('quoting a backward selection includes the first paragraph', async ({fullPage: true,});});++for (const { name, markdown, quoteCount } of [+ {+ name: 'adjacent quotes',+ markdown: '> First original.\n\n> Middle original.\n\n> Last original.',+ quoteCount: 2,+ },+ {+ name: 'quotes separated by unquoted text',+ markdown: '> First original.\n\nMiddle original.\n\n> Last original.',+ quoteCount: 1,+ },+ {+ name: 'unquoted paragraphs',+ markdown: 'First original.\n\nMiddle original.\n\nLast original.',+ quoteCount: 0,+ },+]) {+ test(`pasting over ${name} respects the selected blocks`, async ({+ page,+ context,+ }) => {+ await context.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.includes('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({ status: 401, body: '{}' });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.goto(+ `/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.html?${new URLSearchParams({ initial: markdown })}`+ );+ const editor = page.getByRole('textbox', { name: 'Message' });+ await expect(editor).toBeVisible({ timeout: 60_000 });+ await editor.focus();+ await page.keyboard.press('ControlOrMeta+A');+ await editor.evaluate((element) => {+ const clipboardData = new DataTransfer();+ clipboardData.setData(+ 'text/plain',+ 'First replacement.\n\nSecond replacement.'+ );+ element.dispatchEvent(+ new ClipboardEvent('paste', {+ clipboardData,+ bubbles: true,+ cancelable: true,+ })+ );+ });+ await expect(editor.locator(':scope > blockquote, :scope > p')).toHaveText([+ 'First replacement.',+ 'Second replacement.',+ ]);+ await expect(editor.locator('blockquote')).toHaveCount(quoteCount);+ await page.getByRole('button', { name: 'Save message' }).click();+ await expect(page.getByTestId('saved').locator('blockquote')).toHaveCount(+ quoteCount+ );+ expect(errors).toEqual([]);+ });+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.tsxindex 5ca2b5481a..33a806254a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/quotes.tsx@@ -6,6 +6,7 @@ import {} from '@app/features/channel/Input/utils/formatting';import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { $getRoot, $isTextNode } from 'lexical';import { createSignal, Show } from 'solid-js';import { render } from 'solid-js/web';import { buildConfig } from '../../../builder/MarkdownConfigBuilder';@@ -37,6 +38,7 @@ function Fixture() {<ComposerEditorconfig={editor}initialValue={+ new URLSearchParams(window.location.search).get('initial') ??'First paragraph with enough words to wrap onto several lines.\n\nSecond paragraph with additional words.\n\nThird paragraph finishes the message.'}ariaLabel="Message"@@ -44,6 +46,16 @@ function Fixture() {<button onClick={() => setSaved(editor.controls.getMarkdown())}>Save message</button>+ <button+ onClick={() =>+ editor.lexical.update(() => {+ const text = $getRoot().getFirstDescendant();+ if ($isTextNode(text)) text.select(7, 14);+ })+ }+ >+ Select replacement text+ </button><section data-testid="saved"><StaticMarkdown markdown={saved()} theme={channelTheme} /></section>diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.tsindex b4b80b554b..d90945c7cb 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/markdown-paste/markdownPastePlugin.ts@@ -1,11 +1,16 @@-import { mergeRegister } from '@lexical/utils';+import { $insertGeneratedNodes } from '@lexical/clipboard';+import { $createQuoteNode, $isQuoteNode } from '@lexical/rich-text';+import { $findMatchingParent, mergeRegister } from '@lexical/utils';import {- $insertNodes,+ $getSelection,+ $isParagraphNode,+ $isRangeSelection,$parseSerializedNode,COMMAND_PRIORITY_LOW,createEditor,type LexicalEditor,PASTE_COMMAND,+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,} from 'lexical';import { setEditorStateFromMarkdown } from '../../utils';@@ -31,6 +36,34 @@ function registerMarkdownPastePlugin(editor: LexicalEditor) {window.addEventListener('keyup', onKeyUp);return mergeRegister(+ editor.registerCommand(+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,+ ({ nodes, selection }) => {+ if (!$isRangeSelection(selection)) return false;+ if (+ !$findMatchingParent(selection.anchor.getNode(), $isQuoteNode) ||+ !$findMatchingParent(selection.focus.getNode(), $isQuoteNode) ||+ selection+ .getNodes()+ .some((node) => !$findMatchingParent(node, $isQuoteNode))+ ) {+ return false;+ }++ // Lexical merges only the first pasted paragraph into the current+ // block. Give the remaining paragraphs the same quote style before+ // its normal clipboard insertion, preserving their inline content.+ nodes.forEach((node, index) => {+ if ($isParagraphNode(node)) {+ nodes[index] = $createQuoteNode()+ .updateFromJSON(node.exportJSON())+ .append(...node.getChildren());+ }+ });+ return false;+ },+ COMMAND_PRIORITY_LOW+ ),editor.registerCommand(PASTE_COMMAND,(event: InputEvent | ClipboardEvent) => {@@ -50,6 +83,8 @@ function registerMarkdownPastePlugin(editor: LexicalEditor) {if (!pastedText) {return false;}+ const selection = $getSelection();+ if (!selection) return false;event.preventDefault();setEditorStateFromMarkdown(parseEditor, pastedText, 'both');@@ -57,7 +92,7 @@ function registerMarkdownPastePlugin(editor: LexicalEditor) {const nodes = state.root.children.map((node) =>$parseSerializedNode(node));- $insertNodes(nodes);+ $insertGeneratedNodes(editor, nodes, selection);}return true;},diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex 5a38b3b225..91874e036f 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -40,6 +40,13 @@ format toolbar applies it to the same paragraphs in either selection direction.Verify a selection from the last paragraph back to the start of the first:the first paragraph must receive the format too. A range ending at the start ofthe following paragraph leaves that following paragraph unchanged.+Typing `> ` creates a quote. Pasting text with paragraph breaks into that quote+keeps all pasted paragraphs quoted, including HTML and text copied from another+Macro editor. Inline formatting survives. Verify an empty quote and a selection+within a quote, then type after the paste and save the message; every pasted+paragraph must still have the quote styling.+Selections across adjacent quoted paragraphs preserve quoting too. A selection+that includes unquoted paragraphs keeps the normal paste behavior.The backend-free quote check is documented in the Markdown browser-test READMElinked above.diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 0a5309f530..18c9ce159f 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -2424,6 +2424,8 @@ nodes — use the snapshot itself to verify content. For formatting checks, runBody placeholder advertises: `/` for block commands, `@` to reference files, `;` for snippets.Markdown auto-format works while typing (`#` heading, `[]` checklist, `>` quote).+Pasting multiple paragraphs inside a quote keeps those paragraphs quoted;+see [block formatting](channels.md#block-formatting) for verification.Imported Markdown recognizes bare URLs with the same shared matcher as messages;code and escaped URLs remain literal. Remove link persists through Markdown andeditor-state saves. See [message links](channels.md#message-links) for verification.