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/**
32 * A code element whose pre wrapper fell outside the copied range is still block
33 * code, recognizable by its highlighter line spans or embedded newlines.
34 */
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 const pad = code.startsWith("`") || code.endsWith("`") ? " " : "";
52 return `${fence}${pad}${code}${pad}${fence}`;
53}
54
55function codeFenceFor(code: string): string {
56 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
57 (max, run) => Math.max(max, run.length),
58 0,
59 );
60 return "`".repeat(Math.max(3, longestRun + 1));
61}
62
63function resolveCodeBlockLanguage(pre: Element): string | null {
64 const declared =
65 pre.closest("[data-language]")?.getAttribute("data-language") ??
66 /(?:^|\s)language-(\S+)/.exec(pre.querySelector("code")?.className ?? "")?.[1] ??
67 null;
68 return declared && declared !== "text" ? declared : null;
69}
70
71function serializeCodeBlock(pre: Element): string {
72 const code = (pre.textContent ?? "").replace(/\n$/, "");
73 const fence = codeFenceFor(code);
74 return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
75}
76
77function serializeTableCell(cell: Element): string {
78 return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
79}
80
81function tableSeparatorFor(headerCells: Element[]): string {
82 const markers = headerCells.map((cell) => {
83 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
84 if (align === "center") return ":---:";
85 if (align === "right") return "---:";
86 return "---";
87 });
88 return `| ${markers.join(" | ")} |`;
89}
90
91function serializeTable(table: Element): string {
92 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
93 if (rows.length === 0) return "";
94 const lines: string[] = [];
95 let emittedSeparator = false;
96 for (const row of rows) {
97 const cells = [...row.children].filter(
98 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
99 );
100 if (cells.length === 0) continue;
101 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
102 if (!emittedSeparator) {
103 lines.push(tableSeparatorFor(cells));
104 emittedSeparator = true;
105 }
106 }
107 return `${lines.join("\n")}\n\n`;
108}
109
110function serializeListItem(item: Element, ordered: boolean, index: number): string {
111 const checkbox = item.querySelector(
112 ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]',
113 );
114 const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
115 const bullet = ordered ? `${index}. ` : "- ";
116 const marker = `${bullet}${task}`;
117 let content = serializeChildren(item)
118 .replace(/\n{3,}/g, "\n\n")
119 .trim();
120 if (!item.querySelector(":scope > p")) {
121 content = content.replace(/\n{2,}/g, "\n");
122 }
123 // Nested content lines up with the item text, which starts after the bullet;
124 // a task box is part of that text, not of the list marker.
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 // Mirrors serializeNode's order: an element carrying markdown of its own
265 // still contributes it even when its tag is otherwise skipped, as a file
266 // chip rendered as a button does.
267 if (element.hasAttribute("data-markdown-details")) {
268 scan.other = true;
269 continue;
270 }
271 const markdownCopy = element.getAttribute("data-markdown-copy");
272 if (markdownCopy !== null) {
273 if (markdownCopy.trim().length > 0) scan.other = true;
274 continue;
275 }
276 if (isSkippedElement(element)) continue;
277 if (element.tagName === "PRE") {
278 if (scan.pre) scan.other = true;
279 else scan.pre = element;
280 continue;
281 }
282 if (element.tagName === "IMG" || element.tagName === "HR") {
283 scan.other = true;
284 continue;
285 }
286 if (element.tagName === "LI") {
287 const preBeforeItem = scan.pre;
288 scanForSoleCodeBlock(element, scan);
289 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
290 continue;
291 }
292 scanForSoleCodeBlock(element, scan);
293 }
294}
295
296/**
297 * A drag that ends on a block's final newline pulls the closing `pre` into the
298 * range, so the fragment holds the whole block even though the user only
299 * highlighted code.
300 */
301function soleCodeBlock(container: Node): Element | null {
302 const scan: SoleCodeBlockScan = { pre: null, other: false };
303 scanForSoleCodeBlock(container, scan);
304 return scan.other ? null : scan.pre;
305}
306
307function tidyMarkdown(markdown: string): string {
308 return markdown
309 .split(/(```[\s\S]*?(?:```|$))/)
310 .map((part, index) =>
311 index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
312 )
313 .join("")
314 .trim();
315}
316
317export function serializeRenderedMarkdownFragment(container: Node): string {
318 const codeBlock = soleCodeBlock(container);
319 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
320 return tidyMarkdown(serializeChildren(container));
321}
322
323export function serializeTableElementToMarkdown(table: Element): string {
324 return serializeTable(table).trim();
325}
326
327// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
328// the attribute from authored HTML.
329const MATH_SELECTOR = "[data-markdown-math]";
330
331export function mathWrapperOf(element: Element | null): Element | null {
332 return element?.closest(MATH_SELECTOR) ?? null;
333}
334
335/** A cell's text, with each formula as its TeX. */
336function csvCellText(cell: Element): string {
337 if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
338 const copy = cell.cloneNode(true) as Element;
339 for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
340 wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
341 }
342 return copy.textContent ?? "";
343}
344
345function csvCell(value: string): string {
346 const normalized = value.replace(/\s+/g, " ").trim();
347 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
348}
349
350export function serializeTableElementToCsv(table: Element): string {
351 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
352 const lines: string[] = [];
353 for (const row of rows) {
354 const cells = [...row.children].filter(
355 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
356 );
357 if (cells.length === 0) continue;
358 lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
359 }
360 return lines.join("\n");
361}
362
363function mathSourceElement(wrapper: Element): Element {
364 const code = document.createElement("code");
365 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
366 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
367 const pre = document.createElement("pre");
368 pre.append(code);
369 return pre;
370}
371
372function sanitizedHtmlFrom(container: Element): string {
373 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
374 wrapper.replaceWith(mathSourceElement(wrapper));
375 }
376 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
377 if (
378 node.classList.contains("chat-markdown-file-link") ||
379 node.closest(".chat-markdown-file-link")
380 ) {
381 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
382 node.remove();
383 }
384 continue;
385 }
386 node.remove();
387 }
388 return `<meta charset="utf-8">${container.innerHTML}`;
389}
390
391export function chatMarkdownClipboardPayload(
392 selection: Selection,
393): MarkdownClipboardPayload | null {
394 const texts: string[] = [];
395 const htmls: string[] = [];
396 for (let index = 0; index < selection.rangeCount; index += 1) {
397 const range = selection.getRangeAt(index);
398 if (range.collapsed) continue;
399 const container = document.createElement("div");
400 container.appendChild(range.cloneContents());
401 const ancestor = range.commonAncestorContainer;
402 const ancestorElement =
403 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
404 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
405 const math = mathWrapperOf(ancestorElement);
406 if (math) {
407 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
408 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
409 continue;
410 }
411 if (ancestorElement?.closest("pre")) {
412 const text = range.toString();
413 if (text) {
414 texts.push(text);
415 htmls.push(sanitizedHtmlFrom(container));
416 }
417 continue;
418 }
419 const text = serializeRenderedMarkdownFragment(container);
420 if (!text) continue;
421 texts.push(text);
422 htmls.push(sanitizedHtmlFrom(container));
423 }
424 if (texts.length === 0) return null;
425 return { text: texts.join("\n\n"), html: htmls.join("") };
426}