From 196eff39eb05752b45d9e2f84fb20c1d530dc166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 22 Nov 2026 17:59:22 +0000 Subject: [PATCH] fix(studio): a sealed preview never keeps the keyboard, so no key it reports is acted on (#8521) * test(studio): a sealed preview's key reports never act, even right after a real press * fix(studio): a sealed preview never keeps the keyboard, so no key it reports is acted on * test(studio): in Chrome, a key after a sealed preview takes focus reaches Studio * fix(studio): take the keyboard back from a sealed preview once focus has settled in it * test(studio): the sealed keyboard walk presses Delete once the clip is picked --- .github/workflows/ci.yml | 6 +- .../studio/src/hooks/appHotkeysDispatch.ts | 39 +-- .../useAppHotkeys.previewForwarding.test.tsx | 241 +++++------------- packages/studio/src/hooks/useAppHotkeys.ts | 37 +-- .../player/hooks/usePlaybackKeyboard.test.ts | 91 ++----- .../src/player/hooks/usePlaybackKeyboard.ts | 42 +-- .../src/player/lib/sealedFrameKeyboard.ts | 16 ++ .../e2e/fixtures/sealed-keyboard/index.html | 46 ++++ .../tests/e2e/sealed-preview-keyboard.mjs | 78 ++++++ 9 files changed, 241 insertions(+), 355 deletions(-) create mode 100644 packages/studio/src/player/lib/sealedFrameKeyboard.ts create mode 100644 packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html create mode 100644 packages/studio/tests/e2e/sealed-preview-keyboard.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7e1b3fad2..efa4cb1eb7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1239,7 +1239,7 @@ jobs: STUDIO_PROJECT_DIR="$PWD/packages/studio/data/projects/preview-video-regression" \ OUT_DIR=/tmp/preview-video-regression \ node packages/studio/tests/e2e/preview-video-regression.mjs - - name: Verify a sealed preview's proxy wait gets past its preflight + - name: Verify a sealed preview's proxy wait gets past its preflight, and that it never keeps the keyboard if: success() || failure() run: | set -euo pipefail @@ -1248,6 +1248,7 @@ jobs: cp packages/cli/src/templates/blank/index.html "$project/index.html" ffmpeg -hide_banner -loglevel error -y -f lavfi -i testsrc=size=320x180:rate=30 -t 1 \ -c:v libx264 -pix_fmt yuv420p "$project/clip.mov" + cp -R packages/studio/tests/e2e/fixtures/sealed-keyboard packages/studio/data/projects/sealed-keyboard VITE_STUDIO_OPAQUE_PREVIEW_ENABLED=1 NODE_ENV=production \ bun run --cwd packages/studio dev -- --port 5319 --strictPort & SERVER_PID=$! @@ -1258,6 +1259,9 @@ jobs: done STUDIO_URL="http://localhost:5319/#project/sealed-proxy" \ node packages/studio/tests/e2e/sealed-preview-proxy.mjs + STUDIO_URL="http://localhost:5319/#project/sealed-keyboard" \ + STUDIO_PROJECT_DIR="$PWD/packages/studio/data/projects/sealed-keyboard" \ + node packages/studio/tests/e2e/sealed-preview-keyboard.mjs - name: Upload gate evidence # The gate's whole output is machine-readable evidence, and a red run is # exactly when someone needs to read it. Keep it on failure too. diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.ts index ee6e27f775..f3a7dd9e30 100644 --- a/packages/studio/src/hooks/appHotkeysDispatch.ts +++ b/packages/studio/src/hooks/appHotkeysDispatch.ts @@ -9,12 +9,7 @@ import { shouldIgnoreHistoryShortcut } from "../utils/studioHelpers"; import { canSplitElement } from "../utils/timelineElementSplit"; import { trackStudioEvent } from "../utils/studioTelemetry"; import { razorClaimsKey } from "../player/lib/playbackShortcuts"; -import { - getStudioKeys, - keyHint, - matchesKey, - type StudioKeyAction, -} from "../player/components/studioShortcuts"; +import { getStudioKeys, keyHint, matchesKey } from "../player/components/studioShortcuts"; import { zoomTimelineToSelectedClips } from "../player/components/timelineZoomInput"; import { openAudioGainDialog } from "../player/components/audioGainDialogStore"; import type { LinkShortcutCallbacks } from "./linkShortcuts"; @@ -124,38 +119,6 @@ function dispatchClipboardKey(event: KeyboardEvent, cb: HotkeyCallbacks): boolea return true; } -/** Every action the dispatchers here and dispatchLinkShortcut answer: what a sealed preview forwards to them. */ -export const APP_HOTKEY_ACTIONS = [ - "undo", - "redo", - "redoAlt", - "tabCompositions", - "tabAssets", - "group", - "ungroup", - "copy", - "paste", - "cut", - "duplicate", - "zoomSelection", - "fullscreen", - "split", - "audioGain", - "razorTool", - "selectTool", - "selectLeftward", - "selectRightward", - "cancel", - "deleteSelected", - "deleteSelectedAlt", - "resetKeyframes", - "record", - "linkToggle", - "detachAudio", - "deleteLinked", - "deleteLinkedAlt", -] as const satisfies readonly StudioKeyAction[]; - /** Exported for tests: the shortcuts that act on the editor, each read as a combo at event time. */ export function dispatchModifierKey( event: KeyboardEvent, diff --git a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx index a79f1bbc5c..c17c203ba2 100644 --- a/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx +++ b/packages/studio/src/hooks/useAppHotkeys.previewForwarding.test.tsx @@ -1,6 +1,5 @@ // @vitest-environment happy-dom -import { readFileSync } from "node:fs"; import React, { act, useRef } from "react"; import type { Root } from "react-dom/client"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -9,8 +8,6 @@ import { usePlayerStore } from "../player/store/playerStore"; import { useAppHotkeys } from "./useAppHotkeys"; import { mountReactHarness } from "./domSelectionTestHarness"; import { trackStudioEvent } from "../utils/studioTelemetry"; -import { APP_HOTKEY_ACTIONS } from "./appHotkeysDispatch"; -import { PLAYBACK_ACTIONS } from "../player/hooks/usePlaybackKeyboard"; import { DEFAULT_STUDIO_KEYS } from "../player/components/studioShortcuts"; import { detachedFakeIframe, @@ -205,48 +202,31 @@ describe("preview iframe hotkey forwarding", () => { afterEach(() => closers.splice(0).forEach((close) => close())); // A frame whose document refuses Studio, reached only over the editing port it hands out per connect. - async function sealedFrame( - focus = { inPreview: true }, - { - inPlayer = false, - activation = { queued: [] as boolean[], otherwise: true, reads: 0 }, - } = {}, - ) { + async function sealedFrame() { const frame: Record = {}; const iframe = detachedFakeIframe(frame); const loaded = new Promise((resolve) => iframe.addEventListener("load", resolve, { once: true }), ); - const hasFocus = vi.spyOn(document, "hasFocus").mockImplementation(() => focus.inPreview); const player = document.createElement("div"); document.body.append(player); - if (!inPlayer) document.body.append(iframe); - if (inPlayer) { - const shadow = player.attachShadow({ mode: "open" }); - shadow.append(iframe); - Object.defineProperty(shadow, "activeElement", { - get: () => (focus.inPreview ? iframe : null), - }); - } - Object.defineProperty(document, "activeElement", { - configurable: true, - get: () => (!focus.inPreview ? document.body : inPlayer ? player : iframe), + const shadow = player.attachShadow({ mode: "open" }); + shadow.append(iframe); + const focus = { inPreview: true }; + Object.defineProperty(shadow, "activeElement", { + get: () => (focus.inPreview ? iframe : null), }); - // Studio's own window: active only after a real press or click, in the frame or out of it. + const blur = vi.spyOn(iframe, "blur").mockImplementation(() => { + focus.inPreview = false; + }); + // A real press or click just happened: Studio's window holds transient activation throughout. Object.defineProperty(window.navigator, "userActivation", { configurable: true, - get: () => { - activation.reads += 1; - const isActive = activation.queued.shift() ?? activation.otherwise; - return { isActive, hasBeenActive: isActive }; - }, + get: () => ({ isActive: true, hasBeenActive: true }), }); closers.push(() => { delete (window.navigator as { userActivation?: unknown }).userActivation; - hasFocus.mockRestore(); - delete (document as { activeElement?: unknown }).activeElement; player.remove(); - iframe.remove(); }); Object.defineProperty(iframe, "contentDocument", { value: null }); Object.defineProperty(frame, "document", { @@ -270,169 +250,82 @@ describe("preview iframe hotkey forwarding", () => { ); const report = (combo: string) => { const { mod, meta, ctrl, shift, alt, key } = parseCombo(combo)!; - ports.at(-1)!.postMessage({ - v: 1, - event: "key", - key: { - type: "keydown", - key, - code: "", - altKey: alt, - ctrlKey: ctrl, - metaKey: mod || meta, - shiftKey: shift, - repeat: false, - }, - }); + for (const port of ports) { + port.postMessage({ + v: 1, + event: "key", + key: { + type: "keydown", + key, + code: "", + altKey: alt, + ctrlKey: ctrl, + metaKey: mod || meta, + shiftKey: shift, + repeat: false, + }, + }); + } }; - const keyDown = (key: string, code: string) => - ports.at(-1)!.postMessage({ - v: 1, - event: "key", - key: { - type: "keydown", - key, - code, - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - repeat: false, - }, - }); + const answered = () => previewRequest(iframe, "max-z-index", {}, 1_000); await loaded; - return { iframe, watched, ports, keyDown, report, hasFocus }; + return { iframe, focus, blur, watched, report, answered }; } - it("leaves Studio's own reads of the preview answered while it forwards keys", async () => { - root = mountReactHarness(); - const { iframe, watched } = await sealedFrame(); - let read: Promise | undefined; - act(() => { - sync?.(iframe); - read = previewRequest(iframe, "max-z-index", {}, 1_000); - }); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - await expect(read).resolves.toEqual({ zIndex: 7 }); - }); - - it("deletes the selection on a Delete pressed inside the preview", async () => { - root = mountReactHarness(); - const { iframe, watched, keyDown } = await sealedFrame(); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - expect(new Set(watched[0])).toEqual( - new Set(APP_HOTKEY_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action])), - ); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - }); - - it("deletes the selection on a Delete pressed inside a preview held in the player's shadow root", async () => { - root = mountReactHarness(); - const { iframe, watched, keyDown } = await sealedFrame( - { inPreview: true }, - { inPlayer: true }, - ); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - }); - - it("ignores a key the preview reports while the person is not in the preview", async () => { - root = mountReactHarness(); - const focus = { inPreview: false }; - const { iframe, watched, keyDown, hasFocus } = await sealedFrame(focus); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(hasFocus).toHaveBeenCalledTimes(1)); - focus.inPreview = true; - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); - expect(hasFocus).toHaveBeenCalledTimes(2); - }); - const changesMade = () => [domDelete, historyUndo, historyRedo, ...Object.values(changes)].reduce( (n, spy) => n + spy.mock.calls.length, 0, ); - // fails without the fix: focus in the frame was taken as a person's press, so every report below acted. - it.each([false, true])( - "acts on no app shortcut the frame reports with no real press (read-only preview: %s)", - async (readOnly) => { - readOnlyPreview = readOnly; - usePlayerStore.setState({ - selectedElementIds: new Set(["clip-a"]), - selectedElementId: "clip-a", - }); - root = mountReactHarness(); - // Each report Studio reads is unpressed, then the real Delete after them is pressed. - const activation = { - queued: APP_HOTKEY_ACTIONS.map(() => false), - otherwise: true, - reads: 0, - }; - const { iframe, watched, report, keyDown } = await sealedFrame( - { inPreview: true }, - { inPlayer: true, activation }, - ); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - for (const action of APP_HOTKEY_ACTIONS) report(DEFAULT_STUDIO_KEYS[action]); - keyDown("Delete", "Delete"); - await vi.waitFor(() => expect(activation.reads).toBe(APP_HOTKEY_ACTIONS.length + 1)); - await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(readOnly ? 0 : 1)); - expect(changesMade()).toBe(readOnly ? 0 : 1); - expect(usePlayerStore.getState().selectedElementId).toBe("clip-a"); - }, - ); - - // Known gap, by decision: a report forged within a real press's activation window (about 5 s) still acts. - it("still acts on a forged report while a real press's activation lasts", async () => { + // fails without the fix: a report the frame forged while a real press's activation lasted (about 5 s) acted. + it("acts on no key the frame reports, even right after a real press", async () => { + usePlayerStore.setState({ + selectedElementIds: new Set(["clip-a"]), + selectedElementId: "clip-a", + }); root = mountReactHarness(); - const { iframe, watched, report } = await sealedFrame( - { inPreview: true }, - { inPlayer: true }, - ); + const { iframe, watched, report, answered } = await sealedFrame(); act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - report(DEFAULT_STUDIO_KEYS.undo); - await vi.waitFor(() => expect(historyUndo).toHaveBeenCalledTimes(1)); + await answered(); + for (const combo of Object.values(DEFAULT_STUDIO_KEYS)) report(combo); + await answered(); + expect(watched).toEqual([]); + expect(changesMade()).toBe(0); }); - it("stops watching on the preview's next load, from a new port", async () => { + // fails without the fix: focus could stay in the frame, where Studio only had the frame's word for a key. + it("takes the keyboard back on the next task whenever focus moves into the frame", async () => { root = mountReactHarness(); - const { iframe, watched, ports } = await sealedFrame(); + const { iframe, focus, blur } = await sealedFrame(); act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - act(() => sync?.(iframe)); - await vi.waitFor(() => expect(watched).toHaveLength(3)); - expect(watched.slice(1)).toContainEqual([]); - expect(ports).toHaveLength(2); + await vi.waitFor(() => expect(focus.inPreview).toBe(false)); + focus.inPreview = true; + window.dispatchEvent(new Event("blur")); + expect(focus.inPreview).toBe(true); + await vi.waitFor(() => expect(focus.inPreview).toBe(false)); + expect(blur).toHaveBeenCalledTimes(2); }); - it("watches every action the app's key dispatchers answer, so none is dead in a sealed preview", () => { - const read = (file: string) => readFileSync(new URL(file, import.meta.url), "utf8"); - const answered = new Set([ - ...[...read("./appHotkeysDispatch.ts").matchAll(/matchesKey\(\w+, "(\w+)"\)/g)].map( - (m) => m[1], - ), - ...[...read("./linkShortcuts.ts").matchAll(/\["(\w+)", "\w+"\]/g)].map((m) => m[1]), - ]); - expect(answered.size).toBeGreaterThan(20); - expect(new Set(APP_HOTKEY_ACTIONS)).toEqual(answered); + it("deletes the selection on a real Delete once Studio holds the keyboard", async () => { + root = mountReactHarness(); + const { iframe } = await sealedFrame(); + act(() => sync?.(iframe)); + window.dispatchEvent(new KeyboardEvent("keydown", { key: "Delete", code: "Delete" })); + await vi.waitFor(() => expect(domDelete).toHaveBeenCalledTimes(1)); }); - it("watches no key the playback keys also watch, so the frame forwards each press once", () => { - const app = new Set(APP_HOTKEY_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action])); - const shared = PLAYBACK_ACTIONS.map((action) => DEFAULT_STUDIO_KEYS[action]).filter((combo) => - app.has(combo), - ); - expect(shared).toEqual([]); + it("stops taking focus from the frame once the preview is gone", async () => { + root = mountReactHarness(); + const { iframe, focus, blur } = await sealedFrame(); + act(() => sync?.(iframe)); + await vi.waitFor(() => expect(blur).toHaveBeenCalledTimes(1)); + act(() => sync?.(null)); + focus.inPreview = true; + window.dispatchEvent(new Event("blur")); + // A task after the take-back would have run: it was queued first. + await new Promise((settled) => setTimeout(settled, 0)); + expect(blur).toHaveBeenCalledTimes(1); }); }); }); diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts index 185fe6ded4..207ba6b4c4 100644 --- a/packages/studio/src/hooks/useAppHotkeys.ts +++ b/packages/studio/src/hooks/useAppHotkeys.ts @@ -8,21 +8,15 @@ import { applyCaptionModelToIframe, isCaptionPreviewVisible, } from "../captions/components/CaptionOverlayUtils"; -import { - APP_HOTKEY_ACTIONS, - type HotkeyCallbacks, - dispatchModifierKey, - dispatchPlainKey, -} from "./appHotkeysDispatch"; +import { type HotkeyCallbacks, dispatchModifierKey, dispatchPlainKey } from "./appHotkeysDispatch"; import { useEditHistoryActions, type EditHistoryHandle, type UseEditHistoryActionsOptions, } from "./useEditHistoryActions"; import { useStableHandlers } from "./useStableHandlers"; -import { createEditingPortClient } from "@hyperframes/core/runtime/editing-port"; import { previewFrameOpaque } from "../player/lib/previewChannel"; -import { getStudioKey, subscribeStudioKeys } from "../player/components/studioShortcuts"; +import { keepKeyboardOutOfSealedFrame } from "../player/lib/sealedFrameKeyboard"; function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null { try { @@ -32,31 +26,6 @@ function iframeContentWindow(iframe: HTMLIFrameElement | null): Window | null { } } -// A port of its own: watch-keys replaces a port's whole list, and playback watches its keys on the shared one. -function forwardSealedFrameKeys(iframe: HTMLIFrameElement, onKeyDown: (e: KeyboardEvent) => void) { - const client = createEditingPortClient({ iframe }); - const watch = (combos: string[]) => void client.request("watch-keys", { combos }).catch(() => {}); - const watchApp = () => watch(APP_HOTKEY_ACTIONS.map(getStudioKey)); - watchApp(); - const stopRebinds = subscribeStudioKeys(watchApp); - // The frame can report keys and take focus, but only a real press or click activates Studio's own window. - const pressedByPerson = () => - iframe.ownerDocument.hasFocus() && - (iframe.getRootNode() as Document | ShadowRoot).activeElement === iframe && - iframe.ownerDocument.defaultView?.navigator.userActivation?.isActive === true; - const stopKeys = client.onKey((key) => { - if (key.type === "keydown" && pressedByPerson()) onKeyDown(new KeyboardEvent(key.type, key)); - }); - return () => { - stopRebinds(); - stopKeys(); - void client - .request("watch-keys", { combos: [] }) - .catch(() => {}) - .finally(() => client.dispose()); - }; -} - function safeAddListener(t: EventTarget | null, type: string, h: EventListener, capture = false) { try { t?.addEventListener(type, h, capture); @@ -281,7 +250,7 @@ export function useAppHotkeys({ previewHistoryCleanupRef.current?.(); previewHistoryCleanupRef.current = null; if (iframe && previewFrameOpaque(iframe)) { - previewHistoryCleanupRef.current = forwardSealedFrameKeys(iframe, handleAppKeyDown); + previewHistoryCleanupRef.current = keepKeyboardOutOfSealedFrame(iframe); return; } const win = iframeContentWindow(iframe); diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts index b7b0e6d02c..3e379009ae 100644 --- a/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts +++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.test.ts @@ -9,6 +9,7 @@ import { usePlayerStore } from "../store/playerStore"; import { setStudioKeys } from "../components/studioShortcuts"; import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; import { detachedFakeIframe, serveEditingRequests } from "./timelinePlayerTestHarness"; +import { previewRequest } from "../lib/previewChannel"; globalThis.IS_REACT_ACT_ENVIRONMENT = true; @@ -487,11 +488,12 @@ describe("usePlaybackKeyboard: modifier combos and named keys", () => { }); }); +// fails without the fix: the sealed frame was asked to report playback keys, and every report it sent was acted on. describe("usePlaybackKeyboard: a sealed preview frame", () => { const closers: Array<() => void> = []; afterEach(() => closers.splice(0).forEach((close) => close())); - function sealedFrame() { + it("asks the frame for no keys and plays on none it reports", async () => { const frame: Record = {}; const iframe = detachedFakeIframe(frame); Object.defineProperty(iframe, "contentDocument", { value: null }); @@ -500,28 +502,30 @@ describe("usePlaybackKeyboard: a sealed preview frame", () => { throw new DOMException("blocked", "SecurityError"); }, }); - const watched: string[][] = []; - let port: MessagePort | null = null; + const watched: unknown[] = []; + const ports: MessagePort[] = []; closers.push( serveEditingRequests( frame, (kind, params) => { - if (kind !== "watch-keys") return null; - const { combos } = params as { combos: string[] }; - watched.push(combos); - return { watching: combos.length }; + if (kind === "max-z-index") return { zIndex: 1 }; + if (kind === "watch-keys") watched.push(params); + return null; }, - (framePort) => (port = framePort), + (port) => ports.push(port), ), ); - const forward = (type: "keydown" | "keyup", key: string, code: string) => - port!.postMessage({ + const { attach, spies } = setupHook(iframe); + attach(); + await previewRequest(iframe, "max-z-index", {}, 1_000); + for (const port of ports) { + port.postMessage({ v: 1, event: "key", key: { - type, - key, - code, + type: "keydown", + key: " ", + code: "Space", altKey: false, ctrlKey: false, metaKey: false, @@ -529,62 +533,9 @@ describe("usePlaybackKeyboard: a sealed preview frame", () => { repeat: false, }, }); - return { iframe, watched, forward }; - } - - it("asks the frame for exactly the playback keys, and again when they are remapped", async () => { - const { iframe, watched } = sealedFrame(); - setupHook(iframe).attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - expect(new Set(watched[0])).toEqual( - new Set([ - "Space", - "ArrowLeft", - "ArrowRight", - "shift+ArrowLeft", - "shift+ArrowRight", - "m", - "shift+l", - "k", - "j", - "l", - "i", - "shift+i", - "o", - "shift+o", - "a", - "e", - ]), - ); - act(() => setStudioKeys({ playPause: "p" })); - await vi.waitFor(() => expect(watched).toHaveLength(2)); - expect(watched[1]).toContain("p"); - expect(watched[1]).not.toContain("Space"); - }); - - it("plays and steps from the keys the frame forwards, keyups included", async () => { - const { iframe, watched, forward } = sealedFrame(); - const { attach, spies } = setupHook(iframe); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - forward("keydown", " ", "Space"); - await vi.waitFor(() => expect(spies.play).toHaveBeenCalledOnce()); - forward("keydown", "k", "KeyK"); - forward("keydown", "l", "KeyL"); - await vi.waitFor(() => expect(spies.seek).toHaveBeenCalledOnce()); - forward("keyup", "k", "KeyK"); - forward("keydown", "l", "KeyL"); - await vi.waitFor(() => expect(spies.play).toHaveBeenCalledTimes(2)); - }); - - it("stops watching when its listeners are replaced", async () => { - const { iframe, watched } = sealedFrame(); - const { attach } = setupHook(iframe); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(1)); - attach(); - await vi.waitFor(() => expect(watched).toHaveLength(3)); - expect(watched[1]).toEqual([]); - expect(watched[2]).toEqual(watched[0]); + } + await previewRequest(iframe, "max-z-index", {}, 1_000); + expect(watched).toEqual([]); + expect(spies.play).not.toHaveBeenCalled(); }); }); diff --git a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts index 8486cf7a83..f72975d3fc 100644 --- a/packages/studio/src/player/hooks/usePlaybackKeyboard.ts +++ b/packages/studio/src/player/hooks/usePlaybackKeyboard.ts @@ -15,13 +15,8 @@ import { } from "../lib/playbackShortcuts"; import { canvasNudgeKeysClaimed } from "../../utils/canvasNudgeGate"; import { usePlayerStore } from "../store/playerStore"; -import { - getStudioKey, - matchesKey, - subscribeStudioKeys, - type StudioKeyAction, -} from "../components/studioShortcuts"; -import { previewEditingClient, previewFrameOpaque } from "../lib/previewChannel"; +import { matchesKey, type StudioKeyAction } from "../components/studioShortcuts"; +import { previewFrameOpaque } from "../lib/previewChannel"; import { resolveCanvasNudgeDelta } from "../../components/editor/domEditNudge"; import { stepFrameTime } from "../lib/time"; import { useLinkedClipPreferences } from "../../utils/linkedClipPreferences"; @@ -45,7 +40,7 @@ const FRAME_STEPS = { frameBackTen: -10, frameForwardTen: 10, } as const; -export const PLAYBACK_ACTIONS = [ +const PLAYBACK_ACTIONS = [ "playPause", ...(Object.keys(FRAME_STEPS) as Array), "mute", @@ -73,28 +68,6 @@ function ignoresPlaybackKey(e: KeyboardEvent): boolean { }); } -type KeyHandlerRef = React.RefObject<(e: KeyboardEvent) => void>; - -function forwardSealedFrameKeys( - iframe: HTMLIFrameElement, - keyDown: KeyHandlerRef, - keyUp: KeyHandlerRef, -): () => void { - const client = previewEditingClient(iframe); - const watch = (combos: string[]) => void client.request("watch-keys", { combos }).catch(() => {}); - const watchPlayback = () => watch(PLAYBACK_ACTIONS.map(getStudioKey)); - watchPlayback(); - const stopRebinds = subscribeStudioKeys(watchPlayback); - const stopKeys = client.onKey((key) => - (key.type === "keydown" ? keyDown : keyUp).current(new KeyboardEvent(key.type, key)), - ); - return () => { - stopRebinds(); - stopKeys(); - watch([]); - }; -} - function handleWorkAreaKey( e: KeyboardEvent, action: PlaybackAction, @@ -227,14 +200,7 @@ export function usePlaybackKeyboard({ iframeShortcutCleanupRef.current?.(); iframeShortcutCleanupRef.current = null; const iframe = iframeRef.current; - if (iframe && previewFrameOpaque(iframe)) { - iframeShortcutCleanupRef.current = forwardSealedFrameKeys( - iframe, - playbackKeyDownRef, - playbackKeyUpRef, - ); - return; - } + if (iframe && previewFrameOpaque(iframe)) return; let iframeWin: Window | null = null; let iframeDoc: Document | null = null; diff --git a/packages/studio/src/player/lib/sealedFrameKeyboard.ts b/packages/studio/src/player/lib/sealedFrameKeyboard.ts new file mode 100644 index 0000000000..ebd6e08fd2 --- /dev/null +++ b/packages/studio/src/player/lib/sealedFrameKeyboard.ts @@ -0,0 +1,16 @@ +export function keepKeyboardOutOfSealedFrame(iframe: HTMLIFrameElement): () => void { + const studioWindow = iframe.ownerDocument.defaultView; + let attached = true; + // Chrome drops a blur while focus is still moving into the frame; on the next task the move has settled. + const reclaim = () => + studioWindow?.setTimeout(() => { + const holder = (iframe.getRootNode() as Document | ShadowRoot).activeElement; + if (attached && holder === iframe) iframe.blur(); + }, 0); + reclaim(); + studioWindow?.addEventListener("blur", reclaim); + return () => { + attached = false; + studioWindow?.removeEventListener("blur", reclaim); + }; +} diff --git a/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html b/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html new file mode 100644 index 0000000000..0e6a1a24e3 --- /dev/null +++ b/packages/studio/tests/e2e/fixtures/sealed-keyboard/index.html @@ -0,0 +1,46 @@ + + + + + Sealed keyboard + + + +
+
+ +
+ + diff --git a/packages/studio/tests/e2e/sealed-preview-keyboard.mjs b/packages/studio/tests/e2e/sealed-preview-keyboard.mjs new file mode 100644 index 0000000000..c05574d406 --- /dev/null +++ b/packages/studio/tests/e2e/sealed-preview-keyboard.mjs @@ -0,0 +1,78 @@ +// A sealed preview never keeps the keyboard: when its own script focuses an input in it, the next real key still +// reaches Studio; a real Delete after a canvas click deletes the picked clip. STUDIO_URL: a Studio started with +// VITE_STUDIO_OPAQUE_PREVIEW_ENABLED=1 on the sealed-keyboard fixture, whose folder is STUDIO_PROJECT_DIR. +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { launchStudioChrome } from "./chrome-executable.mjs"; + +const url = process.env.STUDIO_URL; +const projectDir = process.env.STUDIO_PROJECT_DIR; +assert( + url && projectDir, + "STUDIO_URL and STUDIO_PROJECT_DIR must point at a sealed Studio's sealed-keyboard project", +); +const saved = () => readFileSync(join(projectDir, "index.html"), "utf8"); +/** A person's click on an element of the preview, mapped through the frame's on-screen scale. */ +async function clickInPreview(page, frame, selector) { + const inFrame = await frame.evaluate((s) => { + const b = document.querySelector(s).getBoundingClientRect(); + return { x: b.x + b.width / 2, y: b.y + b.height / 2, width: innerWidth }; + }, selector); + const iframe = await page.evaluateHandle(() => + document.querySelector("hyperframes-player").shadowRoot.querySelector("iframe"), + ); + const box = await iframe.boundingBox(); + const scale = box.width / inFrame.width; + await page.mouse.click(box.x + inFrame.x * scale, box.y + inFrame.y * scale, { delay: 120 }); +} +const { browser } = await launchStudioChrome(); +try { + const page = await browser.newPage(); + page.setDefaultTimeout(90_000); + await page.setViewport({ width: 1600, height: 1000 }); + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => document.querySelector("hyperframes-player")?.painted === true); + const frame = page.frames().find((f) => /\/preview\/~[\w-]{43}/.test(f.url())); + assert.ok(frame, "the preview loads under its frame token"); + assert.equal( + await frame.evaluate(() => String(window.origin)), + "null", + "the preview frame is sealed", + ); + await page.evaluate(() => { + window.__studioKeys = []; + addEventListener("keydown", (e) => window.__studioKeys.push(e.key), true); + }); + const keyboardBackInStudio = () => + page.waitForFunction(() => { + let el = document.activeElement; + while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement; + return el?.tagName !== "IFRAME"; + }); + // The frame's own script puts focus on an ordinary input in it, as a composition may. + await frame.evaluate(() => document.getElementById("field").focus()); + await keyboardBackInStudio(); + await page.keyboard.press("y"); + await page.waitForFunction(() => window.__studioKeys.includes("y")); + assert.equal( + await frame.evaluate(() => document.getElementById("field").value), + "", + "the frame got no key", + ); + + // A clip picked on the canvas, then a real Delete: Studio deletes it. + assert.ok(saved().includes('id="plain"')); + await clickInPreview(page, frame, "#plain"); + await page.waitForFunction( + () => new URLSearchParams(location.hash.split("?")[1]).get("selId") === "plain", + ); + await keyboardBackInStudio(); + await page.keyboard.press("Delete"); + for (let i = 0; i < 100 && saved().includes('id="plain"'); i++) + await new Promise((r) => setTimeout(r, 100)); + assert.ok(!saved().includes('id="plain"'), "a real Delete after a canvas click deletes the clip"); + console.log(JSON.stringify({ studioKeys: await page.evaluate(() => window.__studioKeys) })); +} finally { + await browser.close(); +}