@devries-cameron20 / t3code Mirror · read-only / commits / ff9efe89f6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(web): copying items within one list keeps their list markers (#39150)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 16:09 UTC ff9efe89f6e793fed459d3d9c42f68450de78e95
3 files changed +305 -30
apps/web/src/components/ChatMarkdown.browser.test.tsx
+165 -15
@@ -141,7 +141,10 @@ vi.mock(import("../hooks/useSettings"), async (original) => {
141 });
142
143 import ChatMarkdown from "./ChatMarkdown";
144 -import { chatMarkdownClipboardPayload } from "../markdown-clipboard";
144 +import {
145 + chatMarkdownClipboardPayload,
146 + serializeRenderedMarkdownFragment,
147 +} from "../markdown-clipboard";
148 import { AudioPreview } from "./files/AudioPreview";
149
150 it("keeps compact audio playback loaded across signed URL renewals", async () => {
@@ -857,35 +860,182 @@ describe("ChatMarkdown copy", () => {
860 from: "Deeper",
861 text: "2. 2. Deeper\n\nAfter.",
862 },
863 + {
864 + source: "1. Install\n2. Configure\n3. Deploy",
865 + from: "Configure",
866 + to: "Deploy",
867 + text: "2. Configure\n3. Deploy",
868 + },
869 + {
870 + source: "1. A\n2. B\n7. C\n8. D",
871 + from: "B",
872 + to: "C",
873 + userMessage: true,
874 + text: "2. B\n7. C",
875 + },
876 + {
877 + source: "- Install\n- Configure\n- Deploy",
878 + from: "Configure",
879 + to: "Deploy",
880 + text: "- Configure\n- Deploy",
881 + },
882 ])(
861 - "keeps the shown numbers when a copy starts at $from and ends past the list",
862 - async ({ source, from, userMessage, text }) => {
883 + "copies $text with the markers its list shows",
884 + async ({ source, from, to, userMessage, text }) => {
885 setup();
886 await using screen = await renderText(
887 source,
888 userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {},
889 );
868 - const start = [...screen.container.querySelectorAll("li")]
869 - .flatMap((item) => [...item.childNodes])
870 - .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === from)!;
871 - const after = [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
890 + const itemText = (shown: string) =>
891 + [...screen.container.querySelectorAll("li")]
892 + .flatMap((item) => [...item.childNodes])
893 + .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === shown)!;
894 + const end = to
895 + ? itemText(to)
896 + : [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
897 + const range = document.createRange();
898 + range.setStart(itemText(from), 0);
899 + range.setEnd(end, end.textContent!.length);
900 + const selection = window.getSelection()!;
901 + selection.removeAllRanges();
902 + selection.addRange(range);
903 + const payload = chatMarkdownClipboardPayload(selection);
904 + expect(payload?.text).toBe(text);
905 + // Rich paste reads back as the same list.
906 + expect(
907 + serializeRenderedMarkdownFragment(
908 + new DOMParser().parseFromString(payload!.html, "text/html").body,
909 + ),
910 + ).toBe(text);
911 + },
912 + );
913 +
914 + it.each([
915 + {
916 + source: "1. [ ] Install\n2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
917 + from: "Configure",
918 + to: "Deploy",
919 + text: "2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
920 + htmlText: "2. Configure\n3. Test\n4. Deploy",
921 + },
922 + {
923 + source:
924 + "1. First\n2. [x] Outer\n 1. [ ] Setup\n 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
925 + from: "Configure",
926 + text: "2. [x] 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
927 + htmlText: "2. 2. Configure\n 3. Deploy\n\nAfter.",
928 + },
929 + ])(
930 + "copies task items with the markers its list shows: $text",
931 + async ({ source, from, to, text, htmlText }) => {
932 + setup();
933 + await using screen = await renderText(source);
934 + const itemText = (label: string) =>
935 + [...screen.container.querySelectorAll("li")]
936 + .flatMap((item) => [...item.childNodes])
937 + .find((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim() === label)!;
938 + const start = itemText(from);
939 + const end = to ? itemText(to) : screen.container.querySelector("p")!.firstChild!;
940 const range = document.createRange();
873 - range.setStart(start, 0);
874 - range.setEnd(after, after.textContent!.length);
941 + range.setStart(start, start.textContent!.indexOf(from));
942 + range.setEnd(end, end.textContent!.length);
943 const selection = window.getSelection()!;
944 selection.removeAllRanges();
945 selection.addRange(range);
946 const payload = chatMarkdownClipboardPayload(selection);
947 expect(payload?.text).toBe(text);
880 - // Rich paste numbers its list from the same start.
948 + // HTML sanitization strips form controls.
949 expect(
882 - new DOMParser()
883 - .parseFromString(payload!.html, "text/html")
884 - .querySelector("li")
885 - ?.closest("ol")?.start,
886 - ).toBe(Number(text.split(".")[0]));
950 + serializeRenderedMarkdownFragment(
951 + new DOMParser().parseFromString(payload!.html, "text/html").body,
952 + ),
953 + ).toBe(htmlText);
954 },
955 );
956 +
957 + it.each([
958 + {
959 + source: "1. First\n2. Second\n\nAfter.",
960 + from: "First",
961 + skipFrom: true,
962 + text: "2. Second\n\nAfter.",
963 + items: 1,
964 + },
965 + {
966 + source: "Before.\n\n1. First\n2. Second",
967 + from: "Before.",
968 + to: "Second",
969 + skipTo: true,
970 + text: "Before.\n\n1. First",
971 + items: 1,
972 + },
973 + {
974 + source: "1. Outer\n 1. Inner\n 2. Deeper\n2. Next",
975 + from: "Inner",
976 + to: "Next",
977 + skipFrom: true,
978 + text: "1. 2. Deeper\n2. Next",
979 + items: 3,
980 + },
981 + {
982 + source: "1. Outer\n 1. Inner\n2. Next",
983 + from: "Inner",
984 + to: "Next",
985 + skipFrom: true,
986 + text: "2. Next",
987 + items: 1,
988 + },
989 + ])(
990 + "omits edge items outside the selection when copying with the markers its list shows: $text",
991 + async ({ source, from, to, skipFrom, skipTo, text, items }) => {
992 + setup();
993 + await using screen = await renderText(source);
994 + const textNode = (shown: string) => {
995 + const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
996 + for (let node = walker.nextNode(); node; node = walker.nextNode()) {
997 + if (node.textContent === shown) return node;
998 + }
999 + throw new Error(`Could not find text: ${shown}`);
1000 + };
1001 + const end = to ? textNode(to) : textNode("After.");
1002 + const range = document.createRange();
1003 + range.setStart(textNode(from), skipFrom ? from.length : 0);
1004 + range.setEnd(end, skipTo ? 0 : end.textContent!.length);
1005 + const selection = window.getSelection()!;
1006 + selection.removeAllRanges();
1007 + selection.addRange(range);
1008 +
1009 + const payload = chatMarkdownClipboardPayload(selection);
1010 + expect(payload?.text).toBe(text);
1011 + const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1012 + expect(serializeRenderedMarkdownFragment(pasted.body)).toBe(text);
1013 + expect(pasted.querySelectorAll("li")).toHaveLength(items);
1014 + },
1015 + );
1016 +
1017 + it("omits an end item whose selected edge sits inside its link", async () => {
1018 + setup();
1019 + await using screen = await renderText(
1020 + "1. Install\n2. Configure\n3. Deploy\n4. [Verify](https://example.com/verify)",
1021 + );
1022 + const items = [...screen.container.querySelectorAll("li")];
1023 + const start = items.find((item) => item.textContent === "Configure")!.firstChild!;
1024 + const end = items.at(-1)!.querySelector("a > span")!.lastChild!;
1025 + const range = document.createRange();
1026 + range.setStart(start, 0);
1027 + range.setEnd(end, 0);
1028 + const selection = window.getSelection()!;
1029 + selection.removeAllRanges();
1030 + selection.addRange(range);
1031 +
1032 + const payload = chatMarkdownClipboardPayload(selection);
1033 + expect(payload?.text).toBe("2. Configure\n3. Deploy");
1034 + const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
1035 + expect(
1036 + [...pasted.querySelectorAll('ol[start="2"] > li')].map((item) => item.textContent),
1037 + ).toEqual(["Configure", "Deploy"]);
1038 + });
1039 });
1040
1041 describe("ChatMarkdown file chip tooltips", () => {
apps/web/src/markdown-clipboard.ts
+80 -15
@@ -14,6 +14,7 @@ const SANITIZED_HTML_SELECTOR = [
14
15 const ALERT_ATTRIBUTE = "data-markdown-alert";
16 const ALERT_LABEL = "data-markdown-alert-label";
17 +const LIST_ITEM_CHECKBOX = ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]';
18
19 export interface MarkdownClipboardPayload {
20 text: string;
@@ -131,10 +132,8 @@ function serializeListItem(
132 index: number,
133 inTableCell: boolean,
134 ): string {
134 - const checkbox = item.querySelector(
135 - ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]',
136 - );
137 - const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
135 + const checkbox = item.querySelector<HTMLInputElement>(LIST_ITEM_CHECKBOX);
136 + const task = checkbox ? `[${checkbox.checked ? "x" : " "}] ` : "";
137 const bullet = ordered ? `${index}. ` : "- ";
138 const marker = `${bullet}${task}`;
139 let content = outsideCode(serializeChildren(item, inTableCell), (prose) =>
@@ -505,22 +504,89 @@ function sanitizedHtmlFrom(container: Element): string {
504 return `<meta charset="utf-8">${container.innerHTML}`;
505 }
506
508 -/** A list cloned from a later item would renumber from its start; restart it at the shown number. */
509 -function keepStartListNumbers(range: Range, container: Element): void {
510 - // The start's ancestors below the common ancestor clone as the fragment's first-child chain.
507 +function isList(node: Node): node is HTMLOListElement | HTMLUListElement {
508 + return node instanceof Element && (node.tagName === "OL" || node.tagName === "UL");
509 +}
510 +
511 +// An endpoint can clone empty item wrappers at any nesting depth.
512 +function emptyListBoundary(
513 + ancestor: Node,
514 + node: Node,
515 + offset: number,
516 + side: "start" | "end",
517 +): Element | null {
518 + const next = (node: Node) => (side === "start" ? node.nextSibling : node.previousSibling);
519 + if (node instanceof Text && offset !== (side === "start" ? node.length : 0)) return null;
520 +
521 + let boundary: Element | null = null;
522 + let remaining = node.childNodes[side === "start" ? offset : offset - 1] ?? null;
523 + while (node !== ancestor && node.parentNode) {
524 + for (let sibling = remaining; sibling; sibling = next(sibling)) {
525 + if (sibling instanceof Text && !sibling.data.trim()) continue;
526 + if (
527 + sibling instanceof Element &&
528 + isSkippedElement(sibling) &&
529 + !sibling.hasAttribute("data-markdown-copy") &&
530 + !sibling.hasAttribute("data-markdown-details")
531 + ) {
532 + continue;
533 + }
534 + return boundary;
535 + }
536 + if (node instanceof Element && node.tagName === "LI" && isList(node.parentNode)) {
537 + boundary = node;
538 + } else if (boundary && isList(node)) {
539 + boundary = node;
540 + }
541 + remaining = next(node);
542 + node = node.parentNode;
543 + }
544 + return boundary;
545 +}
546 +
547 +/** Clones the selection and restores the markers shown for its copied list items. */
548 +function cloneWithListMarkers(range: Range, container: Element): void {
549 + const originalAncestor = range.commonAncestorContainer;
550 + const start = emptyListBoundary(
551 + originalAncestor,
552 + range.startContainer,
553 + range.startOffset,
554 + "start",
555 + );
556 + const end = emptyListBoundary(originalAncestor, range.endContainer, range.endOffset, "end");
557 + if (start || end) {
558 + range = range.cloneRange();
559 + if (start) range.setStartAfter(start);
560 + if (end) range.setEndBefore(end);
561 + }
562 + const ancestor = range.commonAncestorContainer;
563 + const withinList = isList(ancestor);
564 + container.appendChild(range.cloneContents());
565 + if (withinList) {
566 + // Items copied within one list clone without the list around them.
567 + const list = ancestor.cloneNode(false) as Element;
568 + list.append(...container.childNodes);
569 + container.replaceChildren(list);
570 + }
571 + // The start's ancestors below the cloned top clone as the fragment's first-child chain.
572 + const top = withinList ? ancestor.parentNode : ancestor;
573 const chain: Node[] = [];
512 - for (
513 - let node: Node | null = range.startContainer;
514 - node && node !== range.commonAncestorContainer;
515 - node = node.parentNode
516 - ) {
574 + for (let node: Node | null = range.startContainer; node && node !== top; node = node.parentNode) {
575 chain.unshift(node);
576 }
577 let clone: Node | null = container;
578 for (const [depth, source] of chain.entries()) {
579 clone = clone?.firstChild ?? null;
522 - if (!(clone instanceof Element) || !(source instanceof Element) || source.tagName !== "OL")
580 + if (!(clone instanceof Element) || !(source instanceof Element)) continue;
581 + if (source.tagName === "LI" && clone.tagName === "LI") {
582 + const checkbox = source.querySelector(LIST_ITEM_CHECKBOX);
583 + if (checkbox && !clone.querySelector(LIST_ITEM_CHECKBOX)) {
584 + // Keep the first-child chain intact for nested items.
585 + clone.append(checkbox.cloneNode(false));
586 + }
587 continue;
588 + }
589 + if (source.tagName !== "OL") continue;
590 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
591 if (!firstCopied) continue;
592 const shown = numberedListItems(source).find(
@@ -544,8 +610,7 @@ export function chatMarkdownClipboardPayload(
610 const range = selection.getRangeAt(index);
611 if (range.collapsed) continue;
612 const container = document.createElement("div");
547 - container.appendChild(range.cloneContents());
548 - keepStartListNumbers(range, container);
613 + cloneWithListMarkers(range, container);
614 // The indentation typed at a line start only shows; pasted, it would turn lines into code.
615 for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
616 indentation.remove();
scripts/scenarios/copied-items-within-numbered-list-keep-numbers.e2e.ts new
+60
@@ -0,0 +1,60 @@
1 +/// <reference lib="dom" />
2 +import { expect } from "e2e";
3 +
4 +import { test, WEB } from "./t3.ts";
5 +
6 +test(
7 + "Copying two items within a numbered list keeps their numbers",
8 + WEB,
9 + async ({ t3, app, browser, screen }) => {
10 + const project = await t3.project("demo");
11 + const thread = await t3.thread({
12 + project,
13 + title: "Steps",
14 + messages: ["Steps:\n\n1. Install\n2. Configure\n3. Deploy\n\nThen report back."],
15 + });
16 + await t3.open(thread);
17 + await screen.getByRole("button", /^Agent Steps/).tap();
18 + await screen.getByText("Configure", { exact: true }).waitFor();
19 +
20 + await browser.evaluate(() => {
21 + const items = [...document.querySelectorAll("[data-user-message-body] ol > li")];
22 + const start = items.find((item) => item.textContent === "Configure")?.firstChild;
23 + const end = items.find((item) => item.textContent === "Deploy")?.firstChild;
24 + if (!start || !end) throw new Error("Could not find the two list items");
25 + const range = document.createRange();
26 + range.setStart(start, 0);
27 + range.setEnd(end, end.textContent?.length ?? 0);
28 + const selection = window.getSelection();
29 + selection?.removeAllRanges();
30 + selection?.addRange(range);
31 + return null;
32 + });
33 + await browser.keyboard.press("ControlOrMeta+C");
34 + await screen.getByRole("textbox").tap();
35 + await browser.keyboard.press("ControlOrMeta+V");
36 +
37 + const numberedItems = await browser.evaluate(() => {
38 + const list = document.querySelector<HTMLOListElement>('[role="textbox"] ol');
39 + if (!list) return null;
40 + return [...list.querySelectorAll(":scope > li")].map(
41 + (item, index) => `${list.start + index}. ${item.textContent?.trim()}`,
42 + );
43 + });
44 + await app.screenshot("pasted-list-items");
45 + expect(numberedItems, "The pasted items keep their displayed list numbers").toEqual([
46 + "2. Configure",
47 + "3. Deploy",
48 + ]);
49 +
50 + const renderedItems = await browser.evaluate(() =>
51 + [...document.querySelectorAll('[role="textbox"] ol > li')].map(
52 + (item) => `${item.getAttribute("data-marker")} ${item.textContent?.trim()}`,
53 + ),
54 + );
55 + expect(renderedItems, "The composer renders both pasted markers").toEqual([
56 + "2. Configure",
57 + "3. Deploy",
58 + ]);
59 + },
60 +);