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

markdown-clipboard.ts

311 lines10.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​
40function wrapInlineCode(code: string): string {
41 const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
42 (max, run) => Math.max(max, run.length),
43 0,
44 );
45 const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
46 const pad = code.startsWith("`") || code.endsWith("`") ? " " : "";
47 return `${fence}${pad}${code}${pad}${fence}`;
49​
50function codeFenceFor(code: string): string {
51 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
52 (max, run) => Math.max(max, run.length),
53 0,
54 );
55 return "`".repeat(Math.max(3, longestRun + 1));
57​
58function resolveCodeBlockLanguage(pre: Element): string | null {
59 const declared =
60 pre.closest("[data-language]")?.getAttribute("data-language") ??
61 /(?:^|\s)language-(\S+)/.exec(pre.querySelector("code")?.className ?? "")?.[1] ??
62 null;
63 return declared && declared !== "text" ? declared : null;
65​
66function serializeCodeBlock(pre: Element): string {
67 const code = (pre.textContent ?? "").replace(/\n$/, "");
68 const fence = codeFenceFor(code);
69 return `${fence}${resolveCodeBlockLanguage(pre) ?? ""}\n${code}\n${fence}\n\n`;
71​
72function serializeTableCell(cell: Element): string {
73 return serializeChildren(cell).replace(/\n+/g, " ").trim().replaceAll("|", "\\|");
75​
76function tableSeparatorFor(headerCells: Element[]): string {
77 const markers = headerCells.map((cell) => {
78 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
79 if (align === "center") return ":---:";
80 if (align === "right") return "---:";
81 return "---";
82 });
83 return `| ${markers.join(" | ")} |`;
85​
86function serializeTable(table: Element): string {
87 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
88 if (rows.length === 0) return "";
89 const lines: string[] = [];
90 let emittedSeparator = false;
91 for (const row of rows) {
92 const cells = [...row.children].filter(
93 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
94 );
95 if (cells.length === 0) continue;
96 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
97 if (!emittedSeparator) {
98 lines.push(tableSeparatorFor(cells));
99 emittedSeparator = true;
100 }
101 }
102 return `${lines.join("\n")}\n\n`;
104​
105function serializeListItem(item: Element, ordered: boolean, index: number): string {
106 const checkbox = item.querySelector('input[type="checkbox"]');
107 const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
108 const marker = ordered ? `${index}. ${task}` : `- ${task}`;
109 let content = serializeChildren(item)
110 .replace(/\n{3,}/g, "\n\n")
111 .trim();
112 // Tight list items (no paragraph children) keep nested lists on adjacent lines.
113 if (!item.querySelector(":scope > p")) {
114 content = content.replace(/\n{2,}/g, "\n");
115 }
116 const continuationIndent = " ".repeat(marker.length);
117 const [first = "", ...rest] = content.split("\n");
118 return [
119 `${marker}${first}`,
120 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
121 ].join("\n");
123​
124function serializeList(list: Element, ordered: boolean): string {
125 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1;
126 const items = [...list.children].filter((child) => child.tagName === "LI");
127 if (items.length === 0) return "";
128 return `${items.map((item, index) => serializeListItem(item, ordered, start + index)).join("\n")}\n\n`;
130​
131function serializeBlockquote(quote: Element): string {
132 const content = serializeChildren(quote)
133 .replace(/\n{3,}/g, "\n\n")
134 .trim();
135 if (!content) return "";
136 const quoted = content
137 .split("\n")
138 .map((line) => (line.length > 0 ? `> ${line}` : ">"))
139 .join("\n");
140 return `${quoted}\n\n`;
142​
143function serializeDetails(details: Element): string {
144 const summary =
145 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
146 "Details";
147 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
148 const content = contentNode ? serializeChildren(contentNode).trim() : "";
149 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
150 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
152​
153function serializeAnchor(anchor: Element): string {
154 const markdownCopy = anchor.getAttribute("data-markdown-copy");
155 if (markdownCopy !== null) return markdownCopy;
156 const content = serializeChildren(anchor);
157 const href = anchor.getAttribute("href") ?? "";
158 if (!/^https?:\/\//i.test(href)) return content;
159 const label = content.trim();
160 if (!label) return "";
161 if (label === href) return href;
162 return `[${label}](${href})`;
164​
165function serializeChildren(node: Node): string {
166 let out = "";
167 for (const child of node.childNodes) {
168 out += serializeNode(child);
169 }
170 return out;
172​
173function serializeNode(node: Node): string {
174 if (node.nodeType === Node.TEXT_NODE) {
175 const text = node.textContent ?? "";
176 // Inter-block formatting whitespace from the renderer collapses to a
177 // newline; real inline whitespace passes through untouched.
178 if (text.includes("\n") && text.trim().length === 0) return "\n";
179 return text;
180 }
181 if (node.nodeType !== Node.ELEMENT_NODE) return "";
182 const element = node as Element;
183 if (element.hasAttribute("data-markdown-details")) {
184 return serializeDetails(element);
185 }
186 const markdownCopy = element.getAttribute("data-markdown-copy");
187 if (markdownCopy !== null) return markdownCopy;
188 if (isSkippedElement(element)) return "";
189​
190 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
191 if (headingLevel) {
192 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element).trim()}\n\n`;
193 }
194​
195 switch (element.tagName) {
196 case "BR":
197 return "\n";
198 case "HR":
199 return "---\n\n";
200 case "P":
201 return `${serializeChildren(element).trim()}\n\n`;
202 case "PRE":
203 return serializeCodeBlock(element);
204 case "CODE":
205 return wrapInlineCode(element.textContent ?? "");
206 case "STRONG":
207 case "B":
208 return wrapInlineMarker(serializeChildren(element), "**");
209 case "EM":
210 case "I":
211 return wrapInlineMarker(serializeChildren(element), "*");
212 case "DEL":
213 case "S":
214 return wrapInlineMarker(serializeChildren(element), "~~");
215 case "A":
216 return serializeAnchor(element);
217 case "IMG": {
218 const alt = element.getAttribute("alt") ?? "";
219 const src = element.getAttribute("src") ?? "";
220 return alt && src ? `![${alt}](${src})` : "";
221 }
222 case "UL":
223 return serializeList(element, false);
224 case "OL":
225 return serializeList(element, true);
226 case "BLOCKQUOTE":
227 return serializeBlockquote(element);
228 case "TABLE":
229 return serializeTable(element);
230 case "DIV":
231 case "SECTION":
232 case "ARTICLE": {
233 const content = serializeChildren(element);
234 return content && !content.endsWith("\n") ? `${content}\n` : content;
235 }
236 default:
237 return serializeChildren(element);
238 }
240​
241/** Collapses serializer spacing artifacts without touching fenced code content. */
242function tidyMarkdown(markdown: string): string {
243 return markdown
244 .split(/(```[\s\S]*?(?:```|$))/)
245 .map((part, index) =>
246 index % 2 === 1 ? part : part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n"),
247 )
248 .join("")
249 .trim();
251​
252export function serializeRenderedMarkdownFragment(container: Node): string {
253 return tidyMarkdown(serializeChildren(container));
255​
256export function serializeTableElementToMarkdown(table: Element): string {
257 return serializeTable(table).trim();
259​
260function csvCell(value: string): string {
261 const normalized = value.replace(/\s+/g, " ").trim();
262 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
264​
265export function serializeTableElementToCsv(table: Element): string {
266 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
267 const lines: string[] = [];
268 for (const row of rows) {
269 const cells = [...row.children].filter(
270 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
271 );
272 if (cells.length === 0) continue;
273 lines.push(cells.map((cell) => csvCell(cell.textContent ?? "")).join(","));
274 }
275 return lines.join("\n");
277​
278function sanitizedHtmlFrom(container: Element): string {
279 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
280 if (
281 node.classList.contains("chat-markdown-file-link") ||
282 node.closest(".chat-markdown-file-link")
283 ) {
284 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
285 node.remove();
286 }
287 continue;
288 }
289 node.remove();
290 }
291 return `<meta charset="utf-8">${container.innerHTML}`;
293​
294export function chatMarkdownClipboardPayload(
295 selection: Selection,
296): MarkdownClipboardPayload | null {
297 const texts: string[] = [];
298 const htmls: string[] = [];
299 for (let index = 0; index < selection.rangeCount; index += 1) {
300 const range = selection.getRangeAt(index);
301 if (range.collapsed) continue;
302 const container = document.createElement("div");
303 container.appendChild(range.cloneContents());
304 const text = serializeRenderedMarkdownFragment(container);
305 if (!text) continue;
306 texts.push(text);
307 htmls.push(sanitizedHtmlFrom(container));
308 }
309 if (texts.length === 0) return null;
310 return { text: texts.join("\n\n"), html: htmls.join("") };