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

markdown-clipboard.ts

340 lines11.8 KB

1/**
2 * Converts a DOM selection inside rendered chat markdown back into markdown
3 * source so highlight-and-copy keeps formatting (links, emphasis, lists,
4 * fences, tables) instead of flattening to plain text. The `text/plain`
5 * clipboard flavor carries the markdown; `text/html` carries a sanitized
6 * copy of the rendered fragment for rich-paste targets.
7 */
8​
9const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
10const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
11const SANITIZED_HTML_SELECTOR = [
12 "button",
13 "input",
14 "script",
15 "style",
16 "svg",
17 '[aria-hidden="true"]',
18 ...SKIPPED_CLASS_NAMES.map((className) => `.${className}`),
19].join(", ");
20​
21export interface MarkdownClipboardPayload {
22 text: string;
23 html: string;
25​
26function isSkippedElement(element: Element): boolean {
27 if (SKIPPED_TAGS.has(element.tagName) || element.localName === "svg") return true;
28 if (element.getAttribute("aria-hidden") === "true") return true;
29 return SKIPPED_CLASS_NAMES.some((className) => element.classList.contains(className));
31​
32/** Hoists surrounding whitespace outside the markers: "` bold `" → " **bold** ". */
33function wrapInlineMarker(content: string, marker: string): string {
34 const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(content);
35 const core = match?.[2] ?? "";
36 if (!core) return content;
37 return `${match?.[1] ?? ""}${marker}${core}${marker}${match?.[3] ?? ""}`;
39​
40/**
41 * A code element whose pre wrapper fell outside the copied range is still
42 * block code, recognizable by its highlighter line spans or embedded
43 * newlines. Wrapping it like inline code produces backtick-surrounded
44 * shell commands on paste.
45 */
46function isBlockCodeElement(element: Element, content: string): boolean {
47 if (content.includes("\n")) return true;
48 for (const child of element.childNodes) {
49 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).classList.contains("line")) {
50 return true;
51 }
52 }
53 return false;
55​
56function wrapInlineCode(code: string): string {
57 const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
58 (max, run) => Math.max(max, run.length),
59 0,
60 );
61 const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
62 const pad = code.startsWith("`") || code.endsWith("`") ? " " : "";
63 return `${fence}${pad}${code}${pad}${fence}`;
65​
66function codeFenceFor(code: string): string {
67 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
68 (max, run) => Math.max(max, run.length),
69 0,
70 );
71 return "`".repeat(Math.max(3, longestRun + 1));
73​
74function resolveCodeBlockLanguage(pre: Element): string | null {
75 const declared =
76 pre.closest("[data-language]")?.getAttribute("data-language") ??
77 /(?:^|\s)language-(\S+)/.exec(pre.querySelector("code")?.className ?? "")?.[1] ??
78 null;
79 return declared && declared !== "text" ? declared : null;
81​
82function serializeCodeBlock(pre: Element): string {
83 const code = (pre.textContent ?? "").replace(/\n$/, "");
84 const fence = codeFenceFor(code);
85 return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
87​
88function serializeTableCell(cell: Element): string {
89 return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
91​
92function tableSeparatorFor(headerCells: Element[]): string {
93 const markers = headerCells.map((cell) => {
94 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
95 if (align === "center") return ":---:";
96 if (align === "right") return "---:";
97 return "---";
98 });
99 return `| ${markers.join(" | ")} |`;
101​
102function serializeTable(table: Element): string {
103 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
104 if (rows.length === 0) return "";
105 const lines: string[] = [];
106 let emittedSeparator = false;
107 for (const row of rows) {
108 const cells = [...row.children].filter(
109 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
110 );
111 if (cells.length === 0) continue;
112 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
113 if (!emittedSeparator) {
114 lines.push(tableSeparatorFor(cells));
115 emittedSeparator = true;
116 }
117 }
118 return `${lines.join("\n")}\n\n`;
120​
121function serializeListItem(item: Element, ordered: boolean, index: number): string {
122 const checkbox = item.querySelector('input[type="checkbox"]');
123 const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
124 const marker = ordered ? `${index}. ${task}` : `- ${task}`;
125 let content = serializeChildren(item)
126 .replace(/\n{3,}/g, "\n\n")
127 .trim();
128 // Tight list items (no paragraph children) keep nested lists on adjacent lines.
129 if (!item.querySelector(":scope > p")) {
130 content = content.replace(/\n{2,}/g, "\n");
131 }
132 const continuationIndent = " ".repeat(marker.length);
133 const [first = "", ...rest] = content.split("\n");
134 return [
135 `${marker}${first}`,
136 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
137 ].join("\n");
139​
140function serializeList(list: Element, ordered: boolean): string {
141 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1;
142 const items = [...list.children].filter((child) => child.tagName === "LI");
143 if (items.length === 0) return "";
144 return `${items.map((item, index) => serializeListItem(item, ordered, start + index)).join("\n")}\n\n`;
146​
147function serializeBlockquote(quote: Element): string {
148 const content = serializeChildren(quote)
149 .replace(/\n{3,}/g, "\n\n")
150 .trim();
151 if (!content) return "";
152 const quoted = content
153 .split("\n")
154 .map((line) => (line.length > 0 ? `> ${line}` : ">"))
155 .join("\n");
156 return `${quoted}\n\n`;
158​
159function serializeDetails(details: Element): string {
160 const summary =
161 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
162 "Details";
163 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
164 const content = contentNode ? serializeChildren(contentNode).trim() : "";
165 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
166 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
168​
169function serializeAnchor(anchor: Element): string {
170 const markdownCopy = anchor.getAttribute("data-markdown-copy");
171 if (markdownCopy !== null) return markdownCopy;
172 const content = serializeChildren(anchor);
173 const href = anchor.getAttribute("href") ?? "";
174 if (!/^https?:\/\//i.test(href)) return content;
175 const label = content.trim();
176 if (!label) return "";
177 if (label === href) return href;
178 return `[${label}](${href})`;
180​
181function serializeChildren(node: Node): string {
182 let out = "";
183 for (const child of node.childNodes) {
184 out += serializeNode(child);
185 }
186 return out;
188​
189function serializeNode(node: Node): string {
190 if (node.nodeType === Node.TEXT_NODE) {
191 const text = node.textContent ?? "";
192 // Inter-block formatting whitespace from the renderer collapses to a
193 // newline; real inline whitespace passes through untouched.
194 if (text.includes("\n") && text.trim().length === 0) return "\n";
195 return text;
196 }
197 if (node.nodeType !== Node.ELEMENT_NODE) return "";
198 const element = node as Element;
199 if (element.hasAttribute("data-markdown-details")) {
200 return serializeDetails(element);
201 }
202 const markdownCopy = element.getAttribute("data-markdown-copy");
203 if (markdownCopy !== null) return markdownCopy;
204 if (isSkippedElement(element)) return "";
205​
206 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
207 if (headingLevel) {
208 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element).trim()}\n\n`;
209 }
210​
211 switch (element.tagName) {
212 case "BR":
213 return "\n";
214 case "HR":
215 return "---\n\n";
216 case "P":
217 return `${serializeChildren(element).trim()}\n\n`;
218 case "PRE":
219 return serializeCodeBlock(element);
220 case "CODE": {
221 const content = element.textContent ?? "";
222 return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
223 }
224 case "STRONG":
225 case "B":
226 return wrapInlineMarker(serializeChildren(element), "**");
227 case "EM":
228 case "I":
229 return wrapInlineMarker(serializeChildren(element), "*");
230 case "DEL":
231 case "S":
232 return wrapInlineMarker(serializeChildren(element), "~~");
233 case "A":
234 return serializeAnchor(element);
235 case "IMG": {
236 const alt = element.getAttribute("alt") ?? "";
237 const src = element.getAttribute("src") ?? "";
238 return alt && src ? `![${alt}](${src})` : "";
239 }
240 case "UL":
241 return serializeList(element, false);
242 case "OL":
243 return serializeList(element, true);
244 case "BLOCKQUOTE":
245 return serializeBlockquote(element);
246 case "TABLE":
247 return serializeTable(element);
248 case "DIV":
249 case "SECTION":
250 case "ARTICLE": {
251 const content = serializeChildren(element);
252 return content && !content.endsWith("\n") ? `${content}\n` : content;
253 }
254 default:
255 return serializeChildren(element);
256 }
258​
259/** Collapses serializer spacing artifacts without touching fenced code content. */
260function tidyMarkdown(markdown: string): string {
261 return markdown
262 .split(/(```[\s\S]*?(?:```|$))/)
263 .map((part, index) =>
264 index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
265 )
266 .join("")
267 .trim();
269​
270export function serializeRenderedMarkdownFragment(container: Node): string {
271 return tidyMarkdown(serializeChildren(container));
273​
274export function serializeTableElementToMarkdown(table: Element): string {
275 return serializeTable(table).trim();
277​
278function csvCell(value: string): string {
279 const normalized = value.replace(/\s+/g, " ").trim();
280 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
282​
283export function serializeTableElementToCsv(table: Element): string {
284 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
285 const lines: string[] = [];
286 for (const row of rows) {
287 const cells = [...row.children].filter(
288 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
289 );
290 if (cells.length === 0) continue;
291 lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
292 }
293 return lines.join("\n");
295​
296function sanitizedHtmlFrom(container: Element): string {
297 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
298 if (
299 node.classList.contains("chat-markdown-file-link") ||
300 node.closest(".chat-markdown-file-link")
301 ) {
302 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
303 node.remove();
304 }
305 continue;
306 }
307 node.remove();
308 }
309 return `<meta charset="utf-8">${container.innerHTML}`;
311​
312export function chatMarkdownClipboardPayload(
313 selection: Selection,
314): MarkdownClipboardPayload | null {
315 const texts: string[] = [];
316 const htmls: string[] = [];
317 for (let index = 0; index < selection.rangeCount; index += 1) {
318 const range = selection.getRangeAt(index);
319 if (range.collapsed) continue;
320 const container = document.createElement("div");
321 container.appendChild(range.cloneContents());
322 const ancestor = range.commonAncestorContainer;
323 const ancestorElement =
324 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
325 if (ancestorElement?.closest("pre")) {
326 const text = range.toString();
327 if (text) {
328 texts.push(text);
329 htmls.push(sanitizedHtmlFrom(container));
330 }
331 continue;
332 }
333 const text = serializeRenderedMarkdownFragment(container);
334 if (!text) continue;
335 texts.push(text);
336 htmls.push(sanitizedHtmlFrom(container));
337 }
338 if (texts.length === 0) return null;
339 return { text: texts.join("\n\n"), html: htmls.join("") };