@devries-cameron20 / t3code Mirror · read-only / commits / 17e1087d36
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 23, 13:00 UTC

feat(web): open html render images in the image viewer (#20036)

maria committed Oct 15, 2026 at 22:14 UTC 17e1087d36aa2ed7b6ca6b1a3775a2fe2a9f15c6
4 files changed +109 -24
apps/web/src/components/chat/HtmlRenderFrame.tsx
+1
@@ -135,6 +135,7 @@ export function HtmlRenderFrame(props: {
135 )}
136 onContentHeight={fitPage}
137 onLoad={showPage}
138 + onFullscreenChange={onFullscreenChange}
139 />
140 <div className="absolute end-2 top-2 flex gap-1 opacity-0 transition-opacity duration-150 focus-within:opacity-100 group-hover/html-render:opacity-100 pointer-coarse:opacity-100">
141 <Tooltip>
apps/web/src/components/files/BrowserDocumentFrame.tsx
+56 -20
@@ -13,6 +13,7 @@ import {
13 htmlRenderThemeMessage,
14 htmlRenderResult,
15 readHtmlRenderContentHeight,
16 + readHtmlRenderImageRequest,
17 readHtmlRenderKeyDown,
18 readHtmlRenderLinkRequest,
19 } from "@t3tools/shared/htmlRender";
@@ -24,6 +25,8 @@ import {
25 import { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react";
26
27 import { useOpenLink } from "~/browser/useOpenLink";
28 +import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
29 +import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
30 import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
31 import { shortcutConflictKey } from "~/keybindings";
32 import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
@@ -124,6 +127,8 @@ export function HtmlRenderDocument(props: {
127 readonly threadRef?: ScopedThreadRef | undefined;
128 /** Receives the page's content height whenever it changes, so an inline frame can fit it. */
129 readonly onContentHeight?: (height: number) => void;
130 + /** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */
131 + readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
132 /** Called when the page has loaded. */
133 readonly onLoad?: () => void;
134 }) {
@@ -131,6 +136,7 @@ export function HtmlRenderDocument(props: {
136 const frameRef = useRef<HTMLIFrameElement>(null);
137 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
138 const [loaded, setLoaded] = useState(false);
139 + const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
140 const postTheme = () => {
141 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
142 };
@@ -267,6 +273,31 @@ export function HtmlRenderDocument(props: {
273 window.addEventListener("message", replayKey);
274 return () => window.removeEventListener("message", replayKey);
275 }, []);
276 + // A clicked page image opens in the same viewer as chat images, gated like a link.
277 + useEffect(() => {
278 + const openImage = (event: MessageEvent) => {
279 + const frame = frameRef.current;
280 + const request = readHtmlRenderImageRequest(event.data);
281 + if (
282 + request === undefined ||
283 + frame === null ||
284 + event.source !== frame.contentWindow ||
285 + document.activeElement !== frame ||
286 + navigator.userActivation?.isActive === false
287 + ) {
288 + return;
289 + }
290 + setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
291 + };
292 + window.addEventListener("message", openImage);
293 + return () => window.removeEventListener("message", openImage);
294 + }, []);
295 + const { onFullscreenChange } = props;
296 + useEffect(() => {
297 + if (expandedImage === null) return;
298 + onFullscreenChange?.(true);
299 + return () => onFullscreenChange?.(false);
300 + }, [expandedImage, onFullscreenChange]);
301 const { onContentHeight } = props;
302 // A page posts its height once per change, so listen from the commit that
303 // inserts the frame; a passive effect could run after a fast page's first post.
@@ -282,25 +313,30 @@ export function HtmlRenderDocument(props: {
313 return () => window.removeEventListener("message", resize);
314 }, [onContentHeight]);
315 return (
285 - <iframe
286 - ref={frameRef}
287 - src={src}
288 - title={props.title}
289 - // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
290 - sandbox="allow-scripts allow-forms"
291 - loading="lazy"
292 - onLoad={() => {
293 - setLoaded(true);
294 - // Covers a theme change that landed while the page was loading.
295 - postTheme();
296 - postShortcuts();
297 - props.onLoad?.();
298 - }}
299 - // A frame whose color scheme differs from its document's paints an opaque
300 - // canvas, so the blank document a frame starts with would flash white in
301 - // dark mode. Once the page is in, its prefers-color-scheme follows the app.
302 - className={cn("border-0 scheme-light", props.className)}
303 - style={loaded ? { colorScheme: theme.appearance } : undefined}
304 - />
316 + <>
317 + <iframe
318 + ref={frameRef}
319 + src={src}
320 + title={props.title}
321 + // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
322 + sandbox="allow-scripts allow-forms"
323 + loading="lazy"
324 + onLoad={() => {
325 + setLoaded(true);
326 + // Covers a theme change that landed while the page was loading.
327 + postTheme();
328 + postShortcuts();
329 + props.onLoad?.();
330 + }}
331 + // A frame whose color scheme differs from its document's paints an opaque
332 + // canvas, so the blank document a frame starts with would flash white in
333 + // dark mode. Once the page is in, its prefers-color-scheme follows the app.
334 + className={cn("border-0 scheme-light", props.className)}
335 + style={loaded ? { colorScheme: theme.appearance } : undefined}
336 + />
337 + {expandedImage !== null ? (
338 + <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
339 + ) : null}
340 + </>
341 );
342 }
packages/shared/src/htmlRender.test.ts
+24
@@ -11,6 +11,7 @@ import {
11 injectHtmlRenderBootstrap,
12 htmlRenderThemeMessage,
13 readHtmlRenderContentHeight,
14 + readHtmlRenderImageRequest,
15 readHtmlRenderKeyDown,
16 readHtmlRenderLinkRequest,
17 readHtmlRenderReference,
@@ -109,6 +110,29 @@ describe("readHtmlRenderLinkRequest", () => {
110 });
111 });
112
113 +describe("readHtmlRenderImageRequest", () => {
114 + it("accepts http(s) and inline image URLs in an open-image notification", () => {
115 + const image = (params: unknown) => ({
116 + jsonrpc: "2.0",
117 + method: "t3/notifications/open-image",
118 + params,
119 + });
120 + expect(
121 + readHtmlRenderImageRequest(image({ src: "data:image/png;base64,AA", name: " Chart " })),
122 + ).toEqual({
123 + src: "data:image/png;base64,AA",
124 + name: "Chart",
125 + });
126 + expect(readHtmlRenderImageRequest(image({ src: "https://example.com/a.png" }))).toEqual({
127 + src: "https://example.com/a.png",
128 + name: "Image",
129 + });
130 + expect(readHtmlRenderImageRequest(image({ src: "javascript:alert(1)" }))).toBeUndefined();
131 + expect(readHtmlRenderImageRequest(image({ src: "data:text/html,<p>" }))).toBeUndefined();
132 + expect(readHtmlRenderImageRequest(image({ src: "blob:null/1" }))).toBeUndefined();
133 + });
134 +});
135 +
136 describe("readHtmlRenderKeyDown", () => {
137 it("reads the key of a keydown notification and nothing else", () => {
138 const notification = (params: unknown) => ({
packages/shared/src/htmlRender.ts
+28 -4
@@ -360,6 +360,8 @@ const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
360 // those on.
361 const SHORTCUTS_METHOD = "t3/notifications/shortcuts";
362 const KEY_DOWN_METHOD = "t3/notifications/keydown";
363 +// Not part of MCP Apps: a click on a page image opens it in the app's image viewer.
364 +const OPEN_IMAGE_METHOD = "t3/notifications/open-image";
365
366 /** The content height in a framed render's `ui/notifications/size-changed` notification. */
367 export function readHtmlRenderContentHeight(data: unknown): number | undefined {
@@ -397,6 +399,24 @@ export function readHtmlRenderLinkRequest(data: unknown):
399 : undefined;
400 }
401
402 +/**
403 + * The image a framed render's reader clicked, if `data` is an open-image
404 + * notification for an http(s) or inline image URL. Server-side publishing
405 + * inlines local images, so most arrive as `data:image/` URLs.
406 + */
407 +export function readHtmlRenderImageRequest(
408 + data: unknown,
409 +): { readonly src: string; readonly name: string } | undefined {
410 + if (typeof data !== "object" || data === null) return undefined;
411 + const { jsonrpc, method, params } = data as Record<string, unknown>;
412 + if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;
413 + if (typeof params !== "object" || params === null) return undefined;
414 + const { src, name } = params as Record<string, unknown>;
415 + if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;
416 + const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";
417 + return { src, name: label || "Image" };
418 +}
419 +
420 /** The key a framed render passed on in a `t3/notifications/keydown` notification. */
421 export function readHtmlRenderKeyDown(data: unknown):
422 | {
@@ -478,7 +498,9 @@ const BASE_CSS =
498 "html{background:var(--background);color:var(--foreground);font-family:var(--font-sans);font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;scrollbar-width:none}" +
499 "html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +
500 // Focus outlines paint inside the element, so the frame edge never clips them.
481 - ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}";
501 + ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" +
502 + // An image outside a link or button opens in the app's viewer, as chat images do.
503 + ":where(img:not(a[href] img,button img)){cursor:zoom-in}";
504
505 function rootRule(theme: HtmlRenderTheme): string {
506 const declarations = Object.entries(theme.variables)
@@ -493,14 +515,16 @@ function rootRule(theme: HtmlRenderTheme): string {
515 // then drops the fragment so a page's own hash routing never sees it. A link
516 // the reader clicks to another page never replaces the page inside the thread:
517 // a framed page asks its client to open it, and a top-level page (mobile)
496 -// opens it as a new window, which the client sends to the browser. A framed
497 -// page also reports its content height, measured as the server measures it,
518 +// opens it as a new window, which the client sends to the browser. A plain
519 +// left click on a framed page's image, outside a link or button and not
520 +// prevented by any of the page's listeners, asks the client to open the image
521 +// in its viewer. A framed page also reports its content height, measured as the server measures it,
522 // so its client can fit the frame to the page. A chord the client named as an
523 // app shortcut is passed on rather than left to the browser, unless a text
524 // field has focus or the page handled it: the deciding listener is added while
525 // the key dispatches, so it runs after every listener the page has. Keys
526 // match as resolveEventKeys reads them, so the client accepts what it claims.
503 -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);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);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);}})();`;
527 +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);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);}})();`;
528
529 function bootstrapMarkup(markup: string): string {
530 const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");