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