Compare commits

...
Author SHA1 Message Date
Codeman maintainer 79f85415d8 fix(web): a dialog opened with the mouse hands the keyboard back to the terminal
After App Settings or Session Options was opened with a mouse click and
closed, nothing typed reached the terminal until it was clicked again.
FocusTrap saved document.activeElement when the dialog opened, and by then
the press had already moved focus: onto the pressed control in Chromium and
Firefox, onto <body> in WebKit on macOS, where a button takes no focus from
the mouse.

FocusTrap.focusToReturn() is what a dialog saves now. A pointerdown listener
records the typing field that had focus when a mouse press began (pointerdown
comes before mousedown, whose default action moves focus), and that field is
the answer when focus sits on the pressed control or on <body> as the dialog
opens. Any key forgets the press, so a control reached with the keyboard gets
focus back as before. Only a typing field is remembered, for one press (a
press on a menu item inherits it from the press that opened the menu) and
only for a mouse, so touch is unchanged. Asking spends the press, so nothing
pressed inside the opening dialog can hand the keyboard to a field behind it.

The command palette and the Session Manager save the same answer.

Measured in Chromium against a running server: App Settings and Session
Options opened by mouse ended on the clicked gear before and in the terminal
after, also with the press clearing focus as WebKit on macOS does, with the
tile grid and the split open (the keyboard returns to the pane it was in),
and through a tile's menu. Not run in WebKit on macOS itself.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 10:23:52 +01:00
7 changed files with 756 additions and 2 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
**Closing a dialog you opened with the mouse puts the keyboard back in the terminal.** After App Settings or Session Options was opened with a click and closed again, nothing you typed reached the terminal until you clicked it: focus was left on the button you had clicked, and in Safari and the Mac app on nothing at all. A dialog now returns the keyboard to the field you were typing in when you clicked, which with the tile grid or the split open is the pane you were in. The Session Manager and the command palette follow the same rule. A dialog opened with the keyboard still returns to the control it was opened from.
+1
View File
@@ -28,6 +28,7 @@ export const BROWSER_TEST_GLOBS = [
'test/tab-layout-editing.browser.test.ts',
'test/tab-rail-search.browser.test.ts',
'test/tab-focus.browser.test.ts',
'test/dialog-focus-return.browser.test.ts',
'test/session-sidebar-ux.browser.test.ts',
'test/header-divider.browser.test.ts',
'test/tab-strip-corner.browser.test.ts',
+2
View File
@@ -56,6 +56,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
**Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry)
**Where a dialog hands the keyboard back to** (`FocusTrap.focusToReturn()`, keyboard-accessory.js): a dialog that saves focus on open asks this, never `document.activeElement`. By the time a dialog opens, the mouse press that opened it has already moved focus (onto the pressed control in Chromium and Firefox, onto `<body>` in WebKit on macOS, where a button takes no focus from the mouse), and restoring that left the keyboard out of the terminal until it was clicked. The answer is the typing field (textarea, text-like input, editable region) that had focus at `pointerdown`, whenever focus now sits on the pressed control or on `<body>`. ⚠️ `pointerdown`, never `mousedown` or `click`: moving focus is `mousedown`'s default action, so only the earlier event still sees what had the keyboard. ⚠️ One press, from a typing field, by mouse: the field of an earlier press is not carried over (it can be behind a dialog opened since), a press that began on a button (a dialog opened inside a dialog) still returns to the pressed control, any key but a held modifier forgets the press (a keyboard user gets the control back), and a finger or pen records nothing (a focused field there means the on-screen keyboard). The one press that inherits a field is a press on an item inside `[role="menu"]`, from the press that opened the menu (a tile's menu button, then "Session options"); a menu that hands focus back to its trigger before running the item is not covered. ⚠️ Asking spends the press, so nothing pressed inside the opening dialog can hand the keyboard to a field behind it; call it once, when the dialog opens. Callers: `FocusTrap.activate()` (App Settings, Session Options, Help, Kill All, the phone composer) and `_rememberOverlayFocus()` (command palette, Session Manager); the local model window places its own focus. A dialog that never handed focus back (most of the small confirm dialogs) is not changed by this. Tests: `test/dialog-focus-return.test.ts`, `test/dialog-focus-return.browser.test.ts` (real Chromium, not in the gate).
**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema.
**Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case)
+106 -1
View File
@@ -27,6 +27,8 @@
*
* - FocusTrap (class) — Traps Tab/Shift+Tab keyboard focus within a modal element.
* Saves and restores previously focused element on deactivate. Used by the modal dialogs.
* A dialog opened by a mouse press goes back to the field the user was typing in when
* the press began (FocusTrap.focusToReturn), not to the pressed control.
*
* @globals {object} KeyboardAccessoryBar
* @globals {object} PathPicker
@@ -1846,6 +1848,13 @@ const KeyboardAccessoryBar = {
/**
* FocusTrap - Traps keyboard focus within an element (typically a modal).
* Saves the previously focused element and restores focus when deactivated.
*
* What it saves is {@link FocusTrap.focusToReturn}, not `document.activeElement`.
* By the time a dialog opens, the mouse press that opened it has already moved
* focus: in Chromium and Firefox the pressed control took it, and in WebKit on
* macOS (Safari, the Mac app) a button takes no focus from the mouse, so the
* press clears focus to `<body>`. Handing either one back left the keyboard out
* of the terminal the user was typing in until they clicked it again.
*/
class FocusTrap {
constructor(element) {
@@ -1854,8 +1863,96 @@ class FocusTrap {
this.boundHandleKeydown = this.handleKeydown.bind(this);
}
/**
* The element a dialog that is about to open should hand the keyboard back to
* when it closes.
*
* That is `document.activeElement`, with one exception: a dialog opened by a
* mouse press while the user was typing in a field (a terminal's textarea, the
* CJK field, a search box). The field is the answer when that press is the
* only reason focus is somewhere else now, which is the case when focus sits
* on the pressed control or on nothing at all.
*
* ⚠️ One press, and only from a typing field. A press made from a button (a
* dialog opened from inside another dialog) still returns to the pressed
* control, and the field of an earlier press is not carried over: it can be
* behind a dialog that has opened since. The one exception is a press on a
* menu item, see {@link FocusTrap._notePress}. A control reached with the
* keyboard keeps the usual pattern too, because any key forgets the press.
*
* ⚠️ Asking spends the press. Whatever is pressed inside the dialog that is
* opening starts with nothing remembered, so nothing in it can hand the
* keyboard to a field behind it.
*/
static focusToReturn() {
const active = document.activeElement || null;
const press = FocusTrap._press;
FocusTrap._press = null;
if (!press || !press.field || press.field === active || press.field.isConnected === false) return active;
const moved =
!active ||
active === document.body ||
active === press.target ||
(typeof active.contains === 'function' && active.contains(press.target));
return moved ? press.field : active;
}
/** True for an element text is typed into: a textarea, a text-like input, an editable region. */
static isTypingField(el) {
if (!el || el === document.body) return false;
const tag = String(el.tagName || '').toUpperCase();
if (tag === 'TEXTAREA') return true;
if (tag === 'INPUT') return !FocusTrap.NON_TEXT_INPUT_TYPES.includes(String(el.type || 'text').toLowerCase());
return el.isContentEditable === true;
}
/**
* Remember what a mouse press began on and which typing field had the keyboard.
*
* ⚠️ `pointerdown`, not `mousedown` or `click`: moving focus is the default
* action of `mousedown`, which comes after it, so `activeElement` is still the
* element that had the keyboard before the press.
*
* ⚠️ A finger or a pen forgets the press and records nothing: on a touch device
* a focused field means the on-screen keyboard, and handing focus back to it
* would raise the keyboard when a dialog closes.
*
* ⚠️ A press on an item of a menu (`[role="menu"]`) keeps the field of the
* press before it, the one that opened the menu: a tile's menu button and then
* "Session options" are two presses and one way into a dialog. No other press
* inherits a field.
*/
static _notePress(e) {
if (!e || e.pointerType !== 'mouse') {
FocusTrap._press = null;
return;
}
const active = document.activeElement;
const target = e.target || null;
let field = FocusTrap.isTypingField(active) ? active : null;
if (!field && FocusTrap._press && typeof target?.closest === 'function' && target.closest('[role="menu"]')) {
field = FocusTrap._press.field;
}
FocusTrap._press = { target, field };
}
/** Any key but a modifier held for the click (Shift+click) ends the press's say. */
static _forgetPress(e) {
if (e && FocusTrap.MODIFIER_KEYS.includes(e.key)) return;
FocusTrap._press = null;
}
/** Install the two document listeners behind {@link FocusTrap.focusToReturn}, once per page. */
static watchPresses() {
if (FocusTrap._watching) return;
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return;
FocusTrap._watching = true;
document.addEventListener('pointerdown', FocusTrap._notePress, true);
document.addEventListener('keydown', FocusTrap._forgetPress, true);
}
activate() {
this.previouslyFocused = document.activeElement;
this.previouslyFocused = FocusTrap.focusToReturn();
this.element.addEventListener('keydown', this.boundHandleKeydown);
// Focus first focusable element after a brief delay (for CSS transitions)
@@ -1907,3 +2004,11 @@ class FocusTrap {
}
}
}
/** The last mouse press, `{ target, field }`, or null. See {@link FocusTrap._notePress}. */
FocusTrap._press = null;
FocusTrap._watching = false;
/** `<input>` types nobody types text into; every other type counts as a typing field. */
FocusTrap.NON_TEXT_INPUT_TYPES = ['button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit'];
FocusTrap.MODIFIER_KEYS = ['Shift', 'Control', 'Alt', 'Meta'];
FocusTrap.watchPresses();
+8 -1
View File
@@ -376,7 +376,14 @@ Object.assign(CodemanApp.prototype, {
* for, typing a filter the moment it opens.
*/
_rememberOverlayFocus(key) {
this[key] = (typeof document !== 'undefined' && document.activeElement) || null;
if (typeof document === 'undefined') {
this[key] = null;
return;
}
// The same answer a FocusTrap dialog saves (keyboard-accessory.js): an overlay
// opened by a mouse press goes back to the field the user was typing in, not
// to the pressed button.
this[key] = (typeof FocusTrap === 'function' ? FocusTrap.focusToReturn() : document.activeElement) || null;
},
/**
+274
View File
@@ -0,0 +1,274 @@
/**
* @fileoverview Real-Chromium coverage for where a dialog hands the keyboard
* back to (`FocusTrap.focusToReturn`, keyboard-accessory.js).
*
* What the vm test in `test/dialog-focus-return.test.ts` cannot answer is the
* order a browser does things in: the rule reads `document.activeElement` in a
* `pointerdown` listener and relies on the engine moving focus only afterwards,
* as the default action of `mousedown`. Here a real mouse presses real controls
* and a real keyboard types, on a page that holds the shipping
* keyboard-accessory.js, a textarea standing in for the terminal's own, and a
* dialog built on `FocusTrap` the way App Settings and Session Options are.
*
* Four ways into the dialog: a button (Chromium gives it focus on a press), an
* element that cannot take focus (the press clears focus to `<body>`, which is
* what WebKit on macOS does for a button), a focusable element pressed on an
* icon inside it (a tab's gear), and an item of a menu opened by a press before
* it (a tile's menu button, then "Session options").
*
* Port: none (page.route on a fake origin, no server).
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
const publicDir = resolve(import.meta.dirname, '../src/web/public');
const ORIGIN = 'http://codeman.test/';
const PAGE = `<!doctype html><html><body>
<textarea id="term" style="display:block;width:300px;height:80px"></textarea>
<button id="other">Other</button>
<button id="open">Open</button>
<div id="plain" style="display:inline-block;padding:8px;background:#ccc">Open, takes no focus</div>
<span id="gear" tabindex="0" style="display:inline-block;padding:8px">
<svg width="24" height="24"><rect id="gearIcon" width="24" height="24"></rect></svg>
</span>
<button id="menuButton">Menu</button>
<div id="modal" hidden style="position:fixed;left:40px;top:160px;padding:20px;background:#eee">
<button id="close">Close</button><input id="name">
</div>
</body></html>`;
const WIRING = `
const modal = document.getElementById('modal');
const focused = () => (document.activeElement === document.body ? 'body' : document.activeElement.id);
window.__focused = focused;
window.__focusAtClick = [];
let trap = null;
const open = () => {
window.__focusAtClick.push(focused());
modal.hidden = false;
trap = new FocusTrap(modal);
trap.activate();
};
const close = () => {
if (!trap) return;
modal.hidden = true;
trap.deactivate();
trap = null;
};
for (const id of ['open', 'plain', 'gear']) document.getElementById(id).addEventListener('click', open);
document.getElementById('close').addEventListener('click', close);
// A menu the way the rail's row menu is built: appended to <body>, its first
// item focused, removed by the item's click before the action runs.
document.getElementById('menuButton').addEventListener('click', () => {
const menu = document.createElement('div');
menu.id = 'menu';
menu.setAttribute('role', 'menu');
menu.style.cssText = 'position:fixed;left:400px;top:160px;padding:8px;background:#ddd';
for (const [id, action] of [['menuFirst', () => {}], ['menuOptions', open]]) {
const item = document.createElement('button');
item.id = id;
item.setAttribute('role', 'menuitem');
item.textContent = id;
item.addEventListener('click', () => {
menu.remove();
action();
});
menu.appendChild(item);
}
document.body.appendChild(menu);
menu.querySelector('button').focus();
});
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); }, true);
`;
describe('where a dialog hands the keyboard back to, in Chromium', () => {
let browser: Browser;
const contexts: BrowserContext[] = [];
let page: Page;
const errors: string[] = [];
async function newPage(options: { hasTouch?: boolean } = {}): Promise<Page> {
const context = await browser.newContext({ viewport: { width: 800, height: 500 }, ...options });
contexts.push(context);
const p = await context.newPage();
p.on('pageerror', (e) => errors.push(e.message));
await p.route(ORIGIN, (route) => route.fulfill({ contentType: 'text/html', body: PAGE }));
await p.goto(ORIGIN);
await p.addScriptTag({ content: readFileSync(resolve(publicDir, 'keyboard-accessory.js'), 'utf8') });
await p.addScriptTag({ content: WIRING });
return p;
}
const focused = (p: Page = page) => p.evaluate(() => (window as any).__focused());
const focusAtClick = (p: Page = page) => p.evaluate(() => (window as any).__focusAtClick);
const termText = (p: Page = page) => p.evaluate(() => (document.getElementById('term') as HTMLTextAreaElement).value);
/** Put the keyboard in the terminal stand-in and type, as a user in the middle of a prompt. */
async function typeInTerminal(p: Page = page) {
await p.click('#term');
await p.keyboard.type('a');
expect(await focused(p)).toBe('term');
}
/** The trap moves focus to the dialog's first control one frame after it opens. */
async function dialogOpen(p: Page = page) {
await p.waitForFunction(() => (window as any).__focused() === 'close');
}
beforeAll(async () => {
browser = await chromium.launch({ headless: true });
});
beforeEach(async () => {
errors.length = 0;
page = await newPage();
});
afterAll(async () => {
for (const context of contexts) await context.close();
await browser?.close();
});
it('a button pressed with the mouse: the keyboard is back in the terminal', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
// The engine fact the rule exists for: the press gave the button focus.
expect(await focusAtClick()).toEqual(['open']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
expect(errors).toEqual([]);
});
it('a control that takes no focus (a button in WebKit on macOS): the keyboard is back in the terminal', async () => {
await typeInTerminal();
await page.click('#plain');
await dialogOpen();
// The press cleared focus: before the fix this is what the dialog handed back.
expect(await focusAtClick()).toEqual(['body']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it("a press on the icon inside a focusable control (a tab's gear): the keyboard is back in the terminal", async () => {
await typeInTerminal();
await page.click('#gearIcon');
await dialogOpen();
expect(await focusAtClick()).toEqual(['gear']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it("two presses through a menu (a tile's menu, then Session options): the keyboard is back in the terminal", async () => {
await typeInTerminal();
await page.click('#menuButton');
expect(await focused()).toBe('menuFirst');
await page.click('#menuOptions');
await dialogOpen();
// The item's click removed the menu, so nothing had focus when the dialog opened.
expect(await focusAtClick()).toEqual(['body']);
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('a menu walked with the keyboard keeps the keyboard pattern', async () => {
await typeInTerminal();
await page.click('#menuButton');
await page.keyboard.press('Tab');
expect(await focused()).toBe('menuOptions');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
// Nothing was remembered: the dialog hands back what had focus, and that was nothing.
expect(await focused()).not.toBe('term');
});
it('closing the dialog with the mouse instead of Escape changes nothing', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.click('#close');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('typing in the dialog and opening it a second time still ends in the terminal', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.click('#name');
await page.keyboard.type('x');
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.type('b');
expect(await termText()).toBe('ab');
});
it('a keyboard user gets the control back that opened the dialog', async () => {
await typeInTerminal();
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
expect(await focused()).toBe('open');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a keyboard user gets the control back even after pressing it with the mouse earlier', async () => {
await typeInTerminal();
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('term');
await page.keyboard.press('Tab');
await page.keyboard.press('Tab');
await page.keyboard.press('Enter');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a press that began on a button returns to the pressed control, as before', async () => {
await typeInTerminal();
await page.click('#other');
expect(await focused()).toBe('other');
await page.click('#open');
await dialogOpen();
await page.keyboard.press('Escape');
expect(await focused()).toBe('open');
});
it('a finger changes nothing: focus returns to what had it when the dialog opened', async () => {
const touch = await newPage({ hasTouch: true });
await touch.tap('#term');
expect(await focused(touch)).toBe('term');
await touch.tap('#open');
await dialogOpen(touch);
const atClick = (await focusAtClick(touch))[0];
await touch.keyboard.press('Escape');
expect(await focused(touch)).toBe(atClick);
});
});
+360
View File
@@ -0,0 +1,360 @@
/**
* @fileoverview A dialog hands the keyboard back to the field the user was
* typing in when the mouse press that opened it began.
*
* Measured in Chromium against a real shell session before the change: App
* Settings opened from the header gear and closed left `activeElement` on the
* gear button, Session Options opened from a tab's gear left it on that gear,
* and nothing typed afterwards reached the terminal. With the press clearing
* focus (what WebKit on macOS does for a button) it was left on `<body>`.
*
* `FocusTrap` is loaded with `vm` against a fake document, like the other
* accessory-bar tests. A press is the two steps a browser takes: `pointerdown`
* reaches the page first, then the engine moves focus. The real event order is
* covered in `test/dialog-focus-return.browser.test.ts`.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it, vi } from 'vitest';
type Listener = (e: unknown) => void;
type Node = Record<string, any>;
const read = (name: string) => readFileSync(resolve(import.meta.dirname, '../src/web/public', name), 'utf8');
function node(tagName: string, extra: Node = {}): Node {
return { tagName, isConnected: true, focus: vi.fn(), contains: () => false, ...extra };
}
function loadPage({ panels = false } = {}) {
const listeners: Record<string, Listener[]> = {};
const body = node('BODY');
let active: Node | null = body;
const document = {
body,
get activeElement() {
return active;
},
addEventListener: (type: string, fn: Listener, capture?: boolean) => {
(listeners[`${type}:${capture === true}`] ||= []).push(fn);
},
createElement: () => node('DIV'),
querySelector: () => null,
getElementById: () => null,
};
const CodemanApp = function CodemanApp(this: unknown) {};
const context = vm.createContext({
console,
document,
CodemanApp,
MobileDetection: { isTouchDevice: () => false },
localStorage: { getItem: () => null, setItem: () => {} },
requestAnimationFrame: (fn: () => void) => fn(),
});
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context, {
filename: 'keyboard-accessory.js',
});
if (panels) vm.runInContext(read('panels-ui.js'), context, { filename: 'panels-ui.js' });
const FocusTrap = (context as unknown as { __FocusTrap: any }).__FocusTrap;
const fire = (type: string, event: unknown) => (listeners[`${type}:true`] ?? []).forEach((fn) => fn(event));
return {
FocusTrap,
listeners,
body,
app: panels ? new (CodemanApp as any)() : null,
setActive: (el: Node | null) => (active = el),
/** A press: the page hears `pointerdown`, then the engine moves focus to `focusAfter`. */
press(target: Node, focusAfter?: Node | null, pointerType = 'mouse') {
fire('pointerdown', { pointerType, target });
if (focusAfter !== undefined) active = focusAfter;
},
key: (key: string) => fire('keydown', { key }),
};
}
describe('FocusTrap.focusToReturn', () => {
it('answers the typing field when the pressed control took focus (Chromium, Firefox)', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('answers the typing field when the press cleared focus (a button in WebKit on macOS)', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
page.press(node('BUTTON'), page.body);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('answers the typing field when the press landed inside the control that took focus', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const icon = node('path');
const gear = node('BUTTON', { contains: (el: Node) => el === icon });
page.setActive(terminal);
page.press(icon, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('keeps the control for a keyboard user: any key forgets the press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
// Later the same control is reached with Tab and opened with Enter.
page.key('Tab');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('does not let a modifier held for the click forget the press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
for (const key of ['Shift', 'Control', 'Alt', 'Meta']) page.key(key);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('returns to the pressed control when the press came from a button (a dialog opened inside a dialog)', () => {
const page = loadPage();
const closeButton = node('BUTTON');
const row = node('BUTTON');
page.setActive(closeButton);
page.press(row, row);
expect(page.FocusTrap.focusToReturn()).toBe(row);
});
it('never carries the field of an earlier press over', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
const row = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
// A dialog is open now and the terminal is behind it; the next press starts from a button.
page.press(row, row);
expect(page.FocusTrap.focusToReturn()).toBe(row);
});
it('keeps the field through a menu: the press on a menu item belongs to the press that opened the menu', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const menuButton = node('BUTTON');
const firstItem = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(terminal);
// The menu focuses its first item when it opens.
page.press(menuButton, firstItem);
// The item's click removes the menu, which drops focus on <body>, and opens the dialog.
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
it('keeps nothing through a menu that was opened from a button', () => {
const page = loadPage();
const closeButton = node('BUTTON');
const menuButton = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(closeButton);
page.press(menuButton, menuButton);
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('spends the press when a dialog asks, so nothing pressed inside the dialog reaches the field behind it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
expect(page.FocusTrap.focusToReturn()).toBe(gear);
// The dialog is open. A menu item in it is pressed directly, with a dialog control focused.
const dialogControl = node('BUTTON');
const item = node('BUTTON', { closest: (selector: string) => (selector === '[role="menu"]' ? {} : null) });
page.setActive(dialogControl);
page.press(item, page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('leaves a finger alone, and a finger forgets an earlier mouse press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear, 'touch');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
page.setActive(terminal);
page.press(gear, gear, 'mouse');
page.press(gear, gear, 'touch');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
page.setActive(terminal);
page.press(gear, gear, 'pen');
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('answers what has focus when the field is gone from the page', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
terminal.isConnected = false;
expect(page.FocusTrap.focusToReturn()).toBe(gear);
});
it('answers what has focus when the click itself moved it somewhere else', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const elsewhere = node('BUTTON');
page.setActive(terminal);
page.press(node('BUTTON'), elsewhere);
expect(page.FocusTrap.focusToReturn()).toBe(elsewhere);
});
it('answers what has focus when there was no press at all', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
page.setActive(page.body);
expect(page.FocusTrap.focusToReturn()).toBe(page.body);
});
it('answers the field itself when the press left focus in it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
page.setActive(terminal);
// An accessory key cancels the mousedown default, so the terminal keeps focus.
page.press(node('BUTTON'));
expect(page.FocusTrap.focusToReturn()).toBe(terminal);
});
});
describe('FocusTrap.isTypingField', () => {
it('counts textareas, text-like inputs and editable regions, and nothing else', () => {
const { FocusTrap, body } = loadPage();
expect(FocusTrap.isTypingField(node('TEXTAREA'))).toBe(true);
expect(FocusTrap.isTypingField(node('textarea'))).toBe(true);
expect(FocusTrap.isTypingField(node('INPUT'))).toBe(true);
for (const type of ['text', 'search', 'number', 'password', 'email', 'url']) {
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(true);
}
for (const type of [
'button',
'checkbox',
'color',
'file',
'hidden',
'image',
'radio',
'range',
'reset',
'submit',
]) {
expect(FocusTrap.isTypingField(node('INPUT', { type }))).toBe(false);
}
expect(FocusTrap.isTypingField(node('DIV', { isContentEditable: true }))).toBe(true);
expect(FocusTrap.isTypingField(node('DIV'))).toBe(false);
expect(FocusTrap.isTypingField(node('BUTTON'))).toBe(false);
expect(FocusTrap.isTypingField(node('SELECT'))).toBe(false);
expect(FocusTrap.isTypingField(body)).toBe(false);
expect(FocusTrap.isTypingField(null)).toBe(false);
});
});
describe('the document listeners', () => {
it('are two capture listeners, installed once however often the page asks', () => {
const page = loadPage();
page.FocusTrap.watchPresses();
page.FocusTrap.watchPresses();
expect(Object.keys(page.listeners).sort()).toEqual(['keydown:true', 'pointerdown:true']);
expect(page.listeners['pointerdown:true']).toHaveLength(1);
expect(page.listeners['keydown:true']).toHaveLength(1);
});
it('are skipped on a page with no document to listen on', () => {
const context = vm.createContext({ console, document: { createElement: () => node('DIV') } });
vm.runInContext(`${read('keyboard-accessory.js')}\nglobalThis.__FocusTrap = FocusTrap;`, context);
expect((context as unknown as { __FocusTrap: any }).__FocusTrap._watching).toBe(false);
});
});
describe('a dialog built on FocusTrap', () => {
function dialog() {
return { addEventListener: vi.fn(), removeEventListener: vi.fn(), querySelectorAll: () => [] };
}
it('hands the keyboard back to the terminal after it was opened by a mouse press', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
const trap = new page.FocusTrap(dialog());
trap.activate();
expect(trap.previouslyFocused).toBe(terminal);
trap.deactivate();
expect(terminal.focus).toHaveBeenCalledTimes(1);
expect(gear.focus).not.toHaveBeenCalled();
});
it('still hands it back to the control it was opened from with the keyboard', () => {
const page = loadPage();
const gear = node('BUTTON');
page.setActive(gear);
page.key('Enter');
const trap = new page.FocusTrap(dialog());
trap.activate();
trap.deactivate();
expect(gear.focus).toHaveBeenCalledTimes(1);
});
it('is not misled by the press that closes it', () => {
const page = loadPage();
const terminal = node('TEXTAREA');
const gear = node('BUTTON');
const close = node('BUTTON');
page.setActive(terminal);
page.press(gear, gear);
const trap = new page.FocusTrap(dialog());
trap.activate();
page.setActive(close);
page.press(close, close);
trap.deactivate();
expect(terminal.focus).toHaveBeenCalledTimes(1);
});
});
describe('the command palette and the Session Manager', () => {
it('save the same answer, so an overlay opened by a mouse press returns to the terminal', () => {
const page = loadPage({ panels: true });
const terminal = node('TEXTAREA');
const headerButton = node('BUTTON');
page.setActive(terminal);
page.press(headerButton, headerButton);
page.app._rememberOverlayFocus('_sessionManagerPrevFocus');
expect(page.app._sessionManagerPrevFocus).toBe(terminal);
});
it('save what has focus when the overlay was opened with its shortcut', () => {
const page = loadPage({ panels: true });
const terminal = node('TEXTAREA');
page.setActive(terminal);
page.key('k');
page.app._rememberOverlayFocus('_commandPalettePrevFocus');
expect(page.app._commandPalettePrevFocus).toBe(terminal);
});
});