Skip to content

Commit 6dfeeff

Browse files
committed
fix(web): app shortcuts keep working after clicking into an HTML render
The page passes Cmd/Ctrl chords it left alone to the client, which replays them on the frame so the app's window listeners see them.
1 parent 5889d9b commit 6dfeeff

3 files changed

Lines changed: 86 additions & 2 deletions

File tree

‎apps/web/src/components/files/BrowserDocumentFrame.tsx‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
htmlRenderThemeMessage,
55
htmlRenderResult,
66
readHtmlRenderContentHeight,
7+
readHtmlRenderKeyDown,
78
readHtmlRenderLinkRequest,
89
} from "@t3tools/shared/htmlRender";
910
import { useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
@@ -132,6 +133,29 @@ export function HtmlRenderDocument(props: {
132133
window.addEventListener("message", openLink);
133134
return () => window.removeEventListener("message", openLink);
134135
}, []);
136+
// A focused frame takes every key, so app shortcuts would stop until the
137+
// reader clicked out. The page passes on Cmd/Ctrl chords, which replay on the
138+
// frame element and bubble to the app's window listeners, gated like links.
139+
useEffect(() => {
140+
const replayKey = (event: MessageEvent) => {
141+
const frame = frameRef.current;
142+
const key = readHtmlRenderKeyDown(event.data);
143+
if (
144+
key === undefined ||
145+
frame === null ||
146+
event.source !== frame.contentWindow ||
147+
document.activeElement !== frame ||
148+
navigator.userActivation?.isActive === false
149+
) {
150+
return;
151+
}
152+
frame.dispatchEvent(
153+
new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
154+
);
155+
};
156+
window.addEventListener("message", replayKey);
157+
return () => window.removeEventListener("message", replayKey);
158+
}, []);
135159
const { onContentHeight } = props;
136160
// A page posts its height once per change, so listen from the commit that
137161
// inserts the frame; a passive effect could run after a fast page's first post.

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
injectHtmlRenderBootstrap,
1010
htmlRenderThemeMessage,
1111
readHtmlRenderContentHeight,
12+
readHtmlRenderKeyDown,
1213
readHtmlRenderLinkRequest,
1314
readHtmlRenderReference,
1415
} from "./htmlRender.ts";
@@ -106,6 +107,29 @@ describe("readHtmlRenderLinkRequest", () => {
106107
});
107108
});
108109

110+
describe("readHtmlRenderKeyDown", () => {
111+
it("reads the key of a keydown notification and nothing else", () => {
112+
const notification = (params: unknown) => ({
113+
jsonrpc: "2.0",
114+
method: "t3/notifications/keydown",
115+
params,
116+
});
117+
expect(readHtmlRenderKeyDown(notification({ key: "k", code: "KeyK", metaKey: true }))).toEqual({
118+
key: "k",
119+
code: "KeyK",
120+
metaKey: true,
121+
ctrlKey: false,
122+
shiftKey: false,
123+
altKey: false,
124+
repeat: false,
125+
});
126+
expect(readHtmlRenderKeyDown(notification({ key: 1, code: "KeyK" }))).toBeUndefined();
127+
expect(
128+
readHtmlRenderKeyDown({ jsonrpc: "2.0", method: "ui/open-link", params: { key: "k" } }),
129+
).toBeUndefined();
130+
});
131+
});
132+
109133
describe("readHtmlRenderContentHeight", () => {
110134
it("reads only the height of an MCP Apps size-changed notification", () => {
111135
const notification = (params: unknown) => ({

‎packages/shared/src/htmlRender.ts‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,9 @@ export const HTML_RENDER_LAYOUT_GUIDE = [
274274
const HOST_CONTEXT_CHANGED_METHOD = "ui/notifications/host-context-changed";
275275
const OPEN_LINK_METHOD = "ui/open-link";
276276
const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
277+
// Not part of MCP Apps: a focused frame keeps its keys from the app, so the
278+
// page passes on the Cmd/Ctrl chords app shortcuts are made of.
279+
const KEY_DOWN_METHOD = "t3/notifications/keydown";
277280

278281
/** The content height in a framed render's `ui/notifications/size-changed` notification. */
279282
export function readHtmlRenderContentHeight(data: unknown): number | undefined {
@@ -311,6 +314,38 @@ export function readHtmlRenderLinkRequest(data: unknown):
311314
: undefined;
312315
}
313316

317+
/** The key a framed render passed on in a `t3/notifications/keydown` notification. */
318+
export function readHtmlRenderKeyDown(data: unknown):
319+
| {
320+
readonly key: string;
321+
readonly code: string;
322+
readonly metaKey: boolean;
323+
readonly ctrlKey: boolean;
324+
readonly shiftKey: boolean;
325+
readonly altKey: boolean;
326+
readonly repeat: boolean;
327+
}
328+
| undefined {
329+
if (typeof data !== "object" || data === null) return undefined;
330+
const { jsonrpc, method, params } = data as Record<string, unknown>;
331+
if (jsonrpc !== "2.0" || method !== KEY_DOWN_METHOD) return undefined;
332+
if (typeof params !== "object" || params === null) return undefined;
333+
const { key, code, metaKey, ctrlKey, shiftKey, altKey, repeat } = params as Record<
334+
string,
335+
unknown
336+
>;
337+
if (typeof key !== "string" || typeof code !== "string") return undefined;
338+
return {
339+
key,
340+
code,
341+
metaKey: metaKey === true,
342+
ctrlKey: ctrlKey === true,
343+
shiftKey: shiftKey === true,
344+
altKey: altKey === true,
345+
repeat: repeat === true,
346+
};
347+
}
348+
314349
/** The empty result a client sends back for a render's request. */
315350
export function htmlRenderResult(id: string | number) {
316351
return { jsonrpc: "2.0", id, result: {} } as const;
@@ -355,8 +390,9 @@ function rootRule(theme: HtmlRenderTheme): string {
355390
// a framed page asks its client to open it, and a top-level page (mobile)
356391
// opens it as a new window, which the client sends to the browser. A framed
357392
// page also reports its content height, measured as the server measures it,
358-
// so its client can fit the frame to the page.
359-
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);}})();`;
393+
// so its client can fit the frame to the page, and passes on Cmd/Ctrl chords
394+
// the page left alone outside text fields, so app shortcuts keep working.
395+
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("keydown",function(e){var t=e.target;if(!e.isTrusted||e.defaultPrevented||e.isComposing||!(e.metaKey||e.ctrlKey)||/^(?:Meta|Control|Alt|Shift|OS)$/.test(e.key)||t&&(t.isContentEditable||/^(?:INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))return;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}},"*");});}})();`;
360396

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

0 commit comments

Comments
 (0)