Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(canvas): keep app shortcuts working while a canvas has focus (#85475)

Alessandro Pogliaghi0e84c5f91973
diff --git a/products/canvas/packages/canvas_builder/build.mjs b/products/canvas/packages/canvas_builder/build.mjs
index 6c78b392b892..101cb5377508 100644
--- a/products/canvas/packages/canvas_builder/build.mjs
+++ b/products/canvas/packages/canvas_builder/build.mjs
@@ -216,6 +216,7 @@ function installSelectionSettleGate(doc, callbacks) {
const selectionRuntime = `(()=>{const channel="posthog-canvas";let port,timer=0,published=false;const anchorRect=${commentActionAnchorRect.toString()};const settleGate=${installSelectionSettleGate.toString()};const post=message=>port?.postMessage({channel,...message}),clear=()=>{if(!published)return;published=false;post({type:"text-selection-cleared"})},clearNative=()=>{getSelection()?.removeAllRanges();clear()},report=()=>{clearTimeout(timer);timer=setTimeout(()=>{const selection=getSelection();if(!selection||selection.isCollapsed||selection.rangeCount===0){clear();return}const range=selection.getRangeAt(0);if(!document.body.contains(range.startContainer)||!document.body.contains(range.endContainer)){clear();return}const before=document.createRange();before.selectNodeContents(document.body);before.setEnd(range.startContainer,range.startOffset);const through=document.createRange();through.selectNodeContents(document.body);through.setEnd(range.endContainer,range.endOffset);const whole=document.createRange();whole.selectNodeContents(document.body);const text=whole.toString(),start=before.toString().length,end=through.toString().length,quote=text.slice(start,end);if(!quote.trim()||quote.length>10000){clear();return}const rect=anchorRect(range.getClientRects?range.getClientRects():[],range.getBoundingClientRect());published=true;post({type:"text-selection",selection:{quote,prefix:text.slice(Math.max(0,start-32),start),suffix:text.slice(end,end+32),start,end,rect:{top:rect.top,right:rect.right,bottom:rect.bottom,left:rect.left}}})},80)};addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",event=>{if(event.data?.channel===channel&&event.data?.type==="clear-text-selection")clearNative()});port.start()});const abort=()=>{clearTimeout(timer);clear()};settleGate(document,{onGestureStart:abort,onSelectionSettled:report,onIdleSelectionChange:report,onGestureCancel:abort});document.addEventListener("scroll",abort,true)})();`
const highlightRuntime = `(()=>{const channel="posthog-canvas",style=document.createElement("style");style.textContent="::highlight(posthog-canvas-comment){background:rgba(250,204,21,.32);color:inherit}::highlight(posthog-canvas-comment-active){background:rgba(250,204,21,.48);color:inherit}";document.head.appendChild(style);let items=[],ranges=[],port,timer=0;const indexText=()=>{const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT),entries=[];let text="";for(let node=walker.nextNode();node;node=walker.nextNode()){const start=text.length;text+=node.data;entries.push({node,start,end:text.length})}return{text,entries}},rangeAt=(index,start,end)=>{const find=offset=>{let low=0,high=index.entries.length-1,match=null;while(low<=high){const middle=low+high>>1,entry=index.entries[middle];if(offset<entry.start)high=middle-1;else if(offset>entry.end)low=middle+1;else{match=entry;high=middle-1}}return match},startEntry=find(start),endEntry=find(end);if(!startEntry||!endEntry)return null;const range=document.createRange();range.setStart(startEntry.node,start-startEntry.start);range.setEnd(endEntry.node,end-endEntry.start);return range},resolve=(text,anchor)=>{if(text.slice(anchor.start,anchor.end)===anchor.quote)return{start:anchor.start,end:anchor.end};const matches=[];for(let start=text.indexOf(anchor.quote);start>=0;start=text.indexOf(anchor.quote,start+Math.max(anchor.quote.length,1))){const end=start+anchor.quote.length,prefix=text.slice(Math.max(0,start-anchor.prefix.length),start),suffix=text.slice(end,end+anchor.suffix.length);matches.push({start,end,score:(anchor.prefix&&prefix===anchor.prefix?2:0)+(anchor.suffix&&suffix===anchor.suffix?2:0)})}if(matches.length===1)return matches[0];matches.sort((a,b)=>b.score-a.score);return matches[0]?.score&&matches[0].score!==matches[1]?.score?matches[0]:null},render=next=>{items=next||[];ranges=[];if(!window.Highlight||!window.CSS||!CSS.highlights)return;const normal=new Highlight,active=new Highlight,index=indexText();for(const item of items){const hit=resolve(index.text,item.anchor),range=hit&&rangeAt(index,hit.start,hit.end);if(range){ranges.push({id:item.id,range});(item.active?active:normal).add(range)}}CSS.highlights.set("posthog-canvas-comment",normal);CSS.highlights.set("posthog-canvas-comment-active",active)};addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.addEventListener("message",event=>{if(event.data?.channel===channel&&event.data?.type==="set-comment-highlights")render(event.data.highlights)});port.start()});document.addEventListener("click",event=>{const selection=getSelection();if(selection&&!selection.isCollapsed)return;for(const item of ranges)for(const rect of item.range.getClientRects())if(event.clientX>=rect.left&&event.clientX<=rect.right&&event.clientY>=rect.top&&event.clientY<=rect.bottom){event.preventDefault();event.stopPropagation();port?.postMessage({channel,type:"comment-activate",id:item.id});return}},true);const observeBody=()=>new MutationObserver(()=>{if(!items.length||timer)return;timer=setTimeout(()=>{timer=0;render(items)},500)}).observe(document.body,{childList:true,characterData:true,subtree:true});document.body?observeBody():addEventListener("DOMContentLoaded",observeBody)})();`
+const keyboardRuntime = `(()=>{const channel="posthog-canvas";let port;addEventListener("message",event=>{if(port||event.source!==parent||event.data?.channel!==channel||event.data?.type!=="connect"||!event.ports[0])return;port=event.ports[0];port.start()});addEventListener("keydown",event=>{if(!port||!event.isTrusted||!event.metaKey&&!event.ctrlKey)return;port.postMessage({channel,type:"keydown",key:event.key,code:event.code,metaKey:event.metaKey,ctrlKey:event.ctrlKey,shiftKey:event.shiftKey,altKey:event.altKey})})})();`
// Selection and highlight runtimes extend the shared canvas bridge.
const platformStylesheet = `
@import "tailwindcss";
@@ -531,7 +532,7 @@ async function buildCanvas(project) {
}
const cssPath = `assets/canvas-platform-${sha256(platformCss).slice(0, 10)}.css`
files.push(artifact(cssPath, platformCss))
- files.push(artifact(runtimePath, `${runtime}\n${selectionRuntime}\n${highlightRuntime}`))
+ files.push(artifact(runtimePath, `${runtime}\n${selectionRuntime}\n${highlightRuntime}\n${keyboardRuntime}`))
const networkOrigins = project.capabilities?.network?.origins ?? []
const connectSources = networkOrigins.length ? networkOrigins.join(' ') : "'none'"
const projectCsp = csp.replace("connect-src 'none'", `connect-src ${connectSources}`)
diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
index 40bce9e2c54a..633649e7a4eb 100644
--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts
@@ -338,5 +338,15 @@ export const canvasToHostMessageSchema = z.discriminatedUnion("type", [
type: z.literal("comment-activate"),
id: z.string().min(1).max(128),
}),
+ z.object({
+ channel: z.literal(CANVAS_CHANNEL),
+ type: z.literal("keydown"),
+ key: z.string().min(1).max(32),
+ code: z.string().max(32),
+ metaKey: z.boolean(),
+ ctrlKey: z.boolean(),
+ shiftKey: z.boolean(),
+ altKey: z.boolean(),
+ }),
]);
export type CanvasToHostMessage = z.infer<typeof canvasToHostMessageSchema>;
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
index 9efa820a5831..7adbcf9630e7 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHostMessageRouter.ts
@@ -14,6 +14,34 @@ const EXTERNAL_OPEN_MIN_INTERVAL_MS = 1_000;
const MAX_CONCURRENT_DATA_REQUESTS = 8;
const MAX_DATA_REQUEST_BYTES = 64 * 1024;
const DATA_REQUEST_TIMEOUT_MS = 30_000;
+const REPLAYABLE_SHORTCUT_KEYS = new Set([
+ ",",
+ "/",
+ "[",
+ "]",
+ "{",
+ "}",
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9",
+ "arrowdown",
+ "arrowleft",
+ "arrowright",
+ "arrowup",
+ "b",
+ "i",
+ "j",
+ "k",
+ "n",
+ "t",
+ "tab",
+]);
function isBoundedPayload(payload: unknown): boolean {
try {
@@ -183,6 +211,22 @@ export function createCanvasHostMessageRouter(
options.openExternal(message.url);
}
break;
+ case "keydown": {
+ if (!message.metaKey && !message.ctrlKey) break;
+ if (!REPLAYABLE_SHORTCUT_KEYS.has(message.key.toLowerCase())) break;
+ if (!(document.activeElement instanceof HTMLIFrameElement)) break;
+ const init = {
+ key: message.key,
+ code: message.code,
+ metaKey: message.metaKey,
+ ctrlKey: message.ctrlKey,
+ shiftKey: message.shiftKey,
+ altKey: message.altKey,
+ };
+ document.dispatchEvent(new KeyboardEvent("keydown", init));
+ document.dispatchEvent(new KeyboardEvent("keyup", init));
+ break;
+ }
case "ready":
options.callbacks().onReady?.();
break;
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/canvasHotkeyReplay.test.tsx b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHotkeyReplay.test.tsx
new file mode 100644
index 000000000000..981b4489e4d6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/canvasHotkeyReplay.test.tsx
@@ -0,0 +1,97 @@
+import type { CanvasToHostMessage } from "@posthog/core/canvas/freeformSchemas";
+import { renderHook } from "@testing-library/react";
+import { useHotkeys } from "react-hotkeys-hook";
+import { afterEach, describe, expect, it, type Mock, vi } from "vitest";
+import { createCanvasHostMessageRouter } from "./canvasHostMessageRouter";
+
+interface Harness {
+ onCommandMenu: Mock;
+ onReload: Mock;
+ route: (message: CanvasToHostMessage) => Promise<void>;
+}
+
+describe("canvas keydown replay", () => {
+ afterEach(() => {
+ document.body.replaceChildren();
+ });
+
+ function focusCanvasFrame(): void {
+ const frame = document.createElement("iframe");
+ document.body.append(frame);
+ frame.focus();
+ }
+
+ function setup(): Harness {
+ const onCommandMenu = vi.fn();
+ const onReload = vi.fn();
+ renderHook(() => {
+ useHotkeys("mod+k", onCommandMenu, { enableOnFormTags: true });
+ useHotkeys("mod+shift+r", onReload, { enableOnFormTags: true });
+ });
+ const route = createCanvasHostMessageRouter({
+ post: vi.fn(),
+ callbacks: () => ({ onDataRequest: vi.fn() }),
+ hasUserActivation: () => false,
+ openExternal: vi.fn(),
+ });
+ return { onCommandMenu, onReload, route };
+ }
+
+ const commandMenuKeydown: CanvasToHostMessage = {
+ channel: "posthog-canvas",
+ type: "keydown",
+ key: "k",
+ code: "KeyK",
+ metaKey: false,
+ ctrlKey: true,
+ shiftKey: false,
+ altKey: false,
+ };
+
+ it("fires the app hotkey for a combo pressed inside the canvas", async () => {
+ const { onCommandMenu, route } = setup();
+ focusCanvasFrame();
+
+ await route(commandMenuKeydown);
+
+ expect(onCommandMenu).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves no key held, so a later bare modifier press does not fire it again", async () => {
+ const { onCommandMenu, route } = setup();
+ focusCanvasFrame();
+ await route(commandMenuKeydown);
+
+ document.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Control",
+ code: "ControlLeft",
+ ctrlKey: true,
+ }),
+ );
+
+ expect(onCommandMenu).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores a shortcut outside the replayable set, so canvas code cannot reload the window", async () => {
+ const { onReload, route } = setup();
+ focusCanvasFrame();
+
+ await route({
+ ...commandMenuKeydown,
+ key: "r",
+ code: "KeyR",
+ shiftKey: true,
+ });
+
+ expect(onReload).not.toHaveBeenCalled();
+ });
+
+ it("ignores a keydown while the focus sits outside a canvas frame", async () => {
+ const { onCommandMenu, route } = setup();
+
+ await route(commandMenuKeydown);
+
+ expect(onCommandMenu).not.toHaveBeenCalled();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
index 18e0a40dc89c..93b570c8e044 100644
--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts
@@ -511,6 +511,19 @@ export function buildSandboxDocument(
const applyTheme = (theme) =>
document.documentElement.classList.toggle("dark", theme === "dark");
+ window.addEventListener("keydown", (e) => {
+ if (!e.isTrusted || (!e.metaKey && !e.ctrlKey)) return;
+ post({
+ type: "keydown",
+ key: e.key,
+ code: e.code,
+ metaKey: e.metaKey,
+ ctrlKey: e.ctrlKey,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ });
+ });
+
// --- error reporting (feeds the host's self-repair loop) ---
const reportError = (message, stack) =>
post({ type: "error", message: String(message ?? "Unknown error"), stack });