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

markdown-clipboard.ts

1,179 lines46.5 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 out += serializeNode(child, inTableCell);
416 }
417 return out;
419​
420function serializeNode(node: Node, inTableCell = false): string {
421 if (node.nodeType === Node.TEXT_NODE) {
422 let text = node.textContent ?? "";
423 // A <br> already wrote the line ending that follows it.
424 if (node.previousSibling?.nodeName === "BR") text = text.replace(/^\n/, "");
425 if (text.includes("\n") && text.trim().length === 0) return "\n";
426 return escapeTablePipes(escapeProse(text), inTableCell);
427 }
428 if (node.nodeType !== Node.ELEMENT_NODE) return "";
429 const element = node as Element;
430 if (element.hasAttribute("data-markdown-details")) {
431 return escapeTablePipes(serializeDetails(element), inTableCell);
432 }
433 const markdownCopy = element.getAttribute("data-markdown-copy");
434 if (markdownCopy !== null) {
435 // A diagram copies as its fenced source, which is code too.
436 if (element.hasAttribute("data-markdown-mermaid")) {
437 return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
438 }
439 const copy = element.hasAttribute("data-markdown-math")
440 ? markdownCopy
441 : escapeTablePipes(markdownCopy, inTableCell);
442 return protectVerbatim(copy);
443 }
444 if (isSkippedElement(element)) return "";
445 const alert = element.getAttribute(ALERT_ATTRIBUTE);
446 if (alert === "insight") return serializeInsight(element, inTableCell);
447 if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`);
448​
449 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
450 if (headingLevel) {
451 const content = serializeChildren(element, inTableCell)
452 .trim()
453 .replace(/(^|[ \t])(#+)$/, "$1\\$2");
454 return `${BLOCK_GUARD}${"#".repeat(Number(headingLevel))} ${content}\n\n`;
455 }
456​
457 switch (element.tagName) {
458 case "BR":
459 return "\n";
460 case "HR":
461 return `${BLOCK_GUARD}---\n\n`;
462 case "P":
463 return `${serializeChildren(element, inTableCell).trim()}\n\n`;
464 case "PRE":
465 return escapeTablePipes(serializeCodeBlock(element), inTableCell);
466 case "CODE": {
467 const content = escapeTablePipes(element.textContent ?? "", inTableCell);
468 const code = isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
469 return protectVerbatim(code);
470 }
471 case "STRONG":
472 case "B":
473 return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
474 case "EM":
475 case "I":
476 return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
477 case "DEL":
478 case "S":
479 return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
480 case "A":
481 return serializeAnchor(element, inTableCell);
482 case "IMG": {
483 const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
484 const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
485 return alt && src ? `![${alt}](${src})` : "";
486 }
487 case "UL":
488 return serializeList(element, false, inTableCell);
489 case "OL":
490 return serializeList(element, true, inTableCell);
491 case "BLOCKQUOTE":
492 return serializeBlockquote(element, inTableCell);
493 case "TABLE":
494 return escapeTablePipes(serializeTable(element), inTableCell);
495 case "DIV":
496 case "SECTION":
497 case "ARTICLE": {
498 const content = serializeChildren(element, inTableCell);
499 return content && !content.endsWith("\n") ? `${content}\n` : content;
500 }
501 default:
502 return serializeChildren(element, inTableCell);
503 }
505​
506interface SoleCodeBlockScan {
507 pre: Element | null;
508 other: boolean;
510​
511function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
512 for (const child of node.childNodes) {
513 if (scan.other) return;
514 if (child.nodeType === Node.TEXT_NODE) {
515 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
516 continue;
517 }
518 if (child.nodeType !== Node.ELEMENT_NODE) continue;
519 const element = child as Element;
520 // Explicit markdown still counts on skipped tags such as file-chip buttons.
521 if (element.hasAttribute("data-markdown-details")) {
522 scan.other = true;
523 continue;
524 }
525 const markdownCopy = element.getAttribute("data-markdown-copy");
526 if (markdownCopy !== null) {
527 if (markdownCopy.trim().length > 0) scan.other = true;
528 continue;
529 }
530 if (isSkippedElement(element)) continue;
531 if (element.tagName === "PRE") {
532 if (scan.pre) scan.other = true;
533 else scan.pre = element;
534 continue;
535 }
536 if (element.tagName === "IMG" || element.tagName === "HR") {
537 scan.other = true;
538 continue;
539 }
540 if (element.tagName === "LI") {
541 const preBeforeItem = scan.pre;
542 scanForSoleCodeBlock(element, scan);
543 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
544 continue;
545 }
546 scanForSoleCodeBlock(element, scan);
547 }
549​
550// Selecting a block's final newline pulls in its closing pre even when only code was highlighted.
551function soleCodeBlock(container: Node): Element | null {
552 const scan: SoleCodeBlockScan = { pre: null, other: false };
553 scanForSoleCodeBlock(container, scan);
554 return scan.other ? null : scan.pre;
556​
557function tidyMarkdown(markdown: string): string {
558 // Odd parts are code, kept verbatim, so a selection that starts or ends inside
559 // code keeps that code's leading and trailing whitespace.
560 const parts = escapeBlockStarts(markdown).split(CODE_BOUNDARY);
561 const last = parts.length - 1;
562 return parts
563 .map((part, index) => {
564 if (index % 2 === 1) return part;
565 let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
566 if (index === 0) prose = prose.trimStart();
567 if (index === last) prose = prose.trimEnd();
568 return prose;
569 })
570 .join("");
572​
573export function serializeRenderedMarkdownFragment(container: Node): string {
574 const codeBlock = soleCodeBlock(container);
575 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
576 return tidyMarkdown(serializeChildren(container));
578​
579export function serializeTableElementToMarkdown(table: Element): string {
580 // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
581 return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
583​
584// The wrapper wordsHast puts on every formula it renders. The sanitizer drops
585// the attribute from authored HTML.
586const MATH_SELECTOR = "[data-markdown-math]";
587​
588export function mathWrapperOf(element: Element | null): Element | null {
589 return element?.closest(MATH_SELECTOR) ?? null;
591​
592/** A cell's text on one line, with each formula as its TeX. */
593function csvCellText(cell: Element): string {
594 const parts: string[] = [];
595 collectHtmlCellText(cell, parts, false);
596 return parts.join("").replace(/[\u0001\u0002]+/g, " ");
598​
599function csvCell(value: string): string {
600 const normalized = value.replace(/\s+/g, " ").trim();
601 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
603​
604export function serializeTableElementToCsv(table: Element): string {
605 // Spanned slots stay as empty fields, so values after a span stay under their headers.
606 return tableGrid(table)
607 .map((row) => Array.from(row, (slot) => csvCell(slot?.text ?? "")).join(","))
608 .join("\n");
610​
611// CJK, emoji, flags and keycaps count as two columns: close enough to East Asian Width for chat fonts.
612// The ranges skip nonspacing marks that would make a narrow base look wide.
613// Symbols such as ™, © and ↔ show as text, one column, unless a variation selector makes them emoji.
614const WIDE_GRAPHEME =
615 /\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;
616let graphemes: Intl.Segmenter | undefined;
617​
618function monospaceWidth(text: string): number {
619 graphemes ??= new Intl.Segmenter(undefined, { granularity: "grapheme" });
620 let width = 0;
621 for (const { segment } of graphemes.segment(text)) width += WIDE_GRAPHEME.test(segment) ? 2 : 1;
622 return width;
624​
625function padToWidth(text: string, width: number, align: string): string {
626 const gap = width - monospaceWidth(text);
627 if (align === "right") return " ".repeat(gap) + text;
628 if (align === "center") {
629 const left = Math.floor(gap / 2);
630 return " ".repeat(left) + text + " ".repeat(gap - left);
631 }
632 return text + " ".repeat(gap);
634​
635/** Each rendered row's cells by column; a spanned slot repeats its cell with empty text. */
636function tableGrid(table: Element): Array<Array<{ text: string; cell: Element }>> {
637 // Lay cells onto the grid the table renders, so values after a span stay under their headers.
638 // As in the HTML table model, a row group bounds every rowspan and an empty row still takes a row.
639 // Row groups in document order, with footers last as rendered; consecutive rows directly in
640 // the table form one group.
641 const groups: Element[][] = [];
642 const footers: Element[][] = [];
643 let looseRows: Element[] | undefined;
644 for (const child of table.children) {
645 if (child.tagName === "TR") {
646 if (!looseRows) groups.push((looseRows = []));
647 looseRows.push(child);
648 continue;
649 }
650 looseRows = undefined;
651 if (TABLE_SECTION_TAGS.has(child.tagName)) {
652 const rows = [...child.children].filter((row) => row.tagName === "TR");
653 (child.tagName === "TFOOT" ? footers : groups).push(rows);
654 }
655 }
656 groups.push(...footers);
657 const grid: Array<{ slots: Array<{ text: string; cell: Element }>; hasCells: boolean }> = [];
658 for (const groupRows of groups) {
659 const start = grid.length;
660 for (const _ of groupRows) grid.push({ slots: [], hasCells: false });
661 groupRows.forEach((row, offset) => {
662 const gridRow = grid[start + offset]!;
663 let column = 0;
664 for (const cell of row.children) {
665 if (cell.tagName !== "TH" && cell.tagName !== "TD") continue;
666 gridRow.hasCells = true;
667 while (gridRow.slots[column]) column++;
668 const text = csvCellText(cell).replace(/\s+/g, " ").trim();
669 const colSpan = Math.max(1, tableCellSpan(cell, "colSpan", "colspan"));
670 const remaining = groupRows.length - offset;
671 // rowspan="0" runs to the end of its row group.
672 const rowSpan = Math.min(tableCellSpan(cell, "rowSpan", "rowspan") || remaining, remaining);
673 for (let down = 0; down < rowSpan; down++) {
674 for (let across = 0; across < colSpan; across++) {
675 grid[start + offset + down]!.slots[column + across] = {
676 text: down === 0 && across === 0 ? text : "",
677 cell,
678 };
679 }
680 }
681 column += colSpan;
682 }
683 });
684 }
685 return grid.filter((gridRow) => gridRow.hasCells).map((gridRow) => gridRow.slots);
687​
688/**
689 * Space-aligned columns for chat apps. The plain text is a code fence, which WhatsApp and
690 * Slack show monospaced; rich targets (Teams, Slack) paste the HTML flavor as a code block.
691 */
692export function serializeTableElementForChat(table: Element): MarkdownClipboardPayload {
693 const rows = tableGrid(table);
694 if (rows.length === 0) return { text: "", html: "" };
695 const columns = Math.max(...rows.map((gridRow) => gridRow.length));
696 const texts = rows.map((gridRow) =>
697 Array.from({ length: columns }, (_, column) => gridRow[column]?.text ?? ""),
698 );
699 const widths = Array.from({ length: columns }, (_, column) =>
700 Math.max(1, ...texts.map((cells) => monospaceWidth(cells[column] ?? ""))),
701 );
702 const aligns = widths.map((_, column) => {
703 const header = rows[0]?.[column]?.cell as HTMLElement | undefined;
704 return header?.style?.textAlign || header?.getAttribute("align") || "";
705 });
706 const line = (cells: string[]) =>
707 widths
708 .map((width, column) => padToWidth(cells[column] ?? "", width, aligns[column] ?? ""))
709 .join(" ")
710 .trimEnd();
711 const [header = [], ...body] = texts;
712 const lines = [
713 line(header),
714 widths.map((width) => "-".repeat(width)).join(" "),
715 ...body.map(line),
716 ];
717 const aligned = lines.join("\n");
718 const fence = codeFenceFor(aligned);
719 return {
720 text: `${fence}\n${aligned}\n${fence}`,
721 html: `<meta charset="utf-8"><pre>${escapeHtml(aligned)}</pre>`,
722 };
724​
725const TABLE_SECTION_TAGS = new Set(["THEAD", "TBODY", "TFOOT"]);
726// Elements that start a new line inside a copied cell.
727const HTML_CELL_BLOCK_TAGS = new Set([
728 "ARTICLE",
729 "BLOCKQUOTE",
730 "DETAILS",
731 "DIV",
732 "H1",
733 "H2",
734 "H3",
735 "H4",
736 "H5",
737 "H6",
738 "LI",
739 "OL",
740 "P",
741 "PRE",
742 "SECTION",
743 "SUMMARY",
744 "TABLE",
745 "TR",
746 "UL",
747]);
748​
749// Inline and theme-independent: mail clients and editors drop stylesheets, and a
750// copy from the dark theme must still read on a white page. Header cells set their
751// own text color so the light band stays readable in a dark paste target.
752const HTML_TABLE_STYLE = "border-collapse:collapse";
753const HTML_CELL_STYLE = "border:1px solid #d0d7de;padding:6px 12px;vertical-align:top";
754const HTML_HEADER_CELL_STYLE = `${HTML_CELL_STYLE};background-color:#f6f8fa;color:#1f2328;font-weight:600`;
755​
756function escapeHtml(value: string): string {
757 return value
758 .replaceAll("&", "&amp;")
759 .replaceAll("<", "&lt;")
760 .replaceAll(">", "&gt;")
761 .replaceAll('"', "&quot;");
763​
764// Markers in collected cell text: a block edge is a soft line boundary, a break is a <br>.
765const CELL_BLOCK_EDGE = "\u0001";
766const CELL_LINE_BREAK = "\u0002";
767// HTML's collapsible whitespace; a nonbreaking space is content.
768const COLLAPSIBLE_WHITESPACE = /[ \t\n\r\f]+/g;
769​
770/** Preformatted text keeps its lines and spacing as breaks and nonbreaking spaces. */
771function preformattedCellText(text: string): string {
772 return text
773 .replace(/\r\n?|\n/g, CELL_LINE_BREAK)
774 .replaceAll("\t", "\u00a0".repeat(4))
775 .replaceAll(" ", "\u00a0");
777​
778/** Collects a cell's text with block edges and breaks marked, and each formula as its TeX. */
779function collectHtmlCellText(node: Node, parts: string[], preformatted: boolean): void {
780 for (const child of node.childNodes) {
781 if (child.nodeType === Node.TEXT_NODE) {
782 const text = child.textContent ?? "";
783 parts.push(preformatted ? preformattedCellText(text) : text);
784 continue;
785 }
786 if (child.nodeType !== Node.ELEMENT_NODE) continue;
787 const element = child as Element;
788 if (isSkippedElement(element) && !element.hasAttribute("data-markdown-copy")) continue;
789 if (element.hasAttribute("data-markdown-math")) {
790 parts.push(element.getAttribute("data-markdown-copy")?.trim() ?? "");
791 continue;
792 }
793 if (element.tagName === "BR") {
794 parts.push(CELL_LINE_BREAK);
795 continue;
796 }
797 if (element.tagName === "PRE") {
798 const code: string[] = [];
799 collectHtmlCellText(element, code, true);
800 // A code block's closing newline ends the block, not a blank line.
801 parts.push(CELL_BLOCK_EDGE, code.join("").replace(/\u0002$/, ""), CELL_BLOCK_EDGE);
802 continue;
803 }
804 // Cells of a nested table stay apart on their row's line.
805 const separator = element.tagName === "TD" || element.tagName === "TH" ? " " : "";
806 const boundary = HTML_CELL_BLOCK_TAGS.has(element.tagName) ? CELL_BLOCK_EDGE : separator;
807 parts.push(boundary);
808 collectHtmlCellText(element, parts, preformatted);
809 parts.push(boundary);
810 }
812​
813/**
814 * Every explicit break stays a <br>, including repeated and edge ones. Block edges
815 * become one break between content, and none where a break already ends the line.
816 */
817function htmlCellContent(cell: Element): string {
818 const parts: string[] = [];
819 collectHtmlCellText(cell, parts, false);
820 const tokens = parts
821 .join("")
822 .replace(COLLAPSIBLE_WHITESPACE, " ")
823 .split(/([\u0001\u0002])/);
824 let html = "";
825 let atLineStart = true;
826 let pendingBlockEdge = false;
827 for (const token of tokens) {
828 if (token === CELL_LINE_BREAK) {
829 html = `${html.replace(/ +$/, "")}<br>`;
830 atLineStart = true;
831 pendingBlockEdge = false;
832 } else if (token === CELL_BLOCK_EDGE) {
833 pendingBlockEdge = true;
834 } else {
835 const text = atLineStart || pendingBlockEdge ? token.replace(/^ +/, "") : token;
836 if (!text) continue;
837 if (pendingBlockEdge && !atLineStart) html = `${html.replace(/ +$/, "")}<br>`;
838 html += escapeHtml(text).replaceAll("\u00a0", "&nbsp;");
839 atLineStart = false;
840 pendingBlockEdge = false;
841 }
842 }
843 return html.replace(/ +$/, "");
845​
846/** Physical alignment for a paste target; logical values follow the table direction. */
847function htmlCellAlignment(align: string, rtl: boolean): string {
848 switch (align) {
849 case "left":
850 case "center":
851 case "right":
852 case "justify":
853 return align;
854 case "start":
855 return rtl ? "right" : "left";
856 case "end":
857 return rtl ? "left" : "right";
858 default:
859 return "";
860 }
862​
863/** HTML's non-negative integer parsing: leading digits count, anything invalid is 1. */
864function parseTableSpan(value: string | null): number {
865 const span = Number.parseInt(value ?? "", 10);
866 return Number.isNaN(span) || span < 0 ? 1 : span;
868​
869// The DOM normalizes spans; the attribute fallback covers non-DOM callers.
870function tableCellSpan(
871 cell: Element,
872 property: "colSpan" | "rowSpan",
873 attribute: "colspan" | "rowspan",
874): number {
875 const span = (cell as Partial<HTMLTableCellElement>)[property];
876 return typeof span === "number" ? span : parseTableSpan(cell.getAttribute(attribute));
878​
879function htmlSpanAttributes(cell: Element): string {
880 const columns = tableCellSpan(cell, "colSpan", "colspan");
881 const rows = tableCellSpan(cell, "rowSpan", "rowspan");
882 let attributes = columns > 1 ? ` colspan="${columns}"` : "";
883 // rowspan="0" runs to the end of its section.
884 if (rows !== 1) attributes += ` rowspan="${rows}"`;
885 return attributes;
887​
888function htmlTableCell(cell: Element, rtl: boolean): string {
889 const tag = cell.tagName === "TH" ? "th" : "td";
890 // An absent inline style reads as "", so fall back to the align attribute on any falsy value.
891 const align = (cell as HTMLElement).style?.textAlign || cell.getAttribute("align") || "";
892 // Header cells default to the start side like the chat; paste targets would center them.
893 const textAlign = htmlCellAlignment(align || (tag === "th" ? "start" : ""), rtl);
894 const style = `${tag === "th" ? HTML_HEADER_CELL_STYLE : HTML_CELL_STYLE}${textAlign ? `;text-align:${textAlign}` : ""}`;
895 // Bare text, no <p>: Word would drop its 8pt gap but switch to its web font.
896 return `<${tag} style="${style}"${htmlSpanAttributes(cell)}>${htmlCellContent(cell)}</${tag}>`;
898​
899function htmlTableSection(tag: string, rows: ReadonlyArray<Element>, rtl: boolean): string[] {
900 let hasCells = false;
901 const lines = rows.map((row) => {
902 const cells = [...row.children].filter(
903 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
904 );
905 const html = cells.map((cell) => htmlTableCell(cell, rtl)).join("");
906 hasCells ||= cells.length > 0;
907 return ` <tr>${html}</tr>`;
908 });
909 return hasCells ? [` <${tag}>`, ...lines, ` </${tag}>`] : [];
911​
912/**
913 * Inline-styled `<table>` markup without app chrome, so rich paste targets get a table.
914 * Sections, header cells, spans, line breaks, direction, and alignment follow the source.
915 * Cell content is text: inline formatting and link targets are not copied.
916 */
917export function serializeTableElementToHtml(table: Element): string {
918 const direction = table.getAttribute("dir");
919 const rtl =
920 direction === "rtl" ||
921 (direction !== "ltr" &&
922 table.ownerDocument?.defaultView?.getComputedStyle(table).direction === "rtl");
923 const lines: string[] = [];
924 let looseRows: Element[] = [];
925 const flushLooseRows = () => {
926 lines.push(...htmlTableSection("tbody", looseRows, rtl));
927 looseRows = [];
928 };
929 for (const child of table.children) {
930 if (child.tagName === "TR") {
931 looseRows.push(child);
932 continue;
933 }
934 if (!TABLE_SECTION_TAGS.has(child.tagName)) continue;
935 flushLooseRows();
936 const rows = [...child.children].filter((row) => row.tagName === "TR");
937 lines.push(...htmlTableSection(child.tagName.toLowerCase(), rows, rtl));
938 }
939 flushLooseRows();
940 const open = `<table dir="${rtl ? "rtl" : "ltr"}" style="${HTML_TABLE_STYLE}">`;
941 return lines.length > 0 ? [open, ...lines, "</table>"].join("\n") : "";
943​
944function mermaidSourceHtml(source: string) {
945 const pre = document.createElement("pre");
946 const code = document.createElement("code");
947 code.textContent = source.trim();
948 pre.appendChild(code);
949 return pre;
951​
952function mathSourceElement(wrapper: Element): Element {
953 const code = document.createElement("code");
954 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
955 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
956 const pre = document.createElement("pre");
957 pre.append(code);
958 return pre;
960​
961function sanitizedHtmlFrom(container: Element): string {
962 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
963 const source = diagram.getAttribute("data-markdown-copy");
964 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
965 }
966 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
967 wrapper.replaceWith(mathSourceElement(wrapper));
968 }
969 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
970 if (
971 node.classList.contains("chat-markdown-file-link") ||
972 node.closest(".chat-markdown-file-link")
973 ) {
974 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
975 node.remove();
976 }
977 continue;
978 }
979 node.remove();
980 }
981 return `<meta charset="utf-8">${container.innerHTML}`;
983​
984const TABLE_CONTAINERS = new Set(["TABLE", "THEAD", "TBODY", "TFOOT", "TR"]);
985​
986function isList(node: Node): node is HTMLOListElement | HTMLUListElement {
987 return node instanceof Element && (node.tagName === "OL" || node.tagName === "UL");
989​
990function enclosingWrappers(node: Node): Element[] {
991 if (isList(node)) return [node];
992 if (!(node instanceof Element) || !TABLE_CONTAINERS.has(node.tagName)) return [];
993 const wrappers: Element[] = [];
994 for (let current: Element | null = node; current; current = current.parentElement) {
995 if (!TABLE_CONTAINERS.has(current.tagName)) return [];
996 wrappers.push(current);
997 if (current.tagName === "TABLE") return wrappers;
998 }
999 return [];
1001​
1002const hasTableContent = (element: Element): boolean =>
1003 Boolean(element.textContent?.trim()) ||
1004 element.querySelector("img, [data-markdown-copy], input") !== null;
1005​
1006// An endpoint can clone empty item or table wrappers at any nesting depth.
1007function emptyListBoundary(
1008 ancestor: Node,
1009 node: Node,
1010 offset: number,
1011 side: "start" | "end",
1012): Element | null {
1013 const next = (node: Node) => (side === "start" ? node.nextSibling : node.previousSibling);
1014 if (node instanceof Text && offset !== (side === "start" ? node.length : 0)) return null;
1015​
1016 let boundary: Element | null = null;
1017 let remaining = node.childNodes[side === "start" ? offset : offset - 1] ?? null;
1018 while (node !== ancestor && node.parentNode) {
1019 for (let sibling = remaining; sibling; sibling = next(sibling)) {
1020 if (sibling instanceof Text && !sibling.data.trim()) continue;
1021 if (
1022 sibling instanceof Element &&
1023 isSkippedElement(sibling) &&
1024 !sibling.hasAttribute("data-markdown-copy") &&
1025 !sibling.hasAttribute("data-markdown-details")
1026 ) {
1027 continue;
1029 return boundary;
1031 if (node instanceof Element && node.tagName === "LI" && isList(node.parentNode)) {
1032 boundary = node;
1033 } else if (boundary && isList(node)) {
1034 boundary = node;
1035 } else if (
1036 node instanceof Element &&
1037 ((node.tagName === "TD" || node.tagName === "TH") && node.parentElement?.tagName === "TR"
1038 ? hasTableContent(node)
1039 : TABLE_CONTAINERS.has(node.tagName) && (boundary !== null || hasTableContent(node)))
1040 ) {
1041 boundary = node;
1043 remaining = next(node);
1044 node = node.parentNode;
1046 return boundary;
1048​
1049/** Clones the selection and restores enclosing list markers and table wrappers. */
1050function cloneWithListMarkers(range: Range, container: Element): void {
1051 const originalAncestor = range.commonAncestorContainer;
1052 const start = emptyListBoundary(
1053 originalAncestor,
1054 range.startContainer,
1055 range.startOffset,
1056 "start",
1057 );
1058 const end = emptyListBoundary(originalAncestor, range.endContainer, range.endOffset, "end");
1059 if (start || end) {
1060 range = range.cloneRange();
1061 if (start) range.setStartAfter(start);
1062 if (end) range.setEndBefore(end);
1064 const ancestor = range.commonAncestorContainer;
1065 const wrappers = enclosingWrappers(ancestor);
1066 container.appendChild(range.cloneContents());
1067 // Items or table rows copied within one container clone without their enclosing wrapper tags.
1068 for (const wrapper of wrappers) {
1069 const copy = wrapper.cloneNode(false) as Element;
1070 copy.append(...container.childNodes);
1071 container.replaceChildren(copy);
1073 // The start's ancestors below the cloned top clone as the fragment's first-child chain.
1074 const top = wrappers.at(-1)?.parentNode ?? ancestor;
1075 const chain: Node[] = [];
1076 for (let node: Node | null = range.startContainer; node && node !== top; node = node.parentNode) {
1077 chain.unshift(node);
1079 let clone: Node | null = container;
1080 // A row copied from mid-row lacks its earlier cells; padding waits so the chain walk stays intact.
1081 const rowPadding: Array<[Element, Element]> = [];
1082 for (const [depth, source] of chain.entries()) {
1083 clone = clone?.firstChild ?? null;
1084 if (!(clone instanceof Element) || !(source instanceof Element)) continue;
1085 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
1086 if (source.tagName === "TR" && firstCopied instanceof Element) {
1087 rowPadding.push([clone, firstCopied]);
1089 if (source.tagName === "LI" && clone.tagName === "LI") {
1090 const checkbox = source.querySelector(LIST_ITEM_CHECKBOX);
1091 if (checkbox && !clone.querySelector(LIST_ITEM_CHECKBOX)) {
1092 // Keep the first-child chain intact for nested items.
1093 clone.append(checkbox.cloneNode(false));
1095 continue;
1097 if (source.tagName !== "OL" || !firstCopied) continue;
1098 const shown = numberedListItems(source).find(
1099 ({ item }) =>
1100 item === firstCopied ||
1101 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
1102 );
1103 const cloned = numberedListItems(clone)[0];
1104 if (shown && cloned && shown.number !== cloned.number) {
1105 clone.setAttribute("start", String(shown.number));
1108 for (const [row, firstCell] of rowPadding) {
1109 const table = row.closest("table");
1110 if (!table || table.querySelectorAll(":scope > tr, :scope > * > tr").length < 2) continue;
1111 for (let cell = firstCell.previousElementSibling; cell; cell = cell.previousElementSibling) {
1112 row.prepend(cell.cloneNode(false));
1115 if (wrappers.at(-1)?.tagName === "TABLE") {
1116 const cells = container.querySelectorAll("th, td");
1117 if (cells.length === 1) container.replaceChildren(...cells[0]!.childNodes);
1120​
1121export function chatMarkdownClipboardPayload(
1122 selection: Selection,
1123): MarkdownClipboardPayload | null {
1124 const texts: string[] = [];
1125 const htmls: string[] = [];
1126 for (let index = 0; index < selection.rangeCount; index += 1) {
1127 const range = selection.getRangeAt(index);
1128 if (range.collapsed) continue;
1129 const container = document.createElement("div");
1130 cloneWithListMarkers(range, container);
1131 // The indentation typed at a line start only shows; pasted, it would turn lines into code.
1132 for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
1133 indentation.remove();
1135 const ancestor = range.commonAncestorContainer;
1136 const ancestorElement =
1137 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
1138 const diagramSource = ancestorElement
1139 ?.closest("[data-markdown-mermaid]")
1140 ?.getAttribute("data-markdown-copy");
1141 if (diagramSource != null) {
1142 const text = diagramSource.trim();
1143 if (!text) continue;
1144 texts.push(text);
1145 container.replaceChildren(mermaidSourceHtml(diagramSource));
1146 htmls.push(sanitizedHtmlFrom(container));
1147 continue;
1149 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
1150 const math = mathWrapperOf(ancestorElement);
1151 if (math) {
1152 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
1153 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
1154 continue;
1156 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
1157 if (ancestorElement?.closest("pre, code")) {
1158 const text = range.toString();
1159 if (text) {
1160 texts.push(text);
1161 htmls.push(sanitizedHtmlFrom(container));
1163 continue;
1165 // A range spanning exactly one callout's text clones its contents but not the callout.
1166 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
1167 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
1168 const wrapper = callout.cloneNode(false) as Element;
1169 wrapper.append(...container.childNodes);
1170 container.replaceChildren(wrapper);
1172 const text = serializeRenderedMarkdownFragment(container);
1173 if (!text) continue;
1174 texts.push(text);
1175 htmls.push(sanitizedHtmlFrom(container));
1177 if (texts.length === 0) return null;
1178 return { text: texts.join("\n\n"), html: htmls.join("") };