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

main
ts 662 lines 25.3 KB
Raw
1 import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths";
2
3 const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
4 const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
5 const SANITIZED_HTML_SELECTOR = [
6 "button",
7 "input",
8 "script",
9 "style",
10 "svg",
11 '[aria-hidden="true"]',
12 ...SKIPPED_CLASS_NAMES.map((className) => `.${className}`),
13 ].join(", ");
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;
21 html: string;
22 }
23
24 function isSkippedElement(element: Element): boolean {
25 if (SKIPPED_TAGS.has(element.tagName) || element.localName === "svg") return true;
26 if (element.getAttribute("aria-hidden") === "true") return true;
27 return SKIPPED_CLASS_NAMES.some((className) => element.classList.contains(className));
28 }
29
30 function wrapInlineMarker(content: string, marker: string): string {
31 const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(content);
32 const core = match?.[2] ?? "";
33 if (!core) return content;
34 return `${match?.[1] ?? ""}${marker}${core}${marker}${match?.[3] ?? ""}`;
35 }
36
37 // Highlighter spans or newlines identify block code even when its pre wrapper was not copied.
38 function isBlockCodeElement(element: Element, content: string): boolean {
39 if (content.includes("\n")) return true;
40 for (const child of element.childNodes) {
41 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).classList.contains("line")) {
42 return true;
43 }
44 }
45 return false;
46 }
47
48 function wrapInlineCode(code: string): string {
49 const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
50 (max, run) => Math.max(max, run.length),
51 0,
52 );
53 const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
54 // CommonMark strips one edge space from content that has both and isn't all spaces.
55 const spaceEdges = code.startsWith(" ") && code.endsWith(" ") && /[^ ]/.test(code);
56 const pad = spaceEdges || code.startsWith("`") || code.endsWith("`") ? " " : "";
57 return `${fence}${pad}${code}${pad}${fence}`;
58 }
59
60 function codeFenceFor(code: string): string {
61 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
62 (max, run) => Math.max(max, run.length),
63 0,
64 );
65 return "`".repeat(Math.max(3, longestRun + 1));
66 }
67
68 export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
69 const code = source.replace(/\n$/, "");
70 const fence = codeFenceFor(code);
71 return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
72 }
73
74 // Brackets copied code so tidyMarkdown leaves its whitespace alone. Code is
75 // copied as shown, without fences; DOM text from rendered markdown carries no NUL.
76 const CODE_BOUNDARY = "\u0000";
77
78 function verbatimBlock(code: string): string {
79 return `${CODE_BOUNDARY}${code}${CODE_BOUNDARY}\n\n`;
80 }
81
82 // Odd parts are code and keep their markers, so outer passes still skip them.
83 function outsideCode(markdown: string, tidy: (prose: string) => string): string {
84 return markdown
85 .split(CODE_BOUNDARY)
86 .map((part, index) =>
87 index % 2 === 1 ? `${CODE_BOUNDARY}${part}${CODE_BOUNDARY}` : tidy(part),
88 )
89 .join("");
90 }
91
92 function serializeCodeBlock(pre: Element): string {
93 return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
94 }
95
96 function serializeTableCell(cell: Element): string {
97 return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
98 }
99
100 function tableSeparatorFor(headerCells: Element[]): string {
101 const markers = headerCells.map((cell) => {
102 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
103 if (align === "center") return ":---:";
104 if (align === "right") return "---:";
105 return "---";
106 });
107 return `| ${markers.join(" | ")} |`;
108 }
109
110 function serializeTable(table: Element): string {
111 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
112 if (rows.length === 0) return "";
113 const lines: string[] = [];
114 let emittedSeparator = false;
115 for (const row of rows) {
116 const cells = [...row.children].filter(
117 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
118 );
119 if (cells.length === 0) continue;
120 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
121 if (!emittedSeparator) {
122 lines.push(tableSeparatorFor(cells));
123 emittedSeparator = true;
124 }
125 }
126 return `${lines.join("\n")}\n\n`;
127 }
128
129 function serializeListItem(
130 item: Element,
131 ordered: boolean,
132 index: number,
133 inTableCell: boolean,
134 ): string {
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) =>
140 prose.replace(/\n{3,}/g, "\n\n"),
141 ).trim();
142 if (!item.querySelector(":scope > p")) {
143 content = outsideCode(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
144 }
145 // Continuations align after the bullet; task boxes belong to the item text.
146 const continuationIndent = " ".repeat(bullet.length);
147 const [first = "", ...rest] = content.split("\n");
148 return [
149 `${marker}${first}`,
150 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
151 ].join("\n");
152 }
153
154 /** A list's items with the numbers an ordered list shows: from `start`, reset by each `value`. */
155 function numberedListItems(list: Element): { item: Element; number: number }[] {
156 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10);
157 let next = Number.isNaN(start) ? 1 : start;
158 return [...list.children]
159 .filter((child) => child.tagName === "LI")
160 .map((item) => {
161 const value = Number.parseInt(item.getAttribute("value") ?? "", 10);
162 if (!Number.isNaN(value)) next = value;
163 return { item, number: next++ };
164 });
165 }
166
167 function serializeList(list: Element, ordered: boolean, inTableCell: boolean): string {
168 const items = numberedListItems(list);
169 if (items.length === 0) return "";
170 return `${items
171 .map(({ item, number }) => serializeListItem(item, ordered, number, inTableCell))
172 .join("\n")}\n\n`;
173 }
174
175 function serializeQuoteBody(quote: Element, inTableCell: boolean): string {
176 let content = "";
177 for (const child of quote.childNodes) {
178 // A callout's rendered label stands for the marker its serializer writes.
179 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).hasAttribute(ALERT_LABEL)) {
180 continue;
181 }
182 content += serializeNode(child, inTableCell);
183 }
184 return outsideCode(content, (prose) => prose.replace(/\n{3,}/g, "\n\n")).trim();
185 }
186
187 function serializeBlockquote(quote: Element, inTableCell: boolean, marker = ""): string {
188 const body = serializeQuoteBody(quote, inTableCell);
189 const content = marker && body ? `${marker}\n${body}` : marker || body;
190 if (!content) return "";
191 const quoted = content
192 .split("\n")
193 .map((line) => (line.length > 0 ? `> ${line}` : ">"))
194 .join("\n");
195 return `${quoted}\n\n`;
196 }
197
198 function serializeInsight(insight: Element, inTableCell: boolean): string {
199 const body = serializeQuoteBody(insight, inTableCell);
200 // oxlint-disable-next-line t3code/no-untranslated-copy -- markdown written to the clipboard
201 return `★ Insight ${"─".repeat(37)}\n${body ? `${body}\n` : ""}${"─".repeat(49)}\n\n`;
202 }
203
204 function serializeDetails(details: Element): string {
205 const summary =
206 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
207 "Details";
208 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
209 const content = contentNode ? serializeChildren(contentNode).trim() : "";
210 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
211 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
212 }
213
214 // Prose that would read as inline Markdown once pasted back: a backslash before punctuation,
215 // backticks, brackets, and emphasis or strikethrough runs (user remark-gfm sets singleTilde: false).
216 const INLINE_MARKDOWN = /\\(?=[!-/:-@[-`{-~\n]|$)|[`[\]]|\*+|_+|~{2,}/g;
217 const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
218
219 /** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
220 function escapeProse(text: string): string {
221 return text.replace(/\S+/g, (word, wordOffset: number) => {
222 // Check each word once; testing every escape's growing prefix would be quadratic.
223 const drive = UNFINISHED_DRIVE_PATH.exec(word);
224 const driveStart = drive ? drive.index + drive[0].search(/[A-Za-z]/) + 2 : Infinity;
225 return word.replace(INLINE_MARKDOWN, (match: string, offset: number) => {
226 if (offset >= driveStart) return match;
227 const before = text[wordOffset + offset - 1];
228 const after = text[wordOffset + offset + match.length];
229 if (match === "\\" && after !== undefined && /[^\S\n]/.test(after)) return match;
230 // A text node's edge may touch another node's markers, so it counts as neither.
231 const between = (pattern: RegExp) =>
232 before !== undefined && after !== undefined && pattern.test(before) && pattern.test(after);
233 if (/[*_~]/.test(match[0]!) && between(/\s/)) return match;
234 if (match[0] === "_" && between(/[\p{L}\p{N}]/u)) return match;
235 return match.replace(/[\s\S]/g, "\\$&");
236 });
237 });
238 }
239
240 function serializeAnchor(anchor: Element, inTableCell: boolean): string {
241 const markdownCopy = anchor.getAttribute("data-markdown-copy");
242 if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
243 const content = serializeChildren(anchor, inTableCell);
244 const href = anchor.getAttribute("href") ?? "";
245 if (!/^(?:https?:\/\/|mailto:)/i.test(href)) return content;
246 const label = content.trim();
247 if (!label) return "";
248 // The label arrives escaped; a bare address goes out as shown, since GFM links it again.
249 const shown = label.replace(ESCAPED_PUNCTUATION, "$1");
250 if (shown === href) return escapeTablePipes(href, inTableCell);
251 // GFM autolinks a bare address only when it fits this shape.
252 if (href === `mailto:${shown}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(shown))
253 return shown;
254 const destination = escapeTablePipes(href.replace(/[\\()]/g, "\\$&"), inTableCell);
255 return `[${label}](${destination})`;
256 }
257
258 /**
259 * GFM splits a table row at every unescaped pipe, but its math-aware parsing
260 * keeps a formula's pipes in the cell, so formula source is copied unescaped.
261 */
262 function escapeTablePipes(text: string, inTableCell: boolean): string {
263 return inTableCell ? text.replaceAll("|", "\\|") : text;
264 }
265
266 function serializeChildren(node: Node, inTableCell = false): string {
267 let out = "";
268 for (const child of node.childNodes) {
269 out += serializeNode(child, inTableCell);
270 }
271 return out;
272 }
273
274 function serializeNode(node: Node, inTableCell = false): string {
275 if (node.nodeType === Node.TEXT_NODE) {
276 const text = node.textContent ?? "";
277 if (text.includes("\n") && text.trim().length === 0) return "\n";
278 return escapeTablePipes(escapeProse(text), inTableCell);
279 }
280 if (node.nodeType !== Node.ELEMENT_NODE) return "";
281 const element = node as Element;
282 if (element.hasAttribute("data-markdown-details")) {
283 return escapeTablePipes(serializeDetails(element), inTableCell);
284 }
285 const markdownCopy = element.getAttribute("data-markdown-copy");
286 if (markdownCopy !== null) {
287 // A diagram copies as its fenced source, which is code too.
288 if (element.hasAttribute("data-markdown-mermaid")) {
289 return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
290 }
291 return element.hasAttribute("data-markdown-math")
292 ? markdownCopy
293 : escapeTablePipes(markdownCopy, inTableCell);
294 }
295 if (isSkippedElement(element)) return "";
296 const alert = element.getAttribute(ALERT_ATTRIBUTE);
297 if (alert === "insight") return serializeInsight(element, inTableCell);
298 if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`);
299
300 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
301 if (headingLevel) {
302 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element, inTableCell).trim()}\n\n`;
303 }
304
305 switch (element.tagName) {
306 case "BR":
307 return "\n";
308 case "HR":
309 return "---\n\n";
310 case "P":
311 return `${serializeChildren(element, inTableCell).trim()}\n\n`;
312 case "PRE":
313 return escapeTablePipes(serializeCodeBlock(element), inTableCell);
314 case "CODE": {
315 const content = escapeTablePipes(element.textContent ?? "", inTableCell);
316 return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
317 }
318 case "STRONG":
319 case "B":
320 return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
321 case "EM":
322 case "I":
323 return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
324 case "DEL":
325 case "S":
326 return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
327 case "A":
328 return serializeAnchor(element, inTableCell);
329 case "IMG": {
330 const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
331 const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
332 return alt && src ? `![${alt}](${src})` : "";
333 }
334 case "UL":
335 return serializeList(element, false, inTableCell);
336 case "OL":
337 return serializeList(element, true, inTableCell);
338 case "BLOCKQUOTE":
339 return serializeBlockquote(element, inTableCell);
340 case "TABLE":
341 return escapeTablePipes(serializeTable(element), inTableCell);
342 case "DIV":
343 case "SECTION":
344 case "ARTICLE": {
345 const content = serializeChildren(element, inTableCell);
346 return content && !content.endsWith("\n") ? `${content}\n` : content;
347 }
348 default:
349 return serializeChildren(element, inTableCell);
350 }
351 }
352
353 interface SoleCodeBlockScan {
354 pre: Element | null;
355 other: boolean;
356 }
357
358 function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
359 for (const child of node.childNodes) {
360 if (scan.other) return;
361 if (child.nodeType === Node.TEXT_NODE) {
362 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
363 continue;
364 }
365 if (child.nodeType !== Node.ELEMENT_NODE) continue;
366 const element = child as Element;
367 // Explicit markdown still counts on skipped tags such as file-chip buttons.
368 if (element.hasAttribute("data-markdown-details")) {
369 scan.other = true;
370 continue;
371 }
372 const markdownCopy = element.getAttribute("data-markdown-copy");
373 if (markdownCopy !== null) {
374 if (markdownCopy.trim().length > 0) scan.other = true;
375 continue;
376 }
377 if (isSkippedElement(element)) continue;
378 if (element.tagName === "PRE") {
379 if (scan.pre) scan.other = true;
380 else scan.pre = element;
381 continue;
382 }
383 if (element.tagName === "IMG" || element.tagName === "HR") {
384 scan.other = true;
385 continue;
386 }
387 if (element.tagName === "LI") {
388 const preBeforeItem = scan.pre;
389 scanForSoleCodeBlock(element, scan);
390 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
391 continue;
392 }
393 scanForSoleCodeBlock(element, scan);
394 }
395 }
396
397 // Selecting a block's final newline pulls in its closing pre even when only code was highlighted.
398 function soleCodeBlock(container: Node): Element | null {
399 const scan: SoleCodeBlockScan = { pre: null, other: false };
400 scanForSoleCodeBlock(container, scan);
401 return scan.other ? null : scan.pre;
402 }
403
404 function tidyMarkdown(markdown: string): string {
405 // Odd parts are code, kept verbatim, so a selection that starts or ends inside
406 // code keeps that code's leading and trailing whitespace.
407 const parts = markdown.split(CODE_BOUNDARY);
408 const last = parts.length - 1;
409 return parts
410 .map((part, index) => {
411 if (index % 2 === 1) return part;
412 let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
413 if (index === 0) prose = prose.trimStart();
414 if (index === last) prose = prose.trimEnd();
415 return prose;
416 })
417 .join("");
418 }
419
420 export function serializeRenderedMarkdownFragment(container: Node): string {
421 const codeBlock = soleCodeBlock(container);
422 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
423 return tidyMarkdown(serializeChildren(container));
424 }
425
426 export function serializeTableElementToMarkdown(table: Element): string {
427 // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
428 return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
429 }
430
431 // The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
432 // the attribute from authored HTML.
433 const MATH_SELECTOR = "[data-markdown-math]";
434
435 export function mathWrapperOf(element: Element | null): Element | null {
436 return element?.closest(MATH_SELECTOR) ?? null;
437 }
438
439 /** A cell's text, with each formula as its TeX. */
440 function csvCellText(cell: Element): string {
441 if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
442 const copy = cell.cloneNode(true) as Element;
443 for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
444 wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
445 }
446 return copy.textContent ?? "";
447 }
448
449 function csvCell(value: string): string {
450 const normalized = value.replace(/\s+/g, " ").trim();
451 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
452 }
453
454 export function serializeTableElementToCsv(table: Element): string {
455 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
456 const lines: string[] = [];
457 for (const row of rows) {
458 const cells = [...row.children].filter(
459 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
460 );
461 if (cells.length === 0) continue;
462 lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
463 }
464 return lines.join("\n");
465 }
466
467 function mermaidSourceHtml(source: string) {
468 const pre = document.createElement("pre");
469 const code = document.createElement("code");
470 code.textContent = source.trim();
471 pre.appendChild(code);
472 return pre;
473 }
474
475 function mathSourceElement(wrapper: Element): Element {
476 const code = document.createElement("code");
477 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
478 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
479 const pre = document.createElement("pre");
480 pre.append(code);
481 return pre;
482 }
483
484 function sanitizedHtmlFrom(container: Element): string {
485 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
486 const source = diagram.getAttribute("data-markdown-copy");
487 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
488 }
489 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
490 wrapper.replaceWith(mathSourceElement(wrapper));
491 }
492 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
493 if (
494 node.classList.contains("chat-markdown-file-link") ||
495 node.closest(".chat-markdown-file-link")
496 ) {
497 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
498 node.remove();
499 }
500 continue;
501 }
502 node.remove();
503 }
504 return `<meta charset="utf-8">${container.innerHTML}`;
505 }
506
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[] = [];
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;
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(
593 ({ item }) =>
594 item === firstCopied ||
595 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
596 );
597 const cloned = numberedListItems(clone)[0];
598 if (shown && cloned && shown.number !== cloned.number) {
599 clone.setAttribute("start", String(shown.number));
600 }
601 }
602 }
603
604 export function chatMarkdownClipboardPayload(
605 selection: Selection,
606 ): MarkdownClipboardPayload | null {
607 const texts: string[] = [];
608 const htmls: string[] = [];
609 for (let index = 0; index < selection.rangeCount; index += 1) {
610 const range = selection.getRangeAt(index);
611 if (range.collapsed) continue;
612 const container = document.createElement("div");
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();
617 }
618 const ancestor = range.commonAncestorContainer;
619 const ancestorElement =
620 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
621 const diagramSource = ancestorElement
622 ?.closest("[data-markdown-mermaid]")
623 ?.getAttribute("data-markdown-copy");
624 if (diagramSource != null) {
625 const text = diagramSource.trim();
626 if (!text) continue;
627 texts.push(text);
628 container.replaceChildren(mermaidSourceHtml(diagramSource));
629 htmls.push(sanitizedHtmlFrom(container));
630 continue;
631 }
632 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
633 const math = mathWrapperOf(ancestorElement);
634 if (math) {
635 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
636 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
637 continue;
638 }
639 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
640 if (ancestorElement?.closest("pre, code")) {
641 const text = range.toString();
642 if (text) {
643 texts.push(text);
644 htmls.push(sanitizedHtmlFrom(container));
645 }
646 continue;
647 }
648 // A range spanning exactly one callout's text clones its contents but not the callout.
649 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
650 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
651 const wrapper = callout.cloneNode(false) as Element;
652 wrapper.append(...container.childNodes);
653 container.replaceChildren(wrapper);
654 }
655 const text = serializeRenderedMarkdownFragment(container);
656 if (!text) continue;
657 texts.push(text);
658 htmls.push(sanitizedHtmlFrom(container));
659 }
660 if (texts.length === 0) return null;
661 return { text: texts.join("\n\n"), html: htmls.join("") };
662 }