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
feat(md): paste node for large copy-pasted text (#4281)
Eric Hayescb6cc595171c
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsxindex 64e4aff7e4..3c83ef7332 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx@@ -24,6 +24,7 @@ import {type ImageNode,isSupportedLanguage,normalizedLanguage,+ type PasteNode,type SnapshotNode,SupportedNodeTypes,type ThemeMentionNode,@@ -80,6 +81,7 @@ import { GroupMention as GroupMentionDecorator } from '../decorator/GroupMentionimport { LazyDecorator } from '../decorator/LazyDecorator';import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';+import { PasteNode as PasteNodeDecorator } from '../decorator/PasteNode';import { Snapshot as SnapshotDecorator } from '../decorator/Snapshot';import { ThemeMention as ThemeMentionDecorator } from '../decorator/ThemeMention';import { UnknownMention as UnknownMentionDecorator } from '../decorator/UnknownMention';@@ -686,6 +688,16 @@ const DocumentCard: RenderableEntity<DocumentCardNode> = {},};+const Paste: RenderableEntity<PasteNode> = {+ guard: (node: LexicalNode): node is PasteNode => node.__type === 'paste',+ render: (props) =>+ PasteNodeDecorator({+ ...props.node.exportComponentProps(),+ key: props.node.getKey(),+ theme: props.theme,+ }),+};+// Table rendering components for Lexical tablesconst Table: RenderableElement<TableNode> = {guard: (node: LexicalNode): node is TableNode => node.__type === 'table',@@ -769,6 +781,7 @@ const InlineEntities: Array<RenderableEntity> = [ThemeMention,UnknownMention,Watermark,+ Paste,] as const;const Elements: RenderableElement[] = [diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/PasteNode.tsxnew file mode 100644index 0000000000..55deff0de5--- /dev/null+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx@@ -0,0 +1,211 @@+import { MobileDrawer } from '@app/component/mobile/MobileDrawer';+import { toast } from '@core/component/Toast/Toast';+import { isMobileWidth } from '@core/mobile/mobileWidth';+import { blockElementSignal } from '@core/signal/blockElement';+import {+ $convertPasteToText,+ $isPasteNode,+ type PasteNodeDecoratorProps,+} from '@lexical-core';+import Copy from '@phosphor/copy.svg';+import DotsThree from '@phosphor/list.svg';+import TextT from '@phosphor/text-t.svg';+import TrashSimple from '@phosphor/trash-simple.svg';+import { Button, cn, Dialog, Dropdown, Layer } from '@ui';+import { $createNodeSelection, $getNodeByKey, $setSelection } from 'lexical';+import { createSignal, Show, useContext } from 'solid-js';+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';+import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAndRestoreSelection';++/**+ * Block-level decorator for a {@link PasteNode}. Renders a compact collapsed+ * monospace preview that looks like a code fence and fades to the background+ * color at the bottom, with a "pasted" pill in the bottom-left and a hamburger+ * menu floating in the top-right (Convert to text / Delete). Clicking the node+ * opens the full text styled like a code fence: a scrollable popup on desktop+ * and a bottom drawer on mobile, both dismissable with `esc` or by clicking+ * outside. Mirrors the DocumentCard.+ */+export function PasteNode(props: PasteNodeDecoratorProps) {+ const wrapper = useContext(LexicalWrapperContext);+ const editor = () => wrapper?.editor;+ const selection = () => wrapper?.selection;++ const [open, setOpen] = createSignal(false);+ const [menuOpen, setMenuOpen] = createSignal(false);++ const isSelectedAsNode = () => {+ const sel = selection();+ if (!sel) return false;+ return sel.type === 'node' && sel.nodeKeys.has(props.key);+ };++ const selectNode = () => {+ const e = editor();+ if (!e) return;+ if (!e.isEditable()) return;+ e.update(() => {+ const sel = $createNodeSelection();+ sel.add(props.key);+ $setSelection(sel);+ });+ };++ const convertToText = () => {+ editor()?.update(() => {+ const node = $getNodeByKey(props.key);+ if (!$isPasteNode(node)) return false;+ $convertPasteToText(node);+ return true;+ });+ };++ const copyText = () => {+ try {+ navigator.clipboard.writeText(props.content);+ toast.success('Copied pasted text to clipboard');+ } catch (e) {+ console.error('Failed to copy pasted text to clipboard', e);+ }+ };++ const deletePaste = () => {+ const currentEditor = editor();+ if (!currentEditor) return;+ removeNodeAndRestoreSelection(currentEditor, props.key, $isPasteNode);+ };++ const lineCount = () => props.content.split('\n').length;+ const lineLabel = () =>+ `${lineCount()} ${lineCount() === 1 ? 'line' : 'lines'}`;++ const fullText = () => (+ <pre class="font-mono text-sm leading-relaxed bg-message p-4 m-0 whitespace-pre-wrap wrap-break-word overflow-auto">+ {props.content}+ </pre>+ );++ return (+ <Layer depth={2}>+ <div+ contentEditable={false}+ class={cn(+ 'relative my-2 w-full rounded border border-edge bg-surface no-select-children select-none overflow-hidden cursor-pointer',+ isSelectedAsNode() && 'bg-active outline-edge outline-4'+ )}+ on:click={(e) => {+ // Native listener (not delegated `onClick`) so this fires during+ // real DOM bubbling and its stopPropagation beats the MarkdownTextarea+ // container's native `on:click`, which otherwise calls editor.focus()+ // and steals focus back, instantly closing the modal in input boxes.+ e.preventDefault();+ e.stopPropagation();+ selectNode();+ setOpen(true);+ }}+ >+ {/* Compact monospace preview that fades to the background. */}+ <div class="relative max-h-28 overflow-hidden">+ <pre class="font-mono text-xs leading-relaxed bg-message p-3 m-0 whitespace-pre overflow-hidden">+ {props.content}+ </pre>+ <div class="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-b from-transparent to-message" />+ </div>++ {/* "pasted" pill floating bottom-left. */}+ <span class="absolute bottom-2 left-2 inline-flex items-center px-2 py-1 text-xs leading-none rounded-full border border-edge bg-surface">+ pasted+ </span>++ {/* Hamburger menu floating top-right. Hidden in static / read-only+ renders (no editable editor), mirroring the reference cards. */}+ <Show when={editor()?.isEditable()}>+ <div+ class="absolute top-1 right-1"+ on:click={(e) => e.stopPropagation()}+ >+ <Dropdown open={menuOpen()} onOpenChange={setMenuOpen}>+ <Dropdown.Trigger size="icon-sm" variant="ghost">+ <DotsThree />+ </Dropdown.Trigger>+ <Dropdown.Content mount={blockElementSignal.get()}>+ <Dropdown.Group>+ <Dropdown.Item onSelect={copyText}>+ <Copy class="size-4 shrink-0" />+ <span class="flex-1 truncate">Copy</span>+ </Dropdown.Item>+ <Dropdown.Item onSelect={convertToText}>+ <TextT class="size-4 shrink-0" />+ <span class="flex-1 truncate">Convert to text</span>+ </Dropdown.Item>+ </Dropdown.Group>+ <Dropdown.Group>+ <Dropdown.Item onSelect={deletePaste}>+ <TrashSimple class="size-4 shrink-0" />+ <span class="flex-1 truncate">Delete</span>+ </Dropdown.Item>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ </div>+ </Show>+ </div>++ {/* Full-text view, styled like a code fence. Drawer on mobile, dialog on+ desktop; both scroll correctly and close on esc / outside click. */}+ <Show+ when={isMobileWidth()}+ fallback={+ <Dialog+ open={open()}+ onOpenChange={setOpen}+ position="center"+ class="rounded-lg border border-edge bg-surface shadow-lg"+ >+ <div class="flex items-center justify-between px-4 py-2 border-b border-edge text-xs text-ink-muted">+ <span>Pasted text</span>+ <div class="flex items-center gap-2">+ <span>{lineLabel()}</span>+ <Button+ variant="ghost"+ size="icon-sm"+ class="text-ink-extra-muted/50"+ tooltip="Copy"+ on:click={() => copyText()}+ >+ <Copy />+ </Button>+ </div>+ </div>+ <div class="max-h-[70vh] overflow-auto">{fullText()}</div>+ </Dialog>+ }+ >+ <MobileDrawer side="bottom" open={open()} onOpenChange={setOpen}>+ <MobileDrawer.Portal>+ <MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />+ <MobileDrawer.Content aria-label="Pasted text">+ <MobileDrawer.Handle />+ <div class="flex items-center justify-between px-4 pb-2 text-xs text-ink-muted shrink-0">+ <span>Pasted text</span>+ <div class="flex items-center gap-2">+ <span>{lineLabel()}</span>+ <Button+ variant="ghost"+ size="icon-sm"+ class="text-ink-extra-muted/50"+ tooltip="Copy"+ on:click={() => copyText()}+ >+ <Copy />+ </Button>+ </div>+ </div>+ <div class="flex-1 min-h-0 overflow-auto">{fullText()}</div>+ </MobileDrawer.Content>+ </MobileDrawer.Portal>+ </MobileDrawer>+ </Show>+ </Layer>+ );+}diff --git a/js/app/packages/core/component/LexicalMarkdown/init.ts b/js/app/packages/core/component/LexicalMarkdown/init.tsindex b26adced0e..d5485b6b91 100644--- a/js/app/packages/core/component/LexicalMarkdown/init.ts+++ b/js/app/packages/core/component/LexicalMarkdown/init.ts@@ -10,6 +10,7 @@ import {HorizontalRuleNode,HtmlRenderNode,ImageNode,+ PasteNode as PasteNodeClass,PullRequestMentionNode,SnapshotNode,ThemeMentionNode,@@ -31,6 +32,7 @@ import { HorizontalRule } from './component/decorator/HorizontalRule';import { HtmlRender } from './component/decorator/HtmlRender';import { MarkdownImage } from './component/decorator/MarkdownImage';import { MarkdownVideo } from './component/decorator/MarkdownVideo';+import { PasteNode } from './component/decorator/PasteNode';import { PullRequestMention } from './component/decorator/PullRequestMention';import { Snapshot } from './component/decorator/Snapshot';import { ThemeMention } from './component/decorator/ThemeMention';@@ -49,6 +51,7 @@ export function initializeLexical() {setDecorator(GroupMentionNode, GroupMention);setDecorator(DocumentMentionNode, DocumentMention);setDecorator(DocumentCardNode, DocumentCard);+ setDecorator(PasteNodeClass, PasteNode);setDecorator(PullRequestMentionNode, PullRequestMention);setDecorator(ContactMentionNode, ContactMention);setDecorator(DateMentionNode, DateMention);diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.tsindex 0a165650fc..a90a3c7ac3 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts@@ -6,6 +6,7 @@ import {} from '@core/block';import { isTauri } from '@core/util/platform';import { mergeRegister } from '@lexical/utils';+import { $createPasteNode, PasteNode } from '@lexical-core';import { parseThemeV2Json } from '@theme/utils/themeValidation';import {$getSelection,@@ -14,12 +15,20 @@ import {type LexicalEditor,PASTE_COMMAND,} from 'lexical';+import { $insertNodesAndSplitList } from '../../utils';import {INSERT_DOCUMENT_MENTION_COMMAND,INSERT_PR_MENTION_COMMAND,INSERT_THEME_MENTION_COMMAND,} from '../mentions';+/**+ * Character threshold above which a plain-text paste collapses into a+ * block-level PasteNode (mirroring Anthropic's "pasted" chip) instead of+ * being inserted inline. Chosen to roughly match a few paragraphs of prose.+ */+export const LARGE_PASTE_CHAR_THRESHOLD = 1500;+type MacroAppUrlParsed = {isValid: boolean;id: string | undefined;@@ -162,6 +171,30 @@ function registerTextPastePlugin(editor: LexicalEditor) {!parsedMacroAppUrl.id ||!parsedMacroAppUrl.block) {+ // Large plain-text pastes collapse into a block-level PasteNode+ // (Anthropic-style "pasted" chip). Only handle genuine plain text+ // pastes: defer to the richer paste handlers for HTML / Lexical+ // clipboards, and only when the cursor is a collapsed selection.+ const clipboard = event.clipboardData;+ const isRichClipboard = Boolean(+ clipboard?.getData('application/x-lexical-clipboard') ||+ clipboard?.getData('text/html')+ );+ if (+ !isRichClipboard &&+ editor.hasNode(PasteNode) &&+ pastedText.length > LARGE_PASTE_CHAR_THRESHOLD+ ) {+ const selection = $getSelection();+ if ($isRangeSelection(selection) && !selection.isCollapsed()) {+ return false;+ }+ event.preventDefault();+ $insertNodesAndSplitList([+ $createPasteNode({ content: pastedText }),+ ]);+ return true;+ }return false;}diff --git a/js/app/packages/core/component/LexicalMarkdown/version.ts b/js/app/packages/core/component/LexicalMarkdown/version.tsindex a3520debc3..5c82ec9397 100644--- a/js/app/packages/core/component/LexicalMarkdown/version.ts+++ b/js/app/packages/core/component/LexicalMarkdown/version.ts@@ -11,5 +11,6 @@* Version 1.3 - Apr 30, 2026. Added AwaitNode.* Version 1.4 - Jun 2, 2026. Added persisted await placeholders for pending agent messages.* Version 2.0 - Jun 19, 2026. Added PullRequestMentionNode.+ * Version 2.1 - Jun 23, 2026. Added PasteNode*/-export const MARKDOWN_VERSION_COUNTER = 2.0;+export const MARKDOWN_VERSION_COUNTER = 2.1;diff --git a/js/bun.lock b/js/bun.lockindex 892509cb10..35ce168379 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -848,7 +848,7 @@"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],- "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8", "sha512-6p5xQAkS6Uw6J8Uh0vlj6MjKZXWps5E1Gu0hciBFq1E2BfPBZAgdeeafKnR3diNb4SXWK0JML49nAr+o5PhwKw=="],+ "@inkibra/tauri-plugins": ["@inkibra/tauri-plugins@github:macro-inc/tauri-plugins#26537c8", { "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1" } }, "macro-inc-tauri-plugins-26537c8"],"@inquirer/external-editor": ["@inquirer/[email protected]", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA=="],@@ -2560,7 +2560,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/js/lexical-core/decoratorRegistry.ts b/js/lexical-core/decoratorRegistry.tsindex d0c94c5783..913aa52c71 100644--- a/js/lexical-core/decoratorRegistry.ts+++ b/js/lexical-core/decoratorRegistry.ts@@ -37,6 +37,7 @@ import type {HtmlRenderNode,} from './nodes/HtmlRenderNode';import type { ImageDecoratorProps, ImageNode } from './nodes/ImageNode';+import type { PasteNode, PasteNodeDecoratorProps } from './nodes/PasteNode';import type {PullRequestMentionDecoratorProps,PullRequestMentionNode,@@ -94,6 +95,10 @@ export interface NodeDecoratorMap {klass: typeof DocumentCardNode;props: DocumentCardDecoratorProps;};+ PasteNode: {+ klass: typeof PasteNode;+ props: PasteNodeDecoratorProps;+ };ContactMentionNode: {klass: typeof ContactMentionNode;props: ContactMentionDecoratorProps;diff --git a/js/lexical-core/index.ts b/js/lexical-core/index.tsindex a12f2dd684..584377d152 100644--- a/js/lexical-core/index.ts+++ b/js/lexical-core/index.ts@@ -22,6 +22,7 @@ export * from './nodes/HtmlRenderNode';export * from './nodes/ImageNode';export * from './nodes/InlineSearchNode';export * from './nodes/MediaNode';+export * from './nodes/PasteNode';export * from './nodes/PullRequestMentionNode';export * from './nodes/SnapshotNode';export * from './nodes/ThemeMentionNode';diff --git a/js/lexical-core/node-list.ts b/js/lexical-core/node-list.tsindex d3c0deac70..162a3262bb 100644--- a/js/lexical-core/node-list.ts+++ b/js/lexical-core/node-list.ts@@ -31,6 +31,7 @@ import { HorizontalRuleNode } from './nodes/HorizontalRuleNode';import { HtmlRenderNode } from './nodes/HtmlRenderNode';import { ImageNode } from './nodes/ImageNode';import { InlineSearchNode } from './nodes/InlineSearchNode';+import { PasteNode } from './nodes/PasteNode';import { PullRequestMentionNode } from './nodes/PullRequestMentionNode';import { SearchMatchNode } from './nodes/SearchMatchNode';import { SnapshotNode } from './nodes/SnapshotNode';@@ -71,6 +72,7 @@ export const SupportedNodeTypes = [LineBreakNode,DocumentMentionNode,DocumentCardNode,+ PasteNode,UserMentionNode,ContactMentionNode,DateMentionNode,diff --git a/js/lexical-core/nodes/PasteNode.ts b/js/lexical-core/nodes/PasteNode.tsnew file mode 100644index 0000000000..4a7e28c53c--- /dev/null+++ b/js/lexical-core/nodes/PasteNode.ts@@ -0,0 +1,178 @@+import {+ $applyNodeReplacement,+ $createParagraphNode,+ type DOMConversionMap,+ type EditorConfig,+ type EditorThemeClasses,+ type LexicalEditor,+ type LexicalNode,+ type NodeKey,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';+import { DecoratorBlockNode } from './DecoratorBlockNode';++const VERSION = 1;++export type PasteNodeData = {+ content: string;+};++export type SerializedPasteNode = Spread<PasteNodeData, SerializedLexicalNode>;++export type PasteNodeDecoratorProps = PasteNodeData & {+ key: NodeKey;+ theme: EditorThemeClasses;+};++/**+ * A block-level node that holds a large chunk of pasted plain text. It renders+ * a collapsed monospace preview (like a code fence) that fades out at the+ * bottom and can be expanded into a popup with the full text, mirroring the+ * Anthropic "pasted" chip. Structurally it follows {@link DocumentCardNode}.+ */+export class PasteNode extends DecoratorBlockNode<+ DecoratorComponent<PasteNodeDecoratorProps> | undefined+> {+ __content: string;++ static getType() {+ return 'paste';+ }++ isKeyboardSelectable(): boolean {+ return true;+ }++ static clone(node: PasteNode) {+ return new PasteNode(node.__content, node.__key);+ }++ constructor(content: string, key?: NodeKey) {+ super('center', key);+ this.__content = content;+ }++ static importJSON(serializedNode: SerializedPasteNode) {+ const node = $createPasteNode({+ content: serializedNode.content,+ });+ $applyIdFromSerialized(node, serializedNode);+ return node;+ }++ exportJSON(): SerializedPasteNode {+ return {+ ...super.exportJSON(),+ content: this.__content,+ type: PasteNode.getType(),+ version: VERSION,+ };+ }++ exportComponentProps(): PasteNodeData {+ return {+ content: this.__content,+ };+ }++ createDOM(_config: EditorConfig): HTMLElement {+ const container = document.createElement('div');+ container.style.display = 'block';+ container.setAttribute('data-paste-node', 'true');+ return container;+ }++ updateDOM(): boolean {+ return false;+ }++ static importDOM(): DOMConversionMap<HTMLDivElement> | null {+ const convert = (domNode: HTMLElement) => {+ if (!domNode.hasAttribute('data-paste-node')) {+ return null;+ }+ const content = domNode.getAttribute('data-content') || '';+ const node = $createPasteNode({ content });+ return { node };+ };++ return {+ div: () => ({ conversion: convert, priority: 1 }),+ };+ }++ getDataAttrs(): Record<string, string> {+ return {+ 'data-paste-node': 'true',+ 'data-content': this.__content,+ };+ }++ exportDOM() {+ const element = document.createElement('div');+ const attrs = this.getDataAttrs();+ for (const [k, v] of Object.entries(attrs)) {+ if (v) {+ element.setAttribute(k, v);+ }+ }+ element.textContent = this.__content;+ return { element };+ }++ getTextContent(): string {+ return this.__content;+ }++ getSearchText(): string {+ return this.__content;+ }++ getContent(): string {+ return this.__content;+ }++ setContent(content: string) {+ const writable = this.getWritable();+ writable.__content = content;+ }++ decorate(_: LexicalEditor, config: EditorConfig) {+ const decorator = getDecorator<PasteNodeDecoratorProps>(PasteNode);+ if (decorator) {+ return () =>+ decorator({+ content: this.__content,+ key: this.getKey(),+ theme: config.theme,+ });+ }+ }+}++export function $createPasteNode(params: PasteNodeData): PasteNode {+ const node = new PasteNode(params.content);+ return $applyNodeReplacement(node);+}++export function $isPasteNode(+ node: PasteNode | LexicalNode | null | undefined+): node is PasteNode {+ return node instanceof PasteNode;+}++/**+ * Convert a PasteNode (block) into plain in-document text, inserting the+ * content exactly the way a normal plain-text paste does — i.e. as text with+ * line breaks inside a single paragraph (via `insertRawText`) rather than the+ * block-level PasteNode the large-paste handler would otherwise create.+ */+export function $convertPasteToText(pasteNode: PasteNode): void {+ const content = pasteNode.getContent();+ const paragraph = $createParagraphNode();+ pasteNode.replace(paragraph);+ paragraph.select().insertRawText(content);+}diff --git a/js/lexical-core/tests/paste.test.ts b/js/lexical-core/tests/paste.test.tsnew file mode 100644index 0000000000..8ea20108bc--- /dev/null+++ b/js/lexical-core/tests/paste.test.ts@@ -0,0 +1,164 @@+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+} from '@lexical/markdown';+import { $getRoot, createEditor } from 'lexical';+import { describe, expect, it } from 'vitest';+import { SupportedNodeTypes } from '../node-list';+import {+ $convertPasteToText,+ $createPasteNode,+ $isPasteNode,+} from '../nodes/PasteNode';+import { EXTERNAL_TRANSFORMERS, INTERNAL_TRANSFORMERS } from '../transformers';++function makeEditor() {+ return createEditor({+ nodes: SupportedNodeTypes,+ onError: console.error,+ });+}++describe('PasteNode - internal transformer round-trip', () => {+ it('serializes and deserializes pasted content', async () => {+ const editor = makeEditor();+ const content = 'line one\nline two\n indented three';++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ root.append($createPasteNode({ content }));+ },+ { onUpdate: () => resolve() }+ );+ });++ let markdown = '';+ editor.getEditorState().read(() => {+ markdown = $convertToMarkdownString(INTERNAL_TRANSFORMERS);+ });++ expect(markdown).toContain('<m-paste>');+ expect(markdown).toContain('</m-paste>');++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ $convertFromMarkdownString(markdown, INTERNAL_TRANSFORMERS);+ },+ { onUpdate: () => resolve() }+ );+ });++ editor.getEditorState().read(() => {+ const root = $getRoot();+ const node = root.getChildren().find($isPasteNode);+ expect(node).toBeDefined();+ expect(node?.getContent()).toBe(content);+ });+ });++ it('keeps XML-like content intact through a round-trip', async () => {+ const editor = makeEditor();+ const content = 'before <m-document-card>injected</m-document-card> after';++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ root.append($createPasteNode({ content }));+ },+ { onUpdate: () => resolve() }+ );+ });++ let markdown = '';+ editor.getEditorState().read(() => {+ markdown = $convertToMarkdownString(INTERNAL_TRANSFORMERS);+ });++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ $convertFromMarkdownString(markdown, INTERNAL_TRANSFORMERS);+ },+ { onUpdate: () => resolve() }+ );+ });++ editor.getEditorState().read(() => {+ const root = $getRoot();+ const node = root.getChildren().find($isPasteNode);+ expect(node?.getContent()).toBe(content);+ });+ });+});++describe('PasteNode - external transformer', () => {+ it('exports raw text to external markdown', async () => {+ const editor = makeEditor();+ const content = 'plain pasted text';++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ root.append($createPasteNode({ content }));+ },+ { onUpdate: () => resolve() }+ );+ });++ let markdown = '';+ editor.getEditorState().read(() => {+ markdown = $convertToMarkdownString(EXTERNAL_TRANSFORMERS);+ });++ expect(markdown).toContain(content);+ expect(markdown).not.toContain('<m-paste>');+ });+});++describe('PasteNode - convert to text', () => {+ it('converts a paste node into paragraphs of plain text', async () => {+ const editor = makeEditor();+ const content = 'first line\nsecond line';++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ root.append($createPasteNode({ content }));+ },+ { onUpdate: () => resolve() }+ );+ });++ await new Promise<void>((resolve) => {+ editor.update(+ () => {+ const root = $getRoot();+ const node = root.getChildren().find($isPasteNode);+ if (node) $convertPasteToText(node);+ },+ { onUpdate: () => resolve() }+ );+ });++ editor.getEditorState().read(() => {+ const root = $getRoot();+ expect(root.getChildren().some($isPasteNode)).toBe(false);+ expect(root.getTextContent()).toContain('first line');+ expect(root.getTextContent()).toContain('second line');+ });+ });+});diff --git a/js/lexical-core/transformers/index.ts b/js/lexical-core/transformers/index.tsindex 43a0e3afb4..6daa9234eb 100644--- a/js/lexical-core/transformers/index.ts+++ b/js/lexical-core/transformers/index.ts@@ -26,6 +26,7 @@ import {I_THEME_MENTION,I_USER_MENTION,} from './mentions';+import { E_PASTE_NODE, I_PASTE_NODE } from './paste';import { E_SNAPSHOT_NODE, I_SNAPSHOT_NODE } from './snapshot';import { E_TABLE_NODE, I_TABLE_NODE } from './tables';import {@@ -51,6 +52,7 @@ export { isConversionOnlyTransformer };*/export const INTERNAL_TRANSFORMERS: Transformer[] = [I_SNAPSHOT_NODE, // Must be before mentions to avoid matching inner tags in snapshot content+ I_PASTE_NODE, // Must be before mentions to avoid matching inner tags in paste contentPRESERVE_LINES,LINK_XML, // Prefer internal xml link to handle []() in link textMARK_XML,@@ -90,6 +92,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [HTML_BLOCKQUOTE,E_USER_MENTION,E_GROUP_MENTION,+ E_PASTE_NODE, // export raw pasted text to external markdownI_DOCUMENT_MENTION, // for chat attachmentsE_DOCUMENT_MENTION,I_DOCUMENT_CARD, // for internal representation@@ -114,6 +117,8 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [*/export const ALL_TRANSFORMERS: Transformer[] = [I_SNAPSHOT_NODE, // Must be before mentions to avoid matching inner tags in snapshot content+ I_PASTE_NODE, // Must be before mentions to avoid matching inner tags in paste content+ E_PASTE_NODE,PRESERVE_LINES,LINK_XML, // Prefer internal xml link to handle []() in link textMARK_XML,diff --git a/js/lexical-core/transformers/paste.ts b/js/lexical-core/transformers/paste.tsnew file mode 100644index 0000000000..34bddaca4b--- /dev/null+++ b/js/lexical-core/transformers/paste.ts@@ -0,0 +1,58 @@+import type { ElementTransformer } from '@lexical/markdown';+import type { ElementNode, LexicalNode } from 'lexical';+import { $createPasteNode, $isPasteNode, PasteNode } from '../nodes/PasteNode';++// Internal Paste Node - uses XML-based format for serialization so the+// arbitrary pasted text survives a markdown round-trip without being parsed+// as markdown itself. Angle brackets in the content are escaped as unicode+// escapes so that XML tags inside the content don't get matched by other+// element transformers during import (JSON.parse handles </>).+export const I_PASTE_NODE: ElementTransformer = {+ dependencies: [PasteNode],+ type: 'element',+ regExp: /<m-paste>(.*?)<\/m-paste>/,+ export: (node) => {+ if (!$isPasteNode(node)) return null;+ const data = JSON.stringify({+ content: node.getContent(),+ })+ .replace(/</g, '\\u003c')+ .replace(/>/g, '\\u003e');+ return `<m-paste>${data}</m-paste>`;+ },+ replace: (+ parentNode: ElementNode,+ _children: Array<LexicalNode>,+ match: Array<string>+ ) => {+ try {+ const data = JSON.parse(match[1]);+ if (!('content' in data)) throw new Error('Missing field content');+ const pasteNode = $createPasteNode({ content: data.content });+ parentNode.replace(pasteNode);+ } catch (e) {+ console.error('Error in I_PASTE_NODE replace:', e);+ }+ },+};++// External Paste Node - exports the raw pasted text so external markdown+// consumers see the full content rather than an internal XML tag. Never+// imports (the regex never matches).+export const E_PASTE_NODE: ElementTransformer = {+ dependencies: [PasteNode],+ type: 'element',+ regExp: /$^/,+ export: (node) => {+ if (!$isPasteNode(node)) return null;+ return node.getContent();+ },+ replace: (+ _parentNode: ElementNode,+ _children: Array<LexicalNode>,+ _match: Array<string>,+ _isImport: boolean+ ) => {+ return false;+ },+};