Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep HTML preview canvases transparent (#1119)

Generd94f6e4c0996
diff --git a/src/web/src/lib/community/html-attachment-preview.test.ts b/src/web/src/lib/community/html-attachment-preview.test.ts
index 60e8e362d..619458580 100644
--- a/src/web/src/lib/community/html-attachment-preview.test.ts
+++ b/src/web/src/lib/community/html-attachment-preview.test.ts
@@ -48,8 +48,8 @@ describe("HTML preview response preparation", () => {
describe("generated HTML bootstrap", () => {
- it.each(["light dark", "only light"])("preserves the author's %s scheme and colors when styles load after the theme", async (scheme) => {
- const dom = new JSDOM(prepareHtmlPreview(`<!doctype html><html><head><style data-authored>:root{color-scheme:${scheme}}html,body{background:transparent}#authored{background:#73a3b2;color:#112233}</style></head><body><section id="authored">Original colors</section><input id="state" value="original"></body></html>`), {
+ it.each(["light dark", "only light"])("preserves the author's %s scheme and internal colors while overriding document backgrounds", async (scheme) => {
+ const dom = new JSDOM(prepareHtmlPreview(`<!doctype html><html style="background:#102030!important"><head><style data-authored>:root{color-scheme:${scheme};background:#ff0000!important}html,body{background:linear-gradient(red,blue)!important}#authored{background:#73a3b2;color:#112233}</style></head><body style="background:#203040!important"><section id="authored">Original colors</section><input id="state" value="original"></body></html>`), {
runScripts: "dangerously",
beforeParse(window) {
Object.defineProperty(window, "parent", { value: { postMessage: vi.fn() } })
@@ -75,6 +75,75 @@ describe("generated HTML bootstrap", () => {
} finally { dom.window.close() }
})
+ it("keeps root/body backgrounds transparent after style writes and body replacement with one observer", async () => {
+ const frames = new Map<number, FrameRequestCallback>()
+ let frameId = 0, observerCount = 0, mutationCalls = 0
+ const dom = new JSDOM(prepareHtmlPreview('<html style="background:red!important;padding:17px;color:#123456"><body style="background:blue!important;margin:12px;padding:7px"><section id="card" style="background:#73a3b2">Card</section><input id="state" value="original"></body></html>'), {
+ runScripts: "dangerously",
+ beforeParse(window) {
+ Object.defineProperty(window, "parent", { value: { postMessage: vi.fn() } })
+ window.requestAnimationFrame = callback => { frames.set(++frameId, callback); return frameId }
+ const NativeObserver = window.MutationObserver
+ window.MutationObserver = class extends NativeObserver {
+ constructor(callback: MutationCallback) {
+ super((records, observer) => { mutationCalls += 1; callback(records, observer) })
+ observerCount += 1
+ }
+ }
+ },
+ })
+ try {
+ await new Promise<void>(resolve => dom.window.document.addEventListener("DOMContentLoaded", () => resolve(), { once: true }))
+ const { document } = dom.window
+ const input = document.querySelector<HTMLInputElement>("#state")!
+ input.value = "retained edit"
+ async function settle() {
+ for (let cycle = 0; cycle < 5; cycle += 1) {
+ await Promise.resolve()
+ for (const [id, callback] of [...frames]) { frames.delete(id); callback(0) }
+ }
+ await Promise.resolve()
+ expect(frames.size).toBe(0)
+ }
+ function canvas() {
+ for (const element of [document.documentElement, document.body]) {
+ expect(element.style.getPropertyValue("background")).toBe("transparent")
+ expect(element.style.getPropertyPriority("background")).toBe("important")
+ expect(dom.window.getComputedStyle(element).backgroundColor).toBe("rgba(0, 0, 0, 0)")
+ }
+ expect(document.documentElement.style.padding).toBe("17px")
+ expect(dom.window.getComputedStyle(document.documentElement).color).toBe("rgb(18, 52, 86)")
+ expect(document.body.style.margin).toBe("12px")
+ expect(document.body.style.padding).toBe("7px")
+ expect(dom.window.getComputedStyle(document.querySelector("#card")!).backgroundColor).toBe("rgb(115, 163, 178)")
+ expect(document.querySelector("#state")).toBe(input)
+ expect(input.value).toBe("retained edit")
+ }
+ await settle()
+ canvas()
+ expect(observerCount).toBe(1)
+ document.documentElement.style.setProperty("background", "linear-gradient(red,blue)", "important")
+ document.body.style.cssText = "background:yellow!important;margin:12px;padding:7px"
+ await settle()
+ canvas()
+ const replacement = document.createElement("body")
+ replacement.style.cssText = "background:purple!important;margin:12px;padding:7px"
+ while (document.body.firstChild) replacement.appendChild(document.body.firstChild)
+ document.body.replaceWith(replacement)
+ await settle()
+ canvas()
+ const calls = mutationCalls
+ for (const dark of [true, false, true]) {
+ dom.window.dispatchEvent(new dom.window.MessageEvent("message", { source: dom.window.parent,
+ data: { type: "alook-html-theme", dark, variables: { "--background": dark ? "#121314" : "#ffffff" } } }))
+ }
+ await settle()
+ canvas()
+ expect(observerCount).toBe(1)
+ expect(mutationCalls - calls).toBeLessThanOrEqual(2)
+ } finally { frames.clear(); dom.window.close() }
+ })
+
it("requests the host theme, reports readiness and rejects a different sender", async () => {
const post = vi.fn()
const frames = new Map<number, FrameRequestCallback>()
diff --git a/src/web/src/lib/community/html-attachment-preview.ts b/src/web/src/lib/community/html-attachment-preview.ts
index f80401e71..726a054a2 100644
--- a/src/web/src/lib/community/html-attachment-preview.ts
+++ b/src/web/src/lib/community/html-attachment-preview.ts
@@ -51,7 +51,7 @@ export async function readHtmlPreview(body: ReadableStream<Uint8Array>, signal?:
const CSS_SOURCE = /<!--[\s\S]*?(?:-->|$)|<style\b[^>]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi
const VIEWPORT_HEIGHT = /(?<![\w.+/])(?:\d+(?:\.\d+)?|\.\d+)[sld]?vh(?![\w-])/i
-const BASE_CSS = "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans,system-ui);font-size:15px;line-height:1.6;color-scheme:light dark}body{margin:0}code,pre,kbd,samp{font-family:var(--font-mono,monospace)}:focus-visible{outline:2px solid var(--ring);outline-offset:-2px}"
+const BASE_CSS = "html{background:transparent;color:var(--foreground);font-family:var(--font-sans,system-ui);font-size:15px;line-height:1.6;color-scheme:light dark}body{margin:0;background:transparent}code,pre,kbd,samp{font-family:var(--font-mono,monospace)}:focus-visible{outline:2px solid var(--ring);outline-offset:-2px}"
const BOOTSTRAP = String.raw`(() => {
const framed = window.parent !== window;
const themeStyle = document.getElementById("alook-preview-theme");
@@ -72,6 +72,11 @@ const BOOTSTRAP = String.raw`(() => {
}
}
function schedule() {
+ for (const element of [document.documentElement, document.body]) {
+ if (element && (element.style.getPropertyValue("background") !== "transparent" || element.style.getPropertyPriority("background") !== "important")) {
+ element.style.setProperty("background", "transparent", "important");
+ }
+ }
if (pending) return;
pending = true;
requestAnimationFrame(measure);
@@ -88,6 +93,8 @@ const BOOTSTRAP = String.raw`(() => {
document.documentElement.classList.toggle("dark", data.dark === true);
schedule();
});
+ if (window.MutationObserver) new MutationObserver(schedule).observe(document.documentElement, { subtree: true, childList: true, characterData: true, attributes: true });
+ schedule();
send("alook-html-theme-request");
document.addEventListener("DOMContentLoaded", () => {
send("alook-html-ready");
@@ -97,7 +104,6 @@ const BOOTSTRAP = String.raw`(() => {
observer.observe(document.documentElement);
observer.observe(document.body);
}
- if (window.MutationObserver) new MutationObserver(schedule).observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
});
window.addEventListener("load", schedule);
document.addEventListener("load", schedule, true);
diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
index 26adaf935..adf522434 100644
--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts
@@ -936,14 +936,14 @@ test("HTML attachment markers render once with interactive isolated content acro
await expect.poll(async () => {
const host = await iframe.evaluate((element, tokens) => {
const root = getComputedStyle(document.documentElement), painted = getComputedStyle(element)
- return { dark: document.documentElement.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color, background: root.backgroundColor }
+ return { dark: document.documentElement.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color }
}, names)
const embedded = await content.locator("html").evaluate((element, tokens) => {
const root = getComputedStyle(element), painted = getComputedStyle(document.body)
- return { dark: element.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color, background: painted.backgroundColor }
+ return { dark: element.classList.contains("dark"), variables: Object.fromEntries(tokens.map((name) => [name, root.getPropertyValue(`--${name}`).trim()])), foreground: painted.color, canvas: { html: root.backgroundColor, body: painted.backgroundColor, htmlImage: root.backgroundImage, bodyImage: painted.backgroundImage } }
}, names)
- return { hostDark: host.dark, frameDark: embedded.dark, tokens: JSON.stringify(embedded.variables) === JSON.stringify(host.variables), foreground: embedded.foreground === host.foreground, background: embedded.background === host.background }
- }).toEqual({ hostDark: dark, frameDark: dark, tokens: true, foreground: true, background: true })
+ return { hostDark: host.dark, frameDark: embedded.dark, tokens: JSON.stringify(embedded.variables) === JSON.stringify(host.variables), foreground: embedded.foreground === host.foreground, canvas: embedded.canvas }
+ }).toEqual({ hostDark: dark, frameDark: dark, tokens: true, foreground: true, canvas: { html: "rgba(0, 0, 0, 0)", body: "rgba(0, 0, 0, 0)", htmlImage: "none", bodyImage: "none" } })
await expect(iframe).toHaveCount(1)
await expect(iframe).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")
}
@@ -999,7 +999,7 @@ test("HTML attachment markers render once with interactive isolated content acro
contentType: "application/json",
})
- const transparentHtml = '<!doctype html><html><head><style>:root{color-scheme:light dark}html,body{margin:0;background:transparent}body{min-height:112px;color:var(--foreground)}#authored{position:absolute;left:0;top:48px;width:160px;height:48px;background:#73a3b2;color:#112233}input{position:absolute;left:180px;top:48px}</style></head><body><div id="authored"></div><input id="state" value="original"></body></html>'
+ const transparentHtml = `<!doctype html><html style="background:purple!important;padding:17px;color:#123456"><head><style>:root{color-scheme:light dark;background:linear-gradient(red,blue)!important}html,body{margin:0;background:orange!important}body{min-height:112px;color:var(--foreground)}#authored{position:absolute;left:0;top:48px;width:160px;height:48px;background:#73a3b2;color:#112233}input{position:absolute;left:180px;top:48px}#repaint{position:absolute;left:180px;top:80px}</style></head><body style="background:yellow!important"><div id="authored"></div><input id="state" value="original"><button id="repaint" onclick="document.documentElement.style.setProperty('background','linear-gradient(red,blue)','important');document.body.style.setProperty('background','red','important');document.getElementById('rows').innerHTML='<div style=height:360px></div>'">Repaint canvas and grow</button><div id="rows"></div></body></html>`
const transparentId = await upload("transparent.html", "text/html", transparentHtml)
await appearance("Dark")
const transparentPreviewUrl = new URL(`/api/community/channels/${channelId}/attachments/${transparentId}?preview=html`, page.url()).href
@@ -1074,7 +1074,21 @@ test("HTML attachment markers render once with interactive isolated content acro
await expect(transparentFrame).toHaveCSS("color-scheme", mode.toLowerCase())
await expect(transparentContent.locator("html")).toHaveCSS("color-scheme", "light dark")
await expect.poll(() => transparentContent.locator("html").evaluate(() => matchMedia("(prefers-color-scheme: dark)").matches)).toBe(mode === "Dark")
- for (const selector of ["html", "body"]) await expect(transparentContent.locator(selector)).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")
+ let growth: { before: number; after: number } | undefined
+ if (mode === "Light") {
+ const before = (await transparentFrame.boundingBox())!.height
+ await transparentContent.getByRole("button", { name: "Repaint canvas and grow", exact: true }).click()
+ await expect.poll(async () => (await transparentFrame.boundingBox())!.height).toBeGreaterThan(before)
+ const after = (await transparentFrame.boundingBox())!.height
+ expect(after).toBeLessThanOrEqual(2000)
+ growth = { before, after }
+ }
+ for (const selector of ["html", "body"]) {
+ await expect(transparentContent.locator(selector)).toHaveCSS("background-color", "rgba(0, 0, 0, 0)")
+ await expect(transparentContent.locator(selector)).toHaveCSS("background-image", "none")
+ }
+ await expect(transparentContent.locator("html")).toHaveCSS("padding-top", "17px")
+ await expect(transparentContent.locator("html")).toHaveCSS("color", "rgb(18, 52, 86)")
await expect(transparentContent.locator("#authored")).toHaveCSS("color", "rgb(17, 34, 51)")
const inline = await transparentPixels(`transparent-canvas-${mode.toLowerCase()}-inline.png`)
await transparentPreview.hover()
@@ -1083,7 +1097,7 @@ test("HTML attachment markers render once with interactive isolated content acro
await expect(transparentActions.getByRole("button")).toHaveCount(1)
await expect(transparentPreview).not.toHaveAttribute("aria-modal", "true")
await expect(transparentContent.locator("#state")).toHaveValue("retained edit")
- canvasSamples.push({ mode, inline })
+ canvasSamples.push({ mode, growth, inline })
}
expect(canvasSamples[1]!.inline.canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]!.inline.canvas.reduce((sum, value) => sum + value, 0))
expect(loading.canvas.reduce((sum, value) => sum + value, 0)).toBeLessThan(canvasSamples[0]!.inline.canvas.reduce((sum, value) => sum + value, 0))
@@ -1093,7 +1107,11 @@ test("HTML attachment markers render once with interactive isolated content acro
await expect(transparentContent.locator("#state")).toHaveValue("retained edit")
expect(await transparentFrame.evaluate((element, original) => element === original, originalTransparentFrame)).toBe(true)
await originalTransparentFrame?.dispose()
- await testInfo.attach("transparent-canvas-pixels.json", { body: JSON.stringify({ loadingCanvas: loading.canvas, loadingCarrier: loading.carrier, themes: canvasSamples }, null, 2), contentType: "application/json" })
+ const originalCanvasFile = await page.request.get(`/api/community/channels/${channelId}/attachments/${transparentId}`)
+ expect(originalCanvasFile.status()).toBe(200)
+ expect(originalCanvasFile.headers()["content-disposition"]).toContain("attachment")
+ expect(await originalCanvasFile.text()).toBe(transparentHtml)
+ await testInfo.attach("transparent-canvas-pixels.json", { body: JSON.stringify({ loadingCanvas: loading.canvas, loadingCarrier: loading.carrier, themes: canvasSamples, originalBytes: Buffer.byteLength(transparentHtml) }, null, 2), contentType: "application/json" })
})
for (const viewport of [{ width: 390, height: 844 }, { width: 834, height: 1112 }, { width: 1280, height: 900 }]) {