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

markdown-clipboard.ts

1,187 lines46.9 KB

1import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks";
2import { parseUrl } from "@t3tools/shared/url";
3​
4const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
5const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
6const SANITIZED_HTML_SELECTOR = [
7 "button",
8 "input",
9 "script",
10 "style",
11 "svg",
12 '[aria-hidden="true"]',
13 ...SKIPPED_CLASS_NAMES.map((className) => `.${className}`),
14].join(", ");
15​
16const ALERT_ATTRIBUTE = "data-markdown-alert";
17const ALERT_LABEL = "data-markdown-alert-label";
18const LIST_ITEM_CHECKBOX = ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]';
19​
20export interface MarkdownClipboardPayload {
21 text: string;
22 html: string;
24​
25function isSkippedElement(element: Element): boolean {
26 if (SKIPPED_TAGS.has(element.tagName) || element.localName === "svg") return true;
27 if (element.getAttribute("aria-hidden") === "true") return true;
28 return SKIPPED_CLASS_NAMES.some((className) => element.classList.contains(className));
30​
31function wrapInlineMarker(content: string, marker: string): string {
32 const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(content);
33 const core = match?.[2] ?? "";
34 if (!core) return content;
35 return `${match?.[1] ?? ""}${marker}${core}${marker}${match?.[3] ?? ""}`;
37​
38// Highlighter spans or newlines identify block code even when its pre wrapper was not copied.
39function isBlockCodeElement(element: Element, content: string): boolean {
40 if (content.includes("\n")) return true;
41 for (const child of element.childNodes) {
42 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).classList.contains("line")) {
43 return true;
44 }
45 }
46 return false;
48​
49function wrapInlineCode(code: string): string {
50 const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
51 (max, run) => Math.max(max, run.length),
52 0,
53 );
54 const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
55 // CommonMark strips one edge space from content that has both and isn't all spaces.
56 const spaceEdges = code.startsWith(" ") && code.endsWith(" ") && /[^ ]/.test(code);
57 const pad = spaceEdges || code.startsWith("`") || code.endsWith("`") ? " " : "";
58 return `${fence}${pad}${code}${pad}${fence}`;
60​
61function codeFenceFor(code: string): string {
62 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
63 (max, run) => Math.max(max, run.length),
64 0,
65 );
66 return "`".repeat(Math.max(3, longestRun + 1));
68​
69export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
70 const code = source.replace(/\n$/, "");
71 const fence = codeFenceFor(code);
72 return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
74​
75// Brackets copied code so tidyMarkdown leaves its whitespace alone. Code is
76// copied as shown, without fences; DOM text from rendered markdown carries no NUL.
77const CODE_BOUNDARY = "\u0000";
78// An empty code part before a marker the serializer writes keeps escapeBlockStarts off it.
79const BLOCK_GUARD = `${CODE_BOUNDARY}${CODE_BOUNDARY}`;
80// CommonMark/GFM block starts: headings, quotes, lists, rules, setext, fences, table delimiters.
81// Deeper indentation is indented code or a continuation line, where a backslash would show.
82const BLOCK_START =
83 /\u0000[\s\S]*?\u0000|^( {0,3})(?![ \t])(?:((?:\*[ \t]*){3,}$|(?:_[ \t]*){3,}$|~{3,})|\d{1,9}(?=[.)](?:[ \t]|$))|(?=#{1,6}(?:[ \t]|$)|>|[-+*](?:[ \t]|$)|=+[ \t]*$|(?:-[ \t]*){2,}$|(?:\|[ \t]*)?:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*(?:\|[ \t]*)?$))/gm;
84const escapeBlockStart = (match: string, indent?: string, rule?: string) => {
85 if (indent === undefined) return match;
86 return rule ? `${indent}${rule.replace(/[*_~]/g, "\\$&")}` : `${match}\\`;
87};
88const escapeBlockStarts = (text: string) => text.replace(BLOCK_START, escapeBlockStart);
89const protectVerbatim = (text: string) =>
90 text ? CODE_BOUNDARY + text.replace(/(?<!\n)\n*$/, `${CODE_BOUNDARY}$&`) : "";
91​
92function verbatimBlock(code: string): string {
93 return `${CODE_BOUNDARY}${code}${CODE_BOUNDARY}\n\n`;
95​
96// Odd parts are code and keep their markers, so outer passes still skip them.
97function outsideCode(markdown: string, tidy: (prose: string) => string): string {
98 return markdown
99 .split(CODE_BOUNDARY)
100 .map((part, index) =>
101 index % 2 === 1 ? `${CODE_BOUNDARY}${part}${CODE_BOUNDARY}` : tidy(part),
102 )
103 .join("");
105​
106function serializeCodeBlock(pre: Element): string {
107 return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
109​
110function serializeTableCell(cell: Element): string {
111 return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
113​
114function tableSeparatorFor(headerCells: Element[]): string {
115 const markers = headerCells.map((cell) => {
116 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
117 if (align === "center") return ":---:";
118 if (align === "right") return "---:";
119 return "---";
120 });
121 return `| ${markers.join(" | ")} |`;
123​
124// Footers render after the body even when the source puts them first.
125function tableRows(table: Element): Element[] {
126 return [
127 ...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr"),
128 ...table.querySelectorAll(":scope > tfoot > tr"),
129 ];
131​
132function serializeTable(table: Element): string {
133 const rows = tableRows(table);
134 if (rows.length === 0) return "";
135 const lines: string[] = [];
136 let emittedSeparator = false;
137 for (const row of rows) {
138 const cells = [...row.children].filter(
139 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
140 );
141 if (cells.length === 0) continue;
142 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
143 if (!emittedSeparator) {
144 lines.push(tableSeparatorFor(cells));
145 emittedSeparator = true;
146 }
147 }
148 return `${BLOCK_GUARD}${lines.join(`\n${BLOCK_GUARD}`)}\n\n`;
150​
151function serializeListItem(
152 item: Element,
153 ordered: boolean,
154 index: number,
155 inTableCell: boolean,
156): string {
157 const checkbox = item.querySelector<HTMLInputElement>(LIST_ITEM_CHECKBOX);
158 const task = checkbox ? `[${checkbox.checked ? "x" : " "}] ` : "";
159 const bullet = ordered ? `${index}. ` : "- ";
160 const marker = `${bullet}${task}`;
161 let content = outsideCode(serializeChildren(item, inTableCell), (prose) =>
162 prose.replace(/\n{3,}/g, "\n\n"),
163 ).trim();
164 if (!inTableCell) content = escapeBlockStarts(content);
165 if (!item.querySelector(":scope > p")) {
166 content = outsideCode(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
167 }
168 // Continuations align after the bullet; task boxes belong to the item text.
169 const continuationIndent = " ".repeat(bullet.length);
170 const [first = "", ...rest] = content.split("\n");
171 return [
172 `${BLOCK_GUARD}${marker}${first}`,
173 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
174 ].join("\n");
176​
177/** A list's items with the numbers an ordered list shows: from `start`, reset by each `value`. */
178function numberedListItems(list: Element): { item: Element; number: number }[] {
179 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10);
180 let next = Number.isNaN(start) ? 1 : start;
181 return [...list.children]
182 .filter((child) => child.tagName === "LI")
183 .map((item) => {
184 const value = Number.parseInt(item.getAttribute("value") ?? "", 10);
185 if (!Number.isNaN(value)) next = value;
186 return { item, number: next++ };
187 });
189​
190function serializeList(list: Element, ordered: boolean, inTableCell: boolean): string {
191 const items = numberedListItems(list);
192 if (items.length === 0) return "";
193 // CommonMark markers stop at nine digits and only the first sets the numbering, so items
194 // counted on from a valid marker stay at the limit instead of turning into paragraph text.
195 let cap = Infinity;
196 return `${items
197 .map(({ item, number }, index) => {
198 if (index === 0 || item.hasAttribute("value")) {
199 cap = number <= 999_999_999 ? 999_999_999 : Infinity;
200 return serializeListItem(item, ordered, number, inTableCell);
201 }
202 return serializeListItem(item, ordered, Math.min(number, cap), inTableCell);
203 })
204 .join("\n")}\n\n`;
206​
207function serializeQuoteBody(quote: Element, inTableCell: boolean): string {
208 let content = "";
209 for (const child of quote.childNodes) {
210 // A callout's rendered label stands for the marker its serializer writes.
211 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).hasAttribute(ALERT_LABEL)) {
212 continue;
213 }
214 content += serializeNode(child, inTableCell);
215 }
216 if (!inTableCell) content = escapeBlockStarts(content);
217 return outsideCode(content, (prose) => prose.replace(/\n{3,}/g, "\n\n")).trim();
219​
220function serializeBlockquote(quote: Element, inTableCell: boolean, marker = ""): string {
221 const body = serializeQuoteBody(quote, inTableCell);
222 const content = marker && body ? `${marker}\n${body}` : marker || body;
223 if (!content) return "";
224 const quoted = content
225 .split("\n")
226 .map((line) => (line.length > 0 ? `${BLOCK_GUARD}> ${line}` : `${BLOCK_GUARD}>`))
227 .join("\n");
228 return `${quoted}\n\n`;
230​
231function serializeInsight(insight: Element, inTableCell: boolean): string {
232 const body = serializeQuoteBody(insight, inTableCell);
233 // oxlint-disable-next-line t3code/no-untranslated-copy -- markdown written to the clipboard
234 return `★ Insight ${"─".repeat(37)}\n${body ? `${body}\n` : ""}${"─".repeat(49)}\n\n`;
236​
237function serializeDetails(details: Element): string {
238 const summary =
239 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
240 "Details";
241 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
242 const content = contentNode ? serializeChildren(contentNode).trim() : "";
243 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
244 return `<details${open}>\n<summary>${escapeHtml(summary)}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
246​
247// Prose that would read as inline Markdown once pasted back: a backslash before punctuation,
248// backticks, opening brackets, tag or autolink starts, character references, and emphasis or
249// strikethrough runs (user remark-gfm sets singleTilde: false). A closing bracket stays bare:
250// `\[…\]` would read as display math.
251const INLINE_MARKDOWN =
252 /\\(?=[!-/:-@[-`{-~\n]|$)|[`[]|<(?=[A-Za-z/!?])|&(?=#?[A-Za-z0-9]+;)|\*+|_+|~{2,}/g;
253const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
254​
255/** Where a word's unfinished drive path starts, after which backslashes and brackets read literally. */
256function driveStartOf(word: string): number {
257 // Check each word once; testing every escape's growing prefix would be quadratic.
258 const drive = UNFINISHED_DRIVE_PATH.exec(word);
259 return drive ? drive.index + drive[0].search(/[A-Za-z]/) + 2 : Infinity;
261​
262/** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
263function escapeProse(text: string): string {
264 return text.replace(/\S+/g, (word, wordOffset: number) => {
265 const driveStart = driveStartOf(word);
266 return word.replace(INLINE_MARKDOWN, (match: string, offset: number) => {
267 if (offset >= driveStart) return match;
268 const before = text[wordOffset + offset - 1];
269 const after = text[wordOffset + offset + match.length];
270 if (match === "\\" && after !== undefined && /[^\S\n]/.test(after)) return match;
271 // A text node's edge may touch another node's markers, so it counts as neither.
272 const between = (pattern: RegExp) =>
273 before !== undefined && after !== undefined && pattern.test(before) && pattern.test(after);
274 if (/[*_~]/.test(match[0]!) && between(/\s/)) return match;
275 if (match[0] === "_" && between(/[\p{L}\p{N}]/u)) return match;
276 return match.replace(/[\s\S]/g, "\\$&");
277 });
278 });
280​
281const sameWebUrl = (label: string, href: string) =>
282 /^https?:\/\/[^\s\p{C}<>`"\\]+(?<![?!.,:*_~';)])$/iu.test(label) &&
283 parseUrl(label)?.href === (parseUrl(href)?.href ?? null);
284const autolinksBare = (label: string, href: string) =>
285 /^https?:/i.test(href) ? sameWebUrl(label, href) : label === href;
286​
287/** Restores link destinations only when the HTML and plain clipboard describe the same text. */
288export function restorePastedMarkdownLinks(plain: string, html: string): string {
289 if (!plain || !/<a[\s>]/i.test(html)) return plain;
290 // Template contents stay inert, including resources and custom elements.
291 const template = document.createElement("template");
292 template.innerHTML = html;
293 const fragment = template.content;
294 const destinations = new Map<Node, string>();
295 for (const element of fragment.querySelectorAll("script, style, [hidden]")) element.remove();
296 for (const element of fragment.querySelectorAll<HTMLElement | SVGElement>("[style]")) {
297 if (element.style.display === "none") element.remove();
298 }
299 // Visibility inherits, but a visible descendant can override a hidden ancestor.
300 const invisible = new WeakSet<Element>();
301 const nodes = document.createNodeIterator(
302 fragment,
303 NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
304 );
305 for (let node = nodes.nextNode(); node; node = nodes.nextNode()) {
306 const inheritsHidden = node.parentElement !== null && invisible.has(node.parentElement);
307 if (node instanceof Text) {
308 if (inheritsHidden) node.remove();
309 } else if (node instanceof Element) {
310 const visibility =
311 node instanceof HTMLElement || node instanceof SVGElement ? node.style.visibility : "";
312 if (
313 visibility === "hidden" ||
314 visibility === "collapse" ||
315 (inheritsHidden && visibility !== "visible" && visibility !== "initial")
316 ) {
317 invisible.add(node);
318 }
319 }
320 }
321 for (const anchor of fragment.querySelectorAll("a[href]")) {
322 // Linked identifiers in API docs code samples must stay literal code.
323 if (anchor.closest("pre, code")) continue;
324 const href = anchor.getAttribute("href")?.trim() ?? "";
325 if (!/^(?:https?:\/\/|mailto:)/i.test(href)) continue;
326 let url: URL;
327 try {
328 url = new URL(href);
329 } catch {
330 continue;
331 }
332 const label = document.createTextNode(anchor.textContent ?? "");
333 anchor.replaceWith(label);
334 destinations.set(label, url.href);
335 }
336 if (destinations.size === 0) return plain;
337​
338 // Match visible characters in order. The plain rendition owns line breaks and spacing.
339 const walker = document.createTreeWalker(fragment, NodeFilter.SHOW_TEXT);
340 const characters = plain.matchAll(/\S/g);
341 const parts: string[] = [];
342 let resultEnd = 0;
343 for (let node = walker.nextNode(); node; node = walker.nextNode()) {
344 let start: number | undefined;
345 let end = 0;
346 for (const character of (node.textContent ?? "").matchAll(/\S/g)) {
347 const match = characters.next().value;
348 if (match?.[0] !== character[0]) return plain;
349 start ??= match.index;
350 end = match.index + 1;
351 }
352 const href = destinations.get(node);
353 if (href === undefined || start === undefined) continue;
354 const label = plain.slice(start, end);
355 if (autolinksBare(label, href)) continue;
356 const prefix = plain.slice(resultEnd, start).replace(/(?<!\\)((?:\\\\)*)([!\\])$/, "$1\\$2");
357 parts.push(
358 prefix,
359 label.replace(/\S(?:[^\n]*\S)?/g, (line) => markdownAnchor(escapeProse(line), href, false)),
360 );
361 resultEnd = end;
362 }
363 if (!characters.next().done || parts.length === 0) return plain;
364 return parts.join("") + plain.slice(resultEnd);
366​
367function markdownAnchor(label: string, href: string, inTableCell: boolean): string {
368 const destination = escapeTablePipes(
369 href.replace(/[\\()]/g, "\\$&").replaceAll("&", "&amp;"),
370 inTableCell,
371 );
372 // Prose leaves `]` bare, but inside a label it would end the label. Drive paths stay literal.
373 const text = outsideCode(label, (prose) =>
374 prose.replace(/\S+/g, (word) => {
375 const driveStart = driveStartOf(word);
376 return word.replace(/(?<!\\)(?:\\\\)*\]/g, (match: string, offset: number) =>
377 offset + match.length > driveStart ? match : `${match.slice(0, -1)}\\]`,
378 );
379 }),
380 );
381 return `[${text}](${destination})`;
383​
384function serializeAnchor(anchor: Element, inTableCell: boolean): string {
385 const markdownCopy = anchor.getAttribute("data-markdown-copy");
386 if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
387 const content = serializeChildren(anchor, inTableCell);
388 const href = anchor.getAttribute("href") ?? "";
389 if (!/^(?:https?:\/\/|mailto:)/i.test(href)) return content;
390 const label = content.trim();
391 if (!label) return content;
392 // Markdown keeps spaces inside a label, so a padded link pastes back as it rendered.
393 if (label !== content) return markdownAnchor(content, href, inTableCell);
394 // The label arrives escaped; a bare address goes out as shown, since GFM links it again.
395 const shown = label.replace(ESCAPED_PUNCTUATION, "$1");
396 const bare = !/&#?[A-Za-z0-9]+;/.test(href) && autolinksBare(shown, href);
397 if (bare) return escapeTablePipes(shown, inTableCell);
398 // GFM autolinks a bare address only when it fits this shape.
399 if (href === `mailto:${shown}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(shown))
400 return shown;
401 return markdownAnchor(label, href, inTableCell);
403​
404/**
405 * GFM splits a table row at every unescaped pipe, but its math-aware parsing
406 * keeps a formula's pipes in the cell, so formula source is copied unescaped.
407 */
408function escapeTablePipes(text: string, inTableCell: boolean): string {
409 return inTableCell ? text.replaceAll("|", "\\|") : text;
411​
412function serializeChildren(node: Node, inTableCell = false): string {
413 let out = "";
414 for (const child of node.childNodes) {
415 const next = serializeNode(child, inTableCell);
416 // Text ending in an unescaped `!` would turn a following link into an image.
417 if (next.startsWith("[") && out.endsWith("!")) {
418 let backslashes = 0;
419 while (out[out.length - 2 - backslashes] === "\\") backslashes += 1;
420 if (backslashes % 2 === 0) out = out.slice(0, -1) + "\\!";
421 }
422 out += next;
423 }
424 return out;
426​
427function serializeNode(node: Node, inTableCell = false): string {
428 if (node.nodeType === Node.TEXT_NODE) {
429 let text = node.textContent ?? "";
430 // A <br> already wrote the line ending that follows it.
431 if (node.previousSibling?.nodeName === "BR") text = text.replace(/^\n/, "");
432 if (text.includes("\n") && text.trim().length === 0) return "\n";
433 return escapeTablePipes(escapeProse(text), inTableCell);
434 }
435 if (node.nodeType !== Node.ELEMENT_NODE) return "";
436 const element = node as Element;
437 if (element.hasAttribute("data-markdown-details")) {
438 return escapeTablePipes(serializeDetails(element), inTableCell);
439 }
440 const markdownCopy = element.getAttribute("data-markdown-copy");
441 if (markdownCopy !== null) {
442 // A diagram copies as its fenced source, which is code too.
443 if (element.hasAttribute("data-markdown-mermaid")) {
444 return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
445 }
446 const copy = element.hasAttribute("data-markdown-math")
447 ? markdownCopy
448 : escapeTablePipes(markdownCopy, inTableCell);
449 return protectVerbatim(copy);
450 }
451 if (isSkippedElement(element)) return "";
452 const alert = element.getAttribute(ALERT_ATTRIBUTE);
453 if (alert === "insight") return serializeInsight(element, inTableCell);
454 if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`);
455​
456 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
457 if (headingLevel) {
458 const content = serializeChildren(element, inTableCell)
459 .trim()
460 .replace(/(^|[ \t])(#+)$/, "$1\\$2");
461 return `${BLOCK_GUARD}${"#".repeat(Number(headingLevel))} ${content}\n\n`;
462 }
463​
464 switch (element.tagName) {
465 case "BR":
466 return "\n";
467 case "HR":
468 return `${BLOCK_GUARD}---\n\n`;
469 case "P":
470 return `${serializeChildren(element, inTableCell).trim()}\n\n`;
471 case "PRE":
472 return escapeTablePipes(serializeCodeBlock(element), inTableCell);
473 case "CODE": {
474 const content = escapeTablePipes(element.textContent ?? "", inTableCell);
475 if (!content) return "";
476 const code = isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
477 return protectVerbatim(code);
478 }
479 case "STRONG":
480 case "B":
481 return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
482 case "EM":
483 case "I":
484 return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
485 case "DEL":
486 case "S":
487 return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
488 case "A":
489 return serializeAnchor(element, inTableCell);
490 case "IMG": {
491 const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
492 const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
493 return alt && src ? `![${alt}](${src})` : "";
494 }
495 case "UL":
496 return serializeList(element, false, inTableCell);
497 case "OL":
498 return serializeList(element, true, inTableCell);
499 case "BLOCKQUOTE":
500 return serializeBlockquote(element, inTableCell);
501 case "TABLE":
502 return escapeTablePipes(serializeTable(element), inTableCell);
503 case "DIV":
504 case "SECTION":
505 case "ARTICLE": {
506 const content = serializeChildren(element, inTableCell);
507 return content && !content.endsWith("\n") ? `${content}\n` : content;
508 }
509 default:
510 return serializeChildren(element, inTableCell);
511 }
513​
514interface SoleCodeBlockScan {
515 pre: Element | null;
516 other: boolean;
518​
519function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
520 for (const child of node.childNodes) {
521 if (scan.other) return;
522 if (child.nodeType === Node.TEXT_NODE) {
523 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
524 continue;
525 }
526 if (child.nodeType !== Node.ELEMENT_NODE) continue;
527 const element = child as Element;
528 // Explicit markdown still counts on skipped tags such as file-chip buttons.
529 if (element.hasAttribute("data-markdown-details")) {
530 scan.other = true;
531 continue;
532 }
533 const markdownCopy = element.getAttribute("data-markdown-copy");
534 if (markdownCopy !== null) {
535 if (markdownCopy.trim().length > 0) scan.other = true;
536 continue;
537 }
538 if (isSkippedElement(element)) continue;
539 if (element.tagName === "PRE") {
540 if (scan.pre) scan.other = true;
541 else scan.pre = element;
542 continue;
543 }
544 if (element.tagName === "IMG" || element.tagName === "HR") {
545 scan.other = true;
546 continue;
547 }
548 if (element.tagName === "LI") {
549 const preBeforeItem = scan.pre;
550 scanForSoleCodeBlock(element, scan);
551 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
552 continue;
553 }
554 scanForSoleCodeBlock(element, scan);
555 }
557​
558// Selecting a block's final newline pulls in its closing pre even when only code was highlighted.
559function soleCodeBlock(container: Node): Element | null {
560 const scan: SoleCodeBlockScan = { pre: null, other: false };
561 scanForSoleCodeBlock(container, scan);
562 return scan.other ? null : scan.pre;
564​
565function tidyMarkdown(markdown: string): string {
566 // Odd parts are code, kept verbatim, so a selection that starts or ends inside
567 // code keeps that code's leading and trailing whitespace.
568 const parts = escapeBlockStarts(markdown).split(CODE_BOUNDARY);
569 const last = parts.length - 1;
570 return parts
571 .map((part, index) => {
572 if (index % 2 === 1) return part;
573 let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
574 if (index === 0) prose = prose.trimStart();
575 if (index === last) prose = prose.trimEnd();
576 return prose;
577 })
578 .join("");
580​
581export function serializeRenderedMarkdownFragment(container: Node): string {
582 const codeBlock = soleCodeBlock(container);
583 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
584 return tidyMarkdown(serializeChildren(container));
586​
587export function serializeTableElementToMarkdown(table: Element): string {
588 // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
589 return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
591​
592// The wrapper wordsHast puts on every formula it renders. The sanitizer drops
593// the attribute from authored HTML.
594const MATH_SELECTOR = "[data-markdown-math]";
595​
596export function mathWrapperOf(element: Element | null): Element | null {
597 return element?.closest(MATH_SELECTOR) ?? null;
599​
600/** A cell's text on one line, with each formula as its TeX. */
601function csvCellText(cell: Element): string {
602 const parts: string[] = [];
603 collectHtmlCellText(cell, parts, false);
604 return parts.join("").replace(/[\u0001\u0002]+/g, " ");
606​
607function csvCell(value: string): string {
608 const normalized = value.replace(/\s+/g, " ").trim();
609 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
611​
612export function serializeTableElementToCsv(table: Element): string {
613 // Spanned slots stay as empty fields, so values after a span stay under their headers.
614 return tableGrid(table)
615 .map((row) => Array.from(row, (slot) => csvCell(slot?.text ?? "")).join(","))
616 .join("\n");
618​
619// CJK, emoji, flags and keycaps count as two columns: close enough to East Asian Width for chat fonts.
620// The ranges skip nonspacing marks that would make a narrow base look wide.
621// Symbols such as ™, © and ↔ show as text, one column, unless a variation selector makes them emoji.
622const WIDE_GRAPHEME =
623 /\p{Emoji_Presentation}|\ufe0f|\p{Regional_Indicator}|\u20e3|[\u1100-\u115f\u2e80-\u3029\u302e-\u3098\u309b-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{16fe0}-\u{16fe3}\u{16ff0}-\u{191d2}\u{1aff0}-\u{1b2fb}\u{20000}-\u{2fffd}\u{30000}-\u{3fffd}]/u;
624let graphemes: Intl.Segmenter | undefined;
625​
626function monospaceWidth(text: string): number {
627 graphemes ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });
628 let width = 0;
629 for (const { segment } of graphemes.segment(text)) width += WIDE_GRAPHEME.test(segment) ? 2 : 1;
630 return width;
632​
633function padToWidth(text: string, width: number, align: string): string {
634 const gap = width - monospaceWidth(text);
635 if (align === "right") return " ".repeat(gap) + text;
636 if (align === "center") {
637 const left = Math.floor(gap / 2);
638 return " ".repeat(left) + text + " ".repeat(gap - left);
639 }
640 return text + " ".repeat(gap);
642​
643/** Each rendered row's cells by column; a spanned slot repeats its cell with empty text. */
644function tableGrid(table: Element): Array<Array<{ text: string; cell: Element }>> {
645 // Lay cells onto the grid the table renders, so values after a span stay under their headers.
646 // As in the HTML table model, a row group bounds every rowspan and an empty row still takes a row.
647 // Row groups in document order, with footers last as rendered; consecutive rows directly in
648 // the table form one group.
649 const groups: Element[][] = [];
650 const footers: Element[][] = [];
651 let looseRows: Element[] | undefined;
652 for (const child of table.children) {
653 if (child.tagName === "TR") {
654 if (!looseRows) groups.push((looseRows = []));
655 looseRows.push(child);
656 continue;
657 }
658 looseRows = undefined;
659 if (TABLE_SECTION_TAGS.has(child.tagName)) {
660 const rows = [...child.children].filter((row) => row.tagName === "TR");
661 (child.tagName === "TFOOT" ? footers : groups).push(rows);
662 }
663 }
664 groups.push(...footers);
665 const grid: Array<{ slots: Array<{ text: string; cell: Element }>; hasCells: boolean }> = [];
666 for (const groupRows of groups) {
667 const start = grid.length;
668 for (const _ of groupRows) grid.push({ slots: [], hasCells: false });
669 groupRows.forEach((row, offset) => {
670 const gridRow = grid[start + offset]!;
671 let column = 0;
672 for (const cell of row.children) {
673 if (cell.tagName !== "TH" && cell.tagName !== "TD") continue;
674 gridRow.hasCells = true;
675 while (gridRow.slots[column]) column++;
676 const text = csvCellText(cell).replace(/\s+/g, " ").trim();
677 const colSpan = Math.max(1, tableCellSpan(cell, "colSpan", "colspan"));
678 const remaining = groupRows.length - offset;
679 // rowspan="0" runs to the end of its row group.
680 const rowSpan = Math.min(tableCellSpan(cell, "rowSpan", "rowspan") || remaining, remaining);
681 for (let down = 0; down < rowSpan; down++) {
682 for (let across = 0; across < colSpan; across++) {
683 grid[start + offset + down]!.slots[column + across] = {
684 text: down === 0 && across === 0 ? text : "",
685 cell,
686 };
687 }
688 }
689 column += colSpan;
690 }
691 });
692 }
693 return grid.filter((gridRow) => gridRow.hasCells).map((gridRow) => gridRow.slots);
695​
696/**
697 * Space-aligned columns for chat apps. The plain text is a code fence, which WhatsApp and
698 * Slack show monospaced; rich targets (Teams, Slack) paste the HTML flavor as a code block.
699 */
700export function serializeTableElementForChat(table: Element): MarkdownClipboardPayload {
701 const rows = tableGrid(table);
702 if (rows.length === 0) return { text: "", html: "" };
703 const columns = Math.max(...rows.map((gridRow) => gridRow.length));
704 const texts = rows.map((gridRow) =>
705 Array.from({ length: columns }, (_, column) => gridRow[column]?.text ?? ""),
706 );
707 const widths = Array.from({ length: columns }, (_, column) =>
708 Math.max(1, ...texts.map((cells) => monospaceWidth(cells[column] ?? ""))),
709 );
710 const aligns = widths.map((_, column) => {
711 const header = rows[0]?.[column]?.cell as HTMLElement | undefined;
712 return header?.style?.textAlign || header?.getAttribute("align") || "";
713 });
714 const line = (cells: string[]) =>
715 widths
716 .map((width, column) => padToWidth(cells[column] ?? "", width, aligns[column] ?? ""))
717 .join(" ")
718 .trimEnd();
719 const [header = [], ...body] = texts;
720 const lines = [
721 line(header),
722 widths.map((width) => "-".repeat(width)).join(" "),
723 ...body.map(line),
724 ];
725 const aligned = lines.join("\n");
726 const fence = codeFenceFor(aligned);
727 return {
728 text: `${fence}\n${aligned}\n${fence}`,
729 html: `<meta charset="utf-8"><pre>${escapeHtml(aligned)}</pre>`,
730 };
732​
733const TABLE_SECTION_TAGS = new Set(["THEAD", "TBODY", "TFOOT"]);
734// Elements that start a new line inside a copied cell.
735const HTML_CELL_BLOCK_TAGS = new Set([
736 "ARTICLE",
737 "BLOCKQUOTE",
738 "DETAILS",
739 "DIV",
740 "H1",
741 "H2",
742 "H3",
743 "H4",
744 "H5",
745 "H6",
746 "LI",
747 "OL",
748 "P",
749 "PRE",
750 "SECTION",
751 "SUMMARY",
752 "TABLE",
753 "TR",
754 "UL",
755]);
756​
757// Inline and theme-independent: mail clients and editors drop stylesheets, and a
758// copy from the dark theme must still read on a white page. Header cells set their
759// own text color so the light band stays readable in a dark paste target.
760const HTML_TABLE_STYLE = "border-collapse:collapse";
761const HTML_CELL_STYLE = "border:1px solid #d0d7de;padding:6px 12px;vertical-align:top";
762const HTML_HEADER_CELL_STYLE = `${HTML_CELL_STYLE};background-color:#f6f8fa;color:#1f2328;font-weight:600`;
763​
764function escapeHtml(value: string): string {
765 return value
766 .replaceAll("&", "&amp;")
767 .replaceAll("<", "&lt;")
768 .replaceAll(">", "&gt;")
769 .replaceAll('"', "&quot;");
771​
772// Markers in collected cell text: a block edge is a soft line boundary, a break is a <br>.
773const CELL_BLOCK_EDGE = "\u0001";
774const CELL_LINE_BREAK = "\u0002";
775// HTML's collapsible whitespace; a nonbreaking space is content.
776const COLLAPSIBLE_WHITESPACE = /[ \t\n\r\f]+/g;
777​
778/** Preformatted text keeps its lines and spacing as breaks and nonbreaking spaces. */
779function preformattedCellText(text: string): string {
780 return text
781 .replace(/\r\n?|\n/g, CELL_LINE_BREAK)
782 .replaceAll("\t", "\u00a0".repeat(4))
783 .replaceAll(" ", "\u00a0");
785​
786/** Collects a cell's text with block edges and breaks marked, and each formula as its TeX. */
787function collectHtmlCellText(node: Node, parts: string[], preformatted: boolean): void {
788 for (const child of node.childNodes) {
789 if (child.nodeType === Node.TEXT_NODE) {
790 const text = child.textContent ?? "";
791 parts.push(preformatted ? preformattedCellText(text) : text);
792 continue;
793 }
794 if (child.nodeType !== Node.ELEMENT_NODE) continue;
795 const element = child as Element;
796 if (isSkippedElement(element) && !element.hasAttribute("data-markdown-copy")) continue;
797 if (element.hasAttribute("data-markdown-math")) {
798 parts.push(element.getAttribute("data-markdown-copy")?.trim() ?? "");
799 continue;
800 }
801 if (element.tagName === "BR") {
802 parts.push(CELL_LINE_BREAK);
803 continue;
804 }
805 if (element.tagName === "PRE") {
806 const code: string[] = [];
807 collectHtmlCellText(element, code, true);
808 // A code block's closing newline ends the block, not a blank line.
809 parts.push(CELL_BLOCK_EDGE, code.join("").replace(/\u0002$/, ""), CELL_BLOCK_EDGE);
810 continue;
811 }
812 // Cells of a nested table stay apart on their row's line.
813 const separator = element.tagName === "TD" || element.tagName === "TH" ? " " : "";
814 const boundary = HTML_CELL_BLOCK_TAGS.has(element.tagName) ? CELL_BLOCK_EDGE : separator;
815 parts.push(boundary);
816 collectHtmlCellText(element, parts, preformatted);
817 parts.push(boundary);
818 }
820​
821/**
822 * Every explicit break stays a <br>, including repeated and edge ones. Block edges
823 * become one break between content, and none where a break already ends the line.
824 */
825function htmlCellContent(cell: Element): string {
826 const parts: string[] = [];
827 collectHtmlCellText(cell, parts, false);
828 const tokens = parts
829 .join("")
830 .replace(COLLAPSIBLE_WHITESPACE, " ")
831 .split(/([\u0001\u0002])/);
832 let html = "";
833 let atLineStart = true;
834 let pendingBlockEdge = false;
835 for (const token of tokens) {
836 if (token === CELL_LINE_BREAK) {
837 html = `${html.replace(/ +$/, "")}<br>`;
838 atLineStart = true;
839 pendingBlockEdge = false;
840 } else if (token === CELL_BLOCK_EDGE) {
841 pendingBlockEdge = true;
842 } else {
843 const text = atLineStart || pendingBlockEdge ? token.replace(/^ +/, "") : token;
844 if (!text) continue;
845 if (pendingBlockEdge && !atLineStart) html = `${html.replace(/ +$/, "")}<br>`;
846 html += escapeHtml(text).replaceAll("\u00a0", "&nbsp;");
847 atLineStart = false;
848 pendingBlockEdge = false;
849 }
850 }
851 return html.replace(/ +$/, "");
853​
854/** Physical alignment for a paste target; logical values follow the table direction. */
855function htmlCellAlignment(align: string, rtl: boolean): string {
856 switch (align) {
857 case "left":
858 case "center":
859 case "right":
860 case "justify":
861 return align;
862 case "start":
863 return rtl ? "right" : "left";
864 case "end":
865 return rtl ? "left" : "right";
866 default:
867 return "";
868 }
870​
871/** HTML's non-negative integer parsing: leading digits count, anything invalid is 1. */
872function parseTableSpan(value: string | null): number {
873 const span = Number.parseInt(value ?? "", 10);
874 return Number.isNaN(span) || span < 0 ? 1 : span;
876​
877// The DOM normalizes spans; the attribute fallback covers non-DOM callers.
878function tableCellSpan(
879 cell: Element,
880 property: "colSpan" | "rowSpan",
881 attribute: "colspan" | "rowspan",
882): number {
883 const span = (cell as Partial<HTMLTableCellElement>)[property];
884 return typeof span === "number" ? span : parseTableSpan(cell.getAttribute(attribute));
886​
887function htmlSpanAttributes(cell: Element): string {
888 const columns = tableCellSpan(cell, "colSpan", "colspan");
889 const rows = tableCellSpan(cell, "rowSpan", "rowspan");
890 let attributes = columns > 1 ? ` colspan="${columns}"` : "";
891 // rowspan="0" runs to the end of its section.
892 if (rows !== 1) attributes += ` rowspan="${rows}"`;
893 return attributes;
895​
896function htmlTableCell(cell: Element, rtl: boolean): string {
897 const tag = cell.tagName === "TH" ? "th" : "td";
898 // An absent inline style reads as "", so fall back to the align attribute on any falsy value.
899 const align = (cell as HTMLElement).style?.textAlign || cell.getAttribute("align") || "";
900 // Header cells default to the start side like the chat; paste targets would center them.
901 const textAlign = htmlCellAlignment(align || (tag === "th" ? "start" : ""), rtl);
902 const style = `${tag === "th" ? HTML_HEADER_CELL_STYLE : HTML_CELL_STYLE}${textAlign ? `;text-align:${textAlign}` : ""}`;
903 // Bare text, no <p>: Word would drop its 8pt gap but switch to its web font.
904 return `<${tag} style="${style}"${htmlSpanAttributes(cell)}>${htmlCellContent(cell)}</${tag}>`;
906​
907function htmlTableSection(tag: string, rows: ReadonlyArray<Element>, rtl: boolean): string[] {
908 let hasCells = false;
909 const lines = rows.map((row) => {
910 const cells = [...row.children].filter(
911 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
912 );
913 const html = cells.map((cell) => htmlTableCell(cell, rtl)).join("");
914 hasCells ||= cells.length > 0;
915 return ` <tr>${html}</tr>`;
916 });
917 return hasCells ? [` <${tag}>`, ...lines, ` </${tag}>`] : [];
919​
920/**
921 * Inline-styled `<table>` markup without app chrome, so rich paste targets get a table.
922 * Sections, header cells, spans, line breaks, direction, and alignment follow the source.
923 * Cell content is text: inline formatting and link targets are not copied.
924 */
925export function serializeTableElementToHtml(table: Element): string {
926 const direction = table.getAttribute("dir");
927 const rtl =
928 direction === "rtl" ||
929 (direction !== "ltr" &&
930 table.ownerDocument?.defaultView?.getComputedStyle(table).direction === "rtl");
931 const lines: string[] = [];
932 let looseRows: Element[] = [];
933 const flushLooseRows = () => {
934 lines.push(...htmlTableSection("tbody", looseRows, rtl));
935 looseRows = [];
936 };
937 for (const child of table.children) {
938 if (child.tagName === "TR") {
939 looseRows.push(child);
940 continue;
941 }
942 if (!TABLE_SECTION_TAGS.has(child.tagName)) continue;
943 flushLooseRows();
944 const rows = [...child.children].filter((row) => row.tagName === "TR");
945 lines.push(...htmlTableSection(child.tagName.toLowerCase(), rows, rtl));
946 }
947 flushLooseRows();
948 const open = `<table dir="${rtl ? "rtl" : "ltr"}" style="${HTML_TABLE_STYLE}">`;
949 return lines.length > 0 ? [open, ...lines, "</table>"].join("\n") : "";
951​
952function mermaidSourceHtml(source: string) {
953 const pre = document.createElement("pre");
954 const code = document.createElement("code");
955 code.textContent = source.trim();
956 pre.appendChild(code);
957 return pre;
959​
960function mathSourceElement(wrapper: Element): Element {
961 const code = document.createElement("code");
962 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
963 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
964 const pre = document.createElement("pre");
965 pre.append(code);
966 return pre;
968​
969function sanitizedHtmlFrom(container: Element): string {
970 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
971 const source = diagram.getAttribute("data-markdown-copy");
972 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
973 }
974 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
975 wrapper.replaceWith(mathSourceElement(wrapper));
976 }
977 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
978 if (
979 node.classList.contains("chat-markdown-file-link") ||
980 node.closest(".chat-markdown-file-link")
981 ) {
982 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
983 node.remove();
984 }
985 continue;
986 }
987 node.remove();
988 }
989 return `<meta charset="utf-8">${container.innerHTML}`;
991​
992const TABLE_CONTAINERS = new Set(["TABLE", "THEAD", "TBODY", "TFOOT", "TR"]);
993​
994function isList(node: Node): node is HTMLOListElement | HTMLUListElement {
995 return node instanceof Element && (node.tagName === "OL" || node.tagName === "UL");
997​
998function enclosingWrappers(node: Node): Element[] {
999 if (isList(node)) return [node];
1000 if (!(node instanceof Element) || !TABLE_CONTAINERS.has(node.tagName)) return [];
1001 const wrappers: Element[] = [];
1002 for (let current: Element | null = node; current; current = current.parentElement) {
1003 if (!TABLE_CONTAINERS.has(current.tagName)) return [];
1004 wrappers.push(current);
1005 if (current.tagName === "TABLE") return wrappers;
1007 return [];
1009​
1010const hasTableContent = (element: Element): boolean =>
1011 Boolean(element.textContent?.trim()) ||
1012 element.querySelector("img, [data-markdown-copy], input") !== null;
1013​
1014// An endpoint can clone empty item or table wrappers at any nesting depth.
1015function emptyListBoundary(
1016 ancestor: Node,
1017 node: Node,
1018 offset: number,
1019 side: "start" | "end",
1020): Element | null {
1021 const next = (node: Node) => (side === "start" ? node.nextSibling : node.previousSibling);
1022 if (node instanceof Text && offset !== (side === "start" ? node.length : 0)) return null;
1023​
1024 let boundary: Element | null = null;
1025 let remaining = node.childNodes[side === "start" ? offset : offset - 1] ?? null;
1026 while (node !== ancestor && node.parentNode) {
1027 for (let sibling = remaining; sibling; sibling = next(sibling)) {
1028 if (sibling instanceof Text && !sibling.data.trim()) continue;
1029 if (
1030 sibling instanceof Element &&
1031 isSkippedElement(sibling) &&
1032 !sibling.hasAttribute("data-markdown-copy") &&
1033 !sibling.hasAttribute("data-markdown-details")
1034 ) {
1035 continue;
1037 return boundary;
1039 if (node instanceof Element && node.tagName === "LI" && isList(node.parentNode)) {
1040 boundary = node;
1041 } else if (boundary && isList(node)) {
1042 boundary = node;
1043 } else if (
1044 node instanceof Element &&
1045 ((node.tagName === "TD" || node.tagName === "TH") && node.parentElement?.tagName === "TR"
1046 ? hasTableContent(node)
1047 : TABLE_CONTAINERS.has(node.tagName) && (boundary !== null || hasTableContent(node)))
1048 ) {
1049 boundary = node;
1051 remaining = next(node);
1052 node = node.parentNode;
1054 return boundary;
1056​
1057/** Clones the selection and restores enclosing list markers and table wrappers. */
1058function cloneWithListMarkers(range: Range, container: Element): void {
1059 const originalAncestor = range.commonAncestorContainer;
1060 const start = emptyListBoundary(
1061 originalAncestor,
1062 range.startContainer,
1063 range.startOffset,
1064 "start",
1065 );
1066 const end = emptyListBoundary(originalAncestor, range.endContainer, range.endOffset, "end");
1067 if (start || end) {
1068 range = range.cloneRange();
1069 if (start) range.setStartAfter(start);
1070 if (end) range.setEndBefore(end);
1072 const ancestor = range.commonAncestorContainer;
1073 const wrappers = enclosingWrappers(ancestor);
1074 container.appendChild(range.cloneContents());
1075 // Items or table rows copied within one container clone without their enclosing wrapper tags.
1076 for (const wrapper of wrappers) {
1077 const copy = wrapper.cloneNode(false) as Element;
1078 copy.append(...container.childNodes);
1079 container.replaceChildren(copy);
1081 // The start's ancestors below the cloned top clone as the fragment's first-child chain.
1082 const top = wrappers.at(-1)?.parentNode ?? ancestor;
1083 const chain: Node[] = [];
1084 for (let node: Node | null = range.startContainer; node && node !== top; node = node.parentNode) {
1085 chain.unshift(node);
1087 let clone: Node | null = container;
1088 // A row copied from mid-row lacks its earlier cells; padding waits so the chain walk stays intact.
1089 const rowPadding: Array<[Element, Element]> = [];
1090 for (const [depth, source] of chain.entries()) {
1091 clone = clone?.firstChild ?? null;
1092 if (!(clone instanceof Element) || !(source instanceof Element)) continue;
1093 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
1094 if (source.tagName === "TR" && firstCopied instanceof Element) {
1095 rowPadding.push([clone, firstCopied]);
1097 if (source.tagName === "LI" && clone.tagName === "LI") {
1098 const checkbox = source.querySelector(LIST_ITEM_CHECKBOX);
1099 if (checkbox && !clone.querySelector(LIST_ITEM_CHECKBOX)) {
1100 // Keep the first-child chain intact for nested items.
1101 clone.append(checkbox.cloneNode(false));
1103 continue;
1105 if (source.tagName !== "OL" || !firstCopied) continue;
1106 const shown = numberedListItems(source).find(
1107 ({ item }) =>
1108 item === firstCopied ||
1109 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
1110 );
1111 const cloned = numberedListItems(clone)[0];
1112 if (shown && cloned && shown.number !== cloned.number) {
1113 clone.setAttribute("start", String(shown.number));
1116 for (const [row, firstCell] of rowPadding) {
1117 const table = row.closest("table");
1118 if (!table || table.querySelectorAll(":scope > tr, :scope > * > tr").length < 2) continue;
1119 for (let cell = firstCell.previousElementSibling; cell; cell = cell.previousElementSibling) {
1120 row.prepend(cell.cloneNode(false));
1123 if (wrappers.at(-1)?.tagName === "TABLE") {
1124 const cells = container.querySelectorAll("th, td");
1125 if (cells.length === 1) container.replaceChildren(...cells[0]!.childNodes);
1128​
1129export function chatMarkdownClipboardPayload(
1130 selection: Selection,
1131): MarkdownClipboardPayload | null {
1132 const texts: string[] = [];
1133 const htmls: string[] = [];
1134 for (let index = 0; index < selection.rangeCount; index += 1) {
1135 const range = selection.getRangeAt(index);
1136 if (range.collapsed) continue;
1137 const container = document.createElement("div");
1138 cloneWithListMarkers(range, container);
1139 // The indentation typed at a line start only shows; pasted, it would turn lines into code.
1140 for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
1141 indentation.remove();
1143 const ancestor = range.commonAncestorContainer;
1144 const ancestorElement =
1145 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
1146 const diagramSource = ancestorElement
1147 ?.closest("[data-markdown-mermaid]")
1148 ?.getAttribute("data-markdown-copy");
1149 if (diagramSource != null) {
1150 const text = diagramSource.trim();
1151 if (!text) continue;
1152 texts.push(text);
1153 container.replaceChildren(mermaidSourceHtml(diagramSource));
1154 htmls.push(sanitizedHtmlFrom(container));
1155 continue;
1157 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
1158 const math = mathWrapperOf(ancestorElement);
1159 if (math) {
1160 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
1161 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
1162 continue;
1164 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
1165 if (ancestorElement?.closest("pre, code")) {
1166 const text = range.toString();
1167 if (text) {
1168 texts.push(text);
1169 htmls.push(sanitizedHtmlFrom(container));
1171 continue;
1173 // A range spanning exactly one callout's text clones its contents but not the callout.
1174 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
1175 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
1176 const wrapper = callout.cloneNode(false) as Element;
1177 wrapper.append(...container.childNodes);
1178 container.replaceChildren(wrapper);
1180 const text = serializeRenderedMarkdownFragment(container);
1181 if (!text) continue;
1182 texts.push(text);
1183 htmls.push(sanitizedHtmlFrom(container));
1185 if (texts.length === 0) return null;
1186 return { text: texts.join("\n\n"), html: htmls.join("") };