Skip to content

Commit 1d6ed16

Browse files
committed
fix(shared): keep hosted reloads unpadded without exposing a marker
The hosted marker was appended to window.name at load, so a page's own scripts saw a value they never set and JSON kept in window.name broke. It also outlived its document, and WebKit clears window.name when a sandboxed page reloads, so iOS reloads gained the gutter anyway. Mark the page as it unloads instead, in window.name (which Chromium keeps across the reload) and history.state (which WebKit keeps), and remove the mark on the next load before the page's scripts run. A mark left at another path no longer counts. The layout guide now says the html{padding:0} opt-out must be unlayered.
1 parent 5f927bb commit 1d6ed16

2 files changed

Lines changed: 98 additions & 7 deletions

File tree

‎packages/shared/src/htmlRender.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import * as NodeVM from "node:vm";
2+
13
import { describe, expect, it } from "vite-plus/test";
24

35
import {
6+
htmlRenderThemeFragment,
47
injectHtmlRenderBootstrap,
58
readHtmlRenderImageRequest,
69
readHtmlRenderLinkRequest,
@@ -9,6 +12,89 @@ import { htmlRenderFromToolItem } from "./toolOutput.ts";
912

1013
const reference = { attachmentId: "thread-abc-123.html", title: "Chart", height: 420 };
1114

15+
const bootstrap = injectHtmlRenderBootstrap("<p>x</p>").match(/<script>([\s\S]*)<\/script>/)![1]!;
16+
const themed = htmlRenderThemeFragment({
17+
appearance: "dark",
18+
variables: { "--background": "#000" },
19+
});
20+
21+
// Loads the bootstrap the way a browser runs it: `window` is top-level unless
22+
// framed, and `unload` fires pagehide and returns what a reload could inherit.
23+
function openPage(options: {
24+
readonly framed?: boolean;
25+
readonly hash?: string;
26+
readonly name?: string;
27+
readonly state?: unknown;
28+
readonly pathname?: string;
29+
}) {
30+
const style = { textContent: "" };
31+
const pagehide: Array<(event: { persisted: boolean }) => void> = [];
32+
const history: { state: unknown; replaceState: (state: unknown) => void } = {
33+
state: options.state ?? null,
34+
replaceState(state: unknown) {
35+
history.state = state;
36+
},
37+
};
38+
const window = {
39+
name: options.name ?? "",
40+
parent: {},
41+
addEventListener: (type: string, listener: (event: { persisted: boolean }) => void) => {
42+
if (type === "pagehide") pagehide.push(listener);
43+
},
44+
};
45+
if (!options.framed) window.parent = window;
46+
NodeVM.runInNewContext(bootstrap, {
47+
window,
48+
history,
49+
location: { hash: options.hash ?? "", pathname: options.pathname ?? "/page.html", search: "" },
50+
document: { getElementById: () => style, addEventListener() {}, documentElement: {} },
51+
});
52+
return {
53+
window,
54+
history,
55+
padded: () => style.textContent.includes("padding:16px"),
56+
unload: () => {
57+
for (const listener of pagehide) listener({ persisted: false });
58+
return { name: window.name, state: history.state };
59+
},
60+
};
61+
}
62+
63+
describe("html render bootstrap", () => {
64+
it.each([
65+
{ page: "standalone", options: {}, padded: true },
66+
{ page: "framed", options: { framed: true }, padded: false },
67+
{ page: "top-level themed", options: { hash: themed }, padded: false },
68+
])("gives only a page opened on its own the gutter: $page", ({ options, padded }) => {
69+
expect(openPage(options).padded()).toBe(padded);
70+
});
71+
72+
it.each([
73+
{ engine: "Chromium", kept: "name" },
74+
{ engine: "WebKit", kept: "state" },
75+
] as const)(
76+
"keeps a hosted page unpadded through its own reload in $engine, showing it only its own values",
77+
({ kept }) => {
78+
const hosted = openPage({ hash: themed, state: { tab: 1 } });
79+
expect(hosted.window.name).toBe("");
80+
expect(hosted.history.state).toEqual({ tab: 1 });
81+
hosted.window.name = "saved";
82+
const left = hosted.unload();
83+
const reloaded = openPage({ [kept]: left[kept] });
84+
expect(reloaded.padded()).toBe(false);
85+
expect(reloaded.window.name).toBe(kept === "name" ? "saved" : "");
86+
expect(reloaded.history.state).toEqual(kept === "state" ? { tab: 1 } : null);
87+
},
88+
);
89+
90+
it("pads a standalone page that the tab opens after a hosted one", () => {
91+
const hosted = openPage({ hash: themed, pathname: "/a.html" });
92+
const next = openPage({ name: hosted.unload().name, pathname: "/b.html" });
93+
expect(next.padded()).toBe(true);
94+
expect(next.window.name).toBe("");
95+
});
96+
});
97+
1298
describe("injectHtmlRenderBootstrap", () => {
1399
it("puts the theme ahead of the page's own head content", () => {
14100
const html =

‎packages/shared/src/htmlRender.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ export const HTML_RENDER_LAYOUT_GUIDE = [
244244
"The page sits on the thread's own background, so by default leave html, body, and the outermost element with no background color. This overrides general style preferences such as a fixed black page background.",
245245
"Use a fluid width with no horizontal padding on the outermost element, and no outer card, border, or banner title: the page is part of your reply.",
246246
"Size widths against the container (%, auto, max-width), not the viewport (vw, dvw, svw, lvw, or window.innerWidth) or a fixed pixel width: opened on its own, the page gets a 16px gutter on every side, so anything as wide as the viewport overflows it.",
247-
"A page that must run edge to edge when opened on its own, such as a full-bleed canvas, can remove that gutter by setting html{padding:0}. Treat it as an exception, not a default: do not add it routinely, and do not put html in a reset such as html,body{margin:0;padding:0}. The base stylesheet already zeroes the body margin, so reset body alone, or use *{margin:0;padding:0}, which leaves the gutter.",
247+
"A page that must run edge to edge when opened on its own, such as a full-bleed canvas, can remove that gutter with an unlayered html{padding:0} rule; a rule inside @layer, such as a Tailwind v4 class, loses to the gutter. Treat it as an exception, not a default: do not add it routinely, and do not put html in a reset such as html,body{margin:0;padding:0}. The base stylesheet already zeroes the body margin, so reset body alone, or use *{margin:0;padding:0}, which leaves the gutter.",
248248
"If a box needs its own background (a mock of a specific screen, a panel that must stand apart), give it at least 16px of padding on every side and var(--radius) corners, so content never touches its edge.",
249249
"Give charts fixed pixel heights rather than heights that scale with width.",
250250
"Let content set the page's height. The frame grows to fit the page, so a height that follows the viewport makes it grow again and again: html_preview and html_render reject vh, svh, lvh, and dvh units, and height:100% on html or body has the same problem.",
@@ -383,12 +383,17 @@ const BASE_CSS =
383383
":where(img:not(a[href] img,button img)){cursor:zoom-in}";
384384

385385
// Hosted pages get their gutter from the client. Standalone pages need one
386-
// because the inline stylesheet removes the body margin. A theme fragment
387-
// identifies top-level mobile WebViews and headless measurements as hosted.
388-
// The bootstrap strips that fragment, so it also marks the window's name, which
389-
// survives the page reloading itself in the same WebView.
386+
// because the inline stylesheet removes the body margin. The rule stays
387+
// unlayered so a `*` reset, which loses to it on specificity, keeps the gutter.
388+
// A theme fragment identifies top-level mobile WebViews and headless
389+
// measurements as hosted. The bootstrap strips that fragment and a sandboxed
390+
// page has no storage, so a hosted page leaves a mark as it unloads. Reloading
391+
// a sandboxed page keeps window.name in Chromium and history.state in WebKit,
392+
// so the mark goes in both. The next load takes it off before the page's
393+
// scripts run: a reload stays hosted, and the page only sees values it set.
394+
// A mark left by a page at another path is removed but does not count.
390395
const STANDALONE_CSS = "html{box-sizing:border-box;padding:16px}";
391-
const HOSTED_WINDOW_NAME = "t3-hosted";
396+
const HOSTED_MARK = "t3-hosted:";
392397

393398
function rootRule(theme: HtmlRenderTheme): string {
394399
const declarations = Object.entries(theme.variables)
@@ -412,7 +417,7 @@ function rootRule(theme: HtmlRenderTheme): string {
412417
// field has focus or the page handled it: the deciding listener is added while
413418
// the key dispatches, so it runs after every listener the page has. Keys
414419
// match as resolveEventKeys reads them, so the client accepts what it claims.
415-
const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)};if(window.parent===window&&!/[#&]${THEME_FRAGMENT_KEY}=/.test(location.hash)&&window.name.indexOf(${JSON.stringify(HOSTED_WINDOW_NAME)})<0){b+=${JSON.stringify(STANDALONE_CSS)};s.textContent+=${JSON.stringify(STANDALONE_CSS)};}function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{var m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(m){a(JSON.parse(decodeURIComponent(m[1])));if(window.parent===window&&window.name.indexOf(${JSON.stringify(HOSTED_WINDOW_NAME)})<0)window.name+=${JSON.stringify(HOSTED_WINDOW_NAME)};history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href,metaKey:e.metaKey,ctrlKey:e.ctrlKey}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);window.addEventListener("click",function(e){var t=e.composedPath()[0],u;if(!e.isTrusted||e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||!t||t.tagName!=="IMG"||t.closest("a[href],button"))return;u=t.currentSrc||t.src;if(u)setTimeout(function(){if(!e.defaultPrevented)window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||""}},"*");});});var K=[],B=[],C=${JSON.stringify(EVENT_CODE_SHORTCUT_KEYS)};window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(e.source===window.parent&&d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(SHORTCUTS_METHOD)}&&p&&Array.isArray(p.shortcuts)&&Array.isArray(p.blocked)){K=p.shortcuts;B=p.blocked;}});window.addEventListener("keydown",function(e){var t=e.composedPath()[0],c=e.code||"",l=e.key.toLowerCase(),x=/^[a-z]$/.test(l)?[l]:[l,/^Key[A-Z]$/.test(c)?c.slice(3).toLowerCase():"",C.hasOwnProperty(c)?C[c]:""],f,m=function(s){return s&&s.metaKey===e.metaKey&&s.ctrlKey===e.ctrlKey&&s.shiftKey===e.shiftKey&&s.altKey===e.altKey&&x.indexOf(s.key)>-1;};if(!e.isTrusted||e.isComposing||e.getModifierState("AltGraph")&&!/^[a-z0-9]$/i.test(e.key)||t&&(t.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(t.tagName))||!K.some(m)||B.some(m))return;f=function(v){window.removeEventListener("keydown",f);if(v!==e||e.defaultPrevented)return;e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(KEY_DOWN_METHOD)},params:{key:e.key,code:e.code,metaKey:e.metaKey,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,repeat:e.repeat}},"*");};window.addEventListener("keydown",f);setTimeout(function(){window.removeEventListener("keydown",f);});},true);}})();`;
420+
const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_CSS)},m=/[#&]${THEME_FRAGMENT_KEY}=([^&]*)/.exec(location.hash);if(window.parent===window){var M=${JSON.stringify(HOSTED_MARK)},w=window.name,i=w.lastIndexOf(M),q=history.state,x=!!m;if(i>-1){x=x||w.slice(i)===M+location.pathname;window.name=w.slice(0,i);}if(q&&typeof q==="object"&&M in q){x=true;try{history.replaceState(q[M],"");}catch(y){}}if(x)window.addEventListener("pagehide",function(e){var r={};if(e.persisted)return;window.name+=M+location.pathname;r[M]=history.state;try{history.replaceState(r,"");}catch(y){}});else{b+=${JSON.stringify(STANDALONE_CSS)};s.textContent+=${JSON.stringify(STANDALONE_CSS)};}}function a(t){if(!t||typeof t!=="object"||!t.variables||typeof t.variables!=="object")return;var c=":root{color-scheme:"+(t.appearance==="light"?"light":"dark")+";";for(var k in t.variables){if(/^--[a-z0-9-]+$/.test(k))c+=k+":"+String(t.variables[k]).replace(/[;{}<>]/g,"")+";";}s.textContent=c+"}"+b;}try{if(m){a(JSON.parse(decodeURIComponent(m[1])));history.replaceState(history.state,"",location.pathname+location.search);}}catch(e){}window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(HOST_CONTEXT_CHANGED_METHOD)}&&p&&p.styles)a({appearance:p.theme,variables:p.styles.variables});});document.addEventListener("click",function(e){var l=e.isTrusted?e.composedPath().find(function(t){return t&&t.matches&&t.matches("a[href]");}):null,u;if(!l)return;try{u=new URL(l.getAttribute("href"),document.baseURI);}catch(x){return;}if(!/^https?:$/.test(u.protocol)||u.href.split("#")[0]===location.href.split("#")[0])return;if(window.parent!==window){e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",id:"t3-link-"+(++n),method:${JSON.stringify(OPEN_LINK_METHOD)},params:{url:u.href,metaKey:e.metaKey,ctrlKey:e.ctrlKey}},"*");}else{l.setAttribute("target","_blank");l.setAttribute("rel","noopener");}},true);if(window.parent!==window){var h,o,z=function(){var r=document.documentElement,v=Math.ceil(r.scrollHeight>r.clientHeight?r.scrollHeight:r.getBoundingClientRect().height);if(v===h)return;h=v;window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(SIZE_CHANGED_METHOD)},params:{height:v}},"*");};if(window.ResizeObserver){o=new ResizeObserver(z);o.observe(document.documentElement);}document.addEventListener("DOMContentLoaded",function(){if(o&&document.body)o.observe(document.body);z();});window.addEventListener("load",z);window.addEventListener("click",function(e){var t=e.composedPath()[0],u;if(!e.isTrusted||e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||!t||t.tagName!=="IMG"||t.closest("a[href],button"))return;u=t.currentSrc||t.src;if(u)setTimeout(function(){if(!e.defaultPrevented)window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||""}},"*");});});var K=[],B=[],C=${JSON.stringify(EVENT_CODE_SHORTCUT_KEYS)};window.addEventListener("message",function(e){var d=e.data,p=d&&d.params;if(e.source===window.parent&&d&&d.jsonrpc==="2.0"&&d.method===${JSON.stringify(SHORTCUTS_METHOD)}&&p&&Array.isArray(p.shortcuts)&&Array.isArray(p.blocked)){K=p.shortcuts;B=p.blocked;}});window.addEventListener("keydown",function(e){var t=e.composedPath()[0],c=e.code||"",l=e.key.toLowerCase(),x=/^[a-z]$/.test(l)?[l]:[l,/^Key[A-Z]$/.test(c)?c.slice(3).toLowerCase():"",C.hasOwnProperty(c)?C[c]:""],f,m=function(s){return s&&s.metaKey===e.metaKey&&s.ctrlKey===e.ctrlKey&&s.shiftKey===e.shiftKey&&s.altKey===e.altKey&&x.indexOf(s.key)>-1;};if(!e.isTrusted||e.isComposing||e.getModifierState("AltGraph")&&!/^[a-z0-9]$/i.test(e.key)||t&&(t.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(t.tagName))||!K.some(m)||B.some(m))return;f=function(v){window.removeEventListener("keydown",f);if(v!==e||e.defaultPrevented)return;e.preventDefault();window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(KEY_DOWN_METHOD)},params:{key:e.key,code:e.code,metaKey:e.metaKey,ctrlKey:e.ctrlKey,shiftKey:e.shiftKey,altKey:e.altKey,repeat:e.repeat}},"*");};window.addEventListener("keydown",f);setTimeout(function(){window.removeEventListener("keydown",f);});},true);}})();`;
416421

417422
function bootstrapMarkup(markup: string): string {
418423
const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");

0 commit comments

Comments
 (0)