TypeScript
feat(web): open html render images in the image viewer (#20036)
maria17e1087d36aa
diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsxindex 067ea0d2ba2..4112cc9ebfe 100644--- a/apps/web/src/components/chat/HtmlRenderFrame.tsx+++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx@@ -135,6 +135,7 @@ export function HtmlRenderFrame(props: {)}onContentHeight={fitPage}onLoad={showPage}+ onFullscreenChange={onFullscreenChange}/><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"><Tooltip>diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsxindex 944050dd2aa..237c60939c1 100644--- a/apps/web/src/components/files/BrowserDocumentFrame.tsx+++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx@@ -13,6 +13,7 @@ import {htmlRenderThemeMessage,htmlRenderResult,readHtmlRenderContentHeight,+ readHtmlRenderImageRequest,readHtmlRenderKeyDown,readHtmlRenderLinkRequest,} from "@t3tools/shared/htmlRender";@@ -24,6 +25,8 @@ import {import { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react";import { useOpenLink } from "~/browser/useOpenLink";+import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";+import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";import { shortcutConflictKey } from "~/keybindings";import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";@@ -124,6 +127,8 @@ export function HtmlRenderDocument(props: {readonly threadRef?: ScopedThreadRef | undefined;/** Receives the page's content height whenever it changes, so an inline frame can fit it. */readonly onContentHeight?: (height: number) => void;+ /** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */+ readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;/** Called when the page has loaded. */readonly onLoad?: () => void;}) {@@ -131,6 +136,7 @@ export function HtmlRenderDocument(props: {const frameRef = useRef<HTMLIFrameElement>(null);const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);const [loaded, setLoaded] = useState(false);+ const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);const postTheme = () => {frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");};@@ -267,6 +273,31 @@ export function HtmlRenderDocument(props: {window.addEventListener("message", replayKey);return () => window.removeEventListener("message", replayKey);}, []);+ // A clicked page image opens in the same viewer as chat images, gated like a link.+ useEffect(() => {+ const openImage = (event: MessageEvent) => {+ const frame = frameRef.current;+ const request = readHtmlRenderImageRequest(event.data);+ if (+ request === undefined ||+ frame === null ||+ event.source !== frame.contentWindow ||+ document.activeElement !== frame ||+ navigator.userActivation?.isActive === false+ ) {+ return;+ }+ setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });+ };+ window.addEventListener("message", openImage);+ return () => window.removeEventListener("message", openImage);+ }, []);+ const { onFullscreenChange } = props;+ useEffect(() => {+ if (expandedImage === null) return;+ onFullscreenChange?.(true);+ return () => onFullscreenChange?.(false);+ }, [expandedImage, onFullscreenChange]);const { onContentHeight } = props;// A page posts its height once per change, so listen from the commit that// inserts the frame; a passive effect could run after a fast page's first post.@@ -282,25 +313,30 @@ export function HtmlRenderDocument(props: {return () => window.removeEventListener("message", resize);}, [onContentHeight]);return (- <iframe- ref={frameRef}- src={src}- title={props.title}- // Never allow-same-origin: the opaque origin keeps the page out of the app's session.- sandbox="allow-scripts allow-forms"- loading="lazy"- onLoad={() => {- setLoaded(true);- // Covers a theme change that landed while the page was loading.- postTheme();- postShortcuts();- props.onLoad?.();- }}- // A frame whose color scheme differs from its document's paints an opaque- // canvas, so the blank document a frame starts with would flash white in- // dark mode. Once the page is in, its prefers-color-scheme follows the app.- className={cn("border-0 scheme-light", props.className)}- style={loaded ? { colorScheme: theme.appearance } : undefined}- />+ <>+ <iframe+ ref={frameRef}+ src={src}+ title={props.title}+ // Never allow-same-origin: the opaque origin keeps the page out of the app's session.+ sandbox="allow-scripts allow-forms"+ loading="lazy"+ onLoad={() => {+ setLoaded(true);+ // Covers a theme change that landed while the page was loading.+ postTheme();+ postShortcuts();+ props.onLoad?.();+ }}+ // A frame whose color scheme differs from its document's paints an opaque+ // canvas, so the blank document a frame starts with would flash white in+ // dark mode. Once the page is in, its prefers-color-scheme follows the app.+ className={cn("border-0 scheme-light", props.className)}+ style={loaded ? { colorScheme: theme.appearance } : undefined}+ />+ {expandedImage !== null ? (+ <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />+ ) : null}+ </>);}diff --git a/packages/shared/src/htmlRender.test.ts b/packages/shared/src/htmlRender.test.tsindex 3b88152434e..5bfdd782e36 100644--- a/packages/shared/src/htmlRender.test.ts+++ b/packages/shared/src/htmlRender.test.ts@@ -11,6 +11,7 @@ import {injectHtmlRenderBootstrap,htmlRenderThemeMessage,readHtmlRenderContentHeight,+ readHtmlRenderImageRequest,readHtmlRenderKeyDown,readHtmlRenderLinkRequest,readHtmlRenderReference,@@ -109,6 +110,29 @@ describe("readHtmlRenderLinkRequest", () => {});});+describe("readHtmlRenderImageRequest", () => {+ it("accepts http(s) and inline image URLs in an open-image notification", () => {+ const image = (params: unknown) => ({+ jsonrpc: "2.0",+ method: "t3/notifications/open-image",+ params,+ });+ expect(+ readHtmlRenderImageRequest(image({ src: "data:image/png;base64,AA", name: " Chart " })),+ ).toEqual({+ src: "data:image/png;base64,AA",+ name: "Chart",+ });+ expect(readHtmlRenderImageRequest(image({ src: "https://example.com/a.png" }))).toEqual({+ src: "https://example.com/a.png",+ name: "Image",+ });+ expect(readHtmlRenderImageRequest(image({ src: "javascript:alert(1)" }))).toBeUndefined();+ expect(readHtmlRenderImageRequest(image({ src: "data:text/html,<p>" }))).toBeUndefined();+ expect(readHtmlRenderImageRequest(image({ src: "blob:null/1" }))).toBeUndefined();+ });+});+describe("readHtmlRenderKeyDown", () => {it("reads the key of a keydown notification and nothing else", () => {const notification = (params: unknown) => ({diff --git a/packages/shared/src/htmlRender.ts b/packages/shared/src/htmlRender.tsindex befe63a5224..8f2323ee178 100644--- a/packages/shared/src/htmlRender.ts+++ b/packages/shared/src/htmlRender.ts@@ -360,6 +360,8 @@ const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";// those on.const SHORTCUTS_METHOD = "t3/notifications/shortcuts";const KEY_DOWN_METHOD = "t3/notifications/keydown";+// Not part of MCP Apps: a click on a page image opens it in the app's image viewer.+const OPEN_IMAGE_METHOD = "t3/notifications/open-image";/** The content height in a framed render's `ui/notifications/size-changed` notification. */export function readHtmlRenderContentHeight(data: unknown): number | undefined {@@ -397,6 +399,24 @@ export function readHtmlRenderLinkRequest(data: unknown):: undefined;}+/**+ * The image a framed render's reader clicked, if `data` is an open-image+ * notification for an http(s) or inline image URL. Server-side publishing+ * inlines local images, so most arrive as `data:image/` URLs.+ */+export function readHtmlRenderImageRequest(+ data: unknown,+): { readonly src: string; readonly name: string } | undefined {+ if (typeof data !== "object" || data === null) return undefined;+ const { jsonrpc, method, params } = data as Record<string, unknown>;+ if (jsonrpc !== "2.0" || method !== OPEN_IMAGE_METHOD) return undefined;+ if (typeof params !== "object" || params === null) return undefined;+ const { src, name } = params as Record<string, unknown>;+ if (typeof src !== "string" || !/^(?:https?:\/\/|data:image\/)/i.test(src)) return undefined;+ const label = typeof name === "string" ? name.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) : "";+ return { src, name: label || "Image" };+}+/** The key a framed render passed on in a `t3/notifications/keydown` notification. */export function readHtmlRenderKeyDown(data: unknown):| {@@ -478,7 +498,9 @@ const BASE_CSS ="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}" +"html::-webkit-scrollbar{display:none}body{margin:0}code,kbd,pre,samp{font-family:var(--font-mono)}" +// Focus outlines paint inside the element, so the frame edge never clips them.- ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}";+ ":where(:focus-visible){outline:2px solid var(--ring)}:focus-visible{outline-width:2px!important;outline-offset:-2px!important}" ++ // An image outside a link or button opens in the app's viewer, as chat images do.+ ":where(img:not(a[href] img,button img)){cursor:zoom-in}";function rootRule(theme: HtmlRenderTheme): string {const declarations = Object.entries(theme.variables)@@ -493,14 +515,16 @@ function rootRule(theme: HtmlRenderTheme): string {// then drops the fragment so a page's own hash routing never sees it. A link// the reader clicks to another page never replaces the page inside the thread:// a framed page asks its client to open it, and a top-level page (mobile)-// opens it as a new window, which the client sends to the browser. A framed-// page also reports its content height, measured as the server measures it,+// opens it as a new window, which the client sends to the browser. A plain+// left click on a framed page's image, outside a link or button and not+// prevented by any of the page's listeners, asks the client to open the image+// in its viewer. A framed page also reports its content height, measured as the server measures it,// so its client can fit the frame to the page. A chord the client named as an// app shortcut is passed on rather than left to the browser, unless a text// field has focus or the page handled it: the deciding listener is added while// the key dispatches, so it runs after every listener the page has. Keys// match as resolveEventKeys reads them, so the client accepts what it claims.-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);}})();`;+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);}})();`;function bootstrapMarkup(markup: string): string {const dark = htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark");