TypeScript
fix(web): screen readers can browse and Tab through the threads sidebar again without going into focus mode (#26690)
nibarAhmed5b9731cedc06
diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.tsindex e1c1f04a0c3..233af7115ee 100644--- a/apps/web/src/components/ChatView.logic.browser.test.ts+++ b/apps/web/src/components/ChatView.logic.browser.test.ts@@ -3,20 +3,20 @@ import { userEvent } from "vite-plus/test/browser";import { shouldRefocusComposerOnWindowFocus } from "./ChatView.logic";it("keeps keyboard focus on a sidebar row on window return, but not a clicked row", async () => {- const tree = document.createElement("div");- tree.setAttribute("role", "tree");- const row = (name: string, tabIndex: number) => {+ const list = document.createElement("ul");+ const row = (name: string) => {const element = document.createElement("div");- element.setAttribute("role", "treeitem");- element.tabIndex = tabIndex;+ element.setAttribute("role", "button");+ element.tabIndex = 0;+ element.dataset.sidebarRow = name;element.textContent = name;- tree.append(element);+ list.append(element);return element;};- const clicked = row("Clicked thread", -1);- const tabbed = row("Tabbed thread", 0);- document.body.append(tree);- using _tree = { [Symbol.dispose]: () => tree.remove() };+ const clicked = row("Clicked thread");+ const tabbed = row("Tabbed thread");+ document.body.append(list);+ using _list = { [Symbol.dispose]: () => list.remove() };await userEvent.click(clicked);expect(document.activeElement).toBe(clicked);diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 93468b9e04a..229b72b035e 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -1166,7 +1166,7 @@ export function shouldRefocusComposerOnWindowFocus(}return (activeElement.closest(- '[data-workspace-area]:focus-visible, [role="treeitem"]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]',+ '[data-workspace-area]:focus-visible, [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]',) === null);}diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex deede26763f..8eb32a60582 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -1,5 +1,5 @@import { liveShellEnvironmentIdsAtom } from "../state/shell";-import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree";+import { attachSidebarTree } from "../lib/sidebarTree";import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost";@@ -3292,8 +3292,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve><SortableContext items={sortableIds} strategy={sidebarSortingStrategy}><ul- {...SIDEBAR_TREE_PROPS}ref={attachTreeRef}+ // Presentation flattens VoiceOver's list interaction boundary while preserving descendant+ // controls.+ role="presentation"className={cn("relative flex flex-col gap-px",sidebarListItems.length > 0 && "flex-1",@@ -3581,8 +3583,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve<li className="list-none"><buttontype="button"- role="treeitem"- tabIndex={-1}data-sidebar-row="settled:more"data-sidebar-parent="shelf:settled"disabled={olderSettledShelf.loading}diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsxindex 10581ecb5a6..bc15ca59459 100644--- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx+++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx@@ -82,8 +82,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: {return (<li className="list-none py-0.5"><div- role="treeitem"- tabIndex={-1}+ role="button"+ tabIndex={0}data-sidebar-row={`draft:${draftId}`}aria-label={accessibility.label}aria-current={accessibility.current}diff --git a/apps/web/src/components/sidebar/SidebarListMarkers.tsx b/apps/web/src/components/sidebar/SidebarListMarkers.tsxindex 104bda5582b..3416d80ff5e 100644--- a/apps/web/src/components/sidebar/SidebarListMarkers.tsx+++ b/apps/web/src/components/sidebar/SidebarListMarkers.tsx@@ -130,8 +130,6 @@ export function SidebarSectionHeader(props: {className={cn("relative mx-0.5 h-8", props.className)}><CollapsibleSectionHeader- role="treeitem"- tabIndex={-1}data-sidebar-row={`shelf:${shelf}`}onClick={props.toggle.onToggle}expanded={props.toggle.expanded}diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsxindex a73c3f21f0b..38b1e53bf05 100644--- a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx+++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx@@ -66,8 +66,6 @@ export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHead><buttontype="button"- role="treeitem"- tabIndex={-1}data-sidebar-row={rowId}aria-expanded={!collapsed}onClick={() => props.onToggle(group)}diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsxindex fa87252de14..ed3a8276be8 100644--- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx+++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx@@ -1208,8 +1208,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPrender={<divref={rowRef}- role="treeitem"- tabIndex={-1}+ role="button"+ tabIndex={0}data-sidebar-row={threadKey}data-sidebar-parent={props.navigationParent}aria-label={accessibility.label}@@ -1404,8 +1404,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowPrender={<divref={rowRef}- role="treeitem"- tabIndex={-1}+ role="button"+ tabIndex={0}data-sidebar-row={threadKey}data-sidebar-parent={props.navigationParent}aria-label={accessibility.label}diff --git a/apps/web/src/lib/sidebarTree.browser.test.ts b/apps/web/src/lib/sidebarTree.browser.test.tsindex 6b02cd3b842..c6bb67bd2cb 100644--- a/apps/web/src/lib/sidebarTree.browser.test.ts+++ b/apps/web/src/lib/sidebarTree.browser.test.ts@@ -4,14 +4,12 @@ import { installSidebarTree } from "./sidebarTree";function setup() {const root = document.createElement("div");- root.setAttribute("role", "tree");document.body.append(root);let dispose: (() => void) | undefined;const row = (id: string, parent?: string) => {const element = document.createElement("button");element.dataset.sidebarRow = id;if (parent) element.dataset.sidebarParent = parent;- element.setAttribute("role", "treeitem");element.textContent = id;root.append(element);return element;@@ -36,7 +34,7 @@ function press(target: HTMLElement, key: string, init: KeyboardEventInit = {}) {}describe("sidebar keyboard navigation", () => {- it("moves focus without activating rows, clamps at the ends, and keeps one Tab stop", () => {+ it("moves focus without activating rows, clamps at the ends, and keeps every row in the Tab order", () => {using tree = setup();const first = tree.row("first");const second = tree.row("second");@@ -54,10 +52,10 @@ describe("sidebar keyboard navigation", () => {press(last, "Home");expect(document.activeElement).toBe(first);expect(activate).not.toHaveBeenCalled();- expect(tree.root.querySelectorAll('[tabindex="0"]')).toHaveLength(1);+ expect([first.tabIndex, second.tabIndex, last.tabIndex]).toEqual([0, 0, 0]);});- it("expands a group before entering its first child and returns to the parent", async () => {+ it("expands a group before entering its first child and returns to the parent", () => {using tree = setup();const group = tree.row("project");group.setAttribute("aria-expanded", "false");@@ -72,12 +70,6 @@ describe("sidebar keyboard navigation", () => {press(group, "ArrowRight");expect(group.getAttribute("aria-expanded")).toBe("true");expect(document.activeElement).toBe(group);- // The tree picks up the new child from its mutation observer.- await vi.waitFor(() =>- expect(- tree.root.querySelector('[data-sidebar-parent="project"]')?.getAttribute("aria-level"),- ).toBe("2"),- );press(group, "ArrowRight");const child = document.activeElement as HTMLElement;expect(child.dataset.sidebarRow).toBe("thread");@@ -104,7 +96,7 @@ describe("sidebar keyboard navigation", () => {expect(document.activeElement).toBe(selected);});- it("lets Tab reach only the focused row's buttons", () => {+ it("leaves every row's buttons in the Tab order", () => {using tree = setup();const first = tree.row("first");const second = tree.row("second");@@ -119,10 +111,10 @@ describe("sidebar keyboard navigation", () => {const secondAction = action("second");tree.install();first.focus();- expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, -1]);+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, 0]);press(first, "ArrowDown");expect(document.activeElement).toBe(second);- expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);+ expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, 0]);});it("keeps a rendered row under a collapsed group reachable", () => {@@ -152,26 +144,6 @@ describe("sidebar keyboard navigation", () => {expect(undo.tabIndex).toBe(0);});- it("gives row buttons back their own tab order when the tree reinstalls", () => {- using tree = setup();- tree.row("first");- const second = tree.row("second");- const action = (owner: string) => {- const button = document.createElement("button");- button.dataset.sidebarActionFor = owner;- tree.root.append(button);- return button;- };- const firstAction = action("first");- const secondAction = action("second");- const dispose = installSidebarTree(tree.root);- second.focus();- dispose();- expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([0, 0]);- tree.install();- expect([firstAction.tabIndex, secondAction.tabIndex]).toEqual([-1, 0]);- });-it("keeps the scroll position when focus follows a row that moved away", async () => {using tree = setup();Object.assign(tree.root.style, { height: "100px", overflow: "auto" });@@ -191,7 +163,7 @@ describe("sidebar keyboard navigation", () => {expect(tree.root.scrollTop).toBe(0);});- it("does not pull focus back after a click outside the tree", async () => {+ it("does not pull focus back after a click outside the rows", async () => {using tree = setup();const first = tree.row("first");tree.install();@@ -199,16 +171,18 @@ describe("sidebar keyboard navigation", () => {text.textContent = "Chat text";document.body.append(text);using _text = { [Symbol.dispose]: () => text.remove() };- first.focus();- await userEvent.click(text);- expect(document.activeElement).toBe(document.body);- // A status change re-renders the tree while the user works elsewhere.- tree.row("second");- await vi.waitFor(() =>- expect(- tree.root.querySelector('[data-sidebar-row="second"]')?.getAttribute("aria-posinset"),- ).toBe("2"),- );- expect(document.activeElement).toBe(document.body);+ const spacer = document.createElement("div");+ spacer.textContent = "Empty list space";+ tree.root.append(spacer);+ for (const target of [text, spacer]) {+ first.focus();+ await userEvent.click(target);+ expect(document.activeElement).toBe(document.body);+ // A status change re-renders the list while the user works elsewhere.+ tree.row(`second-${target.tagName}`);+ // The list's mutation observer callback is queued ahead of this continuation.+ await Promise.resolve();+ expect(document.activeElement).toBe(document.body);+ }});});diff --git a/apps/web/src/lib/sidebarTree.ts b/apps/web/src/lib/sidebarTree.tsindex 07859c72bd9..7a6183b5e4a 100644--- a/apps/web/src/lib/sidebarTree.ts+++ b/apps/web/src/lib/sidebarTree.ts@@ -1,139 +1,82 @@const ROW = "[data-sidebar-row]";-const CONTROL = 'button, a[href], input, textarea, select, [contenteditable="true"], [tabindex]';-const TEXT_ENTRY = 'input, textarea, select, [contenteditable="true"]';-function setAttribute(element: Element, name: string, value: string) {- if (element.getAttribute(name) !== value) element.setAttribute(name, value);-}--function setTabIndex(element: HTMLElement, value: number) {- if (element.tabIndex !== value) element.tabIndex = value;-}--export const SIDEBAR_TREE_PROPS = { role: "tree", "aria-label": "Threads" } as const;--/** Ref callback for a sidebar list; installs the tree and returns its cleanup. */+/** Ref callback for a sidebar list; installs its keyboard navigation and returns its cleanup. */export function attachSidebarTree(element: HTMLElement | null) {return element ? installSidebarTree(element) : undefined;}-/** A roving DOM focus, separate from thread activation, as in VS Code's list commands. */+/**+ * Arrow keys move focus between rows without opening them, as in VS Code's list commands.+ * Rows stay ordinary buttons in the Tab order so screen readers can browse the list.+ */export function installSidebarTree(root: HTMLElement) {- let rows: HTMLElement[] = [];let focusedId: string | undefined;+ let focusedParent: string | undefined;+ let focusedIndex = -1;let ownsFocus = false;- let tabStop: HTMLElement | undefined;let contextMenuRow: HTMLElement | undefined;- // A control's own tab index, restored while its row holds the Tab stop and on uninstall.- const ownTabIndex = new Map<HTMLElement, number>();- const rowControls = (row: HTMLElement) => {- const id = row.dataset.sidebarRow;- const linked = id- ? root.querySelectorAll<HTMLElement>(`[data-sidebar-action-for="${CSS.escape(id)}"]`)- : [];- return [...row.querySelectorAll<HTMLElement>(CONTROL), ...linked].filter(- (control) => !control.matches(ROW) && !control.matches(TEXT_ENTRY),- );- };- // Tab reaches the buttons of the focused row only, so the tree stays one stop for the rest.- const setRowControlsReachable = (row: HTMLElement, reachable: boolean) => {- for (const control of rowControls(row)) {- if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);- setTabIndex(control, reachable ? ownTabIndex.get(control)! : -1);- }+ const isVisibleRow = (row: HTMLElement) => {+ const hidden = row.closest('[hidden], [inert], [aria-hidden="true"]');+ // A dialog can temporarily make the whole workspace inert. Keep rows navigable+ // for its return while still excluding exiting row clones.+ return (!hidden || !root.contains(hidden)) && !row.matches(":disabled");};+ const visibleRows = () =>+ Array.from(root.querySelectorAll<HTMLElement>(ROW)).filter(isVisibleRow);- const setTabStop = (row: HTMLElement) => {- if (tabStop === row) return;- if (tabStop) {- setTabIndex(tabStop, -1);- setRowControlsReachable(tabStop, false);- }- setTabIndex(row, 0);- setRowControlsReachable(row, true);- tabStop = row;- focusedId = row.dataset.sidebarRow;+ const ownerRow = (element: HTMLElement) => {+ const row = element.closest<HTMLElement>(ROW);+ if (row) return row;+ const linked = element.dataset.sidebarActionFor;+ return linked+ ? root.querySelector<HTMLElement>(`[data-sidebar-row="${CSS.escape(linked)}"]`)+ : null;};const focusRow = (row: HTMLElement) => {- setTabStop(row);// Revealing before focusing also materializes content-visibility:auto descendants.row.scrollIntoView({ block: "nearest" });row.focus({ preventScroll: true });};- const refresh = () => {- const previousRows = rows;- const previousIndex = previousRows.findIndex((row) => row.dataset.sidebarRow === focusedId);- const previous = previousRows[previousIndex];- rows = Array.from(root.querySelectorAll<HTMLElement>(ROW)).filter((row) => {- const hidden = row.closest('[hidden], [inert], [aria-hidden="true"]');- // A dialog can temporarily make the whole workspace inert. Keep the tree's- // Tab stop ready for its return while still excluding exiting row clones.- return (!hidden || !root.contains(hidden)) && !row.matches(":disabled");- });- let selected =+ // A row that moves shelves remounts and drops focus to the body; follow it.+ const restoreFocus = () => {+ if (!ownsFocus || focusedId === undefined) return;+ const active = document.activeElement;+ const lost =+ active === document.body ||+ (active instanceof HTMLElement &&+ root.contains(active) &&+ active.matches(ROW) &&+ !isVisibleRow(active));+ if (!lost) return;+ const rows = visibleRows();+ const target =rows.find((row) => row.dataset.sidebarRow === focusedId) ??- rows.find((row) => row === document.activeElement);- if (!selected) {- selected =- rows.find((row) => row.dataset.sidebarRow === previous?.dataset.sidebarParent) ??- (previousIndex === -1 ? rows.find((row) => row.hasAttribute("aria-current")) : undefined) ??- rows[Math.min(Math.max(previousIndex, 0), rows.length - 1)];- }- focusedId = selected?.dataset.sidebarRow;- tabStop = selected;- setTabIndex(root, selected ? -1 : 0);- const siblings = new Map<string, HTMLElement[]>();- for (const row of rows) {- const parent = row.dataset.sidebarParent ?? "";- const group = siblings.get(parent) ?? [];- group.push(row);- siblings.set(parent, group);- setAttribute(row, "aria-level", parent ? "2" : "1");- setTabIndex(row, row === selected ? 0 : -1);- }- const byId = new Map(rows.map((row) => [row.dataset.sidebarRow, row]));- for (const control of ownTabIndex.keys()) if (!control.isConnected) ownTabIndex.delete(control);- for (const control of root.querySelectorAll<HTMLElement>(CONTROL)) {- if (control.matches(ROW) || control.matches(TEXT_ENTRY)) continue;- const linked = control.dataset.sidebarActionFor;- const owner = control.closest<HTMLElement>(ROW) ?? (linked ? byId.get(linked) : undefined);- if (!owner) continue;- if (!ownTabIndex.has(control)) ownTabIndex.set(control, control.tabIndex);- setTabIndex(control, owner === selected ? ownTabIndex.get(control)! : -1);- }- for (const group of siblings.values())- group.forEach((row, index) => {- setAttribute(row, "aria-posinset", String(index + 1));- setAttribute(row, "aria-setsize", String(group.length));- });- for (const listItem of root.querySelectorAll("li:not([role])"))- listItem.setAttribute("role", "presentation");- if (- ownsFocus &&- selected &&- (document.activeElement === document.body ||- document.activeElement === root ||- (root.contains(document.activeElement) &&- !rows.includes(document.activeElement as HTMLElement) &&- document.activeElement?.matches(ROW)))- ) {- // A settled row moves to the bottom shelf; scrolling after it fights the route reveal.- selected.focus({ preventScroll: true });- }- if (ownsFocus && !selected && document.activeElement === document.body) root.focus();+ rows.find((row) => row.dataset.sidebarRow === focusedParent) ??+ rows[Math.min(Math.max(focusedIndex, 0), rows.length - 1)];+ // A settled row moves to the bottom shelf; scrolling after it fights the route reveal.+ target?.focus({ preventScroll: true });};- // Clicking non-focusable content drops focus to the body without a focusin event.+ // Clicking non-focusable content, including empty list space, drops focus to the body+ // without a focusin event. A click on the focused row fires no focusin either.const onPointerDown = (event: PointerEvent) => {- if (!root.contains(event.target as Node)) ownsFocus = false;+ const focusable =+ event.target instanceof Element+ ? event.target.closest(`${ROW}, button, a[href], input, [tabindex]`)+ : null;+ ownsFocus = focusable !== null && root.contains(focusable);};const onFocus = (event: FocusEvent) => {ownsFocus = root.contains(event.target as Node);- if (!ownsFocus || !(event.target instanceof HTMLElement) || !event.target.matches(ROW)) return;- setTabStop(event.target);+ if (!ownsFocus || !(event.target instanceof HTMLElement)) return;+ const row = ownerRow(event.target);+ if (!row) return;+ focusedId = row.dataset.sidebarRow;+ focusedParent = row.dataset.sidebarParent;+ focusedIndex = visibleRows().indexOf(row);};const onKeyDown = (event: KeyboardEvent) => {const row = event.target;@@ -162,6 +105,7 @@ export function installSidebarTree(root: HTMLElement) {)return;if (!(row instanceof HTMLElement) || !row.matches(ROW)) return;+ const rows = visibleRows();const index = rows.indexOf(row);if (index < 0) return;let target: HTMLElement | undefined;@@ -219,34 +163,12 @@ export function installSidebarTree(root: HTMLElement) {}),);};- refresh();- const observer = new MutationObserver((records) => {- if (- records.some(- (record) =>- record.type === "attributes" ||- [...record.addedNodes, ...record.removedNodes].some(- (node) =>- node instanceof Element &&- (node.matches(`${ROW}, ${CONTROL}`) || node.querySelector(`${ROW}, ${CONTROL}`)),- ),- )- )- refresh();- });+ const observer = new MutationObserver(restoreFocus);observer.observe(root, {childList: true,subtree: true,attributes: true,- attributeFilter: [- "data-sidebar-row",- "data-sidebar-parent",- "aria-expanded",- "hidden",- "disabled",- "inert",- "aria-hidden",- ],+ attributeFilter: ["hidden", "inert", "aria-hidden"],});document.addEventListener("focusin", onFocus);document.addEventListener("pointerdown", onPointerDown, true);@@ -254,8 +176,6 @@ export function installSidebarTree(root: HTMLElement) {root.addEventListener("keyup", onKeyUp, true);return () => {observer.disconnect();- // A later install reads these as the controls' own tab indexes.- for (const [control, tabIndex] of ownTabIndex) setTabIndex(control, tabIndex);document.removeEventListener("focusin", onFocus);document.removeEventListener("pointerdown", onPointerDown, true);root.removeEventListener("keydown", onKeyDown, true);diff --git a/apps/web/src/lib/workspaceFocus.ts b/apps/web/src/lib/workspaceFocus.tsindex dcdb8ffdabd..810d57a9d60 100644--- a/apps/web/src/lib/workspaceFocus.ts+++ b/apps/web/src/lib/workspaceFocus.ts@@ -114,7 +114,7 @@ export function createWorkspaceFocusController(doc: Document) {!element.matches(":disabled");const preferred = Array.from(area.querySelectorAll<HTMLElement>(- '[data-workspace-focus-default], [role="treeitem"][tabindex="0"], [data-settings-section][tabindex="0"], .xterm-helper-textarea, [contenteditable="true"]',+ '[data-workspace-focus-default], [data-sidebar-row][aria-current="page"], [data-settings-section][tabindex="0"], .xterm-helper-textarea, [contenteditable="true"]',),).find(belongs);const fallback = Array.from(area.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).find(diff --git a/docs/user/keyboard-focus.md b/docs/user/keyboard-focus.mdindex b51262b6d69..8eb80a012f6 100644--- a/docs/user/keyboard-focus.md+++ b/docs/user/keyboard-focus.md@@ -26,9 +26,9 @@ can be remapped in Settings > Keybindings.## Browse threads-Tab enters the sidebar once. Up and Down move between threads without opening them; Enter-opens the focused thread or toggles a group. Right and Left expand and collapse groups.-Tab moves from the focused thread to its buttons. `F2` renames the focused thread.+Tab moves through each thread and its buttons. Up and Down also move between threads+without opening them; Enter opens the focused thread or toggles a group. Right and Left+expand and collapse groups. `F2` renames the focused thread.Press `Shift+F10` or the Context Menu key to open the focused thread's menu. Use the arrowkeys to move through it, Enter to choose, and Escape to close it.