fix(a11y): move focus when the screen is replaced, not only when the tab changes

The shell moved focus to the new screen's heading on a tab change and on
nothing else. Four things replace what <main> shows without changing the tab:
the plan panel and each of its phases, the dependency view, and an opened
environment. Each unmounts the control that was just pressed, so focus fell to
<body>, the next Tab started from the top of the window, and a screen reader
said nothing about a screen that had entirely changed.

A second effect covers them, and only acts when focus was actually lost: a run
advancing from resolving to preview must not pull a keyboard user off Back.

The console drawer had the same hole. Escape closed it and dropped focus; it
goes back to whatever opened the drawer. Its close button was named "Cancel",
beside a Stop that cancels the run, and is "Close console".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Fable 5.2 committed 2026-11-10 20:01:03 +07:00
1 parent 9754b95e66
commit 567b0ae8fa
4 files changed
+227 -4

No files matched your search

+103 -3
View File
@@ -14,16 +14,28 @@
* user can get there at all, and in how many clicks.
*/
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from '@/App'
import { NAV_KEYS } from '@/components/nav'
import type { DepsGraph, Dist, EnvRow } from '@/ipc'
import type {
DepsGraph,
Dist,
EnvRow,
ExecutionOutcome,
ExecutionSummary,
FlowStep,
SnapshotMeta,
} from '@/ipc'
import { joinRows } from '@/screens/rows'
import { useDepsStore, useEnvStore, useLegalStore, useUiStore } from '@/stores'
import { useDepsStore, useEnvStore, useLegalStore, usePlanStore, useUiStore } from '@/stores'
import graphFixture from '@/test/fixtures/deps_graph.json'
import summaryFixture from '@/test/fixtures/execution_summary.json'
import flowStepForced from '@/test/fixtures/flow_step_forced.json'
import listFixture from '@/test/fixtures/pkg_list.json'
import snapshotFixture from '@/test/fixtures/snapshot_list.json'
import { resetStore } from '@/test/stores'
/** Every command that crossed the bridge, in order — the whole point of this file. */
const crossed: string[] = []
@@ -56,6 +68,11 @@ vi.mock('@/ipc', async () => {
const GRAPH = graphFixture as DepsGraph
const DISTS = listFixture as Dist[]
const FORCED_STEP = flowStepForced as FlowStep
const OUTCOME: ExecutionOutcome = {
summary: summaryFixture as ExecutionSummary,
snapshot: (snapshotFixture as SnapshotMeta[])[0]!,
}
const ENV_HASH = 'abc123'
const INTERPRETER = String.raw`C:\proj\.venv\Scripts\python.exe`
@@ -77,6 +94,8 @@ const ROW: EnvRow = {
beforeEach(() => {
crossed.length = 0
// A plan left parked by one test owns the screen in the next, and refuses its shortcuts.
resetStore(usePlanStore)
// Each mock records its own name on the way in. A generic wrapper reads better and does
// not typecheck: `ReturnType<typeof vi.fn>` is `Mock<Procedure | Constructable>`, which is
// not directly callable.
@@ -182,6 +201,87 @@ describe('the dependency view, reached the way a user reaches it', () => {
})
})
describe('where focus goes when the screen is replaced', () => {
// The shell moved focus on a tab change and on nothing else. But four things replace what
// `<main>` shows without changing the tab — the dependency view, an opened environment, the plan
// panel, and each of the panel's phases — and every one of them unmounts the control that was
// just pressed. Focus fell to `<body>`: the next Tab started from the top of the window, and a
// screen reader announced nothing at all about a screen that had entirely changed.
const heading = () => screen.getByRole('heading', { level: 1 })
it('lands on the dependency view when a row opens it', async () => {
render(<App />)
const details = within(rowFor('numpy')).getByLabelText('Show dependencies')
details.focus()
fireEvent.click(details)
await screen.findByText('pandas')
expect(heading()).toHaveTextContent('Dependencies')
expect(heading()).toHaveFocus()
})
it('lands on the table again on the way back', async () => {
render(<App />)
fireEvent.click(within(rowFor('numpy')).getByLabelText('Show dependencies'))
await screen.findByText('pandas')
const back = screen.getByText('Back to packages')
back.focus()
fireEvent.click(back)
expect(heading()).toHaveTextContent('Installed')
expect(heading()).toHaveFocus()
})
it('lands on the plan panel when a plan takes the screen', async () => {
render(<App />)
rowFor('numpy').focus()
act(() => {
usePlanStore.setState({ phase: 'preview', kind: 'update', step: FORCED_STEP, env: ROW.env ?? null })
})
await waitFor(() => {
expect(heading()).toHaveFocus()
})
expect(heading()).toHaveTextContent('Preview')
})
it('lands on the summary when the run ends', async () => {
render(<App />)
act(() => {
usePlanStore.setState({ phase: 'executing', kind: 'update', step: FORCED_STEP, env: ROW.env ?? null })
})
const stop = await screen.findByText('Stop')
stop.focus()
act(() => {
usePlanStore.setState({ phase: 'summary', outcome: OUTCOME })
})
await waitFor(() => {
expect(heading()).toHaveFocus()
})
})
it('does not take focus from a control that is still there', async () => {
// The rule is "focus was lost", not "the phase changed": moving it on every phase would pull
// a keyboard user off *Console* each time a run advanced.
render(<App />)
act(() => {
usePlanStore.setState({ phase: 'resolving', kind: 'update', env: ROW.env ?? null })
})
const back = await screen.findByText('Back')
back.focus()
act(() => {
usePlanStore.setState({ phase: 'preview', step: FORCED_STEP })
})
expect(back).toHaveFocus()
})
})
describe('the keyboard', () => {
it('selects a tab by the physical digit, whatever the layout types', () => {
// U49: on AZERTY, Ctrl+3 reports `"`. Parsing `e.key` made every tab shortcut a no-op there.
+28
View File
@@ -76,6 +76,12 @@ export function App() {
const resetPlan = usePlanStore((s) => s.reset)
const resetDeps = useDepsStore((s) => s.reset)
const guardOpen = planPhase === 'guard' && guard !== null
// What `<main>` is showing besides the tab — see the second focus effect below. Booleans and a
// phase, not the focused package or the opened interpreter: re-centring the dependency view on
// another package is not a new screen, and must not take focus from the link that did it.
const panelPhase = PANEL_PHASES.has(planPhase) ? planPhase : null
const depsOpen = useDepsStore((s) => s.focus !== null)
const envOpen = useEnvStore((s) => s.openFor !== null)
const mainRef = useRef<HTMLElement>(null)
// Shell state, like `nav` — but local, because nothing outside this component reads it.
const [paletteOpen, setPaletteOpen] = useState(false)
@@ -128,6 +134,28 @@ export function App() {
heading.focus()
}, [nav])
// **The same move for the four things that replace the screen without changing the tab**: the
// plan panel and each of its phases, the dependency view, and an opened environment. Each one
// unmounts the control that was just pressed, so focus fell to `<body>` — the next Tab started
// from the top of the window and a screen reader said nothing about a screen that had entirely
// changed. `nav` was the only thing the effect above watched, and none of these change it.
//
// **Only when focus was actually lost.** The effect above moves it unconditionally, because a
// tab change is the user asking to go somewhere. A phase change is not: a run advancing from
// `resolving` to `preview` must not pull a keyboard user off *Back*, and a modal that is open
// over the panel owns focus until it closes. So: wherever focus is, if it is still on something
// in the document, it stays there.
useEffect(() => {
const active = document.activeElement
if (active !== null && active !== document.body && active.isConnected) return
const main = mainRef.current
const target =
main?.querySelector<HTMLElement>('[data-autofocus]') ?? main?.querySelector<HTMLElement>('h1')
if (target === null || target === undefined) return
if (target.tagName === 'H1') target.setAttribute('tabindex', '-1')
target.focus()
}, [panelPhase, depsOpen, envOpen])
// UI-SPEC §8: Ctrl+1..9 select tabs, positionally over NAV_KEYS.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -0,0 +1,78 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { useState } from 'react'
import { describe, expect, it } from 'vitest'
import { PdConsoleDrawer } from '@/components/PdConsoleDrawer'
/** The drawer with the button that opens it, which is what `PdPlanPanel` renders around it. */
function Harness() {
const [open, setOpen] = useState(false)
return (
<>
<PdConsoleDrawer
lines={[{ step: 0, pkg: 'numpy', stream: 'stdout', text: 'Collecting numpy' }]}
open={open}
done={1}
total={2}
onClose={() => {
setOpen(false)
}}
/>
<button
type="button"
onClick={() => {
setOpen(!open)
}}
>
toggle
</button>
</>
)
}
function openDrawer() {
render(<Harness />)
const toggle = screen.getByText('toggle')
toggle.focus()
fireEvent.click(toggle)
return toggle
}
describe('PdConsoleDrawer', () => {
it('names its close button for what it closes', () => {
// It was labelled "Cancel", beside a *Stop* that cancels the run. One of the two was lying.
openDrawer()
expect(screen.getByRole('button', { name: 'Close console' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Cancel' })).toBeNull()
})
it('gives focus back to what opened it when Escape closes it', () => {
// UI-SPEC §8: "Esc closes drawers". It did, and focus fell to <body>, so the next Tab started
// from the top of the window.
const toggle = openDrawer()
const close = screen.getByRole('button', { name: 'Close console' })
close.focus()
fireEvent.keyDown(close, { key: 'Escape' })
expect(screen.queryByRole('button', { name: 'Close console' })).toBeNull()
expect(toggle).toHaveFocus()
})
it('gives focus back when its own button closes it', () => {
const toggle = openDrawer()
const close = screen.getByRole('button', { name: 'Close console' })
close.focus()
fireEvent.click(close)
expect(toggle).toHaveFocus()
})
it('leaves focus alone when it was never inside', () => {
// Toggled shut from the button that opened it: focus is already where it should be.
const toggle = openDrawer()
fireEvent.click(toggle)
expect(toggle).toHaveFocus()
})
})
+18 -1
View File
@@ -51,6 +51,22 @@ export function PdConsoleDrawer({ lines, open, onClose, done, total }: PdConsole
bottom.current?.scrollIntoView({ block: 'end' })
}, [lines.length])
// UI-SPEC §8: "Esc closes drawers" — and then focus has to be somewhere. The drawer unmounts
// with the focused control inside it, so focus fell to `<body>` and the next Tab started from
// the top of the window. `PdDialog` returns focus to its opener for the same reason.
//
// Only when closing is what lost it. Toggled shut from the button that opened it, focus never
// left that button and nothing here should move it.
useEffect(() => {
if (!open) return undefined
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
return () => {
const active = document.activeElement
if (active !== null && active !== document.body && active.isConnected) return
if (opener !== null && opener !== document.body && opener.isConnected) opener.focus()
}
}, [open])
if (!open) return null
return (
@@ -74,7 +90,8 @@ export function PdConsoleDrawer({ lines, open, onClose, done, total }: PdConsole
<button
type="button"
onClick={onClose}
aria-label={t('actions.cancel')}
// Named for what it closes. It was "Cancel", beside a *Stop* that cancels the run.
aria-label={t('plan.closeConsole')}
className="rounded-pd border border-border px-2 py-0.5 text-data"
>
{'✕'}