Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

feat(export): inline computed iframe styles for WeChat paste (#94)

涂瑜ce5035942067
diff --git a/e2e/ui/export-menu.test.ts b/e2e/ui/export-menu.test.ts
index c568f203..4b596375 100644
--- a/e2e/ui/export-menu.test.ts
+++ b/e2e/ui/export-menu.test.ts
@@ -35,6 +35,47 @@ const hyperframesHtml = `<!doctype html>
</body>
</html>`;
+const runtimeDeckHtml = `<!doctype html>
+<html>
+ <head>
+ <title>Runtime Deck</title>
+ <script>
+ const style = document.createElement("style");
+ style.textContent = ".runtime { color: rgb(1, 2, 3); }";
+ document.head.appendChild(style);
+ </script>
+ </head>
+ <body>
+ <section class="slide runtime" data-slide-id="1"><h1>Runtime slide one</h1></section>
+ <section class="slide runtime" data-slide-id="2"><h1>Runtime slide two</h1></section>
+ </body>
+</html>`;
+
+const runtimePlainHtml = `<!doctype html>
+<html><head><script>
+ const style = document.createElement("style");
+ style.textContent =
+ ".runtime { color: rgb(1, 2, 3); }" +
+ ".reveal { opacity: 0; }" +
+ ".reveal.visible { opacity: 1; }" +
+ ".entry { animation: fade-in 700ms linear forwards; }" +
+ "@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }";
+ document.head.appendChild(style);
+ addEventListener("DOMContentLoaded", () => {
+ const target = document.querySelector(".reveal");
+ if (target) new IntersectionObserver(() => target.classList.add("visible"), { threshold: 0 }).observe(target);
+ });
+</script></head>
+<body>
+ <p class="runtime reveal">Observer reveal</p>
+ <p class="runtime entry">Animated entry</p>
+ <p class="runtime">Runtime source-tab content</p>
+</body></html>`;
+
+const delayedHtml = `<!doctype html><html><head>
+ <script src="https://delayed.example/slow.js"></script>
+</head><body><p class="runtime">Delayed clipboard content</p></body></html>`;
+
async function seedStore(page: Page, opts: SeedOptions) {
const now = 1_700_000_000_000;
const task = {
@@ -78,6 +119,31 @@ async function seedStore(page: Page, opts: SeedOptions) {
);
}
+async function captureClipboardHtml(page: Page) {
+ await page.evaluate(() => {
+ Object.defineProperty(window, "ClipboardItem", {
+ configurable: true,
+ value: class ClipboardItem {
+ readonly items: Record<string, Blob | Promise<Blob>>;
+ constructor(items: Record<string, Blob | Promise<Blob>>) {
+ this.items = items;
+ }
+ },
+ });
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: {
+ write: async (items: Array<{ items: Record<string, Blob | Promise<Blob>> }>) => {
+ (window as typeof window & { __clipboardWriteStartedAt?: number }).__clipboardWriteStartedAt = performance.now();
+ const blob = await items[0]?.items["text/html"];
+ (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml =
+ blob ? await blob.text() : "";
+ },
+ },
+ });
+ });
+}
+
test.describe("Export menu", () => {
test("keeps Remotion hidden for regular HTML exports", async ({ page }) => {
await seedStore(page, { html: plainHtml });
@@ -96,6 +162,74 @@ test.describe("Export menu", () => {
await expect(menu.getByRole("button", { name: /Remotion project/ })).toHaveCount(0);
});
+ test("keeps computed styles when exporting from Source and Log tabs", async ({ page }) => {
+ await seedStore(page, { html: runtimePlainHtml });
+ await page.goto("/");
+ await captureClipboardHtml(page);
+
+ for (const tab of [/Source/, /Log/]) {
+ await page.getByRole("button", { name: tab }).click();
+ await page.evaluate(() => {
+ (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml = "";
+ });
+ await page.getByRole("button", { name: /export/i }).click();
+ await page.getByTestId("export-menu").getByRole("button", { name: /WeChat/ }).click();
+
+ await expect.poll(() =>
+ page.evaluate(() => (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml ?? ""),
+ ).toContain("Runtime source-tab content");
+ const copied = await page.evaluate(() =>
+ (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml ?? "",
+ );
+ expect(copied).toContain("color: rgb(1, 2, 3)");
+ expect(copied).toContain("Observer reveal");
+ expect(copied).toContain("Animated entry");
+ expect(copied).not.toContain("opacity: 0");
+ }
+ });
+
+ test("exports every computed-styled slide when slide 2 is selected", async ({ page }) => {
+ await seedStore(page, { html: runtimeDeckHtml });
+ await page.goto("/");
+ await captureClipboardHtml(page);
+
+ await page.getByRole("button", { name: "2", exact: true }).click();
+ await page.getByRole("button", { name: /export/i }).click();
+ await page.getByTestId("export-menu").getByRole("button", { name: /WeChat/ }).click();
+
+ await expect.poll(() =>
+ page.evaluate(() => (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml ?? ""),
+ ).toContain("Runtime slide one");
+ const copied = await page.evaluate(() =>
+ (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml ?? "",
+ );
+ expect(copied).toContain("Runtime slide two");
+ expect(copied).toContain("color: rgb(1, 2, 3)");
+ });
+
+ test("starts the clipboard write before a slow full-document render settles", async ({ page }) => {
+ await page.route("https://delayed.example/slow.js", async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 6000));
+ await route.fulfill({ contentType: "application/javascript", body: "document.body.dataset.ready = '1';" });
+ });
+ await seedStore(page, { html: delayedHtml });
+ await page.goto("/");
+ await captureClipboardHtml(page);
+
+ const clickStartedAt = await page.evaluate(() => performance.now());
+ await page.getByRole("button", { name: /export/i }).click();
+ await page.getByTestId("export-menu").getByRole("button", { name: /WeChat/ }).click();
+
+ await expect.poll(() =>
+ page.evaluate(() => (window as typeof window & { __wechatClipboardHtml?: string }).__wechatClipboardHtml ?? ""),
+ { timeout: 12_000 },
+ ).toContain("Delayed clipboard content");
+ const writeStartedAt = await page.evaluate(() =>
+ (window as typeof window & { __clipboardWriteStartedAt?: number }).__clipboardWriteStartedAt ?? Infinity,
+ );
+ expect(writeStartedAt - clickStartedAt).toBeLessThan(1000);
+ });
+
test("exports a Hyperframes Remotion project zip from the UI", async ({ page }) => {
await seedStore(page, { html: hyperframesHtml });
diff --git a/next/src/lib/export/__tests__/wechat.test.ts b/next/src/lib/export/__tests__/wechat.test.ts
new file mode 100644
index 00000000..acac143e
--- /dev/null
+++ b/next/src/lib/export/__tests__/wechat.test.ts
@@ -0,0 +1,239 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { renderToWechatHtml, toWechatHtmlFromDocument } from "../wechat";
+
+function parseFragment(html: string): HTMLBodyElement {
+ return new DOMParser().parseFromString(`<body>${html}</body>`, "text/html")
+ .body as HTMLBodyElement;
+}
+
+describe("toWechatHtmlFromDocument", () => {
+ afterEach(() => {
+ document.head.innerHTML = "";
+ document.body.innerHTML = "";
+ });
+
+ it("inlines computed styles from the rendered preview DOM", () => {
+ document.head.innerHTML = `
+ <style>
+ .card {
+ background: rgb(12, 34, 56);
+ border-radius: 18px;
+ padding: 24px;
+ }
+ .title {
+ color: rgb(210, 55, 44);
+ font-size: 32px;
+ font-weight: 800;
+ line-height: 1.25;
+ }
+ </style>
+ `;
+ document.body.innerHTML = `
+ <article class="card">
+ <h1 class="title">Styled headline</h1>
+ </article>
+ `;
+
+ const body = parseFragment(toWechatHtmlFromDocument(document));
+ const section = body.querySelector("section");
+ const card = body.querySelector("article");
+ const title = body.querySelector("h1");
+
+ expect(section?.getAttribute("data-tool")).toBe("html-anything");
+ expect(card?.getAttribute("data-tool")).toBe("html-anything");
+ expect(card?.getAttribute("style")).toContain("background-color: rgb(12, 34, 56)");
+ expect(card?.getAttribute("style")).toContain("border-radius: 18px");
+ expect(card?.getAttribute("style")).toContain("padding: 24px");
+ expect(title?.getAttribute("style")).toContain("color: rgb(210, 55, 44)");
+ expect(title?.getAttribute("style")).toContain("font-size: 32px");
+ expect(title?.getAttribute("style")).toContain("font-weight: 800");
+ });
+
+ it("drops fragile page-layout styles so WeChat paste stays in article flow", () => {
+ document.head.innerHTML = `
+ <style>
+ .layout {
+ position: absolute;
+ display: grid;
+ grid-template-columns: 320px 1fr;
+ width: 1280px;
+ height: 720px;
+ gap: 48px;
+ background: rgb(250, 248, 240);
+ padding: 40px;
+ }
+ .panel {
+ display: flex;
+ min-height: 360px;
+ color: rgb(25, 28, 32);
+ border: 2px solid rgb(80, 90, 100);
+ }
+ </style>
+ `;
+ document.body.innerHTML = `
+ <section class="layout">
+ <p class="panel">First paragraph</p>
+ <p class="panel">Second paragraph</p>
+ </section>
+ `;
+
+ const html = toWechatHtmlFromDocument(document);
+ const body = parseFragment(html);
+ const layoutStyle = body.querySelector(".layout")?.getAttribute("style") ?? "";
+ const panelStyle = body.querySelector(".panel")?.getAttribute("style") ?? "";
+
+ expect(layoutStyle).toContain("background-color: rgb(250, 248, 240)");
+ expect(layoutStyle).toContain("padding: 40px");
+ expect(panelStyle).toContain("color: rgb(25, 28, 32)");
+ expect(panelStyle).toContain("border-top: 2px solid rgb(80, 90, 100)");
+ expect(`${layoutStyle}; ${panelStyle}`).not.toMatch(
+ /(?:^|;\s*)(position|display|grid-template-columns|width|height|min-height|gap|flex-direction|flex-wrap|flex):/,
+ );
+ });
+
+ it("materializes ::before and ::after content into real DOM nodes", () => {
+ document.body.innerHTML = `
+ <ul>
+ <li class="check">Item one</li>
+ </ul>
+ <p class="tier">Pro plan</p>
+ `;
+
+ const original = window.getComputedStyle.bind(window);
+ const stub = ((el: Element, pseudo?: string | null) => {
+ const base = original(el);
+ if (!pseudo) return base;
+ const overrides: Record<string, string> = {};
+ if (pseudo === "::before" && (el as HTMLElement).matches?.(".check")) {
+ overrides.content = '"✓"';
+ overrides.color = "rgb(255, 0, 0)";
+ } else if (pseudo === "::before" && (el as HTMLElement).matches?.(".tier")) {
+ overrides.content = '"Recommended"';
+ overrides.color = "rgb(255, 255, 255)";
+ } else if (pseudo === "::after" && (el as HTMLElement).matches?.(".tier")) {
+ overrides.content = '"★"';
+ }
+ return new Proxy(base, {
+ get(target, prop) {
+ if (prop === "getPropertyValue") {
+ return (name: string) => overrides[name] ?? target.getPropertyValue(name);
+ }
+ const value = (target as unknown as Record<string | symbol, unknown>)[prop];
+ return typeof value === "function" ? (value as () => unknown).bind(target) : value;
+ },
+ });
+ }) as typeof window.getComputedStyle;
+ window.getComputedStyle = stub;
+
+ try {
+ const body = parseFragment(toWechatHtmlFromDocument(document));
+ const check = body.querySelector("li.check");
+ const tier = body.querySelector("p.tier");
+
+ const checkBefore = check?.firstElementChild;
+ expect(checkBefore?.getAttribute("data-pseudo")).toBe("::before");
+ expect(checkBefore?.textContent).toBe("✓");
+ expect(checkBefore?.getAttribute("style") ?? "").toContain("color: rgb(255, 0, 0)");
+
+ const tierBefore = tier?.firstElementChild;
+ expect(tierBefore?.getAttribute("data-pseudo")).toBe("::before");
+ expect(tierBefore?.textContent).toBe("Recommended");
+
+ const tierAfter = tier?.lastElementChild;
+ expect(tierAfter?.getAttribute("data-pseudo")).toBe("::after");
+ expect(tierAfter?.textContent).toBe("★");
+ } finally {
+ window.getComputedStyle = original as typeof window.getComputedStyle;
+ }
+ });
+
+ it("keeps descendant styles aligned when an ancestor has generated content", () => {
+ document.body.innerHTML = `
+ <div class="card"><span class="label">Hello</span></div>
+ `;
+
+ const original = window.getComputedStyle.bind(window);
+ const stub = ((el: Element, pseudo?: string | null) => {
+ const base = original(el);
+ const overrides: Record<string, string> = {};
+ if (pseudo === "::before" && (el as HTMLElement).matches?.(".card")) {
+ overrides.content = '"Badge"';
+ } else if (!pseudo && (el as HTMLElement).matches?.(".label")) {
+ overrides.color = "rgb(255, 0, 0)";
+ }
+ return new Proxy(base, {
+ get(target, prop) {
+ if (prop === "getPropertyValue") {
+ return (name: string) => overrides[name] ?? target.getPropertyValue(name);
+ }
+ const value = (target as unknown as Record<string | symbol, unknown>)[prop];
+ return typeof value === "function" ? (value as () => unknown).bind(target) : value;
+ },
+ });
+ }) as typeof window.getComputedStyle;
+ window.getComputedStyle = stub;
+
+ try {
+ const body = parseFragment(toWechatHtmlFromDocument(document));
+ const card = body.querySelector(".card");
+ const pseudo = card?.querySelector("[data-pseudo='::before']");
+ const label = card?.querySelector(".label");
+
+ expect(pseudo?.textContent).toBe("Badge");
+ expect(pseudo?.getAttribute("style") ?? "").not.toContain("color: rgb(255, 0, 0)");
+ expect(label?.getAttribute("style") ?? "").toContain("color: rgb(255, 0, 0)");
+ } finally {
+ window.getComputedStyle = original as typeof window.getComputedStyle;
+ }
+ });
+
+ it("omits computed-hidden speaker notes", () => {
+ document.head.innerHTML = `<style>.notes { display: none !important; }</style>`;
+ document.body.innerHTML = `
+ <section class="slide"><h1>Visible slide</h1><aside class="notes">SECRET NOTES</aside></section>
+ `;
+
+ const exported = toWechatHtmlFromDocument(document);
+ expect(exported).toContain("Visible slide");
+ expect(exported).not.toContain("SECRET NOTES");
+ expect(exported).not.toContain("class=\"notes\"");
+ });
+
+ it("clamps oversized spacing and drops negative margins", () => {
+ document.head.innerHTML = `
+ <style>
+ .loose {
+ margin-top: -24px;
+ margin-bottom: 180px;
+ padding: 96px;
+ color: rgb(40, 40, 40);
+ }
+ </style>
+ `;
+ document.body.innerHTML = `<p class="loose">Too much spacing</p>`;
+
+ const body = parseFragment(toWechatHtmlFromDocument(document));
+ const style = body.querySelector("p")?.getAttribute("style") ?? "";
+
+ expect(style).toContain("margin-bottom: 48px");
+ expect(style).toContain("padding: 48px");
+ expect(style).toContain("color: rgb(40, 40, 40)");
+ expect(style).not.toContain("-24px");
+ expect(style).not.toContain("180px");
+ expect(style).not.toContain("96px");
+ });
+
+ it("keeps every runtime-styled deck slide in the full rendered export", async () => {
+ const fullDeck = `<!doctype html><html><head>
+ <style>.runtime { color: rgb(1, 2, 3); }</style>
+ </head><body>
+ <section class="slide runtime" data-slide-id="1"><h1>Slide one</h1></section>
+ <section class="slide runtime" data-slide-id="2"><h1>Slide two</h1></section>
+ </body></html>`;
+
+ const exported = await renderToWechatHtml(fullDeck);
+ expect(exported).toContain("Slide one");
+ expect(exported).toContain("Slide two");
+ expect(exported).toContain("color: rgb(1, 2, 3)");
+ });
+});
diff --git a/next/src/lib/export/clipboard.ts b/next/src/lib/export/clipboard.ts
index 2bee5b40..3abb2fe1 100644
--- a/next/src/lib/export/clipboard.ts
+++ b/next/src/lib/export/clipboard.ts
@@ -26,6 +26,33 @@ export async function copyHtml(html: string, plain?: string): Promise<void> {
await copySafari(html, fallback);
}
+/**
+ * Start the ClipboardItem write during the user gesture while allowing its
+ * Blob payloads to resolve after a fresh render has settled. Chromium keeps
+ * the activation associated with this write, unlike awaiting the render first.
+ */
+export async function copyHtmlWhenReady(htmlPromise: Promise<string>): Promise<void> {
+ if (typeof window === "undefined") throw new Error("server-side");
+ const fallbackPromise = htmlPromise.then(stripTags);
+
+ if (navigator.clipboard && typeof window.ClipboardItem !== "undefined") {
+ try {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ "text/html": htmlPromise.then((html) => new Blob([html], { type: "text/html" })),
+ "text/plain": fallbackPromise.then((plain) => new Blob([plain], { type: "text/plain" })),
+ }),
+ ]);
+ return;
+ } catch {
+ // fall through after the render promise settles
+ }
+ }
+
+ const html = await htmlPromise;
+ await copySafari(html, await fallbackPromise);
+}
+
export async function copyImage(blob: Blob): Promise<void> {
if (!navigator.clipboard || typeof window.ClipboardItem === "undefined") {
throw new Error("Image clipboard not supported in this browser");
diff --git a/next/src/lib/export/wechat.ts b/next/src/lib/export/wechat.ts
index 87645081..d0d6ae2d 100644
--- a/next/src/lib/export/wechat.ts
+++ b/next/src/lib/export/wechat.ts
@@ -1,7 +1,42 @@
"use client";
import juice from "juice";
-import { copyHtml } from "./clipboard";
+import { copyHtmlWhenReady } from "./clipboard";
+
+/**
+ * Clamp `margin` / `padding` to 48px. Poster- and deck-scale templates
+ * routinely use 80-120px gutters that read as luxurious on a 1080 canvas
+ * but blow up in WeChat's ~375-540px article flow. 48 ≈ 8px baseline × 6
+ * lines — the comfortable max for mobile reading.
+ */
+const MAX_FLOW_SPACING_PX = 48;
+
+const STYLE_PROPS = [
+ "color",
+ "background-color",
+ "background-image",
+ "background-position",
+ "background-size",
+ "background-repeat",
+ "font-family",
+ "font-size",
+ "font-style",
+ "font-weight",
+ "line-height",
+ "letter-spacing",
+ "text-align",
+ "text-decoration",
+ "text-transform",
+ "white-space",
+ "word-break",
+ "overflow-wrap",
+ "list-style-type",
+ "list-style-position",
+ "border-collapse",
+ "box-shadow",
+ "text-shadow",
+ "opacity",
+] as const;
/**
* Take a full HTML document, extract <body> content, inline all CSS via juice,
@@ -13,21 +48,15 @@ export function toWechatHtml(fullHtml: string): string {
const doc = new DOMParser().parseFromString(fullHtml, "text/html");
- // Collect all <style> contents + linked stylesheets we cannot follow
+ // Collect all <style> contents + linked stylesheets we cannot follow.
const styles: string[] = [];
doc.querySelectorAll("style").forEach((s) => {
styles.push(s.textContent ?? "");
});
- // Tailwind via CDN won't be accessible to juice — but the runtime DOM in our
- // preview iframe has *generated* inline styles via `getComputedStyle`. Rather
- // than trying to scrape them, we let users render the fragment in a hidden
- // iframe, walk computed styles, and inline them. Here we do the simple
- // <style>-based inlining plus a fallback marker.
const css = styles.join("\n");
const bodyHtml = doc.body?.innerHTML ?? fullHtml;
- // Tag top-level children
const wrap = document.createElement("div");
wrap.innerHTML = bodyHtml;
Array.from(wrap.children).forEach((child) => {
@@ -46,11 +75,284 @@ export function toWechatHtml(fullHtml: string): string {
inlined = tagged;
}
- // Wrap in a section element so WeChat treats it as a content block
return `<section data-tool="html-anything">${inlined}</section>`;
}
+/**
+ * Export the rendered preview DOM. This preserves class/CDN/runtime styles by
+ * reading computed styles from the browser before writing clipboard HTML.
+ */
+export function toWechatHtmlFromDocument(renderedDoc: Document): string {
+ const body = renderedDoc.body;
+ if (!body) return "";
+
+ const view = renderedDoc.defaultView ?? window;
+ const wrap = document.createElement("div");
+ for (const child of Array.from(body.childNodes)) {
+ if (child.nodeType === Node.ELEMENT_NODE) {
+ const element = child as Element;
+ if (isComputedHidden(element, view)) continue;
+ }
+ const clone = child.cloneNode(true);
+ if (child.nodeType === Node.ELEMENT_NODE && clone.nodeType === Node.ELEMENT_NODE) {
+ inlineComputedTree(child as Element, clone as Element, view);
+ (clone as Element).setAttribute("data-tool", "html-anything");
+ }
+ wrap.appendChild(clone);
+ }
+
+ const section = document.createElement("section");
+ section.setAttribute("data-tool", "html-anything");
+ const bodyStyle = computedStyleText(body, view, { skipMargin: true });
+ if (bodyStyle) section.setAttribute("style", bodyStyle);
+ section.innerHTML = wrap.innerHTML;
+ return section.outerHTML;
+}
+
+/**
+ * Render the complete source document in an offscreen iframe for every
+ * toolbar WeChat export. This keeps Source/Log tabs and DeckViewer from
+ * silently switching the export to a partial or unrendered document.
+ */
+export async function renderToWechatHtml(fullHtml: string): Promise<string> {
+ if (typeof window === "undefined") return toWechatHtml(fullHtml);
+
+ const iframe = document.createElement("iframe");
+ iframe.setAttribute("sandbox", "allow-scripts allow-same-origin");
+ iframe.style.cssText =
+ "position: fixed; left: 0; top: 0; width: 1280px; height: 960px; border: 0; opacity: 0; pointer-events: none; z-index: -2147483648;";
+ iframe.srcdoc = fullHtml;
+ document.body.appendChild(iframe);
+
+ try {
+ await waitForIframeLoad(iframe);
+ const renderedDoc = iframe.contentDocument;
+ if (!renderedDoc?.body) return toWechatHtml(fullHtml);
+ await waitForDocumentReady(renderedDoc);
+ return toWechatHtmlFromDocument(renderedDoc);
+ } catch {
+ return toWechatHtml(fullHtml);
+ } finally {
+ iframe.remove();
+ }
+}
+
export async function copyToWechat(fullHtml: string): Promise<void> {
- const html = toWechatHtml(fullHtml);
- await copyHtml(html);
+ await copyHtmlWhenReady(renderToWechatHtml(fullHtml));
+}
+
+function waitForIframeLoad(iframe: HTMLIFrameElement): Promise<void> {
+ return new Promise((resolve) => {
+ let settled = false;
+ let timeout = 0;
+ const finish = () => {
+ if (settled) return;
+ settled = true;
+ window.clearTimeout(timeout);
+ iframe.removeEventListener("load", finish);
+ resolve();
+ };
+ iframe.addEventListener("load", finish, { once: true });
+ timeout = window.setTimeout(finish, 8000);
+ });
+}
+
+async function waitForDocumentReady(doc: Document): Promise<void> {
+ try {
+ const fonts = (doc as Document & { fonts?: FontFaceSet }).fonts;
+ if (fonts?.ready) await fonts.ready;
+ } catch {
+ // Font loading is best effort; computed styles are still useful without it.
+ }
+
+ const view = doc.defaultView ?? window;
+ await nextFrame(view);
+ await nextFrame(view);
+ await new Promise<void>((resolve) => view.setTimeout(resolve, 50));
+
+ for (const animation of doc.getAnimations?.() ?? []) {
+ try {
+ const timing = animation.effect?.getComputedTiming();
+ if (Number.isFinite(Number(timing?.endTime))) animation.finish();
+ animation.pause();
+ } catch {
+ // Infinite or script-controlled animations are sampled at their current state.
+ }
+ }
+ await nextFrame(view);
+}
+
+function nextFrame(view: Window): Promise<void> {
+ return new Promise((resolve) => view.requestAnimationFrame(() => resolve()));
+}
+
+function inlineComputedTree(source: Element, clone: Element, view: Window): void {
+ if (isComputedHidden(source, view)) {
+ clone.remove();
+ return;
+ }
+ const styleText = computedStyleText(source, view);
+ if (styleText) clone.setAttribute("style", styleText);
+ materializePseudos(source, clone, view);
+
+ // Pseudo-elements are materialized only in the clone, so global descendant
+ // lists no longer have matching indexes. Recurse through real element
+ // children in lockstep and ignore the generated pseudo spans when matching.
+ const sourceChildren = Array.from(source.children);
+ const cloneChildren = Array.from(clone.children).filter(
+ (child) => !child.hasAttribute("data-pseudo"),
+ );
+ for (let i = 0; i < sourceChildren.length; i++) {
+ const cloneChild = cloneChildren[i];
+ if (cloneChild) inlineComputedTree(sourceChildren[i], cloneChild, view);
+ }
+}
+
+function isComputedHidden(element: Element, view: Window): boolean {
+ try {
+ return view.getComputedStyle(element).display === "none";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * WeChat strips pseudo-elements entirely, and our computed-style walk only sees
+ * real DOM nodes. Read ::before/::after from getComputedStyle and turn each into
+ * a real <span> child so the rendered content (✓, Recommended badge, etc.) survives.
+ */
+function materializePseudos(source: Element, clone: Element, view: Window): void {
+ const before = buildPseudoNode(source, view, "::before");
+ if (before) clone.insertBefore(before, clone.firstChild);
+ const after = buildPseudoNode(source, view, "::after");
+ if (after) clone.appendChild(after);
+}
+
+function buildPseudoNode(source: Element, view: Window, pseudo: "::before" | "::after"): HTMLElement | null {
+ let computed: CSSStyleDeclaration;
+ try {
+ computed = view.getComputedStyle(source, pseudo);
+ } catch {
+ return null;
+ }
+ const text = unquoteContent(computed.getPropertyValue("content").trim());
+ if (text === null) return null;
+
+ const span = document.createElement("span");
+ span.setAttribute("data-pseudo", pseudo);
+ if (text) span.textContent = text;
+ const style = computedStyleText(source, view, { pseudoComputed: computed });
+ if (style) span.setAttribute("style", style);
+ return span;
+}
+
+/**
+ * getComputedStyle returns `content` as a CSS token: a string literal (with quotes),
+ * `none`, `normal`, or a function like `attr()` / `counter()` / `url()`. We only
+ * materialize string-literal contents — anything else (including the no-content
+ * sentinels) returns null so the pseudo is skipped.
+ */
+function unquoteContent(value: string): string | null {
+ if (!value || value === "none" || value === "normal") return null;
+ const match = value.match(/^"((?:[^"\\]|\\.)*)"$/) ?? value.match(/^'((?:[^'\\]|\\.)*)'$/);
+ if (!match) return null;
+ return match[1].replace(/\\(.)/g, "$1");
+}
+
+function computedStyleText(
+ el: Element,
+ view: Window,
+ opts?: { skipMargin?: boolean; pseudoComputed?: CSSStyleDeclaration },
+): string {
+ let computed: CSSStyleDeclaration;
+ if (opts?.pseudoComputed) {
+ computed = opts.pseudoComputed;
+ } else {
+ try {
+ computed = view.getComputedStyle(el);
+ } catch {
+ // Cross-origin frames or detached nodes throw here. Skip silently rather than abort the export.
+ return "";
+ }
+ }
+ const styles: string[] = [];
+
+ addBox(styles, computed, "margin", opts?.skipMargin);
+ addBox(styles, computed, "padding");
+ addBorder(styles, computed);
+ addBox(styles, computed, "border-radius");
+
+ for (const prop of STYLE_PROPS) {
+ addProp(styles, computed, prop);
+ }
+
+ return styles.join("; ");
+}
+
+function addProp(styles: string[], computed: CSSStyleDeclaration, prop: string): void {
+ const value = computed.getPropertyValue(prop).trim();
+ if (!shouldKeep(prop, value)) return;
+ styles.push(`${prop}: ${value}`);
+}
+
+function addBox(
+ styles: string[],
+ computed: CSSStyleDeclaration,
+ prefix: "margin" | "padding" | "border-radius",
+ skip = false,
+): void {
+ if (skip) return;
+ const keys =
+ prefix === "border-radius"
+ ? ["top-left", "top-right", "bottom-right", "bottom-left"].map((x) => `border-${x}-radius`)
+ : ["top", "right", "bottom", "left"].map((x) => `${prefix}-${x}`);
+ const values = keys.map((key) => normalizeBoxValue(prefix, computed.getPropertyValue(key).trim()));
+ if (values.every((value) => !shouldKeep(prefix, value))) return;
+ if (values.every((value) => value === values[0])) {
+ styles.push(`${prefix}: ${values[0]}`);
+ return;
+ }
+ keys.forEach((key, idx) => {
+ if (shouldKeep(prefix, values[idx])) styles.push(`${key}: ${values[idx]}`);
+ });
+}
+
+function addBorder(styles: string[], computed: CSSStyleDeclaration): void {
+ for (const side of ["top", "right", "bottom", "left"]) {
+ const width = computed.getPropertyValue(`border-${side}-width`).trim();
+ const style = computed.getPropertyValue(`border-${side}-style`).trim();
+ const color = computed.getPropertyValue(`border-${side}-color`).trim();
+ if (!shouldKeep("border-width", width) || style === "none" || !style) continue;
+ styles.push(`border-${side}: ${width} ${style} ${color}`);
+ }
+}
+
+function shouldKeep(prop: string, value: string): boolean {
+ if (!value) return false;
+ if (value === "initial" || value === "inherit" || value === "unset") return false;
+ if (prop.includes("color") && (value === "rgba(0, 0, 0, 0)" || value === "transparent")) return false;
+ if (prop === "opacity" && (value === "1" || value === "1.0")) return false;
+ if (prop.includes("shadow") && value === "none") return false;
+ if (prop.includes("image") && value === "none") return false;
+ if (prop.includes("radius") && isZero(value)) return false;
+ if ((prop.includes("width") || prop.includes("height")) && value === "auto") return false;
+ if ((prop === "margin" || prop === "padding") && isZero(value)) return false;
+ if (prop.startsWith("border") && isZero(value)) return false;
+ return true;
+}
+
+function normalizeBoxValue(prefix: "margin" | "padding" | "border-radius", value: string): string {
+ if (prefix === "margin" && value.startsWith("-")) return "";
+ if (prefix !== "margin" && prefix !== "padding") return value;
+
+ const px = value.match(/^(-?\d+(?:\.\d+)?)px$/);
+ if (!px) return value;
+
+ const n = Number(px[1]);
+ if (n > MAX_FLOW_SPACING_PX) return `${MAX_FLOW_SPACING_PX}px`;
+ return value;
+}
+
+function isZero(value: string): boolean {
+ return /^0(?:px|em|rem|%)?(?:\s+0(?:px|em|rem|%)?){0,3}$/.test(value);
}