Skip to content

Commit e8172b5

Browse files
matt2ewesbillmanCarl
authored
feat(desktop): hyperlink selected composer text on link paste (block#6684)
## Summary Pasting a link while composer text is selected now turns that text into a hyperlink instead of replacing it — the behavior people expect from every other editor. - `resolveExactLinkPaste` recognizes a clipboard payload that is exactly one supported link (bare or `<…>`-wrapped `http(s)`, or a Buzz deep link, canonicalized through the existing composer-link attribute resolver) and returns the href to apply. - The paste handler applies that href as a `link` mark over the current selection, collapses the caret to the end of the newly linked range, clears stored marks so subsequent typing isn't linked, and refocuses the editor. Edge cases handled: - **No link mark available / selection can't carry marks** — falls through to the existing replace-with-node path rather than silently dropping the paste. - **Selection contains a composer message-link chip** — keeps the old replacement behavior instead of nesting a link over a chip. - **Whitespace in the clipboard payload** — `unwrapExactHttpLink` now rejects any text containing whitespace, so multi-line or "text plus URL" pastes are not treated as an exact link. - **Empty selection (caret paste)** — unchanged. - **Idempotent re-paste** of an already-wrapped link is consumed rather than doubling up. ## Testing `desktop/src/features/messages/lib/composerMessageLinkNode.test.mjs` gains coverage for exact-link resolution (per-shape accept/reject cases, Buzz canonicalization) and for the paste handler: linking selected text, canonicalizing Buzz links over a selection, idempotent wrapped-link paste, fall-through when the selection can't carry marks, all-selection collapse, chip-containing selections, and preserved caret-paste behavior. Full pre-push gate ran green on this branch: `file-size-check`, `desktop-check`, `desktop-typecheck`, and `desktop-test` (5425 tests, 0 failures). ## Demo Pasting an `https://` URL over selected composer text turns the selected words into a hyperlink (instead of replacing them); text typed immediately after is not linked: https://github.com/user-attachments/assets/bbc93574-dd9d-4b1b-bad0-53307b6e887c --------- Signed-off-by: Matt Toohey <[email protected]> Signed-off-by: Wes <[email protected]> Co-authored-by: Wes <[email protected]> Co-authored-by: Carl <32a2e2c9d428ee08902cab75d956da2c1d235a22d4766b0dd4138bf6e2e5db1d@buzz.block.builderlab.xyz>
1 parent 52621c0 commit e8172b5

7 files changed

Lines changed: 855 additions & 61 deletions

File tree

‎desktop/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"embla-carousel-react": "^8.6.0",
6767
"emoji-mart": "^5.6.0",
6868
"jdenticon": "^3.3.0",
69+
"linkifyjs": "^4.3.2",
6970
"lucide-react": "^1.0.0",
7071
"mdast-util-from-markdown": "^2.0.3",
7172
"motion": "^12.38.0",
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
/**
2+
* Composed-editor regression coverage for selected-text link paste.
3+
*
4+
* The unit tests in `composerMessageLinkNode.test.mjs` drive
5+
* `createComposerLinkPasteHandler` against a hand-built schema and a mock
6+
* view — they cannot see what happens *after* the handler declines. That gap
7+
* hid a real bug: `false` from `editorProps.handleDOMEvents.paste` does not end
8+
* paste handling, it hands the event to ProseMirror's built-in paste, which
9+
* runs every plugin's `handlePaste`. TipTap's Link plugin recognised the same
10+
* URLs one layer down and partially linked selections the composer had
11+
* deliberately refused.
12+
*
13+
* So these tests build the *production* editor from `useRichTextEditor` and
14+
* dispatch a real DOM `paste` event at `view.dom`. If someone re-enables
15+
* `linkOnPaste` or slots another URL-aware plugin into the chain, this fails.
16+
*/
17+
import assert from "node:assert/strict";
18+
import { after, afterEach, before, test } from "node:test";
19+
20+
import { JSDOM } from "jsdom";
21+
import { find as findLinks } from "linkifyjs";
22+
23+
const dom = new JSDOM("<!doctype html><html><body></body></html>", {
24+
url: "http://localhost",
25+
});
26+
27+
const CHANNEL_ID = "9a1657ac-f7aa-5db0-b632-d8bbeb6dfb50";
28+
const CHANNEL_HREF = `buzz://channel/${CHANNEL_ID}`;
29+
const MESSAGE_LINK_CHANNELS = [{ id: CHANNEL_ID, name: "general" }];
30+
31+
before(() => {
32+
dom.window.HTMLElement.prototype.scrollIntoView = () => {};
33+
// `navigator` is a getter-only global from Node 21 on, so Object.assign
34+
// throws on it. prosemirror-view reads userAgent for browser quirks.
35+
Object.defineProperty(globalThis, "navigator", {
36+
configurable: true,
37+
value: dom.window.navigator,
38+
});
39+
Object.assign(globalThis, {
40+
ClipboardEvent: dom.window.Event,
41+
CustomEvent: dom.window.CustomEvent,
42+
DOMParser: dom.window.DOMParser,
43+
document: dom.window.document,
44+
Element: dom.window.Element,
45+
Event: dom.window.Event,
46+
getComputedStyle: dom.window.getComputedStyle.bind(dom.window),
47+
HTMLElement: dom.window.HTMLElement,
48+
IS_REACT_ACT_ENVIRONMENT: true,
49+
MutationObserver: dom.window.MutationObserver,
50+
Node: dom.window.Node,
51+
Range: dom.window.Range,
52+
ResizeObserver: class {
53+
disconnect() {}
54+
observe() {}
55+
unobserve() {}
56+
},
57+
window: dom.window,
58+
});
59+
});
60+
61+
afterEach(async () => {
62+
const { cleanup } = await import("@testing-library/react");
63+
cleanup();
64+
});
65+
66+
after(() => dom.window.close());
67+
68+
/**
69+
* Mounts the production composer editor and returns its Tiptap instance.
70+
*/
71+
async function mountComposerEditor() {
72+
const React = await import("react");
73+
const { act, render, waitFor } = await import("@testing-library/react");
74+
const { EditorContent } = await import("@tiptap/react");
75+
const { useRichTextEditor } = await import("./useRichTextEditor.ts");
76+
77+
let editor = null;
78+
function Harness() {
79+
const instance = useRichTextEditor({
80+
messageLinkChannels: MESSAGE_LINK_CHANNELS,
81+
}).editor;
82+
editor = instance;
83+
return instance
84+
? React.createElement(EditorContent, { editor: instance })
85+
: null;
86+
}
87+
88+
await act(async () => {
89+
render(React.createElement(Harness));
90+
});
91+
// Tiptap emits `create` from a `setTimeout(…, 0)`, and Link's `onCreate` is
92+
// what teaches linkify the `buzz` protocol. Paste before that lands and a
93+
// `buzz://` assertion passes for the wrong reason.
94+
await waitFor(() =>
95+
assert.ok(editor?.isInitialized, "composer editor never emitted `create`"),
96+
);
97+
98+
// Check that precondition rather than trust the wait. It has to be checked
99+
// *after* `create`, never as the poll itself: `find` initialises linkify's
100+
// scanner on first call, and `registerCustomProtocol` after that only warns,
101+
// so polling on `find` would break the registration it is watching for.
102+
assert.equal(
103+
findLinks(CHANNEL_HREF)[0]?.href,
104+
CHANNEL_HREF,
105+
"expected Link's onCreate to register the buzz protocol with linkify",
106+
);
107+
return editor;
108+
}
109+
110+
const paragraph = (...content) => ({ type: "paragraph", content });
111+
const codeBlock = (text) => ({
112+
type: "codeBlock",
113+
content: [{ type: "text", text }],
114+
});
115+
const text = (value, marks) => ({
116+
type: "text",
117+
text: value,
118+
...(marks && { marks }),
119+
});
120+
121+
/**
122+
* Seeds the document from ProseMirror JSON. Not an HTML string —
123+
* `tiptap-markdown` parses `setContent` input as Markdown, so HTML arrives as
124+
* literal text and the test silently exercises the wrong document.
125+
*/
126+
function seedDocument(editor, ...content) {
127+
editor.commands.setContent({ type: "doc", content });
128+
}
129+
130+
function selectAll(editor) {
131+
editor.commands.setTextSelection({
132+
from: 0,
133+
to: editor.state.doc.content.size,
134+
});
135+
}
136+
137+
function pasteText(editor, value) {
138+
const event = new dom.window.Event("paste", {
139+
bubbles: true,
140+
cancelable: true,
141+
});
142+
Object.defineProperty(event, "clipboardData", {
143+
value: {
144+
types: ["text/plain"],
145+
getData: (type) => (type === "text/plain" ? value : ""),
146+
},
147+
});
148+
editor.view.dom.dispatchEvent(event);
149+
}
150+
151+
function linkHrefs(editor) {
152+
const hrefs = [];
153+
editor.state.doc.descendants((node) => {
154+
for (const mark of node.marks) {
155+
if (mark.type.name === "link") hrefs.push(mark.attrs.href);
156+
}
157+
});
158+
return hrefs;
159+
}
160+
161+
function nodeTypeNames(editor) {
162+
const names = [];
163+
editor.state.doc.descendants((node) => {
164+
names.push(node.type.name);
165+
});
166+
return names;
167+
}
168+
169+
test("mixed paragraph and code-block selection is replaced, never part-linked", async () => {
170+
const editor = await mountComposerEditor();
171+
seedDocument(
172+
editor,
173+
paragraph(text("ordinary")),
174+
codeBlock("const value = 1;"),
175+
);
176+
selectAll(editor);
177+
178+
pasteText(editor, "https://example.com");
179+
180+
// The whole selection goes, exactly as it would for any non-link paste.
181+
assert.equal(editor.state.doc.textContent, "https://example.com");
182+
assert.ok(!nodeTypeNames(editor).includes("codeBlock"));
183+
// Crucially, "ordinary" is not left behind wearing a link mark.
184+
assert.ok(!editor.state.doc.textContent.includes("ordinary"));
185+
});
186+
187+
test("mixed selection paste of a Buzz link becomes a chip, not a part-link", async () => {
188+
const editor = await mountComposerEditor();
189+
seedDocument(
190+
editor,
191+
paragraph(text("ordinary")),
192+
codeBlock("const value = 1;"),
193+
);
194+
selectAll(editor);
195+
196+
pasteText(editor, CHANNEL_HREF);
197+
198+
const names = nodeTypeNames(editor);
199+
assert.ok(names.includes("composerMessageLink"));
200+
assert.ok(!names.includes("codeBlock"));
201+
assert.ok(!editor.state.doc.textContent.includes("ordinary"));
202+
assert.deepEqual(linkHrefs(editor), []);
203+
});
204+
205+
test("mixed plain and inline-code selection is replaced, never part-linked", async () => {
206+
const editor = await mountComposerEditor();
207+
seedDocument(
208+
editor,
209+
paragraph(text("plain "), text("inline", [{ type: "code" }])),
210+
);
211+
selectAll(editor);
212+
213+
pasteText(editor, "https://example.com");
214+
215+
assert.ok(!editor.state.doc.textContent.includes("plain "));
216+
assert.equal(editor.state.doc.textContent.trim(), "https://example.com");
217+
});
218+
219+
test("fully markable selection keeps its label and gains the link", async () => {
220+
const editor = await mountComposerEditor();
221+
seedDocument(editor, paragraph(text("read this")));
222+
selectAll(editor);
223+
224+
pasteText(editor, "https://example.com");
225+
226+
assert.equal(editor.state.doc.textContent, "read this");
227+
assert.deepEqual(linkHrefs(editor), ["https://example.com"]);
228+
});
229+
230+
test("fully markable selection keeps its label for linkify-only URL shapes", async () => {
231+
for (const [pasted, expectedHref] of [
232+
["www.example.com", "http://www.example.com"],
233+
234+
]) {
235+
const editor = await mountComposerEditor();
236+
seedDocument(editor, paragraph(text("read this")));
237+
selectAll(editor);
238+
239+
pasteText(editor, pasted);
240+
241+
assert.equal(editor.state.doc.textContent, "read this");
242+
assert.deepEqual(linkHrefs(editor), [expectedHref]);
243+
}
244+
});

0 commit comments

Comments
 (0)