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

markdown-clipboard.ts

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