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