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

markdown-clipboard.ts

386 lines12.9 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​
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`;
76​
77function serializeTableCell(cell: Element): string {
78 return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
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(" | ")} |`;
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`;
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 marker = ordered ? `${index}. ${task}` : `- ${task}`;
116 let content = serializeChildren(item)
117 .replace(/\n{3,}/g, "\n\n")
118 .trim();
119 if (!item.querySelector(":scope > p")) {
120 content = content.replace(/\n{2,}/g, "\n");
121 }
122 const continuationIndent = " ".repeat(marker.length);
123 const [first = "", ...rest] = content.split("\n");
124 return [
125 `${marker}${first}`,
126 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
127 ].join("\n");
129​
130function serializeList(list: Element, ordered: boolean): string {
131 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1;
132 const items = [...list.children].filter((child) => child.tagName === "LI");
133 if (items.length === 0) return "";
134 return `${items.map((item, index) => serializeListItem(item, ordered, start + index)).join("\n")}\n\n`;
136​
137function serializeBlockquote(quote: Element): string {
138 const content = serializeChildren(quote)
139 .replace(/\n{3,}/g, "\n\n")
140 .trim();
141 if (!content) return "";
142 const quoted = content
143 .split("\n")
144 .map((line) => (line.length > 0 ? `> ${line}` : ">"))
145 .join("\n");
146 return `${quoted}\n\n`;
148​
149function serializeDetails(details: Element): string {
150 const summary =
151 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
152 "Details";
153 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
154 const content = contentNode ? serializeChildren(contentNode).trim() : "";
155 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
156 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
158​
159function serializeAnchor(anchor: Element): string {
160 const markdownCopy = anchor.getAttribute("data-markdown-copy");
161 if (markdownCopy !== null) return markdownCopy;
162 const content = serializeChildren(anchor);
163 const href = anchor.getAttribute("href") ?? "";
164 if (!/^https?:\/\//i.test(href)) return content;
165 const label = content.trim();
166 if (!label) return "";
167 if (label === href) return href;
168 return `[${label}](${href})`;
170​
171function serializeChildren(node: Node): string {
172 let out = "";
173 for (const child of node.childNodes) {
174 out += serializeNode(child);
175 }
176 return out;
178​
179function serializeNode(node: Node): string {
180 if (node.nodeType === Node.TEXT_NODE) {
181 const text = node.textContent ?? "";
182 if (text.includes("\n") && text.trim().length === 0) return "\n";
183 return text;
184 }
185 if (node.nodeType !== Node.ELEMENT_NODE) return "";
186 const element = node as Element;
187 if (element.hasAttribute("data-markdown-details")) {
188 return serializeDetails(element);
189 }
190 const markdownCopy = element.getAttribute("data-markdown-copy");
191 if (markdownCopy !== null) return markdownCopy;
192 if (isSkippedElement(element)) return "";
193​
194 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
195 if (headingLevel) {
196 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element).trim()}\n\n`;
197 }
198​
199 switch (element.tagName) {
200 case "BR":
201 return "\n";
202 case "HR":
203 return "---\n\n";
204 case "P":
205 return `${serializeChildren(element).trim()}\n\n`;
206 case "PRE":
207 return serializeCodeBlock(element);
208 case "CODE": {
209 const content = element.textContent ?? "";
210 return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
211 }
212 case "STRONG":
213 case "B":
214 return wrapInlineMarker(serializeChildren(element), "**");
215 case "EM":
216 case "I":
217 return wrapInlineMarker(serializeChildren(element), "*");
218 case "DEL":
219 case "S":
220 return wrapInlineMarker(serializeChildren(element), "~~");
221 case "A":
222 return serializeAnchor(element);
223 case "IMG": {
224 const alt = element.getAttribute("alt") ?? "";
225 const src = element.getAttribute("src") ?? "";
226 return alt && src ? `![${alt}](${src})` : "";
227 }
228 case "UL":
229 return serializeList(element, false);
230 case "OL":
231 return serializeList(element, true);
232 case "BLOCKQUOTE":
233 return serializeBlockquote(element);
234 case "TABLE":
235 return serializeTable(element);
236 case "DIV":
237 case "SECTION":
238 case "ARTICLE": {
239 const content = serializeChildren(element);
240 return content && !content.endsWith("\n") ? `${content}\n` : content;
241 }
242 default:
243 return serializeChildren(element);
244 }
246​
247interface SoleCodeBlockScan {
248 pre: Element | null;
249 other: boolean;
251​
252function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
253 for (const child of node.childNodes) {
254 if (scan.other) return;
255 if (child.nodeType === Node.TEXT_NODE) {
256 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
257 continue;
258 }
259 if (child.nodeType !== Node.ELEMENT_NODE) continue;
260 const element = child as Element;
261 // Mirrors serializeNode's order: an element carrying markdown of its own
262 // still contributes it even when its tag is otherwise skipped, as a file
263 // chip rendered as a button does.
264 if (element.hasAttribute("data-markdown-details")) {
265 scan.other = true;
266 continue;
267 }
268 const markdownCopy = element.getAttribute("data-markdown-copy");
269 if (markdownCopy !== null) {
270 if (markdownCopy.trim().length > 0) scan.other = true;
271 continue;
272 }
273 if (isSkippedElement(element)) continue;
274 if (element.tagName === "PRE") {
275 if (scan.pre) scan.other = true;
276 else scan.pre = element;
277 continue;
278 }
279 if (element.tagName === "IMG" || element.tagName === "HR") {
280 scan.other = true;
281 continue;
282 }
283 if (element.tagName === "LI") {
284 const preBeforeItem = scan.pre;
285 scanForSoleCodeBlock(element, scan);
286 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
287 continue;
288 }
289 scanForSoleCodeBlock(element, scan);
290 }
292​
293/**
294 * A drag that ends on a block's final newline pulls the closing `pre` into the
295 * range, so the fragment holds the whole block even though the user only
296 * highlighted code.
297 */
298function soleCodeBlock(container: Node): Element | null {
299 const scan: SoleCodeBlockScan = { pre: null, other: false };
300 scanForSoleCodeBlock(container, scan);
301 return scan.other ? null : scan.pre;
303​
304function tidyMarkdown(markdown: string): string {
305 return markdown
306 .split(/(```[\s\S]*?(?:```|$))/)
307 .map((part, index) =>
308 index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
309 )
310 .join("")
311 .trim();
313​
314export function serializeRenderedMarkdownFragment(container: Node): string {
315 const codeBlock = soleCodeBlock(container);
316 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
317 return tidyMarkdown(serializeChildren(container));
319​
320export function serializeTableElementToMarkdown(table: Element): string {
321 return serializeTable(table).trim();
323​
324function csvCell(value: string): string {
325 const normalized = value.replace(/\s+/g, " ").trim();
326 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
328​
329export function serializeTableElementToCsv(table: Element): string {
330 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
331 const lines: string[] = [];
332 for (const row of rows) {
333 const cells = [...row.children].filter(
334 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
335 );
336 if (cells.length === 0) continue;
337 lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
338 }
339 return lines.join("\n");
341​
342function sanitizedHtmlFrom(container: Element): string {
343 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
344 if (
345 node.classList.contains("chat-markdown-file-link") ||
346 node.closest(".chat-markdown-file-link")
347 ) {
348 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
349 node.remove();
350 }
351 continue;
352 }
353 node.remove();
354 }
355 return `<meta charset="utf-8">${container.innerHTML}`;
357​
358export function chatMarkdownClipboardPayload(
359 selection: Selection,
360): MarkdownClipboardPayload | null {
361 const texts: string[] = [];
362 const htmls: string[] = [];
363 for (let index = 0; index < selection.rangeCount; index += 1) {
364 const range = selection.getRangeAt(index);
365 if (range.collapsed) continue;
366 const container = document.createElement("div");
367 container.appendChild(range.cloneContents());
368 const ancestor = range.commonAncestorContainer;
369 const ancestorElement =
370 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
371 if (ancestorElement?.closest("pre")) {
372 const text = range.toString();
373 if (text) {
374 texts.push(text);
375 htmls.push(sanitizedHtmlFrom(container));
376 }
377 continue;
378 }
379 const text = serializeRenderedMarkdownFragment(container);
380 if (!text) continue;
381 texts.push(text);
382 htmls.push(sanitizedHtmlFrom(container));
383 }
384 if (texts.length === 0) return null;
385 return { text: texts.join("\n\n"), html: htmls.join("") };