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

markdown-clipboard.ts

592 lines22.6 KB

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;
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));
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] ?? ""}`;
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;
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}`;
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));
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`;
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`;
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("");
90​
91function serializeCodeBlock(pre: Element): string {
92 return verbatimBlock((pre.textContent ?? "").replace(/\n$/, ""));
94​
95function serializeTableCell(cell: Element): string {
96 return serializeChildren(cell, true).replace(/\n+/g, " ").trim();
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(" | ")} |`;
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`;
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");
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 });
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`;
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();
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`;
198​
199function serializeInsight(insight: Element, inTableCell: boolean): string {
200 const body = serializeQuoteBody(insight, inTableCell);
201 return `★ Insight ${"─".repeat(37)}\n${body ? `${body}\n` : ""}${"─".repeat(49)}\n\n`;
203​
204function serializeDetails(details: Element): string {
205 const summary =
206 details.querySelector(":scope > [data-markdown-details-summary]")?.textContent?.trim() ??
207 "Details";
208 const contentNode = details.querySelector(":scope > * [data-markdown-details-content]");
209 const content = contentNode ? serializeChildren(contentNode).trim() : "";
210 const open = details.getAttribute("data-markdown-details-open") === "true" ? " open" : "";
211 return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
213​
214// Prose that would read as inline Markdown once pasted back: a backslash before punctuation,
215// backticks, brackets, and emphasis or strikethrough runs (user remark-gfm sets singleTilde: false).
216const INLINE_MARKDOWN = /\\(?=[!-/:-@[-`{-~\n]|$)|[`[\]]|\*+|_+|~{2,}/g;
217const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
218​
219/** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
220function escapeProse(text: string): string {
221 return text.replace(/\S+/g, (word, wordOffset: number) => {
222 // Check each word once; testing every escape's growing prefix would be quadratic.
223 const drive = UNFINISHED_DRIVE_PATH.exec(word);
224 const driveStart = drive ? drive.index + drive[0].search(/[A-Za-z]/) + 2 : Infinity;
225 return word.replace(INLINE_MARKDOWN, (match: string, offset: number) => {
226 if (offset >= driveStart) return match;
227 const before = text[wordOffset + offset - 1];
228 const after = text[wordOffset + offset + match.length];
229 if (match === "\\" && after !== undefined && /[^\S\n]/.test(after)) return match;
230 // A text node's edge may touch another node's markers, so it counts as neither.
231 const between = (pattern: RegExp) =>
232 before !== undefined && after !== undefined && pattern.test(before) && pattern.test(after);
233 if (/[*_~]/.test(match[0]!) && between(/\s/)) return match;
234 if (match[0] === "_" && between(/[\p{L}\p{N}]/u)) return match;
235 return match.replace(/[\s\S]/g, "\\$&");
236 });
237 });
239​
240function serializeAnchor(anchor: Element, inTableCell: boolean): string {
241 const markdownCopy = anchor.getAttribute("data-markdown-copy");
242 if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
243 const content = serializeChildren(anchor, inTableCell);
244 const href = anchor.getAttribute("href") ?? "";
245 if (!/^(?:https?:\/\/|mailto:)/i.test(href)) return content;
246 const label = content.trim();
247 if (!label) return "";
248 // The label arrives escaped; a bare address goes out as shown, since GFM links it again.
249 const shown = label.replace(ESCAPED_PUNCTUATION, "$1");
250 if (shown === href) return escapeTablePipes(href, inTableCell);
251 // GFM autolinks a bare address only when it fits this shape.
252 if (href === `mailto:${shown}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(shown))
253 return shown;
254 const destination = escapeTablePipes(href.replace(/[\\()]/g, "\\$&"), inTableCell);
255 return `[${label}](${destination})`;
257​
258/**
259 * GFM splits a table row at every unescaped pipe, but its math-aware parsing
260 * keeps a formula's pipes in the cell, so formula source is copied unescaped.
261 */
262function escapeTablePipes(text: string, inTableCell: boolean): string {
263 return inTableCell ? text.replaceAll("|", "\\|") : text;
265​
266function serializeChildren(node: Node, inTableCell = false): string {
267 let out = "";
268 for (const child of node.childNodes) {
269 out += serializeNode(child, inTableCell);
270 }
271 return out;
273​
274function serializeNode(node: Node, inTableCell = false): string {
275 if (node.nodeType === Node.TEXT_NODE) {
276 const text = node.textContent ?? "";
277 if (text.includes("\n") && text.trim().length === 0) return "\n";
278 return escapeTablePipes(escapeProse(text), inTableCell);
279 }
280 if (node.nodeType !== Node.ELEMENT_NODE) return "";
281 const element = node as Element;
282 if (element.hasAttribute("data-markdown-details")) {
283 return escapeTablePipes(serializeDetails(element), inTableCell);
284 }
285 const markdownCopy = element.getAttribute("data-markdown-copy");
286 if (markdownCopy !== null) {
287 // A diagram copies as its fenced source, which is code too.
288 if (element.hasAttribute("data-markdown-mermaid")) {
289 return verbatimBlock(escapeTablePipes(markdownCopy.trimEnd(), inTableCell));
290 }
291 return element.hasAttribute("data-markdown-math")
292 ? markdownCopy
293 : escapeTablePipes(markdownCopy, inTableCell);
294 }
295 if (isSkippedElement(element)) return "";
296 const alert = element.getAttribute(ALERT_ATTRIBUTE);
297 if (alert === "insight") return serializeInsight(element, inTableCell);
298 if (alert !== null) return serializeBlockquote(element, inTableCell, `[!${alert.toUpperCase()}]`);
299​
300 const headingLevel = /^H([1-6])$/.exec(element.tagName)?.[1];
301 if (headingLevel) {
302 return `${"#".repeat(Number(headingLevel))} ${serializeChildren(element, inTableCell).trim()}\n\n`;
303 }
304​
305 switch (element.tagName) {
306 case "BR":
307 return "\n";
308 case "HR":
309 return "---\n\n";
310 case "P":
311 return `${serializeChildren(element, inTableCell).trim()}\n\n`;
312 case "PRE":
313 return escapeTablePipes(serializeCodeBlock(element), inTableCell);
314 case "CODE": {
315 const content = escapeTablePipes(element.textContent ?? "", inTableCell);
316 return isBlockCodeElement(element, content) ? content : wrapInlineCode(content);
317 }
318 case "STRONG":
319 case "B":
320 return wrapInlineMarker(serializeChildren(element, inTableCell), "**");
321 case "EM":
322 case "I":
323 return wrapInlineMarker(serializeChildren(element, inTableCell), "*");
324 case "DEL":
325 case "S":
326 return wrapInlineMarker(serializeChildren(element, inTableCell), "~~");
327 case "A":
328 return serializeAnchor(element, inTableCell);
329 case "IMG": {
330 const alt = escapeTablePipes(element.getAttribute("alt") ?? "", inTableCell);
331 const src = escapeTablePipes(element.getAttribute("src") ?? "", inTableCell);
332 return alt && src ? `![${alt}](${src})` : "";
333 }
334 case "UL":
335 return serializeList(element, false, inTableCell);
336 case "OL":
337 return serializeList(element, true, inTableCell);
338 case "BLOCKQUOTE":
339 return serializeBlockquote(element, inTableCell);
340 case "TABLE":
341 return escapeTablePipes(serializeTable(element), inTableCell);
342 case "DIV":
343 case "SECTION":
344 case "ARTICLE": {
345 const content = serializeChildren(element, inTableCell);
346 return content && !content.endsWith("\n") ? `${content}\n` : content;
347 }
348 default:
349 return serializeChildren(element, inTableCell);
350 }
352​
353interface SoleCodeBlockScan {
354 pre: Element | null;
355 other: boolean;
357​
358function scanForSoleCodeBlock(node: Node, scan: SoleCodeBlockScan): void {
359 for (const child of node.childNodes) {
360 if (scan.other) return;
361 if (child.nodeType === Node.TEXT_NODE) {
362 if ((child.textContent ?? "").trim().length > 0) scan.other = true;
363 continue;
364 }
365 if (child.nodeType !== Node.ELEMENT_NODE) continue;
366 const element = child as Element;
367 // Explicit markdown still counts on skipped tags such as file-chip buttons.
368 if (element.hasAttribute("data-markdown-details")) {
369 scan.other = true;
370 continue;
371 }
372 const markdownCopy = element.getAttribute("data-markdown-copy");
373 if (markdownCopy !== null) {
374 if (markdownCopy.trim().length > 0) scan.other = true;
375 continue;
376 }
377 if (isSkippedElement(element)) continue;
378 if (element.tagName === "PRE") {
379 if (scan.pre) scan.other = true;
380 else scan.pre = element;
381 continue;
382 }
383 if (element.tagName === "IMG" || element.tagName === "HR") {
384 scan.other = true;
385 continue;
386 }
387 if (element.tagName === "LI") {
388 const preBeforeItem = scan.pre;
389 scanForSoleCodeBlock(element, scan);
390 if (!scan.other && scan.pre === preBeforeItem) scan.other = true;
391 continue;
392 }
393 scanForSoleCodeBlock(element, scan);
394 }
396​
397// Selecting a block's final newline pulls in its closing pre even when only code was highlighted.
398function soleCodeBlock(container: Node): Element | null {
399 const scan: SoleCodeBlockScan = { pre: null, other: false };
400 scanForSoleCodeBlock(container, scan);
401 return scan.other ? null : scan.pre;
403​
404function tidyMarkdown(markdown: string): string {
405 // Odd parts are code, kept verbatim, so a selection that starts or ends inside
406 // code keeps that code's leading and trailing whitespace.
407 const parts = markdown.split(CODE_BOUNDARY);
408 const last = parts.length - 1;
409 return parts
410 .map((part, index) => {
411 if (index % 2 === 1) return part;
412 let prose = part.replace(/[ \t]+(?=\n)/g, "").replace(/\n{3,}/g, "\n\n");
413 if (index === 0) prose = prose.trimStart();
414 if (index === last) prose = prose.trimEnd();
415 return prose;
416 })
417 .join("");
419​
420export function serializeRenderedMarkdownFragment(container: Node): string {
421 const codeBlock = soleCodeBlock(container);
422 if (codeBlock) return (codeBlock.textContent ?? "").replace(/\n$/, "");
423 return tidyMarkdown(serializeChildren(container));
425​
426export function serializeTableElementToMarkdown(table: Element): string {
427 // Raw HTML can put a pre in a cell; with no tidy pass here, drop its markers.
428 return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim();
430​
431// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops
432// the attribute from authored HTML.
433const MATH_SELECTOR = "[data-markdown-math]";
434​
435export function mathWrapperOf(element: Element | null): Element | null {
436 return element?.closest(MATH_SELECTOR) ?? null;
438​
439/** A cell's text, with each formula as its TeX. */
440function csvCellText(cell: Element): string {
441 if (!cell.querySelector(MATH_SELECTOR)) return cell.textContent ?? "";
442 const copy = cell.cloneNode(true) as Element;
443 for (const wrapper of copy.querySelectorAll(MATH_SELECTOR)) {
444 wrapper.replaceWith(wrapper.getAttribute("data-markdown-copy")?.trim() ?? "");
445 }
446 return copy.textContent ?? "";
448​
449function csvCell(value: string): string {
450 const normalized = value.replace(/\s+/g, " ").trim();
451 return /[",\n]/.test(normalized) ? `"${normalized.replaceAll('"', '""')}"` : normalized;
453​
454export function serializeTableElementToCsv(table: Element): string {
455 const rows = [...table.querySelectorAll(":scope > thead > tr, :scope > tbody > tr, :scope > tr")];
456 const lines: string[] = [];
457 for (const row of rows) {
458 const cells = [...row.children].filter(
459 (cell) => cell.tagName === "TH" || cell.tagName === "TD",
460 );
461 if (cells.length === 0) continue;
462 lines.push(cells.map((cell) => csvCell(csvCellText(cell))).join(","));
463 }
464 return lines.join("\n");
466​
467function mermaidSourceHtml(source: string) {
468 const pre = document.createElement("pre");
469 const code = document.createElement("code");
470 code.textContent = source.trim();
471 pre.appendChild(code);
472 return pre;
474​
475function mathSourceElement(wrapper: Element): Element {
476 const code = document.createElement("code");
477 code.textContent = wrapper.getAttribute("data-markdown-copy")?.trim() ?? "";
478 if (wrapper.getAttribute("data-markdown-math") !== "display") return code;
479 const pre = document.createElement("pre");
480 pre.append(code);
481 return pre;
483​
484function sanitizedHtmlFrom(container: Element): string {
485 for (const diagram of container.querySelectorAll("[data-markdown-mermaid]")) {
486 const source = diagram.getAttribute("data-markdown-copy");
487 if (source !== null) diagram.replaceChildren(mermaidSourceHtml(source));
488 }
489 for (const wrapper of container.querySelectorAll(MATH_SELECTOR)) {
490 wrapper.replaceWith(mathSourceElement(wrapper));
491 }
492 for (const node of container.querySelectorAll(SANITIZED_HTML_SELECTOR)) {
493 if (
494 node.classList.contains("chat-markdown-file-link") ||
495 node.closest(".chat-markdown-file-link")
496 ) {
497 if (node.getAttribute("aria-hidden") === "true" || node.localName === "svg") {
498 node.remove();
499 }
500 continue;
501 }
502 node.remove();
503 }
504 return `<meta charset="utf-8">${container.innerHTML}`;
506​
507/** A list cloned from a later item would renumber from its start; restart it at the shown number. */
508function keepStartListNumbers(range: Range, container: Element): void {
509 // The start's ancestors below the common ancestor clone as the fragment's first-child chain.
510 const chain: Node[] = [];
511 for (
512 let node: Node | null = range.startContainer;
513 node && node !== range.commonAncestorContainer;
514 node = node.parentNode
515 ) {
516 chain.unshift(node);
517 }
518 let clone: Node | null = container;
519 for (const [depth, source] of chain.entries()) {
520 clone = clone?.firstChild ?? null;
521 if (!(clone instanceof Element) || !(source instanceof Element) || source.tagName !== "OL")
522 continue;
523 const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
524 if (!firstCopied) continue;
525 const shown = numberedListItems(source).find(
526 ({ item }) =>
527 item === firstCopied ||
528 firstCopied.compareDocumentPosition(item) & Node.DOCUMENT_POSITION_FOLLOWING,
529 );
530 const cloned = numberedListItems(clone)[0];
531 if (shown && cloned && shown.number !== cloned.number) {
532 clone.setAttribute("start", String(shown.number));
533 }
534 }
536​
537export function chatMarkdownClipboardPayload(
538 selection: Selection,
539): MarkdownClipboardPayload | null {
540 const texts: string[] = [];
541 const htmls: string[] = [];
542 for (let index = 0; index < selection.rangeCount; index += 1) {
543 const range = selection.getRangeAt(index);
544 if (range.collapsed) continue;
545 const container = document.createElement("div");
546 container.appendChild(range.cloneContents());
547 keepStartListNumbers(range, container);
548 const ancestor = range.commonAncestorContainer;
549 const ancestorElement =
550 ancestor.nodeType === Node.ELEMENT_NODE ? (ancestor as Element) : ancestor.parentElement;
551 const diagramSource = ancestorElement
552 ?.closest("[data-markdown-mermaid]")
553 ?.getAttribute("data-markdown-copy");
554 if (diagramSource != null) {
555 const text = diagramSource.trim();
556 if (!text) continue;
557 texts.push(text);
558 container.replaceChildren(mermaidSourceHtml(diagramSource));
559 htmls.push(sanitizedHtmlFrom(container));
560 continue;
561 }
562 // A range inside a formula would clone only KaTeX's glyphs, not the wrapper holding the TeX.
563 const math = mathWrapperOf(ancestorElement);
564 if (math) {
565 texts.push(math.getAttribute("data-markdown-copy")?.trim() ?? "");
566 htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
567 continue;
568 }
569 // A range inside one code element clones only its text, which would otherwise be escaped as prose.
570 if (ancestorElement?.closest("pre, code")) {
571 const text = range.toString();
572 if (text) {
573 texts.push(text);
574 htmls.push(sanitizedHtmlFrom(container));
575 }
576 continue;
577 }
578 // A range spanning exactly one callout's text clones its contents but not the callout.
579 const callout = ancestorElement?.closest(`[${ALERT_ATTRIBUTE}]`);
580 if (callout && range.toString().trim() === (callout.textContent ?? "").trim()) {
581 const wrapper = callout.cloneNode(false) as Element;
582 wrapper.append(...container.childNodes);
583 container.replaceChildren(wrapper);
584 }
585 const text = serializeRenderedMarkdownFragment(container);
586 if (!text) continue;
587 texts.push(text);
588 htmls.push(sanitizedHtmlFrom(container));
589 }
590 if (texts.length === 0) return null;
591 return { text: texts.join("\n\n"), html: htmls.join("") };