Skip to content

Commit 31d3420

Browse files
committed
fix(web): HTML renders keep thread jumps and never claim a key the client would refuse
1 parent 505f814 commit 31d3420

2 files changed

Lines changed: 38 additions & 27 deletions

File tree

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

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { useAtomValue } from "@effect/atom-react";
22
import {
33
type KeybindingCommand,
4+
type KeybindingShortcut,
5+
MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
46
type ScopedThreadRef,
57
THREAD_JUMP_KEYBINDING_COMMANDS,
68
} from "@t3tools/contracts";
@@ -55,6 +57,8 @@ const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
5557
"thread.previous",
5658
"thread.next",
5759
...THREAD_JUMP_KEYBINDING_COMMANDS,
60+
// Share Cmd/Ctrl+digit with thread jumps, and act only while the picker is open.
61+
...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
5862
]);
5963

6064
export const isPdfPreviewFile = (path: string): boolean =>
@@ -136,42 +140,42 @@ export function HtmlRenderDocument(props: {
136140
// would type into the composer instead.
137141
const { shortcuts, blocked } = useMemo(() => {
138142
const mac = isMacPlatform(navigator.platform);
143+
const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
144+
key: shortcut.key,
145+
metaKey: shortcut.metaKey || (shortcut.modKey && mac),
146+
ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
147+
shiftKey: shortcut.shiftKey,
148+
altKey: shortcut.altKey,
149+
});
139150
const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
140151
.filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
141-
.map((binding) => binding.shortcut);
142-
const claimed = new Set(blocked.map((shortcut) => shortcutConflictKey(shortcut)));
143-
const offered = new Map<string, HtmlRenderShortcut>();
152+
.map((binding) => resolve(binding.shortcut));
153+
const shortcuts = new Map<string, HtmlRenderShortcut>();
144154
for (const { command, shortcut } of keybindings) {
145-
const conflictKey = shortcutConflictKey(shortcut);
146155
if (
147-
!HTML_RENDER_SHORTCUT_COMMANDS.has(command) ||
148-
!(shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey) ||
149-
claimed.has(conflictKey)
156+
HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
157+
(shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
150158
) {
151-
continue;
159+
shortcuts.set(shortcutConflictKey(shortcut), resolve(shortcut));
152160
}
153-
offered.set(conflictKey, {
154-
key: shortcut.key,
155-
metaKey: shortcut.metaKey || (shortcut.modKey && mac),
156-
ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
157-
shiftKey: shortcut.shiftKey,
158-
altKey: shortcut.altKey,
159-
});
160161
}
161-
return { shortcuts: [...offered.values()], blocked };
162+
return { shortcuts: [...shortcuts.values()], blocked };
162163
}, [environmentKeybindings, keybindings]);
163164
const postShortcuts = () => {
164-
frameRef.current?.contentWindow?.postMessage(htmlRenderShortcutsMessage(shortcuts), "*");
165+
frameRef.current?.contentWindow?.postMessage(
166+
htmlRenderShortcutsMessage(shortcuts, blocked),
167+
"*",
168+
);
165169
};
166-
useEffect(postShortcuts, [shortcuts]);
170+
useEffect(postShortcuts, [blocked, shortcuts]);
167171
// The page reports the key and code, and a page script can report any pair,
168172
// so a key that could match another command's binding is never replayed.
169173
const isShortcut = useEffectEvent(
170-
(key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) =>
171-
shortcuts.some((shortcut) =>
172-
matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform),
173-
) &&
174-
!blocked.some((shortcut) => matchesKeybindingShortcut(key, shortcut, navigator.platform)),
174+
(key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
175+
const matches = (shortcut: HtmlRenderShortcut) =>
176+
matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
177+
return shortcuts.some(matches) && !blocked.some(matches);
178+
},
175179
);
176180
const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
177181
const openLink = useOpenLink(props.threadRef);

‎packages/shared/src/htmlRender.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -359,9 +359,16 @@ export interface HtmlRenderShortcut {
359359
readonly altKey: boolean;
360360
}
361361

362-
/** The `t3/notifications/shortcuts` notification a client posts into a render: the chords it may pass on. */
363-
export function htmlRenderShortcutsMessage(shortcuts: ReadonlyArray<HtmlRenderShortcut>) {
364-
return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts } } as const;
362+
/**
363+
* The `t3/notifications/shortcuts` notification a client posts into a render:
364+
* the chords it may pass on, and chords of other commands that the page keeps
365+
* even when one also matches an allowed chord.
366+
*/
367+
export function htmlRenderShortcutsMessage(
368+
shortcuts: ReadonlyArray<HtmlRenderShortcut>,
369+
blocked: ReadonlyArray<HtmlRenderShortcut>,
370+
) {
371+
return { jsonrpc: "2.0", method: SHORTCUTS_METHOD, params: { shortcuts, blocked } } as const;
365372
}
366373

367374
/** The empty result a client sends back for a render's request. */
@@ -413,7 +420,7 @@ function rootRule(theme: HtmlRenderTheme): string {
413420
// field has focus or the page handled it: the deciding listener is added while
414421
// the key dispatches, so it runs after every listener the page has. Keys
415422
// match as resolveEventKeys reads them, so the client accepts what it claims.
416-
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=[],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))K=p.shortcuts;});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;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(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;}))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);}})();`;
423+
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);}})();`;
417424

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

0 commit comments

Comments
 (0)