Skip to content

Commit 72adefb

Browse files
authored
fix(ui): keep modal keyboard ownership across shadow roots (#129747)
1 parent 34d5fd1 commit 72adefb

9 files changed

Lines changed: 132 additions & 16 deletions

‎ui/src/app/app-host-native-shell.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import { render } from "lit";
44
import { afterEach, describe, expect, it, vi } from "vitest";
55
import "../components/sidebar-update-card.ts";
6+
import { getRenderedModalDialog, installDialogPolyfill } from "../test-helpers/modal-dialog.ts";
67
import "./app-host.ts";
78
import { resetAppHostTestGlobals, type ShellKeyboardState } from "./app-host.test-support.ts";
89
import type { ApplicationContext } from "./context.ts";
@@ -149,6 +150,42 @@ describe("OpenClaw native shell", () => {
149150
}
150151
});
151152

153+
it("lets a shadow-root confirmation own Escape without leaving Settings", async () => {
154+
const restoreDialogPolyfill = installDialogPolyfill();
155+
const navigate = vi.fn();
156+
const shell = document.createElement(
157+
"openclaw-app-shell",
158+
) as unknown as ShellSettingsEscapeState;
159+
shell.runtime = {
160+
context: {
161+
navigate,
162+
overlays: { snapshot: { devicePairSetupOpen: false } },
163+
} as unknown as ApplicationContext,
164+
};
165+
shell.lastWorkspaceLocation = { routeId: "usage", pathname: "/usage", search: "" };
166+
shell.navDrawerOpen = false;
167+
shell.routeState = { routeId: "appearance" };
168+
const container = document.body.appendChild(document.createElement("div"));
169+
const modal = container.appendChild(document.createElement("openclaw-modal-dialog"));
170+
const cancel = modal.appendChild(document.createElement("button"));
171+
172+
try {
173+
const { dialog } = await getRenderedModalDialog(container);
174+
expect(dialog.open).toBe(true);
175+
expect(document.querySelector("dialog[open]")).toBeNull();
176+
cancel.addEventListener("keydown", (event) => shell.handleDocumentKeydown(event));
177+
const event = new KeyboardEvent("keydown", { key: "Escape", cancelable: true });
178+
179+
cancel.dispatchEvent(event);
180+
181+
expect(event.defaultPrevented).toBe(false);
182+
expect(navigate).not.toHaveBeenCalled();
183+
} finally {
184+
container.remove();
185+
restoreDialogPolyfill();
186+
}
187+
});
188+
152189
it("toggles the navigation sidebar when the native macOS titlebar button fires", () => {
153190
const snapshot = { navCollapsed: false };
154191
const update = vi.fn((next: { navCollapsed: boolean }) => {

‎ui/src/app/app-shell-chrome.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ export class ShellChromeOwner {
486486
?.isOpen ||
487487
overlaySnapshot?.devicePairSetupOpen ||
488488
host.approvalOverlay?.dialogOpen === true ||
489-
document.querySelector("dialog[open]")
489+
document.openClawModalLayers?.size
490490
) {
491491
return true;
492492
}

‎ui/src/components/modal-dialog.test.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ describe("openclaw-modal-dialog", () => {
4848
});
4949

5050
it("opens a labelled modal dialog with an optional description", async () => {
51-
const { webAwesomeDialog, dialog } = await renderModal();
51+
const { modal, webAwesomeDialog, dialog } = await renderModal();
5252

5353
expect(dialog.open).toBe(true);
5454
expect(dialog.localName).toBe("dialog");
@@ -57,6 +57,18 @@ describe("openclaw-modal-dialog", () => {
5757
expect(dialog.getAttribute("aria-label")).toBe("Confirm action");
5858
expect(dialog.getAttribute("aria-description")).toBe("Review the operation before continuing.");
5959
expect(dialog.getRootNode()).toBe(webAwesomeDialog.shadowRoot);
60+
expect(document.openClawModalLayers?.has(modal)).toBe(true);
61+
62+
modal.hide();
63+
await modal.updateComplete;
64+
expect(document.openClawModalLayers?.has(modal)).toBe(false);
65+
66+
modal.show();
67+
await modal.updateComplete;
68+
expect(document.openClawModalLayers?.has(modal)).toBe(true);
69+
70+
modal.remove();
71+
expect(document.openClawModalLayers?.has(modal)).toBe(false);
6072
});
6173

6274
it("focuses the dialog container first", async () => {

‎ui/src/components/modal-dialog.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import { css, html, type PropertyValues } from "lit";
55
import { property, query } from "lit/decorators.js";
66
import { OpenClawLitElement } from "../lit/openclaw-element.ts";
77

8-
const modalToastLayers = (document.openClawModalToastLayers ??= new Set<HTMLElement>());
8+
const modalLayers = (document.openClawModalLayers ??= new Set<HTMLElement>());
99

10-
function setModalToastLayer(modal: HTMLElement, open: boolean) {
11-
modalToastLayers.delete(modal);
10+
function setModalLayer(modal: HTMLElement, open: boolean) {
11+
modalLayers.delete(modal);
1212
if (open) {
13-
modalToastLayers.add(modal);
13+
modalLayers.add(modal);
1414
}
1515
}
1616

@@ -144,7 +144,7 @@ export class OpenClawModalDialog extends OpenClawLitElement {
144144
}
145145

146146
override disconnectedCallback() {
147-
setModalToastLayer(this, false);
147+
setModalLayer(this, false);
148148
this.syncGeneration += 1;
149149
const webAwesomeDialog = this.webAwesomeDialog;
150150
const dialog = webAwesomeDialog?.shadowRoot?.querySelector("dialog");
@@ -182,7 +182,7 @@ export class OpenClawModalDialog extends OpenClawLitElement {
182182

183183
protected override updated(changed: PropertyValues<this>) {
184184
if (changed.has("open")) {
185-
setModalToastLayer(this, this.open);
185+
setModalLayer(this, this.open);
186186
}
187187
void this.syncAccessibility();
188188
void this.syncDialogOpen();
@@ -330,7 +330,7 @@ if (!customElements.get("openclaw-modal-dialog")) {
330330

331331
declare global {
332332
interface Document {
333-
openClawModalToastLayers?: Set<HTMLElement>;
333+
openClawModalLayers?: Set<HTMLElement>;
334334
}
335335

336336
interface HTMLElementTagNameMap {

‎ui/src/e2e/channels-whatsapp-logout.e2e.test.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,20 @@ suite.define(() => {
204204
await expect(firstConfirm.textContent()).resolves.toContain(
205205
"Logging out of account default stops its listener and deletes its saved credentials.",
206206
);
207-
await firstConfirm.getByRole("button", { name: "Cancel" }).click();
207+
await firstConfirm.getByRole("button", { name: "Cancel" }).focus();
208+
await page.keyboard.press("Escape");
209+
if (captureUiProofEnabled) {
210+
await mkdir(uiProofArtifactDir, { recursive: true });
211+
await page.screenshot({
212+
animations: "disabled",
213+
fullPage: true,
214+
path: path.join(
215+
uiProofArtifactDir,
216+
`modal-escape-${process.env.OPENCLAW_UI_PROOF_LABEL ?? "dismissed"}.png`,
217+
),
218+
});
219+
}
220+
await expect.poll(() => new URL(page.url()).pathname).toBe("/settings/channels");
208221
await expect.poll(() => page.locator("openclaw-modal-dialog").count()).toBe(1);
209222
await expect.poll(async () => gateway.getRequests("channels.logout")).toHaveLength(0);
210223
await expect(qr.getAttribute("src")).resolves.toBe(QR_DATA_URL);

‎ui/src/lib/toast.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@ const DEFAULT_TOAST_DURATION_MS = 6_000;
2626
const TOAST_EXIT_FALLBACK_MS = 450;
2727

2828
function activeModalToastLayer() {
29-
return [...(document.openClawModalToastLayers ?? [])].findLast(
30-
(candidate) => candidate.isConnected,
31-
);
29+
return [...(document.openClawModalLayers ?? [])].findLast((candidate) => candidate.isConnected);
3230
}
3331

3432
// Outcomes reported during startup (a restored post-update result, for example)

‎ui/src/pages/chat/chat-pane-lifecycle.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ import { ChatPaneSessionPanelToggleController } from "./chat-pane-session-panel-
4646
import {
4747
CHAT_AUTOTYPE_EXEMPT_SELECTOR,
4848
CHAT_COMPOSER_TEXTAREA_SELECTOR,
49-
CHAT_MODAL_SELECTOR,
5049
CHAT_OPEN_DETAILS_SELECTOR,
5150
CHAT_SPACE_ACTIVATION_SELECTOR,
5251
keyboardEventPathMatches,
@@ -351,7 +350,8 @@ export abstract class ChatPaneLifecycle extends ChatPaneSessionCreation {
351350
event.key.length === 1 &&
352351
!keyboardEventPathMatches(event, CHAT_AUTOTYPE_EXEMPT_SELECTOR) &&
353352
!(event.key === " " && keyboardEventPathMatches(event, CHAT_SPACE_ACTIVATION_SELECTOR)) &&
354-
!document.querySelector(CHAT_MODAL_SELECTOR)
353+
!document.openClawModalLayers?.size &&
354+
!document.querySelector("[aria-modal='true']")
355355
) {
356356
const composer = this.querySelector<HTMLTextAreaElement>(CHAT_COMPOSER_TEXTAREA_SELECTOR);
357357
if (composer && !composer.disabled && !composer.readOnly) {

‎ui/src/pages/chat/chat-pane-shared.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,6 @@ export const CHAT_AUTOTYPE_EXEMPT_SELECTOR =
239239
"input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='combobox'], [role='listbox'], [role='textbox'], [data-chat-autotype-exempt]";
240240
export const CHAT_SPACE_ACTIVATION_SELECTOR =
241241
"a[href], button, summary, [role='button'], [role='checkbox'], [role='link'], [role='radio'], [role='switch']";
242-
export const CHAT_MODAL_SELECTOR = "dialog[open], [aria-modal='true']";
243242

244243
export const NEW_SESSION_ACTIVE_RUN_MESSAGE =
245244
"Start a new session after the active run or queued messages finish.";

‎ui/src/pages/chat/chat-pane.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { createInitialUserMessageHandoff } from "../../app/initial-user-message-
88
import { t } from "../../i18n/index.ts";
99
import { showToast } from "../../lib/toast.ts";
1010
import {
11+
getRenderedModalDialog,
1112
installDialogPolyfill,
1213
waitForConfirmDialogActions,
1314
} from "../../test-helpers/modal-dialog.ts";
@@ -693,6 +694,62 @@ describe("chat pane initialization", () => {
693694
});
694695

695696
describe("chat pane keyboard shortcuts", () => {
697+
it("does not steal typing focus from a shadow-root confirmation", async () => {
698+
const restoreDialogPolyfill = installDialogPolyfill();
699+
const { pane } = createTestChatPane({
700+
client: createGatewayBrowserClientFixture(),
701+
sessions: createSessionCapabilityFixture(),
702+
});
703+
pane.active = true;
704+
pane.presented = true;
705+
const composer = document.createElement("div");
706+
composer.className = "agent-chat__composer-combobox";
707+
const textarea = composer.appendChild(document.createElement("textarea"));
708+
pane.append(composer);
709+
const focus = vi.spyOn(textarea, "focus");
710+
const container = document.body.appendChild(document.createElement("div"));
711+
const modal = container.appendChild(document.createElement("openclaw-modal-dialog"));
712+
const cancel = modal.appendChild(document.createElement("button"));
713+
714+
try {
715+
const { dialog } = await getRenderedModalDialog(container);
716+
expect(dialog.open).toBe(true);
717+
expect(document.querySelector("dialog[open]")).toBeNull();
718+
cancel.addEventListener("keydown", (event) => pane.handleDocumentKeydown(event));
719+
720+
cancel.dispatchEvent(new KeyboardEvent("keydown", { key: "x", cancelable: true }));
721+
722+
expect(focus).not.toHaveBeenCalled();
723+
} finally {
724+
container.remove();
725+
restoreDialogPolyfill();
726+
}
727+
});
728+
729+
it("does not steal typing focus from a light-DOM confirmation", () => {
730+
const { pane } = createTestChatPane({
731+
client: createGatewayBrowserClientFixture(),
732+
sessions: createSessionCapabilityFixture(),
733+
});
734+
pane.active = true;
735+
pane.presented = true;
736+
const composer = document.createElement("div");
737+
composer.className = "agent-chat__composer-combobox";
738+
const textarea = composer.appendChild(document.createElement("textarea"));
739+
pane.append(composer);
740+
const focus = vi.spyOn(textarea, "focus");
741+
const modal = document.body.appendChild(document.createElement("div"));
742+
modal.setAttribute("aria-modal", "true");
743+
744+
try {
745+
pane.handleDocumentKeydown(new KeyboardEvent("keydown", { key: "x", cancelable: true }));
746+
747+
expect(focus).not.toHaveBeenCalled();
748+
} finally {
749+
modal.remove();
750+
}
751+
});
752+
696753
it("toggles only the active pane's session workspace", () => {
697754
const client = createGatewayBrowserClientFixture();
698755
const sessions = createSessionCapabilityFixture();

0 commit comments

Comments
 (0)