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