Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdown-clipboard.ts

453 lines15.5 KB

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