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