@devries-cameron20 / t3code Mirror · read-only / commits / 4c679a21e7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 07:15 UTC

fix(web): page scripts in inline HTML renders no longer scroll the chat (#38832)

Co-authored-by: StudioEtc <james@studioetc.net>

Julius Marminge committed Nov 18, 2026 at 19:10 UTC 4c679a21e73f998832d2c32f9e16078aca28e2c5
5 files changed +122 -4
apps/web/src/components/chat/HtmlRenderFrame.tsx
+1
@@ -92,6 +92,7 @@ export function HtmlRenderFrame(props: {
92 title={title}
93 threadRef={props.threadRef}
94 className="block size-full"
95 + containScroll
96 onContentHeight={(height) => {
97 rememberContentHeight(attachmentId, height);
98 setContentHeight(height);
apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx
+98
@@ -118,6 +118,104 @@ it("keeps the chat in place when a label far from its hidden radio is clicked",
118 expect(scroller.scrollTop).toBe(scrollTop);
119 });
120
121 +const scrollIntoViewPage = injectHtmlRenderBootstrap(`<!doctype html><html><head><style>
122 + .fill { height: 1400px; }
123 + .panel { height: 200px; overflow: auto; }
124 + .card { height: 100px; overflow: hidden; }
125 + .gap { height: 600px; }
126 + .card .gap { height: 300px; }
127 +</style></head><body>
128 + <nav id="top">Index</nav>
129 + <div class="fill"></div>
130 + <div class="panel" id="panel"><div class="gap"></div>
131 + <div class="card" id="card"><div class="gap"></div><p id="deep">Deep</p></div>
132 + </div>
133 +<script>
134 + addEventListener("message", function(event) {
135 + if (event.data?.type !== "scroll-into-view") return;
136 + document.getElementById(event.data.id).scrollIntoView({ block: "nearest" });
137 + parent.postMessage({
138 + type: "scrolled",
139 + id: event.data.id,
140 + card: document.getElementById("card").scrollTop,
141 + panel: document.getElementById("panel").scrollTop,
142 + page: document.scrollingElement.scrollTop,
143 + }, "*");
144 + });
145 +</script></body></html>`);
146 +
147 +// Inline chat frames are fitted and contained; the expanded view keeps native scrolling, since
148 +// its dialog scroller is how the page's own navigation reaches a section.
149 +it.each([
150 + { name: "a fitted inline frame", containScroll: true, fitted: true },
151 + { name: "a fitted expanded frame", containScroll: false, fitted: true },
152 + { name: "a capped inline frame", containScroll: true, fitted: false },
153 +])(
154 + "scrolls only what it should when a page script scrolls into view in $name",
155 + async (frameCase) => {
156 + const src = URL.createObjectURL(new Blob([scrollIntoViewPage], { type: "text/html" }));
157 + using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) };
158 + const scroller = document.createElement("div");
159 + scroller.style.cssText = "height: 400px; overflow: auto; width: 728px;";
160 + const scrolled = vi.fn();
161 + const messages = new AbortController();
162 + using _messages = { [Symbol.dispose]: () => messages.abort() };
163 + window.addEventListener(
164 + "message",
165 + (event) => {
166 + if (event.data?.type === "scrolled") scrolled(event.data);
167 + },
168 + { signal: messages.signal },
169 + );
170 + const contentHeight = vi.fn((height: number) => {
171 + if (frameCase.fitted) scroller.style.setProperty("--content-height", `${height}px`);
172 + });
173 + await using screen = await render(
174 + <>
175 + <style>{`iframe[title="Index"] {
176 + display: block; width: 100%; height: var(--content-height, 300px); border: 0;
177 + }`}</style>
178 + <div style={{ height: 600 }} />
179 + <HtmlRenderDocument
180 + src={src}
181 + title="Index"
182 + containScroll={frameCase.containScroll}
183 + onContentHeight={contentHeight}
184 + />
185 + <div style={{ height: 100 }} />
186 + </>,
187 + { container: scroller },
188 + );
189 +
190 + const frame = screen.getByTitle("Index").element() as HTMLIFrameElement;
191 + await vi.waitFor(() => expect(contentHeight).toHaveBeenCalled());
192 + if (frameCase.fitted) {
193 + await vi.waitFor(() => expect(frame.getBoundingClientRect().height).toBeGreaterThan(1400));
194 + }
195 + scroller.scrollTop = scroller.scrollHeight;
196 + const scrollTop = scroller.scrollTop;
197 +
198 + frame.contentWindow?.postMessage({ type: "scroll-into-view", id: "deep" }, "*");
199 + await vi.waitFor(() =>
200 + expect(scrolled).toHaveBeenCalledWith(expect.objectContaining({ id: "deep" })),
201 + );
202 + const deep = scrolled.mock.lastCall?.[0];
203 + // Every scroller inside the page moves, as the browser would: the clipped card, its panel,
204 + // and in a capped frame the page itself.
205 + expect(deep.card).toBeGreaterThan(0);
206 + expect(deep.panel).toBeGreaterThan(0);
207 + if (!frameCase.fitted) expect(deep.page).toBeGreaterThan(0);
208 + expect(scroller.scrollTop).toBe(scrollTop);
209 +
210 + frame.contentWindow?.postMessage({ type: "scroll-into-view", id: "top" }, "*");
211 + await vi.waitFor(() =>
212 + expect(scrolled).toHaveBeenCalledWith(expect.objectContaining({ id: "top" })),
213 + );
214 + if (frameCase.containScroll) expect(scroller.scrollTop).toBe(scrollTop);
215 + else expect(scroller.scrollTop).toBeLessThan(scrollTop);
216 + },
217 +);
218 +
219 it("keeps the first and last selected card rings inside the fitted renderer frame", async () => {
220 const html = injectHtmlRenderBootstrap(`<!doctype html><html><head><style>
221 main { display: grid; gap: 12px; }
apps/web/src/components/files/BrowserDocumentFrame.tsx
+7 -1
@@ -13,6 +13,7 @@ import {
13 readFilePreviewScroll,
14 type HtmlRenderShortcut,
15 htmlRenderShortcutsMessage,
16 + HTML_RENDER_CONTAIN_SCROLL_FRAGMENT,
17 htmlRenderThemeFragment,
18 htmlRenderThemeMessage,
19 htmlRenderResult,
@@ -296,12 +297,17 @@ export function HtmlRenderDocument(props: {
297 readonly className?: string;
298 readonly threadRef?: ScopedThreadRef | undefined;
299 readonly onContentHeight?: (height: number) => void;
300 + /** Keeps the page's scrollIntoView calls from scrolling the host, for frames inline in the chat. */
301 + readonly containScroll?: boolean | undefined;
302 /** Reports fullscreen changes so virtualized rows can stay mounted. */
303 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
304 }) {
305 const theme = useHtmlRenderTheme();
306 const frameRef = useRef<HTMLIFrameElement>(null);
304 - const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
307 + const [src] = useState(
308 + () =>
309 + `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}${props.containScroll ? HTML_RENDER_CONTAIN_SCROLL_FRAGMENT : ""}`,
310 + );
311 const [loaded, setLoaded] = useState(false);
312 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
313 const postTheme = () => {
apps/web/src/components/guest/GuestHtmlRender.tsx
+4 -2
@@ -2,6 +2,7 @@ import { GUEST_RENDER_ROUTE, GUEST_SHARE_PARAM } from "@t3tools/contracts";
2 import {
3 type HtmlRenderReference,
4 HTML_RENDER_COLUMN_WIDTH,
5 + HTML_RENDER_CONTAIN_SCROLL_FRAGMENT,
6 htmlRenderFrameHeight,
7 htmlRenderResult,
8 htmlRenderThemeFragment,
@@ -33,10 +34,11 @@ export function GuestHtmlRender({
34 const frameRef = useRef<HTMLIFrameElement>(null);
35 const [width, setWidth] = useState(HTML_RENDER_COLUMN_WIDTH);
36 const [contentHeight, setContentHeight] = useState<number>();
36 - // The theme rides in the fragment for the first paint; later changes are posted.
37 + // The theme rides in the fragment for the first paint; later changes are posted. The page sits
38 + // inline among the shared messages, so its scrollIntoView calls are contained.
39 const [src] = useState(
40 () =>
39 - `${GUEST_RENDER_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}${htmlRenderThemeFragment(theme)}`,
41 + `${GUEST_RENDER_ROUTE}?${GUEST_SHARE_PARAM}=${encodeURIComponent(shareId)}&item=${encodeURIComponent(itemId)}${htmlRenderThemeFragment(theme)}${HTML_RENDER_CONTAIN_SCROLL_FRAGMENT}`,
42 );
43 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the frame box and follows its width with a ResizeObserver before paint
44 useLayoutEffect(() => {
packages/shared/src/htmlRender.ts
+12 -1
@@ -379,6 +379,11 @@ export function htmlRenderThemeFragment(theme: HtmlRenderTheme): string {
379 return `#${THEME_FRAGMENT_KEY}=${encodeURIComponent(JSON.stringify(theme))}`;
380 }
381
382 +const CONTAIN_SCROLL_FRAGMENT_KEY = "t3-contain-scroll";
383 +
384 +/** Appended after the theme fragment for a frame whose page must not scroll the host. */
385 +export const HTML_RENDER_CONTAIN_SCROLL_FRAGMENT = `&${CONTAIN_SCROLL_FRAGMENT_KEY}`;
386 +
387 export function htmlRenderThemeMessage(theme: HtmlRenderTheme) {
388 return {
389 jsonrpc: "2.0",
@@ -401,9 +406,15 @@ function rootRule(theme: HtmlRenderTheme): string {
406 return `:root{color-scheme:${theme.appearance};${declarations}}`;
407 }
408
409 +// Native scrollIntoView also scrolls every scroller outside a framed page, such as the chat around an
410 +// inline render. In a contained frame, it scrolls each scroller inside the page and then the page's own
411 +// viewport, innermost first, aligning the target as the browser would (block, inline, scroll-margin,
412 +// scroll-padding, clamped offsets), and stops there. A fixed target or ancestor leaves the viewport alone.
413 +const CONTAINED_SCROLL_INTO_VIEW = `Element.prototype.scrollIntoView=function(v){var o=v!==null&&(typeof v==="object"||typeof v==="function")?v:{block:v===undefined||v===null||v?"start":"end"},B=o.block||"start",I=o.inline||"nearest",H=o.behavior||"auto",m=function(z){return parseFloat(z)||0;},g=getComputedStyle(this),r=this.getBoundingClientRect(),t=r.top-m(g.scrollMarginTop),b=r.bottom+m(g.scrollMarginBottom),l=r.left-m(g.scrollMarginLeft),R=r.right+m(g.scrollMarginRight),x=0,y=0,e=this,f=g.position==="fixed",d=function(a,z,lo,hi,k){var L=z-a>hi-lo;return k==="start"?a-lo:k==="end"?z-hi:k==="center"?(a+z-lo-hi)/2:a<lo&&z>hi?0:a<lo?L?z-hi:a-lo:z>hi?L?a-lo:z-hi:0;},w=function(top,left,c,s,go){var p=function(n){return m(s["scrollPadding"+n]);},n=s.direction==="rtl"?c.clientWidth-c.scrollWidth:0,dy=d(t-y,b-y,top+p("Top"),top+c.clientHeight-p("Bottom"),B),dx=d(l-x,R-x,left+p("Left"),left+c.clientWidth-p("Right"),I);dy=Math.max(-c.scrollTop,Math.min(c.scrollHeight-c.clientHeight-c.scrollTop,dy));dx=Math.max(n-c.scrollLeft,Math.min(n+c.scrollWidth-c.clientWidth-c.scrollLeft,dx));if(dx||dy)go({left:dx,top:dy,behavior:H});x+=dx;y+=dy;},u=document.scrollingElement||document.documentElement;while(!f){e=e.parentElement||(e.getRootNode&&e.getRootNode().host);if(!e)break;if(e===u||e===document.documentElement)continue;var h=getComputedStyle(document.documentElement),s=getComputedStyle(e),c=e.getBoundingClientRect();if(e===document.body&&h.overflowX+h.overflowY==="visiblevisible")continue;if(/auto|scroll|hidden/.test(s.overflowX+s.overflowY))w(c.top+e.clientTop,c.left+e.clientLeft,e,s,e.scrollBy.bind(e));f=s.position==="fixed";}if(!f)w(0,0,u,getComputedStyle(u),window.scrollBy.bind(window));};`;
414 +
415 // Apply overridable theme CSS before paint and strip the fragment before routing; framed navigation uses the client.
416 // Forward shortcuts after page handlers; text fields retain their keys.
406 -const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0;if(!s)return;var b=${JSON.stringify(BASE_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])));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);document.addEventListener("click",function(e){var t=e.composedPath()[0],l=t&&t.closest?t.closest("label,a[href],button,input,select,textarea"):null,c=l&&l.tagName==="LABEL"?l.control:null;if(e.isTrusted&&c&&document.activeElement!==c)c.focus({preventScroll:true});},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(){var g=[],i=-1;if(e.defaultPrevented)return;Array.prototype.forEach.call(document.images,function(m){var v=m.currentSrc||m.src;if(!v||m.closest("a[href],button"))return;if(m===t)i=g.length;g.push({src:v,name:m.alt||m.title||""});});window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||"",images:g,index:i}},"*");});});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():"",l==="+"&&!e.shiftKey&&!e.altKey&&!/^Digit/.test(c)?"":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);}})();`;
417 +const BOOTSTRAP_SCRIPT = `(function(){var s=document.getElementById("t3-theme"),n=0,P=/[#&]${CONTAIN_SCROLL_FRAGMENT_KEY}(?:&|$)/.test(location.hash);if(!s)return;var b=${JSON.stringify(BASE_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])));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);document.addEventListener("click",function(e){var t=e.composedPath()[0],l=t&&t.closest?t.closest("label,a[href],button,input,select,textarea"):null,c=l&&l.tagName==="LABEL"?l.control:null;if(e.isTrusted&&c&&document.activeElement!==c)c.focus({preventScroll:true});},true);if(window.parent!==window){if(P){${CONTAINED_SCROLL_INTO_VIEW}}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(){var g=[],i=-1;if(e.defaultPrevented)return;Array.prototype.forEach.call(document.images,function(m){var v=m.currentSrc||m.src;if(!v||m.closest("a[href],button"))return;if(m===t)i=g.length;g.push({src:v,name:m.alt||m.title||""});});window.parent.postMessage({jsonrpc:"2.0",method:${JSON.stringify(OPEN_IMAGE_METHOD)},params:{src:u,name:t.alt||t.title||"",images:g,index:i}},"*");});});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():"",l==="+"&&!e.shiftKey&&!e.altKey&&!/^Digit/.test(c)?"":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);}})();`;
418
419 function bootstrapMarkup(markup: string): string {
420 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");