fix(studio): a key pressed in a sealed preview reaches Studio's hotkeys (#8444)

* test(studio): a key pressed in a sealed preview inside the player reaches Studio

* fix(studio): a key pressed in a sealed preview reaches Studio's hotkeys

* test(core): a key typed into a field inside a shadow root stays with the field

* fix(core): a key typed into a field inside a shadow root is not taken as a shortcut

* test(studio): the sealed preview fixture connects after its frame has loaded

* test(core): a modal or button around a shadow root still owns the keys focused inside it

* fix(core): a modal or button around a shadow root still owns the keys focused inside it

* fix(core): a key target with no shadow root still reaches the playback checks
This commit is contained in:
Miguel Ángel
2026-11-22 06:57:04 +00:00
committed by GitHub
parent 84ff7d71c2
commit 34d5c4678d
5 changed files with 130 additions and 20 deletions
@@ -760,6 +760,31 @@ describe("installEditingAgent", () => {
]);
});
it("leaves a key typed into a field inside a shadow root to the field", async () => {
const host = document.createElement("div");
document.body.append(host);
const field = host
.attachShadow({ mode: "open" })
.appendChild(document.createElement("input"));
field.focus();
const port = connectedPort();
await watch(port, ["b"]);
const seen = collect(port);
const event = new KeyboardEvent("keydown", {
key: "b",
code: "KeyB",
bubbles: true,
cancelable: true,
composed: true,
});
field.dispatchEvent(event);
expect(event.defaultPrevented).toBe(false);
expect(await received(port, seen)).toEqual([]);
host.remove();
});
it("leaves a key the film cancelled before it", async () => {
const film = (event: Event) => event.preventDefault();
window.addEventListener("keydown", film, true);
+47
View File
@@ -0,0 +1,47 @@
import { afterEach, expect, it } from "vitest";
import { isTypingTarget, shouldIgnorePlaybackShortcutTarget } from "./typingTarget";
afterEach(() => document.body.replaceChildren());
it("treats a shadow host as typing while a field inside its shadow root has focus", () => {
const host = document.createElement("div");
document.body.append(host);
const field = host.attachShadow({ mode: "open" }).appendChild(document.createElement("input"));
field.focus();
expect(document.activeElement).toBe(host);
expect(isTypingTarget(document.activeElement)).toBe(true);
});
it("does not treat a shadow host as typing when its focused element is not a field", () => {
const host = document.createElement("div");
document.body.append(host);
const frame = host.attachShadow({ mode: "open" }).appendChild(document.createElement("iframe"));
frame.focus();
expect(isTypingTarget(document.activeElement)).toBe(false);
});
function focusedInShadowOf(container: HTMLElement): HTMLElement {
document.body.append(container);
const host = container.appendChild(document.createElement("span"));
const leaf = host.attachShadow({ mode: "open" }).appendChild(document.createElement("span"));
leaf.tabIndex = 0;
leaf.focus();
return leaf;
}
it("treats focus inside a shadow root whose host sits in a modal dialog as typing", () => {
const dialog = document.createElement("div");
dialog.setAttribute("role", "dialog");
dialog.setAttribute("aria-modal", "true");
focusedInShadowOf(dialog);
expect(isTypingTarget(document.activeElement)).toBe(true);
});
it("leaves playback keys to a button that holds the focused shadow root's host", () => {
focusedInShadowOf(document.createElement("button"));
expect(shouldIgnorePlaybackShortcutTarget(document.activeElement)).toBe(true);
});
+22 -13
View File
@@ -15,15 +15,18 @@
* Space and arrow keys even when they do not accept text.
*/
export function isTypingTarget(target: EventTarget | null): boolean {
const element = asElement(target);
const element = elementThroughShadowFocus(target);
if (!element) return false;
if (element.isContentEditable) return true;
return element.closest(TYPING_SELECTOR) !== null;
return closestAcrossShadow(element, TYPING_SELECTOR) !== null;
}
/** Plain keys (arrows, Space, Delete) also belong to a focused slider or player; Cmd shortcuts still do not. */
export function ownsPlainKeys(target: EventTarget | null): boolean {
return isTypingTarget(target) || asElement(target)?.closest(KEY_OWNING_CONTROLS) != null;
return (
isTypingTarget(target) ||
closestAcrossShadow(elementThroughShadowFocus(target), KEY_OWNING_CONTROLS) != null
);
}
// A slider steps and a native player seeks and plays with these keys themselves.
@@ -49,10 +52,21 @@ const TYPING_SELECTOR = [
".cm-editor",
].join(",");
function asElement(target: EventTarget | null): HTMLElement | null {
function elementThroughShadowFocus(target: EventTarget | null): HTMLElement | null {
if (!target || typeof target !== "object") return null;
const candidate = target as { closest?: unknown; isContentEditable?: unknown };
return typeof candidate.closest === "function" ? (target as HTMLElement) : null;
const candidate = target as { closest?: unknown; shadowRoot?: ShadowRoot | null };
if (typeof candidate.closest !== "function") return null;
const inner = candidate.shadowRoot?.activeElement;
return inner ? elementThroughShadowFocus(inner) : (target as HTMLElement);
}
function closestAcrossShadow(element: Element | null, selector: string): Element | null {
for (let at = element; at; ) {
const hit = at.closest(selector);
if (hit) return hit;
at = (at.getRootNode?.() as Partial<ShadowRoot> | undefined)?.host ?? null;
}
return null;
}
const PLAYBACK_SHORTCUT_IGNORED_SELECTOR = [
@@ -71,13 +85,8 @@ export function shouldIgnorePlaybackShortcutTarget(target: EventTarget | null):
// Anything the user is typing into owns its keys outright, editable elements
// included: a letter claimed here never reaches the text. So does a native player.
if (ownsPlainKeys(target)) return true;
if (!target || typeof target !== "object") return false;
const candidate = target as { closest?: unknown };
if (typeof candidate.closest !== "function") return false;
return (
(candidate.closest as (selector: string) => Element | null).call(
target,
PLAYBACK_SHORTCUT_IGNORED_SELECTOR,
) !== null
closestAcrossShadow(elementThroughShadowFocus(target), PLAYBACK_SHORTCUT_IGNORED_SELECTOR) !=
null
);
}
@@ -182,17 +182,32 @@ 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.
function sealedFrame(focus = { inPreview: true }) {
async function sealedFrame(focus = { inPreview: true }, { inPlayer = false } = {}) {
const frame: Record<string, unknown> = {};
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 ? iframe : document.body),
get: () => (!focus.inPreview ? document.body : inPlayer ? player : iframe),
});
closers.push(() => {
hasFocus.mockRestore();
delete (document as { activeElement?: unknown }).activeElement;
player.remove();
iframe.remove();
});
Object.defineProperty(iframe, "contentDocument", { value: null });
Object.defineProperty(frame, "document", {
@@ -229,12 +244,13 @@ describe("preview iframe hotkey forwarding", () => {
repeat: false,
},
});
await loaded;
return { iframe, watched, ports, keyDown, hasFocus };
}
it("leaves Studio's own reads of the preview answered while it forwards keys", async () => {
root = mountReactHarness(<Harness />);
const { iframe, watched } = sealedFrame();
const { iframe, watched } = await sealedFrame();
let read: Promise<unknown> | undefined;
act(() => {
sync?.(iframe);
@@ -246,7 +262,7 @@ describe("preview iframe hotkey forwarding", () => {
it("deletes the selection on a Delete pressed inside the preview", async () => {
root = mountReactHarness(<Harness />);
const { iframe, watched, keyDown } = sealedFrame();
const { iframe, watched, keyDown } = await sealedFrame();
act(() => sync?.(iframe));
await vi.waitFor(() => expect(watched).toHaveLength(1));
expect(new Set(watched[0])).toEqual(
@@ -256,10 +272,22 @@ describe("preview iframe hotkey forwarding", () => {
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(<Harness />);
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(<Harness />);
const focus = { inPreview: false };
const { iframe, watched, keyDown, hasFocus } = sealedFrame(focus);
const { iframe, watched, keyDown, hasFocus } = await sealedFrame(focus);
act(() => sync?.(iframe));
await vi.waitFor(() => expect(watched).toHaveLength(1));
keyDown("Delete", "Delete");
@@ -272,7 +300,7 @@ describe("preview iframe hotkey forwarding", () => {
it("stops watching on the preview's next load, from a new port", async () => {
root = mountReactHarness(<Harness />);
const { iframe, watched, ports } = sealedFrame();
const { iframe, watched, ports } = await sealedFrame();
act(() => sync?.(iframe));
await vi.waitFor(() => expect(watched).toHaveLength(1));
act(() => sync?.(iframe));
+2 -1
View File
@@ -41,7 +41,8 @@ function forwardSealedFrameKeys(iframe: HTMLIFrameElement, onKeyDown: (e: Keyboa
const stopRebinds = subscribeStudioKeys(watchApp);
// The frame can report keys nobody pressed: act only while the person is in the preview.
const focused = () =>
iframe.ownerDocument.hasFocus() && iframe.ownerDocument.activeElement === iframe;
iframe.ownerDocument.hasFocus() &&
(iframe.getRootNode() as Document | ShadowRoot).activeElement === iframe;
const stopKeys = client.onKey((key) => {
if (key.type === "keydown" && focused()) onKeyDown(new KeyboardEvent(key.type, key));
});