Open History to see the last commit
1import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths";
2
3const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
4const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
5const SANITIZED_HTML_SELECTOR = [
6 "button",
7 "input",
8 "script",
9 "style",
10 "svg",
11 '[aria-hidden="true"]',
12 ...SKIPPED_CLASS_NAMES.map((className) => `.${className}`),
13].join(", ");
14
15const ALERT_ATTRIBUTE = "data-markdown-alert";
16const ALERT_LABEL = "data-markdown-alert-label";
17
18export interface MarkdownClipboardPayload {
19 text: string;
20 html: string;
21}
22
23function isSkippedElement(element: Element): boolean {
24 if (SKIPPED_TAGS.has(element.tagName) || element.localName === "svg") return true;
25 if (element.getAttribute("aria-hidden") === "true") return true;
26 return SKIPPED_CLASS_NAMES.some((className) => element.classList.contains(className));
27}
28
29function wrapInlineMarker(content: string, marker: string): string {
30 const match = /^(\s*)([\s\S]*?)(\s*)$/.exec(content);
31 const core = match?.[2] ?? "";
32 if (!core) return content;
33 return `${match?.[1] ?? ""}${marker}${core}${marker}${match?.[3] ?? ""}`;
34}
35
36// Highlighter spans or newlines identify block code even when its pre wrapper was not copied.
37function isBlockCodeElement(element: Element, content: string): boolean {
38 if (content.includes("\n")) return true;
39 for (const child of element.childNodes) {
40 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).classList.contains("line")) {
41 return true;
42 }
43 }
44 return false;
45}
46
47function wrapInlineCode(code: string): string {
48 const longestRun = [...(code.match(/`+/g) ?? [])].reduce(
49 (max, run) => Math.max(max, run.length),
50 0,
51 );
52 const fence = "`".repeat(Math.max(1, longestRun + (longestRun > 0 ? 1 : 0)));
53 // CommonMark strips one edge space from content that has both and isn't all spaces.
54 const spaceEdges = code.startsWith(" ") && code.endsWith(" ") && /[^ ]/.test(code);
55 const pad = spaceEdges || code.startsWith("`") || code.endsWith("`") ? " " : "";
56 return `${fence}${pad}${code}${pad}${fence}`;
57}
58
59function codeFenceFor(code: string): string {
60 const longestRun = [...(code.match(/`{3,}/g) ?? [])].reduce(
61 (max, run) => Math.max(max, run.length),
62 0,
63 );
64 return "`".repeat(Math.max(3, longestRun + 1));
65}
66
67export function serializeCodeBlockToMarkdown(source: string, language: string | null): string {
68 const code = source.replace(/\n$/, "");
69 const fence = codeFenceFor(code);
70 return `${fence}${language ?? ""}\n${code}\n${fence}\n\n`;
71}
72
73// Brackets copied code so tidyMarkdown leaves its whitespace alone. Code is
74// copied as shown, without fences; DOM text from rendered markdown carries no NUL.
75const CODE_BOUNDARY = "\u0000";
76
77function verbatimBlock(code: string): string {
78 return `${CODE_BOUNDARY}${code}${CODE_BOUNDARY}\n\n`;
79}
80
81// Odd parts are code and keep their markers, so outer passes still skip them.
82function outsideCode(markdown: string, tidy: (prose: string) => string): string {
83 return markdown
84 .split(CODE_BOUNDARY)
85 .map((part, index) =>
86 index % 2 === 1 ? `${CODE_BOUNDARY}${part}${CODE_BOUNDARY}` : tidy(part),
87 )
88 .join("");
89}
90
91function serializeCodeBlock(pre: Element): string {
92 return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
93}
94
95function serializeTableCell(cell: Element): string {
96 return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
97}
98
99function tableSeparatorFor(headerCells: Element[]): string {
100 const markers = headerCells.map((cell) => {
101 const align = (cell as HTMLElement).style?.textAlign ?? cell.getAttribute("align") ?? "";
102 if (align === "center") return ":---:";
103 if (align === "right") return "---:";
104 return "---";
105 });
106 return `| ${markers.join(" | ")} |`;
107}
108
109function serializeTable(table: Element): string {
110 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
111 if (rows.length === 0) return "";
112 const lines: string[] = [];
113 let emittedSeparator = false;
114 for (const row of rows) {
115 const cells = [...row.children].filter(
116 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
117 );
118 if (cells.length === 0) continue;
119 lines.push(`| ${cells.map((cell) => serializeTableCell(cell)).join(" | ")} |`);
120 if (!emittedSeparator) {
121 lines.push(tableSeparatorFor(cells));
122 emittedSeparator = true;
123 }
124 }
125 return `${lines.join("\n")}\n\n`;
126}
127
128function serializeListItem(
129 item: Element,
130 ordered: boolean,
131 index: number,
132 inTableCell: boolean,
133): string {
134 const checkbox = item.querySelector(
135 ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]',
136 );
137 const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
138 const bullet = ordered ? `${index}. ` : "- ";
139 const marker = `${bullet}${task}`;
140 let content = outsideCode(serializeChildren(item, inTableCell), (prose) =>
141 prose.replace(/\n{3,}/g, "\n\n"),
142 ).trim();
143 if (!item.querySelector(":scope > p")) {
144 content = outsideCode(content, (prose) => prose.replace(/\n{2,}/g, "\n"));
145 }
146 // Continuations align after the bullet; task boxes belong to the item text.
147 const continuationIndent = " ".repeat(bullet.length);
148 const [first = "", ...rest] = content.split("\n");
149 return [
150 `${marker}${first}`,
151 ...rest.map((line) => (line.length > 0 ? `${continuationIndent}${line}` : line)),
152 ].join("\n");
153}
154
155/** A list's items with the numbers an ordered list shows: from `start`, reset by each `value`. */
156function numberedListItems(list: Element): { item: Element; number: number }[] {
157 const start = Number.parseInt(list.getAttribute("start") ?? "1", 10);
158 let next = Number.isNaN(start) ? 1 : start;
159 return [...list.children]
160 .filter((child) => child.tagName === "LI")
161 .map((item) => {
162 const value = Number.parseInt(item.getAttribute("value") ?? "", 10);
163 if (!Number.isNaN(value)) next = value;
164 return { item, number: next++ };
165 });
166}
167
168function serializeList(list: Element, ordered: boolean, inTableCell: boolean): string {
169 const items = numberedListItems(list);
170 if (items.length === 0) return "";
171 return `${items
172 .map(({ item, number }) => serializeListItem(item, ordered, number, inTableCell))
173 .join("\n")}\n\n`;
174}
175
176function serializeQuoteBody(quote: Element, inTableCell: boolean): string {
177 let content = "";
178 for (const child of quote.childNodes) {
179 // A callout's rendered label stands for the marker its serializer writes.
180 if (child.nodeType === Node.ELEMENT_NODE && (child as Element).hasAttribute(ALERT_LABEL)) {
181 continue;
182 }
183 content += serializeNode(child, inTableCell);
184 }
185 return outsideCode(content, (prose) => prose.replace(/\n{3,}/g, "\n\n")).trim();
186}
187
188function serializeBlockquote(quote: Element, inTableCell: boolean, marker = ""): string {
189 const body = serializeQuoteBody(quote, inTableCell);
190 const content = marker && body ? `${marker}\n${body}` : marker || body;
191 if (!content) return "";
192 const quoted = content
193 .split("\n")
194 .map((line) => (line.length > 0 ? `> ${line}` : ">"))
195 .join("\n");
196 return `${quoted}\n\n`;
197}
198
199function serializeInsight(insight: Element, inTableCell: boolean): string {
200 const body = serializeQuoteBody(insight, inTableCell);
201 // oxlint-disable-next-line t3code/no-untranslated-copy -- markdown written to the clipboard
202 return `★ Insight ${"─".repeat(37)}\n${body ? `${body}\n` : ""}${"─".repeat(49)}\n\n`;
203}
204
205function serializeDetails(details: Element): string {
206 const summary =
207 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
208 "Details";
209 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
210 const content = contentNode ? serializeChildren(contentNode).trim() : "";
211 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
212 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
213}
214
215// Prose that would read as inline Markdown once pasted back: a backslash before punctuation,
216// backticks, brackets, and emphasis or strikethrough runs (user remark-gfm sets singleTilde: false).
217const INLINE_MARKDOWN = /\\(?=[!-/:-@[-`{-~\n]|$)|[`[\]]|\*+|_+|~{2,}/g;
218const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
219
220/** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
221function escapeProse(text: string): string {
222 return text.replace(/\S+/g, (word, wordOffset: number) => {
223 // Check each word once; testing every escape's growing prefix would be quadratic.
224 const drive = UNFINISHED_DRIVE_PATH.exec(word);
225 const driveStart = drive ? drive.index + drive[0].search(/[A-Za-z]/) + 2 : Infinity;
226 return word.replace(INLINE_MARKDOWN, (match: string, offset: number) => {
227 if (offset >= driveStart) return match;
228 const before = text[wordOffset + offset - 1];
229 const after = text[wordOffset + offset + match.length];
230 if (match === "\\" && after !== undefined && /[^\S\n]/.test(after)) return match;
231 // A text node's edge may touch another node's markers, so it counts as neither.
232 const between = (pattern: RegExp) =>
233 before !== undefined && after !== undefined && pattern.test(before) && pattern.test(after);
234 if (/[*_~]/.test(match[0]!) && between(/\s/)) return match;
235 if (match[0] === "_" && between(/[\p{L}\p{N}]/u)) return match;
236 return match.replace(/[\s\S]/g, "\\$&");
237 });
238 });
239}
240
241function serializeAnchor(anchor: Element, inTableCell: boolean): string {
242 const markdownCopy = anchor.getAttribute("data-markdown-copy");
243 if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
244 const content = serializeChildren(anchor, inTableCell);
245 const href = anchor.getAttribute("href") ?? "";
246 if (!/^(?:https?:\/\/|mailto:)/i.test(href)) return content;
247 const label = content.trim();
248 if (!label) return "";
249 // The label arrives escaped; a bare address goes out as shown, since GFM links it again.
250 const shown = label.replace(ESCAPED_PUNCTUATION, "$1");
251 if (shown === href) return escapeTablePipes(href, inTableCell);
252 // GFM autolinks a bare address only when it fits this shape.
253 if (href === `mailto:${shown}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(shown))
254 return shown;
255 const destination = escapeTablePipes(href.replace(/[\\()]/g, "\\$&"), inTableCell);
256 return `[${label}](${destination})`;
257}
258
259/**
260 * GFM splits a table row at every unescaped pipe, but its math-aware parsing
261 * keeps a formula's pipes in the cell, so formula source is copied unescaped.
262 */
263function escapeTablePipes(text: string, inTableCell: boolean): string {
264 return inTableCell ? text.replaceAll("|", "\\|") : text;
265}
266
267function serializeChildren(node: Node, inTableCell = false): string {
268 let out = "";
269 for (const child of node.childNodes) {
270 out += serializeNode(child, inTableCell);
271 }
272 return out;
273}
274
275function serializeNode(node: Node, inTableCell = false): string {
276 if (node.nodeType === Node.TEXT_NODE) {
277 const text = node.textContent ?? "";
278 if (text.includes("\n") && text.trim().length === 0) return "\n";
279 return escapeTablePipes(escapeProse(text), inTableCell);
280 }
281 if (node.nodeType !== Node.ELEMENT_NODE) return "";
282 const element = node as Element;
283 if (element.hasAttribute("data-markdown-details")) {
284 return escapeTablePipes(serializeDetails(element), inTableCell);
285 }
286 const markdownCopy = element.getAttribute("data-markdown-copy");
287 if (markdownCopy !== null) {
288 // A diagram copies as its fenced source, which is code too.
289 if (element.hasAttribute("data-markdown-mermaid")) {
290 return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
291 }
292 return element.hasAttribute("data-markdown-math")
293 ? markdownCopy
294 : escapeTablePipes(markdownCopy, inTableCell);
295 }
296 if (isSkippedElement(element)) return "";
297 const alert = element.getAttribute(ALERT_ATTRIBUTE);
298 if (alert === "insight") return serializeInsight(element, inTableCell);
299 if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`);
300
301 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
302 if (headingLevel) {
303 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element, inTableCell).trim()}\n\n`;
304 }
305
306 switch (element.tagName) {
307 case "BR":
308 return "\n";
309 case "HR":
310 return "---\n\n";
311 case "P":
312 return `${serializeChildren(element, inTableCell).trim()}\n\n`;
313 case "PRE":
314 return escapeTablePipes(serializeCodeBlock(element), inTableCell);
315 case "CODE": {
316 const content = escapeTablePipes(element.textContent ?? "", inTableCell);
317 return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
318 }
319 case "STRONG":
320 case "B":
321 return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
322 case "EM":
323 case "I":
324 return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
325 case "DEL":
326 case "S":
327 return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
328 case "A":
329 return serializeAnchor(element, inTableCell);
330 case "IMG": {
331 const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
332 const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
333 return alt && src ? `` : "";
334 }
335 case "UL":
336 return serializeList(element, false, inTableCell);
337 case "OL":
338 return serializeList(element, true, inTableCell);
339 case "BLOCKQUOTE":
340 return serializeBlockquote(element, inTableCell);
341 case "TABLE":
342 return escapeTablePipes(serializeTable(element), inTableCell);
343 case "DIV":
344 case "SECTION":
345 case "ARTICLE": {
346 const content = serializeChildren(element, inTableCell);
347 return content && !content.endsWith("\n") ? `${content}\n` : content;
348 }
349 default:
350 return serializeChildren(element, inTableCell);
351 }
352}
353
354interface SoleCodeBlockScan {
355 pre: Element | null;
356 other: boolean;
357}
358
359function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
360 for (const child of node.childNodes) {
361 if (scan.other) return;
362 if (child.nodeType === Node.TEXT_NODE) {
363 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
364 continue;
365 }
366 if (child.nodeType !== Node.ELEMENT_NODE) continue;
367 const element = child as Element;
368 // Explicit markdown still counts on skipped tags such as file-chip buttons.
369 if (element.hasAttribute("data-markdown-details")) {
370 scan.other = true;
371 continue;
372 }
373 const markdownCopy = element.getAttribute("data-markdown-copy");
374 if (markdownCopy !== null) {
375 if (markdownCopy.trim().length > 0) scan.other = true;
376 continue;
377 }
378 if (isSkippedElement(element)) continue;
379 if (element.tagName === "PRE") {
380 if (scan.pre) scan.other = true;
381 else scan.pre = element;
382 continue;
383 }
384 if (element.tagName === "IMG" || element.tagName === "HR") {
385 scan.other = true;
386 continue;
387 }
388 if (element.tagName === "LI") {
389 const preBeforeItem = scan.pre;
390 scanForSoleCodeBlock(element, scan);
391 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
392 continue;
393 }
394 scanForSoleCodeBlock(element, scan);
395 }
396}
397
398// Selecting a block's final newline pulls in its closing pre even when only code was highlighted.
399function soleCodeBlock(container: Node): Element | null {
400 const scan: SoleCodeBlockScan = { pre: null, other: false };
401 scanForSoleCodeBlock(container, scan);
402 return scan.other ? null : scan.pre;
403}
404
405function tidyMarkdown(markdown: string): string {
406 // Odd parts are code, kept verbatim, so a selection that starts or ends inside
407 // code keeps that code's leading and trailing whitespace.
408 const parts = markdown.split(CODE_BOUNDARY);
409 const last = parts.length - 1;
410 return parts
411 .map((part, index) => {
412 if (index % 2 === 1) return part;
413 let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
414 if (index === 0) prose = prose.trimStart();
415 if (index === last) prose = prose.trimEnd();
416 return prose;
417 })
418 .join("");
419}
420
421export function serializeRenderedMarkdownFragment(container: Node): string {
422 const codeBlock = soleCodeBlock(container);
423 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
424 return tidyMarkdown(serializeChildren(container));
425}
426
427export function serializeTableElementToMarkdown(table: Element): string {
428 // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
429 return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
430}
431
432// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
433// the attribute from authored HTML.
434const MATH_SELECTOR = "[data-markdown-math]";
435
436export function mathWrapperOf(element: Element | null): Element | null {
437 return element?.closest(MATH_SELECTOR) ?? null;
438}
439
440/** A cell's text, with each formula as its TeX. */
441function csvCellText(cell: Element): string {
442 if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
443 const copy = cell.cloneNode(true) as Element;
444 for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
445 wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
446 }
447 return copy.textContent ?? "";
448}
449
450function csvCell(value: string): string {
451 const normalized = value.replace(/\s+/g, " ").trim();
452 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
453}
454
455export function serializeTableElementToCsv(table: Element): string {
456 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
457 const lines: string[] = [];
458 for (const row of rows) {
459 const cells = [...row.children].filter(
460 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
461 );
462 if (cells.length === 0) continue;
463 lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
464 }
465 return lines.join("\n");
466}
467
468function mermaidSourceHtml(source: string) {
469 const pre = document.createElement("pre");
470 const code = document.createElement("code");
471 code.textContent = source.trim();
472 pre.appendChild(code);
473 return pre;
474}
475
476function mathSourceElement(wrapper: Element): Element {
477 const code = document.createElement("code");
478 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
479 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
480 const pre = document.createElement("pre");
481 pre.append(code);
482 return pre;
483}
484
485function sanitizedHtmlFrom(container: Element): string {
486 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
487 const source = diagram.getAttribute("data-markdown-copy");
488 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
489 }
490 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
491 wrapper.replaceWith(mathSourceElement(wrapper));
492 }
493 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
494 if (
495 node.classList.contains("chat-markdown-file-link") ||
496 node.closest(".chat-markdown-file-link")
497 ) {
498 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
499 node.remove();
500 }
501 continue;
502 }
503 node.remove();
504 }
505 return `<meta charset="utf-8">${container.innerHTML}`;
506}
507
508/** A list cloned from a later item would renumber from its start; restart it at the shown number. */
509function keepStartListNumbers(range: Range, container: Element): void {
510 // The start's ancestors below the common ancestor clone as the fragment's first-child chain.
511 const chain: Node[] = [];
512 for (
513 let node: Node | null = range.startContainer;
514 node && node !== range.commonAncestorContainer;
515 node = node.parentNode
516 ) {
517 chain.unshift(node);
518 }
519 let clone: Node | null = container;
520 for (const [depth, source] of chain.entries()) {
521 clone = clone?.firstChild ?? null;
522 if (!(clone instanceof Element) || !(source instanceof Element) || source.tagName !== "OL")
523 continue;
524 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
525 if (!firstCopied) continue;
526 const shown = numberedListItems(source).find(
527 ({ item }) =>
528 item === firstCopied ||
529 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
530 );
531 const cloned = numberedListItems(clone)[0];
532 if (shown && cloned && shown.number !== cloned.number) {
533 clone.setAttribute("start", String(shown.number));
534 }
535 }
536}
537
538export function chatMarkdownClipboardPayload(
539 selection: Selection,
540): MarkdownClipboardPayload | null {
541 const texts: string[] = [];
542 const htmls: string[] = [];
543 for (let index = 0; index < selection.rangeCount; index += 1) {
544 const range = selection.getRangeAt(index);
545 if (range.collapsed) continue;
546 const container = document.createElement("div");
547 container.appendChild(range.cloneContents());
548 keepStartListNumbers(range, container);
549 // The indentation typed at a line start only shows; pasted, it would turn lines into code.
550 for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
551 indentation.remove();
552 }
553 const ancestor = range.commonAncestorContainer;
554 const ancestorElement =
555 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
556 const diagramSource = ancestorElement
557 ?.closest("[data-markdown-mermaid]")
558 ?.getAttribute("data-markdown-copy");
559 if (diagramSource != null) {
560 const text = diagramSource.trim();
561 if (!text) continue;
562 texts.push(text);
563 container.replaceChildren(mermaidSourceHtml(diagramSource));
564 htmls.push(sanitizedHtmlFrom(container));
565 continue;
566 }
567 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
568 const math = mathWrapperOf(ancestorElement);
569 if (math) {
570 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
571 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
572 continue;
573 }
574 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
575 if (ancestorElement?.closest("pre, code")) {
576 const text = range.toString();
577 if (text) {
578 texts.push(text);
579 htmls.push(sanitizedHtmlFrom(container));
580 }
581 continue;
582 }
583 // A range spanning exactly one callout's text clones its contents but not the callout.
584 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
585 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
586 const wrapper = callout.cloneNode(false) as Element;
587 wrapper.append(...container.childNodes);
588 container.replaceChildren(wrapper);
589 }
590 const text = serializeRenderedMarkdownFragment(container);
591 if (!text) continue;
592 texts.push(text);
593 htmls.push(sanitizedHtmlFrom(container));
594 }
595 if (texts.length === 0) return null;
596 return { text: texts.join("\n\n"), html: htmls.join("") };
597}