Skip to content

Commit 20353d5

Browse files
matt2eclaude
andcommitted
fix(composer): paste this app's copied blocks and marks as nodes
Copying a rendered message (or another composer's content) and pasting it into the composer flattened the parsed document to Markdown source and inserted it as one text node, so bullet, numbered and nested lists, bold/italic/strike, inline code, fenced code blocks and blockquotes all showed as literal `- `, `**`, ```` ``` ```` and `> ` markers in a single paragraph. The wire Markdown was already right; only the composer view was wrong. Split `markdown()` in selection-copy.ts into an exported `copyDocument` that returns the parsed editor document, and replace `buzzCopyMarkdown` with `buzzCopyDocument`, which demotes parsed anchors and line breaks to source text so the host's decorations still decide which links become chips, as for typed source. The paste handler inserts that document as a ProseMirror `Slice` in one `closeHistory`'d transaction: a single paragraph pastes inline, anything else lands as sibling blocks; the `maxLength` guard, caret placement, undo-as-one-step and `promoteRecipients` behave as before. Unformatted prose still takes the text path, inheriting the caret's marks and the message-link spacing. Unchanged: `text/plain` pastes stay literal (PR #455), the code-block guard, and external HTML's links-only import (PR #1069). Pasting two rendered paragraphs mid-sentence now splits the sentence around them instead of merging into its words. Tests assert the composer DOM (`ul li`, `ol[start]`, `blockquote`, `pre`, `strong`) in the timeline → composer and composer → composer round trips, plus new cases for a list after prose, inline marks mid-sentence, paragraph splitting, promotion inside pasted blocks, the code-block guard and the paste limit. `buzzCopyDocument` and `copyDocument` get node-shape cases; the Chromium journey checks the pasted blocks before sending. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent ec1b9ac commit 20353d5

9 files changed

Lines changed: 292 additions & 41 deletions

File tree

‎docs/channels.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1237,7 +1237,9 @@ implemented. In the composer, typing the third character of a line holding only
12371237
Shift+Enter on an empty last line leaves the block. Only a fence that opens a block converts: a
12381238
fence typed inside an existing code block stays literal, and so does pasted or restored fenced
12391239
text, including its closing fence line, so Enter after a pasted or edited fenced block sends or
1240-
saves as usual and the text still renders as code once sent.
1240+
saves as usual and the text still renders as code once sent. Content copied from a rendered
1241+
message or from a composer pastes with its lists, quotes, code blocks and inline formatting as
1242+
the composer's own blocks and formatting; text copied from anywhere else pastes literally.
12411243
Typing the space after a list or quote marker that starts a line (`- `, `* `, `+ ` or `• `, a number
12421244
with a dot or parenthesis such as `1. ` or `3) `, or `> `) turns that line into a bullet, a
12431245
numbered item starting at that number, or a quoted paragraph at once, the same block the

‎src/bundled/channels/ChannelCompletion.test.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import { LinkLabel } from "../links/InlineLink";
2020
import { ChannelCompletion } from "./ChannelCompletion";
2121
import {
2222
composerClipboard,
23-
buzzCopyMarkdown,
23+
buzzCopyDocument,
2424
} from "../../features/messages/composer-clipboard";
2525
import { composerSchema } from "../../features/messages/composer-document";
2626

@@ -206,7 +206,7 @@ it.each(["Beta", "a [b] *c* _d_ ~e~ &amp; <f> \\ !"])(
206206
const html = new DOMParser().parseFromString(copied.html, "text/html");
207207
expect(html.querySelector("a")?.textContent).toBe(`#${name}`);
208208
expect(
209-
scanMarkdown(buzzCopyMarkdown(copied.html) ?? "").links[0],
209+
scanMarkdown(buzzCopyDocument(copied.html)?.textContent ?? "").links[0],
210210
).toMatchObject({
211211
url: "buzz://channel/beta",
212212
children: [{ type: "text", value: `#${name}` }],

‎src/features/messages/EditableInput.test.tsx‎

Lines changed: 88 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2832,23 +2832,25 @@ it("uses plain text when pasting rich content into an existing code block", asyn
28322832
});
28332833

28342834
it.each([
2835-
["First\n\nSecond", "First\n\nSecond"],
2836-
["First\nSecond", "First\nSecond"],
2837-
["> First\n>\n> Second", "First\n\nSecond"],
2838-
["- one\n- two", "one\ntwo"],
2839-
["3. first\n4. second", "first\nsecond"],
2840-
["> quoted", "quoted"],
2841-
["```sh\necho hi\n```", "echo hi\n"],
2842-
["```sh\necho hi\n\n```", "echo hi\n\n"],
2843-
["| a | b |\n| - | - |\n| 1 | 2 |", "a\tb\n1\t2"],
2844-
["para\n\n```sh\necho hi\n```\n\nafter", "para\n\necho hi\n\nafter"],
2835+
["First\n\nSecond", "First\n\nSecond", ""],
2836+
["First\nSecond", "First\nSecond", ""],
2837+
["> First\n>\n> Second", "First\n\nSecond", "blockquote"],
2838+
["- one\n- two", "one\ntwo", "ul li + li"],
2839+
["3. first\n4. second", "first\nsecond", 'ol[start="3"] li + li'],
2840+
["- one\n \n - sub\n- two", "one\n\nsub\ntwo", "ul li ul li"],
2841+
["> quoted", "quoted", "blockquote"],
2842+
["```sh\necho hi\n```", "echo hi\n", 'pre[data-language="sh"]'],
2843+
["```sh\necho hi\n\n```", "echo hi\n\n", 'pre[data-language="sh"]'],
2844+
["| a | b |\n| - | - |\n| 1 | 2 |", "a\tb\n1\t2", ""],
2845+
["para\n\n```sh\necho hi\n```\n\nafter", "para\n\necho hi\n\nafter", "pre"],
28452846
[
28462847
"intro\n\n- one\n- two\n\n> quoted\n\nouter",
28472848
"intro\n\none\ntwo\n\nquoted\n\nouter",
2849+
"ul li + li, blockquote",
28482850
],
28492851
])(
28502852
"copies real timeline structure through the composer: %s",
2851-
(content, plain) => {
2853+
(content, plain, shown) => {
28522854
const view = render(
28532855
<MessageMarkdown
28542856
row={{
@@ -2888,6 +2890,9 @@ it.each([
28882890
const target = mount();
28892891
paste(target.input, copied.text, copied.html);
28902892
expect(target.markdown()).toBe(content.startsWith("|") ? plain : content);
2893+
// The composer shows the copied blocks, not their source.
2894+
for (const selector of shown ? shown.split(", ") : [])
2895+
expect(target.input.querySelector(selector)).not.toBeNull();
28912896
},
28922897
);
28932898

@@ -2929,6 +2934,8 @@ it.each(["-", "3."])(
29292934
const target = mount();
29302935
paste(target.input, text, html);
29312936
expect(target.markdown()).toBe("sk **Morgan** ab");
2937+
expect(target.input.querySelector("strong")).toHaveTextContent("Morgan");
2938+
expect(target.input.querySelector("ul, ol")).toBeNull();
29322939

29332940
// Selecting the enclosing list still keeps its marker and starting number.
29342941
range.selectNodeContents(view.getByRole("list"));
@@ -3061,10 +3068,79 @@ it("copies marked whitespace, lists, a quote and a fence as HTML that reads back
30613068
),
30623069
});
30633070
expect(readBack(copied.html)).toBe(h.markdown());
3064-
// Pasted into another composer, the message sends with the same source.
3071+
// Pasted into another composer, the message sends with the same source and
3072+
// shows the same blocks and marks.
30653073
const target = mount();
30663074
paste(target.input, copied.text ?? "", copied.html);
30673075
expect(target.markdown()).toBe(h.markdown());
3076+
for (const selector of [
3077+
"strong",
3078+
"ul li + li",
3079+
'ol[start="3"] li',
3080+
"blockquote p",
3081+
'pre[data-language="sh"] code',
3082+
])
3083+
expect(target.input.querySelector(selector)).not.toBeNull();
3084+
});
3085+
3086+
it("pastes this app's blocks as sibling nodes, one paragraph inline, and undoes as one step", () => {
3087+
const list = copyHtml("<ul><li><p>one</p></li><li><p>two</p></li></ul>");
3088+
const h = mount("intro");
3089+
act(() => h.input.setSelectionRange(5, 5));
3090+
paste(h.input, "one\ntwo", list);
3091+
expect(h.input.querySelectorAll("ul li")).toHaveLength(2);
3092+
expect(h.markdown()).toBe("intro\n\n- one\n- two");
3093+
expect(h.input.selectionStart).toBe(h.input.value.length);
3094+
act(() => h.input.undo(false));
3095+
expect(h.markdown()).toBe("intro");
3096+
expect(h.input.querySelector("ul")).toBeNull();
3097+
// One marked paragraph stays in the sentence; several paragraphs split it.
3098+
const inline = mount("xxyy");
3099+
act(() => inline.input.setSelectionRange(2, 2));
3100+
paste(inline.input, "a b c", copyHtml("<p>a <strong>b</strong> c</p>"));
3101+
expect(inline.markdown()).toBe("xxa **b** cyy");
3102+
expect(inline.input.querySelectorAll("p")).toHaveLength(1);
3103+
expect(inline.input.querySelector("strong")).toHaveTextContent("b");
3104+
const split = mount("xxyy");
3105+
act(() => split.input.setSelectionRange(2, 2));
3106+
paste(
3107+
split.input,
3108+
"First\n\nSecond",
3109+
'<div data-buzz-copy="timeline"><p>First</p><p>Second</p></div>',
3110+
);
3111+
expect(split.markdown()).toBe("xx\nFirst\n\nSecond\nyy");
3112+
});
3113+
3114+
it("promotes identity links inside this app's pasted blocks", () => {
3115+
const accept = vi.fn((pubkey: string) => ({ pubkey, name: "Mic" }));
3116+
const h = mount("", { links: true, acceptRecipient: accept });
3117+
paste(
3118+
h.input,
3119+
"Ping @Mic",
3120+
copyHtml(
3121+
`<ul><li><p>Ping <a href="${profileTarget(mic)}">@Mic</a></p></li></ul>`,
3122+
),
3123+
);
3124+
expect(h.input.querySelector("ul li [data-mention]")).toHaveTextContent(
3125+
"@Mic",
3126+
);
3127+
expect(h.markdown()).toBe("- Ping @Mic");
3128+
expect(h.draft().recipients).toEqual([
3129+
{ pubkey: mic, name: "Mic", start: 5, end: 9 },
3130+
]);
3131+
});
3132+
3133+
it("keeps this app's blocks literal in a code block and within the paste limit", () => {
3134+
const list = copyHtml("<ul><li><p>one</p></li><li><p>two</p></li></ul>");
3135+
const h = mount();
3136+
act(() => h.input.toggleFormat("code_block"));
3137+
paste(h.input, "one\ntwo", list);
3138+
expect(h.markdown()).toBe("```\none\ntwo\n```");
3139+
expect(h.input.querySelector("ul")).toBeNull();
3140+
const limited = mount("", { maxLength: 8 });
3141+
paste(limited.input, "one\ntwo", list);
3142+
expect(limited.markdown()).toBe("");
3143+
expect(limited.input.querySelector("ul")).toBeNull();
30683144
});
30693145

30703146
it("pastes this app's HTML as identity Markdown and other HTML as its text/plain", () => {

‎src/features/messages/EditableInput.tsx‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import {
3232
selectAll,
3333
} from "prosemirror-commands";
3434
import { sinkListItem, liftListItem } from "prosemirror-schema-list";
35-
import { Fragment } from "prosemirror-model";
35+
import { Fragment, Slice, type Node as EditorNode } from "prosemirror-model";
3636
import {
3737
composerSchema,
3838
readComposerDocument,
@@ -61,7 +61,7 @@ import {
6161
} from "./composer-inline-input";
6262
import { composerMarkdown } from "./composer-markdown";
6363
import {
64-
buzzCopyMarkdown,
64+
buzzCopyDocument,
6565
externalLinkMarkdown,
6666
composerClipboard,
6767
identityLink,
@@ -604,6 +604,26 @@ export function EditableInput({
604604
if (focus) editor.focus();
605605
return true;
606606
};
607+
/** Paste this app's own copied blocks and marks as the nodes they are. One
608+
* paragraph joins the caret's line; anything else lands as sibling blocks,
609+
* splitting the caret's paragraph rather than merging into its text. */
610+
const insertDocument = (doc: EditorNode) => {
611+
if (!editable() || composing.current || editor.composing) return false;
612+
const paragraph = doc.childCount === 1 ? doc.firstChild : null;
613+
const slice =
614+
paragraph?.type === composerSchema.nodes.paragraph
615+
? new Slice(paragraph.content, 0, 0)
616+
: new Slice(doc.content, 0, 0);
617+
const tr = closeHistory(editor.state.tr).replaceSelection(slice);
618+
if (
619+
composerMarkdown(projectComposerDocument(tr.doc).draft).length >
620+
current.current.maxLength
621+
)
622+
return false;
623+
editor.dispatch(tr.scrollIntoView());
624+
editor.focus();
625+
return true;
626+
};
607627
const replaceRecipients = (recipients: readonly MentionRecipient[]) => {
608628
if (!editable() || composing.current || editor.composing) return false;
609629
const source = projection();
@@ -1579,9 +1599,30 @@ export function EditableInput({
15791599
const plain = event.clipboardData?.getData("text/plain") ?? "";
15801600
const hasPlain =
15811601
!!plain || event.clipboardData?.types?.includes("text/plain");
1602+
const copy = code ? undefined : buzzCopyDocument(html);
1603+
// Unformatted prose takes the text path: it inherits the caret's
1604+
// marks and the link spacing below. Structure pastes as nodes.
1605+
const paragraph = copy?.childCount === 1 ? copy.firstChild : null;
1606+
const prose =
1607+
paragraph?.type === composerSchema.nodes.paragraph &&
1608+
paragraph.childCount <= 1 &&
1609+
!paragraph.firstChild?.marks.length
1610+
? paragraph.textContent
1611+
: undefined;
1612+
const source = projection(),
1613+
start = source.source(editor.state.selection.from),
1614+
end = source.source(editor.state.selection.to);
1615+
if (copy && prose === undefined) {
1616+
if (insertDocument(copy))
1617+
promoteRecipients(
1618+
start,
1619+
projection().source(editor.state.selection.to),
1620+
);
1621+
return true;
1622+
}
15821623
let text =
15831624
(!code &&
1584-
(buzzCopyMarkdown(html) ??
1625+
(prose ??
15851626
externalLinkMarkdown(html, hasPlain ? plain : undefined))) ||
15861627
plain ||
15871628
"";
@@ -1591,9 +1632,6 @@ export function EditableInput({
15911632
messageLinkParts(text, undefined, (start, end) => {
15921633
if (start === 0 && end === text.length) link = true;
15931634
});
1594-
const source = projection(),
1595-
start = source.source(editor.state.selection.from),
1596-
end = source.source(editor.state.selection.to);
15971635
const reuse = link && source.draft.text[end] === " ";
15981636
if (
15991637
link &&
Lines changed: 77 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,89 @@
11
// @vitest-environment jsdom
22
import { expect, it } from "vitest";
3-
import { buzzCopyMarkdown, composerClipboard } from "./composer-clipboard";
3+
import { buzzCopyDocument, composerClipboard } from "./composer-clipboard";
44
import { composerSchema } from "./composer-document";
55

6+
const { doc, paragraph, bullet_list, list_item, token } = composerSchema.nodes;
7+
68
it("copies plain text and unlinked tokens as text and round-trips clipboard HTML", () => {
79
const source = "<img src=x onerror=alert(1)> & text";
8-
const doc = composerSchema.nodes.doc.create(
9-
null,
10-
composerSchema.nodes.paragraph.create(null, [
11-
composerSchema.text("before "),
12-
composerSchema.nodes.token.create({ source }),
13-
composerSchema.text(" after"),
14-
]),
10+
const copied = composerClipboard(
11+
doc.create(
12+
null,
13+
paragraph.create(null, [
14+
composerSchema.text("before "),
15+
token.create({ source }),
16+
composerSchema.text(" after"),
17+
]),
18+
),
19+
document,
1520
);
16-
const copied = composerClipboard(doc, document);
1721
const html = new DOMParser().parseFromString(copied.html, "text/html");
1822
expect(html.body.textContent).toBe(`before ${source} after`);
1923
expect(html.querySelector("img")).toBeNull();
2024
expect(copied.text).toBe(`before ${source} after`);
21-
expect(buzzCopyMarkdown(copied.html)).toBe(copied.text);
25+
expect(buzzCopyDocument(copied.html)?.toJSON()).toEqual({
26+
type: "doc",
27+
content: [
28+
{
29+
type: "paragraph",
30+
content: [{ type: "text", text: `before ${source} after` }],
31+
},
32+
],
33+
});
34+
});
35+
36+
it("reads its own blocks and marks back as nodes, with anchors and breaks as text", () => {
37+
const bold = [composerSchema.marks.bold.create()];
38+
const copied = composerClipboard(
39+
doc.create(null, [
40+
paragraph.create(null, [
41+
composerSchema.text("a"),
42+
composerSchema.text("\nb", bold),
43+
]),
44+
bullet_list.create(
45+
null,
46+
list_item.create(
47+
null,
48+
paragraph.create(null, [
49+
composerSchema.text("see "),
50+
token.create({ source: "[docs](https://example.com/)" }),
51+
]),
52+
),
53+
),
54+
]),
55+
document,
56+
);
57+
expect(copied.html).toBe(
58+
'<div data-buzz-copy="composer"><p>a<strong><br>b</strong></p><ul><li><p>see <a href="https://example.com/">docs</a></p></li></ul></div>',
59+
);
60+
expect(buzzCopyDocument(copied.html)?.toJSON()).toEqual({
61+
type: "doc",
62+
content: [
63+
{
64+
type: "paragraph",
65+
content: [
66+
{ type: "text", text: "a" },
67+
{ type: "text", text: "\nb", marks: [{ type: "bold" }] },
68+
],
69+
},
70+
{
71+
type: "bullet_list",
72+
content: [
73+
{
74+
type: "list_item",
75+
content: [
76+
{
77+
type: "paragraph",
78+
content: [
79+
{ type: "text", text: "see [docs](https://example.com/)" },
80+
],
81+
},
82+
],
83+
},
84+
],
85+
},
86+
],
87+
});
88+
expect(buzzCopyDocument("<p>other</p>")).toBeUndefined();
2289
});

‎src/features/messages/composer-clipboard.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { safeLinkUrl, scanMarkdown } from "../relay/message-content";
99
import { composerSchema, projectComposerDocument } from "./composer-document";
1010
import { composerMarkdown } from "./composer-markdown";
1111
import { messageLinkParts } from "./message-link-parts";
12-
import { serializeNode } from "./selection-copy";
12+
import { copyDocument, serializeNode } from "./selection-copy";
1313

1414
/** The identity locator a whole source is: `[@Name](nostr:npub…)`. */
1515
export function identityLink(
@@ -162,13 +162,22 @@ export function composerClipboard(doc: EditorNode, document: Document) {
162162
};
163163
}
164164

165-
/** Markdown for this app's own `text/html` payload; other HTML is never read. */
166-
export function buzzCopyMarkdown(html: string): string | undefined {
165+
/** This app's own `text/html` payload as editor content; other HTML is never
166+
* read. Its blocks and marks paste as they are, while anchors and line breaks
167+
* become source text: the host's decorations decide which links are chips, as
168+
* for typed source, and paragraphs keep line breaks as text. */
169+
export function buzzCopyDocument(html: string): EditorNode | undefined {
167170
if (!html.includes("data-buzz-copy")) return;
168171
const copy = new DOMParser()
169172
.parseFromString(html, "text/html")
170173
.querySelector("[data-buzz-copy]");
171-
return copy ? serializeNode(copy, "markdown") : undefined;
174+
return copy ? sourced(copyDocument(copy)) : undefined;
175+
}
176+
177+
function sourced(node: EditorNode): EditorNode {
178+
if (node.isText) return node;
179+
if (node.isLeaf) return composerSchema.text(node.textContent, node.marks);
180+
return node.copy(Fragment.fromArray(node.content.content.map(sourced)));
172181
}
173182

174183
/** External HTML contributes web links, never Buzz identity metadata or styling. */

0 commit comments

Comments
 (0)