Open History to see the last commit
1import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks";
2
3const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
4const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
5const 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
15const ALERT_ATTRIBUTE = "data-markdown-alert";
16const ALERT_LABEL = "data-markdown-alert-label";
17const LIST_ITEM_CHECKBOX = ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]';
18
19export interface MarkdownClipboardPayload {
20 text: string;
21 html: string;
22}
23
24function 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
30function 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.
38function 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
48function 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
60function 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
68export 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.
76const CODE_BOUNDARY = "\u0000";
77
78function 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.
83function 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
92function serializeCodeBlock(pre: Element): string {
93 return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
94}
95
96function serializeTableCell(cell: Element): string {
97 return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
98}
99
100function 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
110function 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
129function 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`. */
155function 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
167function 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
175function 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
187function 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
198function 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
204function 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).
216const INLINE_MARKDOWN = /\\(?=[!-/:-@[-`{-~\n]|$)|[`[\]]|\*+|_+|~{2,}/g;
217const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
218
219/** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
220function 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
240function 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 */
262function escapeTablePipes(text: string, inTableCell: boolean): string {
263 return inTableCell ? text.replaceAll("|", "\\|") : text;
264}
265
266function 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
274function 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 ? `` : "";
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
353interface SoleCodeBlockScan {
354 pre: Element | null;
355 other: boolean;
356}
357
358function 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.
398function 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
404function 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
420export 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
426export 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 wordsHast puts on every formula it renders. The sanitizer drops
432// the attribute from authored HTML.
433const MATH_SELECTOR = "[data-markdown-math]";
434
435export 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. */
440function 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
449function csvCell(value: string): string {
450 const normalized = value.replace(/\s+/g, " ").trim();
451 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
452}
453
454export 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
467const TABLE_SECTION_TAGS = new Set(["THEAD", "TBODY", "TFOOT"]);
468// Elements that start a new line inside a copied cell.
469const HTML_CELL_BLOCK_TAGS = new Set([
470 "ARTICLE",
471 "BLOCKQUOTE",
472 "DETAILS",
473 "DIV",
474 "H1",
475 "H2",
476 "H3",
477 "H4",
478 "H5",
479 "H6",
480 "LI",
481 "OL",
482 "P",
483 "PRE",
484 "SECTION",
485 "SUMMARY",
486 "TABLE",
487 "TR",
488 "UL",
489]);
490
491// Inline and theme-independent: mail clients and editors drop stylesheets, and a
492// copy from the dark theme must still read on a white page. Header cells set their
493// own text color so the light band stays readable in a dark paste target.
494const HTML_TABLE_STYLE = "border-collapse:collapse";
495const HTML_CELL_STYLE = "border:1px solid #d0d7de;padding:6px 12px;vertical-align:top";
496const HTML_HEADER_CELL_STYLE = `${HTML_CELL_STYLE};background-color:#f6f8fa;color:#1f2328;font-weight:600`;
497
498function escapeHtml(value: string): string {
499 return value
500 .replaceAll("&", "&")
501 .replaceAll("<", "<")
502 .replaceAll(">", ">")
503 .replaceAll('"', """);
504}
505
506// Markers in collected cell text: a block edge is a soft line boundary, a break is a <br>.
507const CELL_BLOCK_EDGE = "\u0001";
508const CELL_LINE_BREAK = "\u0002";
509// HTML's collapsible whitespace; a nonbreaking space is content.
510const COLLAPSIBLE_WHITESPACE = /[ \t\n\r\f]+/g;
511
512/** Preformatted text keeps its lines and spacing as breaks and nonbreaking spaces. */
513function preformattedCellText(text: string): string {
514 return text
515 .replace(/\r\n?|\n/g, CELL_LINE_BREAK)
516 .replaceAll("\t", "\u00a0".repeat(4))
517 .replaceAll(" ", "\u00a0");
518}
519
520/** Collects a cell's text with block edges and breaks marked, and each formula as its TeX. */
521function collectHtmlCellText(node: Node, parts: string[], preformatted: boolean): void {
522 for (const child of node.childNodes) {
523 if (child.nodeType === Node.TEXT_NODE) {
524 const text = child.textContent ?? "";
525 parts.push(preformatted ? preformattedCellText(text) : text);
526 continue;
527 }
528 if (child.nodeType !== Node.ELEMENT_NODE) continue;
529 const element = child as Element;
530 if (isSkippedElement(element) && !element.hasAttribute("data-markdown-copy")) continue;
531 if (element.hasAttribute("data-markdown-math")) {
532 parts.push(element.getAttribute("data-markdown-copy")?.trim() ?? "");
533 continue;
534 }
535 if (element.tagName === "BR") {
536 parts.push(CELL_LINE_BREAK);
537 continue;
538 }
539 if (element.tagName === "PRE") {
540 const code: string[] = [];
541 collectHtmlCellText(element, code, true);
542 // A code block's closing newline ends the block, not a blank line.
543 parts.push(CELL_BLOCK_EDGE, code.join("").replace(/\u0002$/, ""), CELL_BLOCK_EDGE);
544 continue;
545 }
546 // Cells of a nested table stay apart on their row's line.
547 const separator = element.tagName === "TD" || element.tagName === "TH" ? " " : "";
548 const boundary = HTML_CELL_BLOCK_TAGS.has(element.tagName) ? CELL_BLOCK_EDGE : separator;
549 parts.push(boundary);
550 collectHtmlCellText(element, parts, preformatted);
551 parts.push(boundary);
552 }
553}
554
555/**
556 * Every explicit break stays a <br>, including repeated and edge ones. Block edges
557 * become one break between content, and none where a break already ends the line.
558 */
559function htmlCellContent(cell: Element): string {
560 const parts: string[] = [];
561 collectHtmlCellText(cell, parts, false);
562 const tokens = parts
563 .join("")
564 .replace(COLLAPSIBLE_WHITESPACE, " ")
565 .split(/([\u0001\u0002])/);
566 let html = "";
567 let atLineStart = true;
568 let pendingBlockEdge = false;
569 for (const token of tokens) {
570 if (token === CELL_LINE_BREAK) {
571 html = `${html.replace(/ +$/, "")}<br>`;
572 atLineStart = true;
573 pendingBlockEdge = false;
574 } else if (token === CELL_BLOCK_EDGE) {
575 pendingBlockEdge = true;
576 } else {
577 const text = atLineStart || pendingBlockEdge ? token.replace(/^ +/, "") : token;
578 if (!text) continue;
579 if (pendingBlockEdge && !atLineStart) html = `${html.replace(/ +$/, "")}<br>`;
580 html += escapeHtml(text).replaceAll("\u00a0", " ");
581 atLineStart = false;
582 pendingBlockEdge = false;
583 }
584 }
585 return html.replace(/ +$/, "");
586}
587
588/** Physical alignment for a paste target; logical values follow the table direction. */
589function htmlCellAlignment(align: string, rtl: boolean): string {
590 switch (align) {
591 case "left":
592 case "center":
593 case "right":
594 case "justify":
595 return align;
596 case "start":
597 return rtl ? "right" : "left";
598 case "end":
599 return rtl ? "left" : "right";
600 default:
601 return "";
602 }
603}
604
605/** HTML's non-negative integer parsing: leading digits count, anything invalid is 1. */
606function parseTableSpan(value: string | null): number {
607 const span = Number.parseInt(value ?? "", 10);
608 return Number.isNaN(span) || span < 0 ? 1 : span;
609}
610
611function htmlSpanAttributes(cell: Element): string {
612 // The DOM normalizes spans; the attribute fallback covers non-DOM callers.
613 const { colSpan, rowSpan } = cell as Partial<HTMLTableCellElement>;
614 const columns =
615 typeof colSpan === "number" ? colSpan : parseTableSpan(cell.getAttribute("colspan"));
616 const rows = typeof rowSpan === "number" ? rowSpan : parseTableSpan(cell.getAttribute("rowspan"));
617 let attributes = columns > 1 ? ` colspan="${columns}"` : "";
618 // rowspan="0" runs to the end of its section.
619 if (rows !== 1) attributes += ` rowspan="${rows}"`;
620 return attributes;
621}
622
623function htmlTableCell(cell: Element, rtl: boolean): string {
624 const tag = cell.tagName === "TH" ? "th" : "td";
625 // An absent inline style reads as "", so fall back to the align attribute on any falsy value.
626 const align = (cell as HTMLElement).style?.textAlign || cell.getAttribute("align") || "";
627 // Header cells default to the start side like the chat; paste targets would center them.
628 const textAlign = htmlCellAlignment(align || (tag === "th" ? "start" : ""), rtl);
629 const style = `${tag === "th" ? HTML_HEADER_CELL_STYLE : HTML_CELL_STYLE}${textAlign ? `;text-align:${textAlign}` : ""}`;
630 // Bare text, no <p>: Word would drop its 8pt gap but switch to its web font.
631 return `<${tag} style="${style}"${htmlSpanAttributes(cell)}>${htmlCellContent(cell)}</${tag}>`;
632}
633
634function htmlTableSection(tag: string, rows: ReadonlyArray<Element>, rtl: boolean): string[] {
635 let hasCells = false;
636 const lines = rows.map((row) => {
637 const cells = [...row.children].filter(
638 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
639 );
640 const html = cells.map((cell) => htmlTableCell(cell, rtl)).join("");
641 hasCells ||= cells.length > 0;
642 return ` <tr>${html}</tr>`;
643 });
644 return hasCells ? [` <${tag}>`, ...lines, ` </${tag}>`] : [];
645}
646
647/**
648 * Inline-styled `<table>` markup without app chrome, so rich paste targets get a table.
649 * Sections, header cells, spans, line breaks, direction, and alignment follow the source.
650 * Cell content is text: inline formatting and link targets are not copied.
651 */
652export function serializeTableElementToHtml(table: Element): string {
653 const direction = table.getAttribute("dir");
654 const rtl =
655 direction === "rtl" ||
656 (direction !== "ltr" &&
657 table.ownerDocument?.defaultView?.getComputedStyle(table).direction === "rtl");
658 const lines: string[] = [];
659 let looseRows: Element[] = [];
660 const flushLooseRows = () => {
661 lines.push(...htmlTableSection("tbody", looseRows, rtl));
662 looseRows = [];
663 };
664 for (const child of table.children) {
665 if (child.tagName === "TR") {
666 looseRows.push(child);
667 continue;
668 }
669 if (!TABLE_SECTION_TAGS.has(child.tagName)) continue;
670 flushLooseRows();
671 const rows = [...child.children].filter((row) => row.tagName === "TR");
672 lines.push(...htmlTableSection(child.tagName.toLowerCase(), rows, rtl));
673 }
674 flushLooseRows();
675 const open = `<table dir="${rtl ? "rtl" : "ltr"}" style="${HTML_TABLE_STYLE}">`;
676 return lines.length > 0 ? [open, ...lines, "</table>"].join("\n") : "";
677}
678
679function mermaidSourceHtml(source: string) {
680 const pre = document.createElement("pre");
681 const code = document.createElement("code");
682 code.textContent = source.trim();
683 pre.appendChild(code);
684 return pre;
685}
686
687function mathSourceElement(wrapper: Element): Element {
688 const code = document.createElement("code");
689 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
690 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
691 const pre = document.createElement("pre");
692 pre.append(code);
693 return pre;
694}
695
696function sanitizedHtmlFrom(container: Element): string {
697 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
698 const source = diagram.getAttribute("data-markdown-copy");
699 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
700 }
701 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
702 wrapper.replaceWith(mathSourceElement(wrapper));
703 }
704 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
705 if (
706 node.classList.contains("chat-markdown-file-link") ||
707 node.closest(".chat-markdown-file-link")
708 ) {
709 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
710 node.remove();
711 }
712 continue;
713 }
714 node.remove();
715 }
716 return `<meta charset="utf-8">${container.innerHTML}`;
717}
718
719function isList(node: Node): node is HTMLOListElement | HTMLUListElement {
720 return node instanceof Element && (node.tagName === "OL" || node.tagName === "UL");
721}
722
723// An endpoint can clone empty item wrappers at any nesting depth.
724function emptyListBoundary(
725 ancestor: Node,
726 node: Node,
727 offset: number,
728 side: "start" | "end",
729): Element | null {
730 const next = (node: Node) => (side === "start" ? node.nextSibling : node.previousSibling);
731 if (node instanceof Text && offset !== (side === "start" ? node.length : 0)) return null;
732
733 let boundary: Element | null = null;
734 let remaining = node.childNodes[side === "start" ? offset : offset - 1] ?? null;
735 while (node !== ancestor && node.parentNode) {
736 for (let sibling = remaining; sibling; sibling = next(sibling)) {
737 if (sibling instanceof Text && !sibling.data.trim()) continue;
738 if (
739 sibling instanceof Element &&
740 isSkippedElement(sibling) &&
741 !sibling.hasAttribute("data-markdown-copy") &&
742 !sibling.hasAttribute("data-markdown-details")
743 ) {
744 continue;
745 }
746 return boundary;
747 }
748 if (node instanceof Element && node.tagName === "LI" && isList(node.parentNode)) {
749 boundary = node;
750 } else if (boundary && isList(node)) {
751 boundary = node;
752 }
753 remaining = next(node);
754 node = node.parentNode;
755 }
756 return boundary;
757}
758
759/** Clones the selection and restores the markers shown for its copied list items. */
760function cloneWithListMarkers(range: Range, container: Element): void {
761 const originalAncestor = range.commonAncestorContainer;
762 const start = emptyListBoundary(
763 originalAncestor,
764 range.startContainer,
765 range.startOffset,
766 "start",
767 );
768 const end = emptyListBoundary(originalAncestor, range.endContainer, range.endOffset, "end");
769 if (start || end) {
770 range = range.cloneRange();
771 if (start) range.setStartAfter(start);
772 if (end) range.setEndBefore(end);
773 }
774 const ancestor = range.commonAncestorContainer;
775 const withinList = isList(ancestor);
776 container.appendChild(range.cloneContents());
777 if (withinList) {
778 // Items copied within one list clone without the list around them.
779 const list = ancestor.cloneNode(false) as Element;
780 list.append(...container.childNodes);
781 container.replaceChildren(list);
782 }
783 // The start's ancestors below the cloned top clone as the fragment's first-child chain.
784 const top = withinList ? ancestor.parentNode : ancestor;
785 const chain: Node[] = [];
786 for (let node: Node | null = range.startContainer; node && node !== top; node = node.parentNode) {
787 chain.unshift(node);
788 }
789 let clone: Node | null = container;
790 for (const [depth, source] of chain.entries()) {
791 clone = clone?.firstChild ?? null;
792 if (!(clone instanceof Element) || !(source instanceof Element)) continue;
793 if (source.tagName === "LI" && clone.tagName === "LI") {
794 const checkbox = source.querySelector(LIST_ITEM_CHECKBOX);
795 if (checkbox && !clone.querySelector(LIST_ITEM_CHECKBOX)) {
796 // Keep the first-child chain intact for nested items.
797 clone.append(checkbox.cloneNode(false));
798 }
799 continue;
800 }
801 if (source.tagName !== "OL") continue;
802 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
803 if (!firstCopied) continue;
804 const shown = numberedListItems(source).find(
805 ({ item }) =>
806 item === firstCopied ||
807 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
808 );
809 const cloned = numberedListItems(clone)[0];
810 if (shown && cloned && shown.number !== cloned.number) {
811 clone.setAttribute("start", String(shown.number));
812 }
813 }
814}
815
816export function chatMarkdownClipboardPayload(
817 selection: Selection,
818): MarkdownClipboardPayload | null {
819 const texts: string[] = [];
820 const htmls: string[] = [];
821 for (let index = 0; index < selection.rangeCount; index += 1) {
822 const range = selection.getRangeAt(index);
823 if (range.collapsed) continue;
824 const container = document.createElement("div");
825 cloneWithListMarkers(range, container);
826 // The indentation typed at a line start only shows; pasted, it would turn lines into code.
827 for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
828 indentation.remove();
829 }
830 const ancestor = range.commonAncestorContainer;
831 const ancestorElement =
832 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
833 const diagramSource = ancestorElement
834 ?.closest("[data-markdown-mermaid]")
835 ?.getAttribute("data-markdown-copy");
836 if (diagramSource != null) {
837 const text = diagramSource.trim();
838 if (!text) continue;
839 texts.push(text);
840 container.replaceChildren(mermaidSourceHtml(diagramSource));
841 htmls.push(sanitizedHtmlFrom(container));
842 continue;
843 }
844 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
845 const math = mathWrapperOf(ancestorElement);
846 if (math) {
847 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
848 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
849 continue;
850 }
851 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
852 if (ancestorElement?.closest("pre, code")) {
853 const text = range.toString();
854 if (text) {
855 texts.push(text);
856 htmls.push(sanitizedHtmlFrom(container));
857 }
858 continue;
859 }
860 // A range spanning exactly one callout's text clones its contents but not the callout.
861 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
862 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
863 const wrapper = callout.cloneNode(false) as Element;
864 wrapper.append(...container.childNodes);
865 container.replaceChildren(wrapper);
866 }
867 const text = serializeRenderedMarkdownFragment(container);
868 if (!text) continue;
869 texts.push(text);
870 htmls.push(sanitizedHtmlFrom(container));
871 }
872 if (texts.length === 0) return null;
873 return { text: texts.join("\n\n"), html: htmls.join("") };
874}