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