A platform for community discussion. Free, open, simple.
DEV: Add a `dRovingFocus` keyboard-navigation modifier (#42381)
Sérgio Saquetim333121a5e7f0
diff --git a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md b/docs/developer-guides/docs/03-code-internals/02-ui-kit.mdindex 91194918a59..80cd199ca14 100644--- a/docs/developer-guides/docs/03-code-internals/02-ui-kit.md+++ b/docs/developer-guides/docs/03-code-internals/02-ui-kit.md@@ -140,15 +140,16 @@ Form-level composition belongs to [FormKit](22-form-kit.md). These are the under## Modifiers-| Modifier | Use it for |-| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |-| `d-auto-focus` | Focus an element when it renders. |-| `d-trap-tab` | Keep keyboard focus inside a dialog. |-| `d-tab-to-sibling` | Make Tab move focus between sibling elements. |-| `d-close-on-click-outside` | Dismiss an overlay when the user clicks elsewhere. |-| `d-on-resize`, `d-observe-intersection`, `d-scroll-into-view` | React to layout and visibility. |-| `d-autocomplete` | Attach an autocomplete popup to a text input. |-| `d-swipe`, `d-pointer-drag`, `d-resize-edge`, `d-drag-dwell`, `d-drag-and-drop-*` | Gestures. See [Drag, resize, and gesture primitives](30-drag-and-gesture-primitives.md). |+| Modifier | Use it for |+| --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `d-auto-focus` | Focus an element when it renders. |+| `d-trap-tab` | Keep keyboard focus inside a dialog. |+| `d-tab-to-sibling` | Make Tab move focus between sibling elements. |+| `d-roving-focus` | Arrow-key navigation over a group of items (a toolbar, listbox, menu, or tree) with a single tab stop, via roving tabindex or `aria-activedescendant`. See [Roving focus](https://meta.discourse.org/styleguide/molecules/roving-focus). |+| `d-close-on-click-outside` | Dismiss an overlay when the user clicks elsewhere. |+| `d-on-resize`, `d-observe-intersection`, `d-scroll-into-view` | React to layout and visibility. |+| `d-autocomplete` | Attach an autocomplete popup to a text input. |+| `d-swipe`, `d-pointer-drag`, `d-resize-edge`, `d-drag-dwell`, `d-drag-and-drop-*` | Gestures. See [Drag, resize, and gesture primitives](30-drag-and-gesture-primitives.md). |# Adding a primitive@@ -162,6 +163,7 @@ When you add one:- **Use BEM class names rooted at the component name** (older primitives predate this rule; new ones must follow it), `d-<name>`, `d-<name>__part`, `d-<name>--modifier`, and put the stylesheet at `app/assets/stylesheets/common/components/d-<name>.scss`, registered in `_index.scss`. Use colour and spacing tokens only; no hard-coded colours. See [CSS guidelines](26-css-guidelines-bem.md).- **Prefer named blocks over boolean arguments** when the consumer supplies content, and yield a small API object when the consumer needs to call back into the component.- **Take strings already translated.** A primitive receives display text as a plain `string` argument (`@label`, `@title`) that the consumer has already passed through `i18n()`; it never resolves translation keys itself. The kit does not know which locale file a consumer's key lives in, and a key-taking argument forces a parallel `@translatedX` argument for every string. `d-resize-separator.gts` documents its `label` this way. `DButton`'s `@label`-as-key plus `@translatedLabel` pair predates this rule; do not copy it.+- **Gate development-only warnings and assertions on `DEBUG`** from `@glimmer/env`. It is a build-time constant, so the gated code and its messages are stripped from production bundles; `d-resize-handles.gts` and `modifiers/d-roving-focus/diagnostics.ts` do this.- **Do not mention plugins or specific libraries** in its docs or comments; describe the mechanism instead.## Splitting a large primitivediff --git a/frontend/discourse/app/lib/load-accessible-name.js b/frontend/discourse/app/lib/load-accessible-name.jsnew file mode 100644index 00000000000..461e5444266--- /dev/null+++ b/frontend/discourse/app/lib/load-accessible-name.js@@ -0,0 +1,45 @@+import { waitForPromise } from "@ember/test-waiters";++/*+Plugins & themes are unable to async-import npm modules directly.+This wrapper provides them with a way to compute accessible names, while keeping the `import()`+in core's codebase.+*/++/**+ * Loads the accessible-name implementation and returns it with our corrections applied.+ *+ * Returns a corrected function rather than the library's raw export on purpose: importing+ * `dom-accessibility-api` directly loses the corrections below silently, and a second copy of+ * them is worse than none, because only one of the two gets fixed next time another is found.+ *+ * Serves the type-ahead wording in the WAI-ARIA Authoring Practices, which specifies moving to+ * "the next item with a NAME that starts with the typed character" — the name, not the text:+ * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/+ *+ * @returns {Promise<(element: Element) => string>} Computes the accessible name of an element,+ * per https://w3c.github.io/accname/ — what assistive technology announces for it.+ */+export default async function loadAccessibleName() {+ const { computeAccessibleName } = await waitForPromise(+ import("dom-accessibility-api")+ );++ return function accessibleName(element) {+ // `inert` is not implemented by the library, and it exposes no hook to supply one, so the+ // guard lives here: an inert subtree is out of the accessibility tree, so nothing in it has+ // a name to announce. Honest limitation — this covers an inert ROOT only. An+ // `aria-labelledby` reference reaching INTO an inert subtree is still counted, which would+ // need a fork to fix.+ if (element.closest("[inert]")) {+ return "";+ }++ // Defaults to false, which silently drops CSS `content` from every computed name. That+ // default exists for JSDOM, which logs errors for the second argument; real browsers+ // support it, and an item labelled through a pseudo-element is otherwise unmatchable.+ return computeAccessibleName(element, {+ computedStyleSupportsPseudoElements: true,+ });+ };+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.tsnew file mode 100644index 00000000000..01bd29ea6ff--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus.ts@@ -0,0 +1,629 @@+import { DEBUG } from "@glimmer/env";+import { assert } from "@ember/debug";+import { registerDestructor } from "@ember/destroyable";+import { guidFor } from "@ember/object/internals";+import type Owner from "@ember/owner";+import Modifier, { type ArgsFor } from "ember-modifier";+import { createRovingFocusApi } from "./d-roving-focus/api";+import { apiStep } from "./d-roving-focus/api-navigation";+import {+ type DRovingFocusConfig,+ normalizeConfig,+} from "./d-roving-focus/config";+import createRovingFocusDiagnostics from "./d-roving-focus/diagnostics";+import ItemScope from "./d-roving-focus/item-scope";+import KeyboardRouter from "./d-roving-focus/keyboard";+import ActiveDescendantStrategy from "./d-roving-focus/strategies/active-descendant";+import RovingTabindexStrategy from "./d-roving-focus/strategies/roving-tabindex";+import type {+ DRovingFocusApi,+ DRovingFocusArgs,+ DRovingFocusSignature,+ DRovingFocusStrategy,+} from "./d-roving-focus/types";++export type {+ DRovingFocusApi,+ DRovingFocusAxis,+ DRovingFocusDisabledItems,+ DRovingFocusEntry,+ DRovingFocusStepResult,+ DRovingFocusStrategy,+} from "./d-roving-focus/types";++/**+ * Keyboard navigation for a one-dimensional list or a two-dimensional grid of+ * items, in DOM order.+ *+ * Its conformance target is the WAI-ARIA Authoring Practices' keyboard-interface practice,+ * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/ — the sections implemented here+ * are Discernible and Predictable Focus, Navigation Between Components, Navigation Inside+ * Components, and the focusability of disabled controls. Focus VS Selection is split: the+ * modifier owns the indicator, the consumer owns the chosen value.+ *+ * **Where the boundary falls.** Key BINDINGS come from the individual pattern pages, which that+ * document delegates to, and pattern-specific SEMANTICS belong to consumers. So the modifier+ * moves a cursor and reports what happened; what a step, an activation or a cross-axis press+ * MEANS for a tree, a menubar or a treegrid is not its business. A behaviour earns a place here+ * only if it means the same thing in every composite pattern.+ *+ * **What the practice page does not ask for.** Five arguments are deliberate extensions:+ * `logicalCount`, `onJump` and `onRegisterApi` pair the cursor with a virtualised list, where the+ * DOM holds a window rather than the whole set, and `itemsKey` and `resetKey` are reactivity+ * plumbing. They are collected here so the conformance surface stays legible.+ *+ * It implements the two WAI-ARIA "single tab stop" patterns+ * from one engine, chosen with `focusStrategy`:+ *+ * - `"roving-tabindex"` (the default) — exactly one item is reachable with Tab+ * (`tabindex="0"`) and the rest are set to `tabindex="-1"`; with `tabStop=false` every item is+ * set to `-1`. Arrow keys move real DOM focus between items and update tabindex along with it.+ * Use this when the active item should itself hold focus (a tile grid, a toolbar).+ * - `"active-descendant"` — DOM focus stays on a separate controller+ * element (typically a text input); arrow keys move a *virtual* highlight through+ * the items by pointing the controller's `aria-activedescendant` at the active+ * item and toggling `activeClass` on it. Use this for a combobox where the user+ * must keep typing while navigating results.+ *+ * The single-tab-stop invariant holds as long as the modifier is told when the items change:+ * it only re-runs when a named argument does, so a group whose rows come from state it cannot+ * see must pass `itemsKey`.+ *+ * Navigation is always DOM order, which is a CONSTRAINT ON CONSUMERS rather than an+ * implementation detail: the practice page stresses keeping the navigation order aligned with+ * reading order, and CSS can reorder a grid visually (`order`, `grid-auto-flow: dense`, an+ * explicit line placement) without moving anything in the DOM. Where those disagree the cursor+ * follows the DOM and the reader sees it jump. Order the markup the way it should be read.+ *+ * Row and column arithmetic uses the items that occupy a layout+ * position — a disabled or `visibility: hidden` row still fills its cell, so counting only the+ * navigable ones would land a vertical step a column adrift. The column count is derived from+ * the resolved `grid-template-columns` at keydown time, never from element geometry+ * (`offsetTop`/`offsetLeft`), so a responsive grid that reflows is handled without+ * re-configuration. Only a CSS grid publishes a track list, so a group laid out some other+ * two-dimensional way (wrapping flex, multi-column) navigates on one axis, and says so in+ * development.+ *+ * The modifier is deliberately role-agnostic: the consumer supplies the container+ * and item roles (`role="listbox"`/`"grid"` + `role="option"`, and, for active mode,+ * `role="combobox"` + `aria-controls` on the controller). The modifier owns only the+ * keyboard cursor — `tabindex` (focus mode) or `aria-activedescendant` + `activeClass`+ * plus an `id` minted onto any highlighted item that lacks one (active mode). It never touches+ * `aria-selected`, which expresses a *chosen value* (a separate concept the consumer owns).+ *+ * @example A toolbar whose buttons are navigated with the left and right arrows.+ * ```gjs+ * <div role="toolbar" {{dRovingFocus orientation="horizontal" itemSelector="[role=button]"}}>+ * <button role="button">Bold</button>+ * <button role="button">Italic</button>+ * </div>+ * ```+ *+ * @example A combobox whose input keeps focus while the arrows move a virtual highlight.+ * ```gjs+ * <input id="q" role="combobox" aria-controls="results" />+ * <div+ * id="results"+ * role="listbox"+ * {{dRovingFocus+ * focusStrategy="active-descendant"+ * controllerElement="#q"+ * itemSelector="[role=option]"+ * activeClass="--active"+ * itemsKey=this.query+ * onActivate=this.choose+ * }}+ * >+ * {{#each this.results key="id" as |result|}}+ * <div role="option" id={{result.id}}>{{result.label}}</div>+ * {{/each}}+ * </div>+ * ```+ */+export default class DRovingFocusModifier extends Modifier<DRovingFocusSignature> {+ /** The element the modifier is attached to (the items' container). */+ #element: HTMLElement | null = null;++ /** The fully-resolved arguments from the latest completed `modify()`. */+ #config: DRovingFocusConfig | null = null;++ /** The live DOM query retained with the configuration that owns its artifacts. */+ #scope: ItemScope | null = null;++ /** The current roving strategy session, when that mode owns the cursor. */+ #rovingStrategy: RovingTabindexStrategy | null = null;++ /** The current active-descendant strategy session, when that mode owns the cursor. */+ #activeStrategy: ActiveDescendantStrategy | null = null;++ #itemSelector?: string;+ #keyboard = new KeyboardRouter();+ #onActiveChange?: (+ item: HTMLElement | null,+ meta?: { pointer: boolean }+ ) => void;++ /** The ARIA anchor: the container (focus) or controller (active). */+ #listenElement: HTMLElement | null = null;++ /** The container the shared `mousedown`/`focusin` listeners are currently bound to. */+ #boundContainer: HTMLElement | null = null;++ /** Whether `modify()` has run at least once, so the first run is not mistaken for a reset. */+ #hasRun = false;++ /** Owns the once-per-group development diagnostics. */+ #diagnostics = DEBUG ? createRovingFocusDiagnostics() : undefined;++ /**+ * Monotonic counter behind minted ids. Never reset, so an id cannot be reissued to a second+ * element while the first still carries it — which the set's size would allow after a mode or+ * selector change clears the bookkeeping.+ */+ #mintCounter = 0;++ /**+ * The last `resetKey` seen. The sentinel is a fresh symbol so the first `modify()` always counts+ * as a change — harmless, since there is no cursor yet to preserve, and it keeps the "unset"+ * case from colliding with a consumer that legitimately passes `undefined`.+ */+ #resetKey: unknown = Symbol("unset");++ #mode: DRovingFocusStrategy = "roving-tabindex";++ /** Stable controls registered with the consumer for moving the cursor within the group. */+ #api: DRovingFocusApi = createRovingFocusApi({+ items: () => this.#items(),+ currentItem: () => {+ const cells = this.#cells();+ return this.#currentElement(cells);+ },+ activate: (item) => this.#setActive(item),+ clear: () => {+ if (+ this.#mode !== "active-descendant" ||+ !this.#activeStrategy?.clear()+ ) {+ return false;+ }+ this.#onActiveChange?.(null);+ return true;+ },+ step: (axis, delta) => {+ if (!this.#config || !this.#scope) {+ return "unavailable";+ }+ return apiStep(axis, delta, {+ config: this.#config,+ scope: this.#scope,+ current: (items) => this.#currentElement(items),+ activate: (item) => this.#setActive(item),+ columnCount: () => this.#columnCount(),+ });+ },+ reannounce: () => this.#activeStrategy?.reannounce() ?? false,+ });++ /** The callback already given the stable API, retained to avoid render-time churn. */+ #registeredApiCallback?: (api: DRovingFocusApi | null) => void;++ /**+ * Routes a keydown to the cursor. Only the keys this group owns are consumed; everything else+ * — including any chorded key, and the page keys when there is no logical row count — is left+ * un-prevented so the surrounding UI can act on it.+ *+ * @param event - The keydown from the container (focus mode) or the controller (active mode).+ */+ #handleKeydown = (event: KeyboardEvent): void => {+ if (!this.#config || !this.#scope) {+ return;+ }+ this.#keyboard.handle(event, {+ config: this.#config,+ scope: this.#scope,+ controller: this.#listenElement,+ api: this.#api,+ warnWindowed: DEBUG+ ? () => this.#diagnostics!.warnWindowedTypeAhead()+ : undefined,+ current: (items) => this.#currentElement(items),+ columnCount: () => this.#columnCount(),+ activate: (item) => this.#setActive(item),+ });+ };++ /**+ * Active mode only — moves the cursor onto the item a pointer press landed on, so the keyboard+ * continues from where the reader last acted rather than from wherever a re-seed would put it.+ * Ignores a press that missed an item (padding, a group header, a scrollbar) and one on an item+ * the keyboard would refuse to land on.+ *+ * @param event - The `mousedown` that landed on the container.+ */+ #handlePointerDown = (event: MouseEvent): void => {+ if (this.#mode !== "active-descendant" || !this.#itemSelector) {+ return;+ }+ // Only a primary press moves the cursor. A right- or middle-click opens a context menu or+ // pastes; moving the highlight under either reads as a selection the reader did not make.+ // `defaultPrevented` is deliberately NOT consulted: preventing default on `mousedown` is how+ // a combobox keeps focus on its input, so it marks an ordinary selection, not a claimed press.+ if (event.button !== 0) {+ return;+ }+ const target = (event.target as HTMLElement | null)?.closest<HTMLElement>(+ this.#itemSelector+ );+ // `closest` walks past the container, so a matching ANCESTOR would otherwise be given a+ // minted id and an `activeClass` that nothing scoped to this group could ever clean up.+ if (!target || !this.#element?.contains(target)) {+ return;+ }+ if (!this.#isNavigable(target)) {+ return;+ }+ this.#setActive(target, true);+ };++ /**+ * Focus mode — keeps the tab stop on whichever item actually holds focus, so the group is+ * re-entered where the reader left it rather than where seeding put it. Without this, clicking+ * the fifth option, tabbing away and tabbing back lands on the first.+ *+ * Bound on `focusin` rather than extended from the pointer handler because focus also arrives+ * with no pointer event at all, and a pointer-only fix would leave those cases behind.+ *+ * Only restamps; it never moves focus and never reports a cursor move. The cursor is already+ * wherever focus is, so calling {@link DRovingFocusArgs.onActiveChange} here would report a+ * move that the arrow path has already reported, or invent one the reader did not make.+ */+ #handleFocusIn = (event: FocusEvent): void => {+ if (this.#mode !== "roving-tabindex" || !this.#itemSelector) {+ return;+ }+ const target = (event.target as HTMLElement | null)?.closest<HTMLElement>(+ this.#itemSelector+ );+ // `closest` walks past the container, so a matching ANCESTOR would otherwise be promoted+ // into a tab stop this group never owned.+ if (!target || !this.#element?.contains(target)) {+ return;+ }+ if (!this.#isNavigable(target)) {+ return;+ }+ this.#rovingStrategy?.recordFocus(target);+ };++ constructor(owner: Owner, args: ArgsFor<DRovingFocusSignature>) {+ super(owner, args);+ registerDestructor(this, () => {+ this.#cleanup();+ });+ }++ /**+ * Reads the named args, (re)binds the keydown listener to the right element, and+ * seeds the cursor. Re-runs whenever a tracked arg changes — passing+ * `itemsKey=this.query` is how a filtering consumer asks the modifier to+ * re-reconcile the cursor against a freshly-rendered item set.+ */+ modify(element: HTMLElement, _positional: [], named: DRovingFocusArgs): void {+ const config = normalizeConfig(named);+ const previousMode = this.#config?.focusStrategy ?? this.#mode;+ const previousItemSelector =+ this.#config?.itemSelector ?? this.#itemSelector;+ const nextMode = config.focusStrategy;++ // Everything the previous configuration wrote has to be swept BEFORE the new arguments are+ // adopted, because every sweep resolves items through the CURRENT `itemSelector` and class.+ // Adopting them first would aim the cleanup at the new item set and strand the old one.+ if (+ previousItemSelector !== config.itemSelector ||+ previousMode !== nextMode+ ) {+ this.#exitEnteredModes();+ }++ this.#element = element;+ this.#config = config;+ this.#scope = new ItemScope(+ element,+ config.itemSelector,+ config.disabledItems+ );+ if (nextMode === "roving-tabindex") {+ if (this.#rovingStrategy) {+ this.#rovingStrategy.update(this.#scope, config);+ } else {+ this.#rovingStrategy = new RovingTabindexStrategy(this.#scope, config);+ }+ }+ this.#mode = nextMode;+ // Asserted rather than merely typed: a consumer casting this modifier to a hand-written+ // `ModifierLike` signature bypasses the type entirely, and without a selector the group binds+ // its listener, matches nothing, and silently swallows every key.+ assert(+ "dRovingFocus requires an `itemSelector` matching the navigable items",+ config.itemSelector+ );+ this.#itemSelector = config.itemSelector;+ this.#keyboard.configure(config);+ this.#onActiveChange = config.onActiveChange;+ // Never on the first run: the sentinel guarantees a difference there, and treating that as a+ // reset would discard an author-supplied `tabindex="0"` before the group has done anything.+ const resetKeyChanged = this.#hasRun && config.resetKey !== this.#resetKey;+ this.#resetKey = config.resetKey;+ this.#hasRun = true;++ const listenElement =+ this.#mode === "active-descendant"+ ? this.#resolveController(config.controllerElement)+ : element;++ if (nextMode === "active-descendant") {+ if (this.#activeStrategy) {+ this.#activeStrategy.update(this.#scope, config, listenElement);+ } else {+ this.#activeStrategy = new ActiveDescendantStrategy(+ this.#scope,+ config,+ listenElement,+ () => `${guidFor(this)}-${this.#mintCounter++}`,+ () => this.#reconcileActive()+ );+ }+ }++ // Rebind only when the listener target changes (the controller element can be+ // swapped, or arrive late once its own `didInsert` has run).+ if (this.#listenElement !== listenElement) {+ this.#listenElement?.removeEventListener("keydown", this.#handleKeydown);+ // The outgoing controller must not keep pointing at an option it no longer controls.+ this.#listenElement?.removeAttribute("aria-activedescendant");+ this.#listenElement = listenElement ?? null;+ this.#listenElement?.addEventListener("keydown", this.#handleKeydown);+ }++ // Bound to the container, not the items, because items come and go. `mousedown` rather than+ // click so the cursor is in place before any consumer handler rebuilds the list: otherwise+ // activating by pointer leaves the reconcile below with no cursor to preserve, and it seeds+ // one at the top — marking a row the reader never touched and pointing+ // `aria-activedescendant` at it.+ if (this.#boundContainer !== element) {+ this.#boundContainer?.removeEventListener(+ "mousedown",+ this.#handlePointerDown+ );+ this.#boundContainer?.removeEventListener("focusin", this.#handleFocusIn);+ this.#boundContainer = element;+ element.addEventListener("mousedown", this.#handlePointerDown);+ element.addEventListener("focusin", this.#handleFocusIn);+ }++ if (this.#mode === "active-descendant") {+ if (DEBUG) {+ this.#diagnostics!.warnMissingFocusIndicator(+ Boolean(config.activeClass || config.onActiveChange)+ );+ }+ this.#reconcileActive(resetKeyChanged);+ } else {+ this.#rovingStrategy?.seed(resetKeyChanged);+ const restoration = this.#rovingStrategy?.restorationTarget();+ if (restoration) {+ this.#setActive(restoration);+ }+ }+ // Recorded last, so the next run compares against what this one ended with.+ this.#rovingStrategy?.finishRender();++ // Registered last, so a consumer that drives the cursor from inside the callback acts on a+ // bound listener and an already-seeded group.+ if (this.#registeredApiCallback !== config.onRegisterApi) {+ // Tell the superseded holder its registration has ended. The handle it already has stays+ // functional while the modifier lives — there is one shared API object, and only teardown+ // makes it inert — so this is a notification, not a revocation.+ this.#registeredApiCallback?.(null);+ this.#registeredApiCallback = config.onRegisterApi;+ config.onRegisterApi?.(this.#api);+ }+ }++ /**+ * Resolves the controller element from an `Element` or a CSS selector (matched+ * against the document).+ */+ #resolveController(+ controllerElement: Element | string | null | undefined+ ): HTMLElement | null {+ if (controllerElement instanceof HTMLElement) {+ return controllerElement;+ }+ if (typeof controllerElement === "string") {+ // Scoped to the document because the controller is deliberately OUTSIDE the group it+ // drives. A selector shared by several instances of the same widget therefore resolves to+ // the first match for all of them; pass the element itself when more than one can exist.+ return document.querySelector<HTMLElement>(controllerElement);+ }+ // `null`/`undefined` is a legitimate transient: the controller may not have rendered yet, and+ // a later `modify()` picks it up.+ return null;+ }++ /**+ * The live, navigable items in DOM order — the cursor's legal landing places. Re-queried on+ * every read (never cached) so a consumer that re-renders its list between keystrokes never+ * navigates a stale NodeList.+ *+ * @returns Every item the cursor may rest on.+ */+ #items(): HTMLElement[] {+ return this.#scope?.items() ?? [];+ }++ /**+ * The items that occupy a layout position, in DOM order. This is the coordinate space row and+ * column arithmetic must use: a row that is merely disabled or `visibility: hidden` still fills+ * its grid cell, so counting only the navigable items would shift every subsequent cell and make+ * a vertical step land a column adrift. `display: none` rows are excluded because the grid+ * genuinely reflows around them.+ *+ * @returns Every item that takes up space, navigable or not.+ */+ #cells(): HTMLElement[] {+ return this.#scope?.cells() ?? [];+ }++ /**+ * Whether an item can be a navigation target — it occupies space, is not hidden, and is not+ * disabled in a way that would refuse focus. Which disabled items qualify is+ * {@link DRovingFocusArgs.disabledItems}; the native spelling never does.+ *+ * @param el - The candidate item.+ * @returns `true` when the cursor may rest on the item.+ */+ #isNavigable(el: HTMLElement): boolean {+ return this.#scope?.isNavigable(el) ?? false;+ }++ /**+ * The number of columns the cursor navigates by.+ *+ * Only a `"grid"` group in `"roving-tabindex"` mode has a second axis, so both other cases resolve to one+ * column without measuring anything. Active mode leaves the horizontal arrows to its+ * controller's caret, so its cursor can never reach a second column — deriving one would+ * strand every item outside the first.+ *+ * Otherwise derived from the resolved `grid-template-columns` track list+ * (e.g. `"96px 96px 96px"` → 3), which the browser resolves even for `repeat(auto-fill, …)`,+ * so a responsive grid that reflows needs no re-configuration. Falls back to a single column+ * when the computed value is empty or `none`.+ *+ * @returns The column count, at least 1.+ */+ #columnCount(): number {+ if (+ this.#mode === "active-descendant" ||+ this.#config?.orientation !== "grid"+ ) {+ return 1;+ }+ if (!this.#element) {+ return 1;+ }+ // One read serves both the track list and the degradation check below, so the diagnostic+ // costs no extra style resolution.+ const style = getComputedStyle(this.#element);+ const tracks = style.gridTemplateColumns;+ // Named grid lines survive into the computed value (`[full-start] 300px [mid] 300px`) and+ // are not tracks; counting them reads a two-track grid as five columns. `subgrid` is not a+ // track either.+ const count =+ !tracks || tracks === "none"+ ? 1+ : tracks+ .trim()+ .replace(/\[[^\]]*\]/g, " ")+ .split(/\s+/)+ .filter((token) => token && token !== "subgrid").length || 1;+ if (DEBUG && count === 1) {+ this.#diagnostics!.warnUndetectedSecondAxis(style);+ }+ return count;+ }++ /**+ * Resolves the cursor through the current strategy without measuring the item set.+ */+ #currentElement(items: HTMLElement[]): HTMLElement | null {+ if (this.#mode === "active-descendant") {+ return this.#activeStrategy?.current(items) ?? null;+ }+ return this.#rovingStrategy?.current(items) ?? null;+ }++ /**+ * Moves the cursor to `target`: in focus mode, updates the items' tabindex values+ * and moves DOM focus; in active mode, repoints `aria-activedescendant`, moves+ * `activeClass`, and scrolls the item into view without moving focus.+ *+ * @param target - The item to move the cursor onto.+ * @param pointer - Whether a pointer press placed it, forwarded to `onActiveChange` so a+ * consumer can distinguish "the cursor moved" from "show the cursor".+ */+ #setActive(target: HTMLElement, pointer = false): void {+ if (this.#mode === "active-descendant") {+ this.#activeStrategy!.activate(target);+ if (DEBUG) {+ this.#diagnostics!.warnUnreachableActiveDescendant(+ this.#listenElement,+ target+ );+ }+ } else {+ this.#rovingStrategy?.activate(target);+ }+ this.#onActiveChange?.(target, { pointer });+ }++ /**+ * Active mode — reconciles the highlight after the item set may have changed+ * (`itemsKey`). If the previously-active id is gone (or there was none), clears the+ * highlight so `aria-activedescendant` never points at a removed element; the next+ * Arrow keypress seeds a new active option.+ *+ * @param reseed - Treat the cursor as gone even if its row survived, because the items now+ * answer a different question (`resetKey`).+ */+ #reconcileActive(reseed = false): void {+ const result = this.#activeStrategy?.reconcile(reseed);+ if (result?.kind === "activate") {+ this.#setActive(result.target);+ } else if (result?.kind === "cleared") {+ this.#onActiveChange?.(null);+ }+ }++ /**+ * Undoes everything every mode this instance actually ran in wrote to the DOM. Branching on+ * whichever mode happens to be current would strand the other one's artifacts, while exiting+ * modes that never ran would remove attributes the author owns.+ */+ #exitEnteredModes(): void {+ this.#activeStrategy?.destroy();+ this.#activeStrategy = null;+ this.#rovingStrategy?.destroy();+ this.#rovingStrategy = null;+ }++ /**+ * Releases every listener, observer and timer, and gives back everything either mode wrote to+ * the DOM. Registered as the destructor, so it also tells the consumer its registration has+ * ended. That notification is final, unlike the one a supersede sends: every API method+ * reports failure once the modifier is torn down.+ */+ #cleanup(): void {+ this.#keyboard.destroy();+ this.#activeStrategy?.disarmPendingSeed();+ this.#listenElement?.removeEventListener("keydown", this.#handleKeydown);+ this.#boundContainer?.removeEventListener(+ "mousedown",+ this.#handlePointerDown+ );+ this.#boundContainer?.removeEventListener("focusin", this.#handleFocusIn);+ // Every mode this instance ran in, not just the current one: a modifier that spent part of+ // its life in active mode and ended in focus mode still has that mode's ids and attribute to+ // give back.+ this.#exitEnteredModes();+ this.#listenElement = null;+ this.#boundContainer = null;+ this.#rovingStrategy = null;+ this.#activeStrategy = null;+ this.#element = null;+ this.#scope = null;+ this.#config = null;+ this.#registeredApiCallback?.(null);+ this.#registeredApiCallback = undefined;+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.tsnew file mode 100644index 00000000000..46fcd88291d--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api-navigation.ts@@ -0,0 +1,112 @@+import type { DRovingFocusConfig } from "./config";+import ItemScope from "./item-scope";+import { scan, step, type StepOutcome, stepRow } from "./navigation";+import type { DRovingFocusAxis, DRovingFocusStepResult } from "./types";++/** Operations and state needed to step the cursor from the public API. */+export interface ApiNavigationContext {+ config: DRovingFocusConfig;+ scope: ItemScope;+ current(items: HTMLElement[]): HTMLElement | null;+ activate(item: HTMLElement): void;+ columnCount(): number;+}++/**+ * Steps the cursor one item on behalf of the public API, seeding an end when there is no cursor.+ *+ * The boundary callback is deliberately never emitted from this path: it announces that a READER+ * pushed against an end, which a programmatic call has not done. The three-valued return is what+ * a caller gets instead.+ *+ * @param axis - The axis to travel in a grid; defaults to vertical, the axis a caller that names+ * none is asking for in a list.+ * @param delta - `1` for forward or `-1` for backward DOM order.+ * @returns Whether the cursor moved, sat against an edge, or had nowhere to go at all.+ */+export function apiStep(+ axis: DRovingFocusAxis | undefined,+ delta: 1 | -1,+ context: ApiNavigationContext+): DRovingFocusStepResult {+ if (context.config.orientation !== "grid") {+ return stepLinear(delta, context);+ }+ const cells = context.scope.cells();+ if (!cells.some((cell) => context.scope.isNavigable(cell))) {+ return "unavailable";+ }+ const currentElement = context.current(cells);+ const current = currentElement ? cells.indexOf(currentElement) : -1;+ const resolvedAxis = axis ?? "vertical";+ const outcome = applyStep(+ resolvedAxis,+ delta,+ cells,+ current,+ context.columnCount(),+ context+ );+ return outcome.kind === "move" ? "moved" : "edge";+}++/** Steps a single-axis group, where no column arithmetic applies and the axis argument is moot. */+function stepLinear(+ delta: 1 | -1,+ context: ApiNavigationContext+): DRovingFocusStepResult {+ const items = context.scope.all();+ const last = items.length - 1;+ const current = context.current(items);+ const from = current ? items.indexOf(current) : -1;+ if (from < 0) {+ const seed = scan(items, delta > 0 ? 0 : last, delta, 0, last, (item) =>+ context.scope.isNavigable(item)+ );+ if (seed == null) {+ return "unavailable";+ }+ context.activate(items[seed]);+ return "moved";+ }+ const next = scan(items, from + delta, delta, 0, last, (item) =>+ context.scope.isNavigable(item)+ );+ if (next == null) {+ return "edge";+ }+ context.activate(items[next]);+ return "moved";+}++/**+ * Runs the grid step and commits a landing. Travels the row axis whenever there is no cursor yet,+ * because the column walk has no anchor to count from.+ */+function applyStep(+ axis: DRovingFocusAxis,+ delta: 1 | -1,+ cells: HTMLElement[],+ current: number,+ columns: number,+ context: ApiNavigationContext+): StepOutcome {+ const outcome =+ axis === "horizontal" || current < 0+ ? step(+ current,+ delta,+ cells,+ columns,+ context.config.orientation,+ context.config.wrap,+ (cell) => context.scope.isNavigable(cell)+ )+ : stepRow(current, delta, cells, columns, context.config.wrap, (cell) =>+ context.scope.isNavigable(cell)+ );+ if (outcome.kind === "move") {+ context.activate(cells[outcome.index]);+ }+ return outcome;+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api.tsnew file mode 100644index 00000000000..003c9092c78--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/api.ts@@ -0,0 +1,96 @@+import type {+ DRovingFocusApi,+ DRovingFocusAxis,+ DRovingFocusStepResult,+} from "./types";++/** Internal operations used to bind the stable public cursor API to its owner. */+export interface RovingFocusApiPort {+ items(): HTMLElement[];+ currentItem(): HTMLElement | null;+ activate(item: HTMLElement): void;+ clear(): boolean;+ step(+ axis: DRovingFocusAxis | undefined,+ delta: 1 | -1+ ): DRovingFocusStepResult;+ reannounce(): boolean;+}++/** Creates an immutable cursor API backed by the supplied strategy port. */+export function createRovingFocusApi(+ port: RovingFocusApiPort+): DRovingFocusApi {+ const api: DRovingFocusApi = {+ focusFirst: () => {+ const items = port.items();+ if (!items.length) {+ return false;+ }+ port.activate(items[0]);+ return true;+ },+ focusLast: () => {+ const items = port.items();+ if (!items.length) {+ return false;+ }+ port.activate(items[items.length - 1]);+ return true;+ },+ focusIndex: (index) => {+ const items = port.items();+ if (!items.length || !Number.isInteger(index)) {+ return false;+ }+ const last = items.length - 1;+ port.activate(items[Math.max(0, Math.min(index, last))]);+ return true;+ },+ focusLogicalIndex: (index) => {+ const items = port.items();+ if (!items.length || !Number.isFinite(index)) {+ return false;+ }+ const match = items.find((item) => {+ const stamp = item.dataset.logicalIndex ?? item.dataset.index;+ return stamp !== undefined && Number(stamp) === index;+ });+ if (match) {+ port.activate(match);+ return true;+ }+ const positional = items.every(+ (item) =>+ item.dataset.logicalIndex === undefined &&+ item.dataset.index === undefined+ );+ // Stamped lookup accepts any finite numeric match, but positional lookup indexes an array.+ if (+ !positional ||+ !Number.isInteger(index) ||+ index < 0 ||+ index >= items.length+ ) {+ return false;+ }+ port.activate(items[index]);+ return true;+ },+ clear: () => port.clear(),+ focusNext: (axis) => port.step(axis, 1),+ focusPrevious: (axis) => port.step(axis, -1),+ items: () => port.items(),+ currentItem: () => port.currentItem(),+ indexOf: (item) => port.items().indexOf(item),+ focusElement: (item) => {+ if (!port.items().includes(item)) {+ return false;+ }+ port.activate(item);+ return true;+ },+ reannounceActive: () => port.reannounce(),+ };+ return Object.freeze(api);+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.tsnew file mode 100644index 00000000000..24ce319d723--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/config.ts@@ -0,0 +1,67 @@+import type {+ DRovingFocusArgs,+ DRovingFocusDisabledItems,+ DRovingFocusEntry,+ DRovingFocusStrategy,+ Orientation,+} from "./types";++/**+ * {@link DRovingFocusArgs} with every default resolved, so no consumer of a configuration has to+ * re-decide what an omitted argument meant.+ */+export interface DRovingFocusConfig {+ focusStrategy: DRovingFocusStrategy;+ orientation: Orientation;+ itemSelector: string;+ onActivate: DRovingFocusArgs["onActivate"];+ onActiveChange: DRovingFocusArgs["onActiveChange"];+ onBoundary: DRovingFocusArgs["onBoundary"];+ logicalCount: number | undefined;+ onJump: DRovingFocusArgs["onJump"];+ onRegisterApi: DRovingFocusArgs["onRegisterApi"];+ wrap: boolean;+ tabStop: boolean;+ restoreLostFocus: boolean;+ activeClass: string | null;+ itemsKey: unknown;+ resetKey: unknown;+ controllerElement: HTMLElement | string | null | undefined;+ entryFocus: DRovingFocusEntry;+ fallbackSkipsMarked: boolean;+ disabledItems: DRovingFocusDisabledItems;+ onCrossAxis: DRovingFocusArgs["onCrossAxis"];+ typeAhead: boolean;+}++/**+ * Resolves the named arguments into a configuration, reading every one of them so the modifier+ * re-runs when any changes.+ */+export function normalizeConfig(named: DRovingFocusArgs): DRovingFocusConfig {+ return {+ focusStrategy: named.focusStrategy ?? "roving-tabindex",+ orientation: named.orientation ?? "grid",+ itemSelector: named.itemSelector,+ onActivate: named.onActivate,+ onActiveChange: named.onActiveChange,+ onBoundary: named.onBoundary,+ logicalCount: named.logicalCount,+ onJump: named.onJump,+ onRegisterApi: named.onRegisterApi,+ wrap: named.wrap ?? false,+ tabStop: named.tabStop ?? true,+ restoreLostFocus: named.restoreLostFocus ?? true,+ activeClass: named.activeClass ?? null,+ // This read is load-bearing even though the value is never consulted: consuming the+ // tag is what makes a changed `itemsKey` re-run `modify()` and reconcile the cursor.+ itemsKey: named.itemsKey,+ resetKey: named.resetKey,+ controllerElement: named.controllerElement,+ entryFocus: named.entryFocus ?? "selected-or-first",+ fallbackSkipsMarked: named.fallbackSkipsMarked ?? false,+ disabledItems: named.disabledItems ?? "skip",+ onCrossAxis: named.onCrossAxis,+ typeAhead: named.typeAhead ?? false,+ };+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/diagnostics.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/diagnostics.tsnew file mode 100644index 00000000000..f1b822f8ec7--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/diagnostics.ts@@ -0,0 +1,123 @@+import { DEBUG } from "@glimmer/env";++/** Creates the development-only diagnostics for one group. */+export default function createRovingFocusDiagnostics():+ | RovingFocusDiagnostics+ | undefined {+ if (DEBUG) {+ return new RovingFocusDiagnostics();+ }+}++/** Emits each configuration diagnostic at most once per group. */+class RovingFocusDiagnostics {+ #warnedWindowedTypeAhead = false;+ #warnedUndetectedSecondAxis = false;+ #warnedNoIndicator = false;+ #warnedUnreachableActiveDescendant = false;++ /** Warns once when type-ahead is declined for a partially mounted data set. */+ warnWindowedTypeAhead(): void {+ if (this.#warnedWindowedTypeAhead) {+ return;+ }+ this.#warnedWindowedTypeAhead = true;+ // eslint-disable-next-line no-console+ console.warn(+ `dRovingFocus: typeAhead is declined because logicalCount exceeds the mounted rows. A ` ++ `search over part of the set answers with a nearer match while a truer one sits ` ++ `off-window. Search the full data from the consumer instead.`+ );+ }++ /** Warns once when active-descendant mode has no visible indicator mechanism. */+ warnMissingFocusIndicator(hasIndicator: boolean): void {+ if (hasIndicator) {+ return;+ }+ if (this.#warnedNoIndicator) {+ return;+ }+ this.#warnedNoIndicator = true;+ // eslint-disable-next-line no-console+ console.warn(+ `dRovingFocus: focusStrategy="active-descendant" with neither activeClass nor onActiveChange, so ` ++ `nothing marks the active item and the cursor is invisible. Pass activeClass, or ` ++ `render the highlight yourself from onActiveChange.`+ );+ }++ /** Warns once when a two-dimensional layout exposes no measurable column tracks. */+ warnUndetectedSecondAxis(style: CSSStyleDeclaration): void {+ const wrappingFlex =+ (style.display === "flex" || style.display === "inline-flex") &&+ style.flexWrap.startsWith("wrap");+ const multiColumn = Number(style.columnCount) > 1;+ if (!wrappingFlex && !multiColumn) {+ return;+ }+ if (this.#warnedUndetectedSecondAxis) {+ return;+ }+ this.#warnedUndetectedSecondAxis = true;+ // eslint-disable-next-line no-console+ console.warn(+ `dRovingFocus: orientation="grid" on a ${+ wrappingFlex ? "wrapping flex" : "multi-column"+ } container, which publishes no column track list, so the group navigates on one axis. ` ++ `Lay it out with CSS grid to get the second axis.`+ );+ }++ /** Warns once when ARIA does not permit the controller to reference the active item. */+ warnUnreachableActiveDescendant(+ controller: HTMLElement | null,+ target: HTMLElement+ ): void {+ if (!controller || this.#isReachable(controller, target)) {+ return;+ }+ if (this.#warnedUnreachableActiveDescendant) {+ return;+ }+ this.#warnedUnreachableActiveDescendant = true;+ // eslint-disable-next-line no-console+ console.warn(+ `dRovingFocus: the controller points aria-activedescendant at an item it does not ` ++ `contain, does not aria-own, and does not reach through aria-controls, which ARIA ` ++ `does not permit. Assistive technology will not follow the cursor. Put the items ` ++ `inside the controller, or add aria-owns, or give a combobox/textbox/searchbox ` ++ `controller an aria-controls pointing at the list.`+ );+ }++ #isReachable(controller: HTMLElement, target: HTMLElement): boolean {+ if (controller.contains(target)) {+ return true;+ }+ if (this.#ariaIds(controller, "aria-owns").includes(target.id)) {+ return true;+ }+ const role = controller.getAttribute("role");+ const textual = role+ ? role === "combobox" || role === "textbox" || role === "searchbox"+ : controller instanceof HTMLInputElement ||+ controller instanceof HTMLTextAreaElement;+ if (!textual) {+ return false;+ }+ const document = controller.ownerDocument;+ return this.#ariaIds(controller, "aria-controls").some((id) => {+ const controlled = document.getElementById(id);+ return (+ !!controlled &&+ (controlled.contains(target) ||+ this.#ariaIds(controlled, "aria-owns").includes(target.id))+ );+ });+ }++ #ariaIds(element: HTMLElement, attribute: string): string[] {+ return (element.getAttribute(attribute) ?? "").split(/\s+/).filter(Boolean);+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.tsnew file mode 100644index 00000000000..0a908dcf377--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/entry-policy.ts@@ -0,0 +1,63 @@+import type { DRovingFocusConfig } from "./config";++function hasCurrentToken(item: HTMLElement): boolean {+ const current = item.getAttribute("aria-current");+ return current !== null && current !== "" && current !== "false";+}++/** Returns whether entry should prefer a marked item. */+export function prefersSelected(config: DRovingFocusConfig): boolean {+ return (+ config.entryFocus === "selected-or-first" ||+ config.entryFocus === "selected-or-none"+ );+}++/** Returns whether entry may fall back to the first eligible item. */+export function fallsBackToFirst(config: DRovingFocusConfig): boolean {+ return (+ config.entryFocus === "first" || config.entryFocus === "selected-or-first"+ );+}++/** Returns whether an item carries any supported chosen-value marker. */+export function isMarked(item: HTMLElement): boolean {+ return (+ item.getAttribute("aria-selected") === "true" ||+ item.getAttribute("aria-checked") === "true" ||+ hasCurrentToken(item)+ );+}++/**+ * Finds the highest-priority eligible marker, searching by attribute before document order so+ * explicit selection consistently outranks a merely current item.+ */+export function findMarked(+ items: HTMLElement[],+ eligible: (item: HTMLElement) => boolean = () => true+): HTMLElement | undefined {+ return (+ items.find(+ (item) => item.getAttribute("aria-selected") === "true" && eligible(item)+ ) ??+ items.find(+ (item) => item.getAttribute("aria-checked") === "true" && eligible(item)+ ) ??+ items.find((item) => hasCurrentToken(item) && eligible(item))+ );+}++/** Chooses the active-descendant entry target under the configured fallback policy. */+export function activeSeed(+ items: HTMLElement[],+ config: DRovingFocusConfig+): HTMLElement | undefined {+ const selected = prefersSelected(config) ? findMarked(items) : undefined;+ if (selected || !fallsBackToFirst(config)) {+ return selected;+ }+ return config.fallbackSkipsMarked+ ? items.find((item) => !isMarked(item))+ : items[0];+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.tsnew file mode 100644index 00000000000..9c7747a739a--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/item-scope.ts@@ -0,0 +1,69 @@+import type { DRovingFocusDisabledItems } from "./types";++/** Queries an item group and applies its navigation eligibility rules. */+export default class ItemScope {+ constructor(+ readonly container: HTMLElement,+ readonly selector: string,+ readonly disabledItems: DRovingFocusDisabledItems+ ) {}++ /** Returns every selector-matched item in DOM order. */+ all(): HTMLElement[] {+ return Array.from(+ this.container.querySelectorAll<HTMLElement>(this.selector)+ );+ }++ /** Returns the items the cursor may land on. */+ items(): HTMLElement[] {+ return this.all().filter((item) => this.isNavigable(item));+ }++ /** Returns the items that occupy positions in the navigation coordinate space. */+ cells(): HTMLElement[] {+ return this.all().filter((item) => this.occupiesLayout(item));+ }++ /**+ * Whether activation is allowed; deliberately narrower than navigation eligibility because a+ * disabled item may remain discoverable without becoming operable.+ */+ isActivatable(item: HTMLElement): boolean {+ return !this.isAriaDisabled(item) && this.isNavigable(item);+ }++ /** Whether the cursor may land on an item. */+ isNavigable(item: HTMLElement): boolean {+ if (this.disabledItems === "skip" && this.isAriaDisabled(item)) {+ return false;+ }+ // The selector also catches controls disabled through an ancestor fieldset, unlike the IDL+ // property on the candidate alone.+ if (item.matches(":disabled")) {+ return false;+ }+ // Inertness applies to descendants, so checking only the candidate's attribute is insufficient.+ if (item.closest("[inert]")) {+ return false;+ }+ if (!this.occupiesLayout(item)) {+ return false;+ }+ // Visibility is checked last because resolving computed style is the expensive predicate.+ return getComputedStyle(item).visibility === "visible";+ }++ /**+ * Whether an item occupies layout; client rects retain fixed-position items that have no+ * `offsetParent` while still excluding items removed from layout.+ */+ occupiesLayout(item: HTMLElement): boolean {+ return Boolean(item.offsetParent) || item.getClientRects().length > 0;+ }++ /** Returns whether the item carries the enabled ARIA-disabled state. */+ isAriaDisabled(item: HTMLElement): boolean {+ return item.getAttribute("aria-disabled") === "true";+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.tsnew file mode 100644index 00000000000..ebb46179432--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/keyboard.ts@@ -0,0 +1,419 @@+import type { DRovingFocusConfig } from "./config";+import type ItemScope from "./item-scope";+import { scan, step, type StepOutcome, stepRow } from "./navigation";+import TypeAhead from "./type-ahead";+import type { DRovingFocusApi, DRovingFocusAxis } from "./types";++/**+ * Input types with no text caret, so an arrow key means navigation there rather than a cursor+ * move the field owns.+ */+const NON_ARROW_INPUT_TYPES = new Set([+ "button",+ "checkbox",+ "file",+ "image",+ "reset",+ "submit",+]);++/** Operations and state needed to route one keypress. */+export interface KeyboardContext {+ config: DRovingFocusConfig;+ scope: ItemScope;+ controller: HTMLElement | null;+ api: DRovingFocusApi;+ warnWindowed?: () => void;+ current(items: HTMLElement[]): HTMLElement | null;+ columnCount(): number;+ activate(item: HTMLElement): void;+}++/** Routes owned keyboard commands to navigation, activation, or type-ahead. */+export default class KeyboardRouter {+ #typeAhead = new TypeAhead();++ /** Applies the type-ahead portion of the latest configuration. */+ configure(config: DRovingFocusConfig): void {+ this.#typeAhead.configure(config.typeAhead);+ }++ /** Routes a keydown while leaving unowned keys unconsumed. */+ handle(event: KeyboardEvent, context: KeyboardContext): void {+ const { config, scope } = context;+ if (event.isComposing) {+ return;+ }+ if (+ config.focusStrategy === "roving-tabindex" &&+ this.#isEditable(event.target)+ ) {+ return;+ }+ // A container routinely holds focusable controls that are not items and do+ // not sit inside one, such as a row's own switch beside the handle that is+ // the cursor's item. Routing their keys anyway resolves the cursor to+ // whichever item happens to hold the tab stop, dragging focus off the+ // control the user is actually on.+ if (+ config.focusStrategy === "roving-tabindex" &&+ !this.#ownsTarget(event.target, context)+ ) {+ return;+ }+ // Type-ahead must run before the active-mode allow-list and chord guard: printable keys are+ // absent from the allow-list, and Shift is how a capital letter arrives.+ if (+ config.typeAhead &&+ this.#typeAhead.handle(event, {+ editableController:+ config.focusStrategy === "active-descendant" &&+ this.#isEditable(context.controller),+ logicalCount: config.logicalCount,+ mountedCount: () => scope.all().length,+ items: () => scope.items(),+ currentIndex: (items) => this.#currentIndex(items, context),+ activate: context.activate,+ reannounce: () => void context.api.reannounceActive(),+ warnWindowed: context.warnWindowed,+ })+ ) {+ return;+ }+ // Active mode owns Home and End only when the controller has no text caret to move.+ if (+ config.focusStrategy === "active-descendant" &&+ event.key !== "ArrowDown" &&+ event.key !== "ArrowUp" &&+ event.key !== "Enter" &&+ event.key !== "PageUp" &&+ event.key !== "PageDown" &&+ !(+ (event.key === "Home" || event.key === "End") &&+ !this.#isEditable(context.controller)+ )+ ) {+ return;+ }+ if (event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) {+ return;+ }++ const cells = scope.cells();+ if (!cells.length) {+ return;+ }+ const current = this.#currentIndex(cells, context);+ const columns = context.columnCount();+ const last = cells.length - 1;+ const horizontal =+ config.orientation === "horizontal" || config.orientation === "grid";+ const vertical =+ config.focusStrategy === "active-descendant" ||+ config.orientation === "vertical" ||+ config.orientation === "grid";+ const key = this.#logicalKey(event.key, scope.container);++ let outcome: StepOutcome;+ switch (key) {+ case "ArrowRight":+ case "ArrowLeft": {+ if (!horizontal) {+ this.#emitCrossAxis(+ key === "ArrowRight" ? "forward" : "backward",+ cells,+ current,+ event,+ config+ );+ return;+ }+ const delta = key === "ArrowRight" ? 1 : -1;+ outcome = this.#applyStep(+ "horizontal",+ delta,+ cells,+ current,+ columns,+ context+ );+ if (outcome.kind === "group-edge") {+ this.#emitBoundary(delta, "horizontal", current, event, config);+ return;+ }+ break;+ }+ case "ArrowDown":+ case "ArrowUp": {+ if (!vertical) {+ this.#emitCrossAxis(+ key === "ArrowDown" ? "forward" : "backward",+ cells,+ current,+ event,+ config+ );+ return;+ }+ const direction = key === "ArrowDown" ? 1 : -1;+ outcome = this.#applyStep(+ "vertical",+ direction,+ cells,+ current,+ columns,+ context+ );+ if (outcome.kind === "group-edge") {+ this.#emitBoundary(direction, "vertical", current, event, config);+ return;+ }+ break;+ }+ case "Home":+ if (config.logicalCount != null) {+ this.#jump(0, "backward", event, context);+ return;+ }+ outcome = this.#applyOutcome(+ this.#edgeOutcome(cells, 0, 1, last, scope),+ cells,+ context+ );+ break;+ case "End":+ if (config.logicalCount != null) {+ this.#jump(config.logicalCount - 1, "forward", event, context);+ return;+ }+ outcome = this.#applyOutcome(+ this.#edgeOutcome(cells, last, -1, last, scope),+ cells,+ context+ );+ break;+ case "PageUp":+ case "PageDown": {+ if (config.logicalCount == null) {+ return;+ }+ const forward = key === "PageDown";+ // With no cursor, anchor on the mounted window; calculating from -1 would page backward.+ const anchor =+ current >= 0+ ? current+ : scan(+ cells,+ forward ? 0 : last,+ forward ? 1 : -1,+ 0,+ last,+ (cell) => scope.isNavigable(cell)+ );+ const logical = this.#logicalIndex(cells, anchor ?? 0);+ // A placeholder-only window has no navigable items, but a zero-sized page would stall.+ const page = Math.max(1, scope.items().length);+ this.#jump(+ forward+ ? Math.min(logical + page, config.logicalCount - 1)+ : Math.max(logical - page, 0),+ forward ? "forward" : "backward",+ event,+ context+ );+ return;+ }+ case "Enter":+ case " ":+ // These guards are independent: containment can resolve a nested control as the current+ // item, while disabled cells remain in the coordinate space to preserve grid arithmetic.+ if (+ current >= 0 &&+ config.onActivate &&+ scope.isActivatable(cells[current]) &&+ (config.focusStrategy === "active-descendant" ||+ event.target === cells[current])+ ) {+ event.preventDefault();+ config.onActivate(cells[current], event);+ }+ return;+ default:+ return;+ }++ if (outcome.kind === "move" || outcome.kind === "row-edge") {+ event.preventDefault();+ }+ }++ /** Releases type-ahead resources. */+ destroy(): void {+ this.#typeAhead.destroy();+ }++ #currentIndex(items: HTMLElement[], context: KeyboardContext): number {+ const current = context.current(items);+ return current ? items.indexOf(current) : -1;+ }++ /**+ * Runs one step and commits a landing. Travels the row axis whenever there is no cursor yet,+ * because the column walk has no anchor to count from.+ */+ #applyStep(+ axis: DRovingFocusAxis,+ delta: 1 | -1,+ cells: HTMLElement[],+ current: number,+ columns: number,+ context: KeyboardContext+ ): StepOutcome {+ const { config, scope } = context;+ const outcome =+ axis === "horizontal" || current < 0+ ? step(+ current,+ delta,+ cells,+ columns,+ config.orientation,+ config.wrap,+ (cell) => scope.isNavigable(cell)+ )+ : stepRow(current, delta, cells, columns, config.wrap, (cell) =>+ scope.isNavigable(cell)+ );+ return this.#applyOutcome(outcome, cells, context);+ }++ #applyOutcome(+ outcome: StepOutcome,+ cells: HTMLElement[],+ context: KeyboardContext+ ): StepOutcome {+ if (outcome.kind === "move") {+ context.activate(cells[outcome.index]);+ }+ return outcome;+ }++ #edgeOutcome(+ cells: HTMLElement[],+ from: number,+ delta: number,+ last: number,+ scope: ItemScope+ ): StepOutcome {+ const index = scan(cells, from, delta, 0, last, (cell) =>+ scope.isNavigable(cell)+ );+ return index == null ? { kind: "group-edge" } : { kind: "move", index };+ }++ #emitBoundary(+ delta: number,+ axis: DRovingFocusAxis,+ current: number,+ event: KeyboardEvent,+ config: DRovingFocusConfig+ ): void {+ if (current >= 0 && config.onBoundary) {+ event.preventDefault();+ config.onBoundary(delta > 0 ? "forward" : "backward", axis);+ }+ }++ #emitCrossAxis(+ direction: "forward" | "backward",+ cells: HTMLElement[],+ current: number,+ event: KeyboardEvent,+ config: DRovingFocusConfig+ ): void {+ if (+ current >= 0 &&+ config.onCrossAxis?.(direction, cells[current], event)+ ) {+ event.preventDefault();+ }+ }++ /**+ * Moves to an absolute logical index, handing off to the consumer when that row is not mounted.+ * The key is left un-prevented when neither can service it, so it stays a dead key nowhere.+ */+ #jump(+ target: number,+ direction: "forward" | "backward",+ event: KeyboardEvent,+ context: KeyboardContext+ ): void {+ if (context.api.focusLogicalIndex(target)) {+ event.preventDefault();+ } else if (context.config.onJump) {+ event.preventDefault();+ context.config.onJump(target, direction);+ }+ }++ /**+ * The absolute index a mounted row stands for, falling back to its position when the consumer+ * stamps neither attribute, which is what a non-windowed group looks like.+ */+ #logicalIndex(cells: HTMLElement[], current: number): number {+ const element = cells[current];+ const value = element?.dataset.logicalIndex ?? element?.dataset.index;+ if (value === undefined) {+ return current;+ }+ const parsed = Number(value);+ return Number.isFinite(parsed) ? parsed : current;+ }++ /**+ * Mirrors the horizontal arrows under a right-to-left container, so every path downstream reads+ * a key as the direction a reader means by it rather than as a physical side.+ */+ #logicalKey(key: string, container: HTMLElement): string {+ if (getComputedStyle(container).direction !== "rtl") {+ return key;+ }+ if (key === "ArrowLeft") {+ return "ArrowRight";+ }+ return key === "ArrowRight" ? "ArrowLeft" : key;+ }++ /** Whether a target owns a text caret, and so owns the keys that move one. */+ #isEditable(target: EventTarget | null): boolean {+ if (!(target instanceof HTMLElement)) {+ return false;+ }+ const tag = target.tagName;+ if (tag === "TEXTAREA" || tag === "SELECT" || target.isContentEditable) {+ return true;+ }+ return (+ tag === "INPUT" &&+ !NON_ARROW_INPUT_TYPES.has((target as HTMLInputElement).type)+ );+ }++ /**+ * Whether a keydown started inside this group's own item set.+ *+ * Resolved by containment rather than identity: an item may hold its own+ * controls, and a key pressed on one of those still navigates from the item+ * that contains it.+ */+ #ownsTarget(target: EventTarget | null, context: KeyboardContext): boolean {+ if (!(target instanceof Element)) {+ return false;+ }+ const item = target.closest<HTMLElement>(context.scope.selector);+ // `closest` walks past the container, so a matching ancestor outside this+ // group would otherwise read as one of its items.+ return Boolean(item && context.scope.container.contains(item));+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.tsnew file mode 100644index 00000000000..6f15dd47dd5--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/navigation.ts@@ -0,0 +1,165 @@+import type { Orientation } from "./types";++/**+ * The result of one navigation step. A row edge consumes the key without leaving the group;+ * a group edge may be reported for handoff. A wrap that lands on the cursor is a row edge so+ * wrapping suppresses boundary reporting without claiming a move.+ */+export type StepOutcome =+ | { kind: "move"; index: number }+ | { kind: "row-edge" }+ | { kind: "group-edge" };++/**+ * Walks a bounded coordinate space by `delta` for the first navigable item.+ *+ * @param items - The coordinate space to walk.+ * @param from - The inclusive starting index.+ * @param delta - The positive or negative stride.+ * @param min - The lowest index the walk may visit.+ * @param max - The highest index the walk may visit.+ * @param isNavigable - Whether the cursor may land on a candidate.+ * @returns The first matching index, or `null` when the walk runs out.+ */+export function scan<T>(+ items: T[],+ from: number,+ delta: number,+ min: number,+ max: number,+ isNavigable: (item: T) => boolean+): number | null {+ for (let index = from; index >= min && index <= max; index += delta) {+ if (isNavigable(items[index])) {+ return index;+ }+ }+ return null;+}++/**+ * Steps along the row axis without crossing a closed grid row.+ *+ * @param index - The cursor position, or a negative value when there is no cursor.+ * @param delta - `1` for forward or `-1` for backward DOM order.+ * @param cells - The coordinate space to move through.+ * @param columns - The current column count.+ * @param orientation - Whether navigation is row-bounded as a grid.+ * @param wrap - Whether to wrap within the current row.+ * @param isNavigable - Whether the cursor may land on a candidate.+ * @returns The landing index or the edge that blocked the step.+ */+export function step<T>(+ index: number,+ delta: 1 | -1,+ cells: T[],+ columns: number,+ orientation: Orientation,+ wrap: boolean,+ isNavigable: (item: T) => boolean+): StepOutcome {+ const last = cells.length - 1;+ if (index < 0) {+ const seed = scan(cells, delta > 0 ? 0 : last, delta, 0, last, isNavigable);+ return seed == null+ ? { kind: "group-edge" }+ : { kind: "move", index: seed };+ }++ const rowBound = orientation === "grid" && columns > 1;+ const rowStart = rowBound ? index - (index % columns) : 0;+ // Close a ragged last row on its real end rather than on a phantom column.+ const rowEnd = rowBound ? Math.min(rowStart + columns - 1, last) : last;+ const next = scan(cells, index + delta, delta, rowStart, rowEnd, isNavigable);+ if (next != null) {+ return { kind: "move", index: next };+ }+ if (wrap) {+ const wrapped = scan(+ cells,+ delta > 0 ? rowStart : rowEnd,+ delta,+ rowStart,+ rowEnd,+ isNavigable+ );+ if (wrapped != null) {+ // Returning to the cursor is not a move, but wrap must still suppress a boundary report.+ return wrapped === index+ ? { kind: "row-edge" }+ : { kind: "move", index: wrapped };+ }+ }+ const atGroupEdge = delta > 0 ? rowEnd === last : rowStart === 0;+ return { kind: atGroupEdge ? "group-edge" : "row-edge" };+}++/**+ * Steps along the column axis, with a trailing-cell fallback for a ragged final row.+ *+ * @param index - The cursor position; the caller seeds an end before invoking this path.+ * @param direction - `1` for down or `-1` for up.+ * @param cells - The coordinate space to move through.+ * @param columns - The current column count.+ * @param wrap - Whether to wrap within the current column.+ * @param isNavigable - Whether the cursor may land on a candidate.+ * @returns The landing index or the edge that blocked the step.+ */+export function stepRow<T>(+ index: number,+ direction: 1 | -1,+ cells: T[],+ columns: number,+ wrap: boolean,+ isNavigable: (item: T) => boolean+): StepOutcome {+ const last = cells.length - 1;+ const next = scan(+ cells,+ index + direction * columns,+ direction * columns,+ 0,+ last,+ isNavigable+ );+ if (next != null) {+ return { kind: "move", index: next };+ }++ // A missing column in a shorter final row falls back to that row's last navigable cell; a+ // present but non-navigable cell remains a true column edge rather than causing diagonal travel.+ const lastRowStart = last - (last % columns);+ if (+ direction > 0 &&+ Math.floor(index / columns) < Math.floor(last / columns) &&+ index + columns > last+ ) {+ const trailing = scan(cells, last, -1, lastRowStart, last, isNavigable);+ if (trailing != null) {+ return { kind: "move", index: trailing };+ }+ }+ if (wrap) {+ // Wrap to the far end of the same column, not by flat list modulo.+ const column = index % columns;+ const from =+ direction > 0+ ? column+ : column + Math.floor((last - column) / columns) * columns;+ const wrapped = scan(+ cells,+ from,+ direction * columns,+ 0,+ last,+ isNavigable+ );+ if (wrapped != null) {+ // Returning to the cursor suppresses the edge without reporting a move.+ return wrapped === index+ ? { kind: "row-edge" }+ : { kind: "move", index: wrapped };+ }+ }+ return { kind: "group-edge" };+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.tsnew file mode 100644index 00000000000..84b5d059565--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/active-descendant.ts@@ -0,0 +1,255 @@+import { cancel, next as nextRunloop } from "@ember/runloop";+import type { DRovingFocusConfig } from "../config";+import { activeSeed } from "../entry-policy";+import ItemScope from "../item-scope";++/** The state transition requested by active-descendant reconciliation. */+export type ActiveReconcileResult =+ | { kind: "preserved" }+ | { kind: "activate"; target: HTMLElement }+ | { kind: "cleared" };++/** Maintains the active-descendant cursor, indicator, and deferred work. */+export default class ActiveDescendantStrategy {+ #scope: ItemScope;+ #config: DRovingFocusConfig;+ #controller: HTMLElement | null;+ #activeId: string | null = null;+ /** Tracks minted item ids so teardown never removes an author-supplied id. */+ #mintedIds = new Set<string>();+ /**+ * A one-shot observer owed only when an entry seed found no items; it disconnects before+ * reconciling so later row churn cannot repeatedly return the cursor to the start.+ */+ #pendingSeed: MutationObserver | null = null;+ /** Pending restoration of the temporarily dropped `aria-activedescendant`. */+ #reannounceTimer?: ReturnType<typeof nextRunloop>;+ #destroyed = false;++ constructor(+ scope: ItemScope,+ config: DRovingFocusConfig,+ controller: HTMLElement | null,+ readonly mintId: () => string,+ readonly onItemsArrived: () => void+ ) {+ this.#scope = scope;+ this.#config = config;+ this.#controller = controller;+ }++ /** The id of the currently highlighted item. */+ get activeId(): string | null {+ return this.#activeId;+ }++ /** Adopts the latest scope, configuration, and controller. */+ update(+ scope: ItemScope,+ config: DRovingFocusConfig,+ controller: HTMLElement | null+ ): void {+ if (this.#config.activeClass !== config.activeClass) {+ this.#clearClass(this.#config.activeClass, this.#scope);+ }+ if (this.#controller !== controller) {+ this.#cancelReannounce();+ this.#controller?.removeAttribute("aria-activedescendant");+ this.#controller = controller;+ }+ this.#scope = scope;+ this.#config = config;+ }++ /** Resolves the item whose id is currently active. */+ current(items: HTMLElement[]): HTMLElement | null {+ return items.find((item) => item.id === this.#activeId) ?? null;+ }++ /** Activates an item and returns its existing or newly minted id. */+ activate(target: HTMLElement): string {+ this.#clearClass(this.#config.activeClass, this.#scope);+ const id = this.#ensureId(target);+ this.#activeId = id;+ if (this.#config.activeClass) {+ target.classList.add(this.#config.activeClass);+ }+ this.#controller?.setAttribute("aria-activedescendant", id);+ this.#scrollIntoView(target);+ return id;+ }++ /** Clears the virtual cursor, reporting whether one existed. */+ clear(): boolean {+ if (!this.#activeId) {+ return false;+ }+ this.#activeId = null;+ this.#controller?.removeAttribute("aria-activedescendant");+ this.#clearClass(this.#config.activeClass, this.#scope);+ return true;+ }++ /** Temporarily drops and restores the active descendant so it is announced again. */+ reannounce(): boolean {+ const id = this.#activeId;+ const controller = this.#controller;+ if (+ !id ||+ !controller ||+ !this.#scope.items().some((item) => item.id === id)+ ) {+ return false;+ }+ controller.removeAttribute("aria-activedescendant");+ this.#cancelReannounce();+ this.#reannounceTimer = nextRunloop(() => {+ this.#reannounceTimer = undefined;+ if (+ !this.#destroyed &&+ this.#controller === controller &&+ this.#activeId === id &&+ this.#scope.items().some((item) => item.id === id)+ ) {+ controller.setAttribute("aria-activedescendant", id);+ }+ });+ return true;+ }++ /**+ * Watches for the first navigable items only after seeding found none. A present set with no+ * eligible seed is a policy decision, not an absence that later mutations should override.+ */+ armPendingSeed(): void {+ if (this.#pendingSeed || this.#config.entryFocus === "none") {+ return;+ }+ this.#pendingSeed = new MutationObserver(() => {+ if (this.#destroyed || this.#config.entryFocus === "none") {+ this.disarmPendingSeed();+ return;+ }+ if (!this.#scope.items().length) {+ return;+ }+ this.disarmPendingSeed();+ this.onItemsArrived();+ });+ this.#pendingSeed.observe(this.#scope.container, {+ childList: true,+ subtree: true,+ });+ }++ /** Cancels the one-shot pending-seed observer. */+ disarmPendingSeed(): void {+ this.#pendingSeed?.disconnect();+ this.#pendingSeed = null;+ }++ /** Preserves, reseeds, or clears the cursor against the current item set. */+ reconcile(reseed: boolean): ActiveReconcileResult {+ const items = this.#scope.items();+ const current = reseed ? null : this.current(items);+ if (current) {+ if (this.#config.activeClass) {+ this.#clearClass(this.#config.activeClass, this.#scope);+ current.classList.add(this.#config.activeClass);+ }+ this.#controller?.setAttribute("aria-activedescendant", this.#activeId!);+ return { kind: "preserved" };+ }++ const seed = activeSeed(items, this.#config);+ if (seed) {+ this.disarmPendingSeed();+ return { kind: "activate", target: seed };+ }+ if (!items.length) {+ this.armPendingSeed();+ }+ this.#activeId = null;+ this.#controller?.removeAttribute("aria-activedescendant");+ this.#clearClass(this.#config.activeClass, this.#scope);+ return { kind: "cleared" };+ }++ /** Removes active-descendant artifacts and cancels deferred work. */+ destroy(): void {+ this.#destroyed = true;+ this.disarmPendingSeed();+ this.#cancelReannounce();+ this.#controller?.removeAttribute("aria-activedescendant");+ this.#clearClass(this.#config.activeClass, this.#scope);+ for (const item of this.#scope.all()) {+ if (this.#mintedIds.has(item.id)) {+ item.removeAttribute("id");+ }+ }+ this.#mintedIds.clear();+ this.#activeId = null;+ }++ #ensureId(item: HTMLElement): string {+ if (!item.id) {+ const id = this.mintId();+ item.id = id;+ this.#mintedIds.add(id);+ }+ return item.id;+ }++ #clearClass(className: string | null, scope: ItemScope): void {+ if (!className) {+ return;+ }+ for (const item of scope.all()) {+ item.classList.remove(className);+ }+ }++ #cancelReannounce(): void {+ if (this.#reannounceTimer) {+ cancel(this.#reannounceTimer);+ this.#reannounceTimer = undefined;+ }+ }++ /**+ * Scrolls only the nearest list scroller, never the page; scrolling every ancestor can move the+ * document while a detached container is still awaiting its anchored position.+ */+ #scrollIntoView(target: HTMLElement): void {+ const container = this.#scrollableAncestor(target);+ if (!container) {+ return;+ }+ const itemRect = target.getBoundingClientRect();+ const containerRect = container.getBoundingClientRect();+ if (itemRect.top < containerRect.top) {+ container.scrollTop -= containerRect.top - itemRect.top;+ } else if (itemRect.bottom > containerRect.bottom) {+ container.scrollTop += itemRect.bottom - containerRect.bottom;+ }+ }++ /** Finds the nearest vertical scroller without ever returning the document scroller. */+ #scrollableAncestor(element: HTMLElement): HTMLElement | null {+ let node: HTMLElement | null = element.parentElement;+ while (+ node &&+ node !== document.body &&+ node !== document.documentElement+ ) {+ const overflowY = getComputedStyle(node).overflowY;+ // Do not require current overflow: a not-yet-sized intended scroller would be skipped in+ // favor of an unrelated ancestor, while an adjustment on it is harmless.+ if (overflowY === "auto" || overflowY === "scroll") {+ return node;+ }+ node = node.parentElement;+ }+ return null;+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.tsnew file mode 100644index 00000000000..191b693d7a2--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/strategies/roving-tabindex.ts@@ -0,0 +1,186 @@+import type { DRovingFocusConfig } from "../config";+import {+ fallsBackToFirst,+ findMarked,+ isMarked,+ prefersSelected,+} from "../entry-policy";+import ItemScope from "../item-scope";++/** Maintains the single-tab-stop strategy and focus restoration state. */+export default class RovingTabindexStrategy {+ #scope: ItemScope;+ #config: DRovingFocusConfig;+ /**+ * Items already demoted to `tabindex="-1"`. Identity tracking prevents an incoming authored+ * `tabindex="0"` from creating a second tab stop; weak references do not retain removed items.+ */+ #stamped = new WeakSet<HTMLElement>();+ #tabStopHolder: HTMLElement | null = null;+ /**+ * The last focused item and its raw-item index, retained to distinguish removal from focus+ * moving away and to address its positional replacement.+ */+ #lastFocusedItem: HTMLElement | null = null;+ #lastFocusedIndex = -1;+ /**+ * The previous render's items, used only to distinguish one removal from whole-list replacement.+ */+ #previousItems: HTMLElement[] = [];++ constructor(scope: ItemScope, config: DRovingFocusConfig) {+ this.#scope = scope;+ this.#config = config;+ }++ /** Adopts the latest item scope and configuration. */+ update(scope: ItemScope, config: DRovingFocusConfig): void {+ this.#scope = scope;+ this.#config = config;+ }++ /** Resolves the current item from DOM focus, then the established tab stop. */+ current(items: HTMLElement[]): HTMLElement | null {+ const active = document.activeElement;+ for (let index = items.length - 1; index >= 0; index--) {+ if (items[index] === active || items[index].contains(active)) {+ return items[index];+ }+ }+ return items.find((item) => item.getAttribute("tabindex") === "0") ?? null;+ }++ /** Records focus that entered an item and promotes it as the tab stop. */+ recordFocus(target: HTMLElement): void {+ this.#promote(target);+ this.#lastFocusedItem = target;+ this.#lastFocusedIndex = this.#scope.all().indexOf(target);+ }++ /** Promotes an item and moves DOM focus to it. */+ activate(target: HTMLElement): void {+ this.#promote(target);+ target.focus();+ }++ /**+ * Chooses and stamps the tab stop without moving focus. Seeding controls where a future Tab+ * arrives; it must not pull focus into the group during initial render or reconciliation.+ *+ * @param reseed - Whether to disregard the established tab stop and choose afresh.+ */+ seed(reseed: boolean): void {+ const all = this.#scope.all();+ let preferred: HTMLElement | undefined;+ if (this.#config.tabStop) {+ const navigable = (item: HTMLElement) => this.#scope.isNavigable(item);+ const current = reseed ? null : this.current(all);+ preferred =+ (current && navigable(current) ? current : undefined) ??+ (reseed+ ? undefined+ : all.find(+ (item) => item.getAttribute("tabindex") === "0" && navigable(item)+ )) ??+ (prefersSelected(this.#config)+ ? findMarked(all, navigable)+ : undefined) ??+ (fallsBackToFirst(this.#config)+ ? this.#firstSeed(all, navigable)+ : undefined);+ }+ for (const item of all) {+ if (!this.#stamped.has(item)) {+ item.tabIndex = -1;+ this.#stamped.add(item);+ }+ }+ this.#promote(preferred);+ }++ /**+ * Returns a replacement only when restoration is enabled and the remembered focused item was+ * removed. A surviving prior item proves the group was edited rather than replaced; focus must+ * have fallen to the document body so an intentional move is not reclaimed; and a non-empty+ * group is required because only the consumer can choose an external fallback.+ */+ restorationTarget(): HTMLElement | null {+ const remembered = this.#lastFocusedItem;+ if (!remembered || remembered.isConnected) {+ return null;+ }+ // Forgotten before the opt-out check: a removal declined now must not be acted on by a+ // later run that finds restoration re-enabled, nor retain the detached element.+ this.#lastFocusedItem = null;+ if (!this.#config.restoreLostFocus) {+ return null;+ }+ if (!this.#previousItems.some((item) => item.isConnected)) {+ return null;+ }+ const document = this.#scope.container.ownerDocument;+ if (document.activeElement && document.activeElement !== document.body) {+ return null;+ }+ const all = this.#scope.all();+ if (!all.length) {+ return null;+ }+ const start = Math.min(this.#lastFocusedIndex, all.length - 1);+ for (let index = start; index < all.length; index++) {+ if (this.#scope.isNavigable(all[index])) {+ return all[index];+ }+ }+ for (let index = start - 1; index >= 0; index--) {+ if (this.#scope.isNavigable(all[index])) {+ return all[index];+ }+ }+ return null;+ }++ /** Snapshots the rendered items for removal-versus-replacement detection on the next pass. */+ finishRender(): void {+ this.#previousItems = this.#scope.all();+ }++ /** Removes tab-stop artifacts and releases retained state. */+ destroy(): void {+ for (const item of this.#scope.all()) {+ item.removeAttribute("tabindex");+ }+ this.#stamped = new WeakSet();+ this.#tabStopHolder = null;+ this.#lastFocusedItem = null;+ this.#previousItems = [];+ }++ #promote(target: HTMLElement | undefined): void {+ if (this.#tabStopHolder && this.#tabStopHolder !== target) {+ this.#tabStopHolder.tabIndex = -1;+ }+ this.#tabStopHolder = null;+ if (!target) {+ return;+ }+ target.tabIndex = this.#config.tabStop ? 0 : -1;+ this.#stamped.add(target);+ if (this.#config.tabStop) {+ this.#tabStopHolder = target;+ }+ }++ #firstSeed(+ items: HTMLElement[],+ navigable: (item: HTMLElement) => boolean+ ): HTMLElement | undefined {+ if (!this.#config.fallbackSkipsMarked) {+ return items.find(navigable);+ }+ return (+ items.find((item) => !isMarked(item) && navigable(item)) ??+ items.find(navigable)+ );+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/type-ahead.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/type-ahead.tsnew file mode 100644index 00000000000..0de98efa9a5--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/type-ahead.ts@@ -0,0 +1,166 @@+import loadAccessibleName from "discourse/lib/load-accessible-name";++/**+ * Base sensitivity folds case AND diacritics, so `e` reaches a name starting with `É`. Case+ * folding alone would leave a reader unable to type an accented label on an unaccented keyboard.+ */+const COLLATOR = new Intl.Collator(undefined, {+ sensitivity: "base",+ usage: "search",+});++/** How long a buffered query survives without a keystroke before the next one starts afresh. */+const LAPSE_MS = 1000;++/** Operations and state needed to resolve a type-ahead keypress. */+export interface TypeAheadContext {+ editableController: boolean;+ logicalCount: number | undefined;++ /** Returns the number of selector-matched items currently mounted. */+ mountedCount: () => number;+ items: () => HTMLElement[];+ currentIndex: (items: HTMLElement[]) => number;+ activate: (item: HTMLElement) => void;+ reannounce: () => void;+ warnWindowed?: () => void;+}++/** Matches buffered printable input against item accessible names. */+export default class TypeAhead {+ #query = "";+ #queryAt = 0;+ #accessibleName: ((element: Element) => string) | null = null;+ #namerPending = false;+ #destroyed = false;+ #enabled = false;+ #loader: typeof loadAccessibleName;++ /** @param loader - Loads the accessible-name implementation. */+ constructor(loader: typeof loadAccessibleName = loadAccessibleName) {+ this.#loader = loader;+ }++ /** Enables or disables matching and primes the accessible-name implementation. */+ configure(enabled: boolean): void {+ this.#enabled = enabled;+ this.#load();+ }++ /** Handles a claimed character and reports whether keyboard routing should stop. */+ handle(event: KeyboardEvent, context: TypeAheadContext): boolean {+ this.#expire(event.timeStamp);+ if (!this.#claims(event, context)) {+ return false;+ }+ if (!this.#accessibleName) {+ // A group that never reconfigures would otherwise stay dead after a failed load, so the+ // keystroke itself is the retry.+ this.#load();+ return true;+ }+ const items = context.items();+ // A partial window makes prefix search report a nearer mounted match while a truer one is+ // unmounted; compare against all mounted matches, not only the navigable subset.+ if (+ context.logicalCount != null &&+ context.logicalCount > context.mountedCount()+ ) {+ context.warnWindowed?.();+ return true;+ }+ const repeated =+ this.#query !== "" &&+ [...this.#query].every((char) => char === event.key);+ this.#query += event.key;+ this.#queryAt = event.timeStamp;+ if (!items.length) {+ return true;+ }+ const from = context.currentIndex(items);+ const search = repeated ? event.key : this.#query;+ const match = this.#find(items, search, from, search.length > 1 ? 0 : 1);+ if (!match) {+ return true;+ }+ event.preventDefault();+ if (from >= 0 && items[from] === match) {+ context.reannounce();+ } else {+ context.activate(match);+ }+ return true;+ }++ /** Prevents a pending name-loader result from reviving matching after teardown. */+ destroy(): void {+ this.#destroyed = true;+ }++ #load(): void {+ if (!this.#enabled || this.#accessibleName || this.#namerPending) {+ return;+ }+ this.#namerPending = true;+ this.#loader().then(+ (namer) => {+ this.#namerPending = false;+ if (!this.#destroyed && this.#enabled) {+ this.#accessibleName = namer;+ }+ },+ () => {+ this.#namerPending = false;+ }+ );+ }++ #expire(now: number): void {+ if (this.#query && now - this.#queryAt > LAPSE_MS) {+ this.#query = "";+ }+ }++ #claims(event: KeyboardEvent, context: TypeAheadContext): boolean {+ if (event.key.length !== 1) {+ return false;+ }+ // AltGr sets both Ctrl and Alt on ISO layouts, so only Ctrl without Alt is a shortcut.+ if (event.metaKey || (event.ctrlKey && !event.altKey)) {+ return false;+ }+ if (context.editableController) {+ return false;+ }+ // Space activates on an empty query and extends a non-empty one.+ return event.key !== " " || this.#query !== "";+ }++ /**+ * Finds the first prefix match at or after `from + offset`, wrapping once.+ *+ * @param items - The navigable items, in DOM order.+ * @param query - The buffer, or only the repeated character when cycling by initial.+ * @param from - The cursor position, or a negative value when there is no cursor.+ * @param offset - Whether to skip the item at the cursor.+ */+ #find(+ items: HTMLElement[],+ query: string,+ from: number,+ offset: number+ ): HTMLElement | undefined {+ const start = from < 0 ? 0 : (from + offset) % items.length;+ for (let step = 0; step < items.length; step++) {+ const candidate = items[(start + step) % items.length];+ const name = this.#accessibleName?.(candidate) ?? "";+ if (+ name.length >= query.length &&+ COLLATOR.compare(name.slice(0, query.length), query) === 0+ ) {+ return candidate;+ }+ }+ return undefined;+ }+}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.ts b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.tsnew file mode 100644index 00000000000..70b5791c852--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-roving-focus/types.ts@@ -0,0 +1,418 @@+/**+ * Which of the practice page's two focus-management strategies the group uses:+ * a roving tabindex that moves DOM focus, or `aria-activedescendant` on a controller that keeps+ * it. Named for the strategies rather than for selection, which the page is emphatic is a+ * different concept.+ */+export type DRovingFocusStrategy = "roving-tabindex" | "active-descendant";++/**+ * Whether an `aria-disabled` item is a cursor target. Named for the two behaviours rather than+ * spelled as a boolean, because the call site should say which one it wants.+ */+export type DRovingFocusDisabledItems = "skip" | "focusable";+export type Orientation = "grid" | "horizontal" | "vertical";++/**+ * Controls for moving the cursor to a live item in the roving-focus group.+ *+ * The `focus*` members return whether they landed on an item — `false` when the group is+ * currently empty (e.g. a re-render dropped every item), when the index fails the member's own+ * numeric predicate, or, for+ * {@link DRovingFocusApi.focusLogicalIndex}, when the target row is not mounted — so the caller+ * can fall back. The two stepping members are the exception: they report a three-valued+ * {@link DRovingFocusStepResult}, because "already at the end" and "nothing to step through" want+ * different fallbacks. {@link DRovingFocusApi.reannounceActive} moves nothing and carries its own+ * return contract.+ */+export interface DRovingFocusApi {+ /** Moves the cursor to the first navigable item. */+ focusFirst(): boolean;+ /** Moves the cursor to the last navigable item. */+ focusLast(): boolean;+ /**+ * Moves the cursor to a position among the navigable items, clamping an out-of-range index to+ * the first or last one (and still reporting `true`). A non-integer index reports `false`.+ */+ focusIndex(index: number): boolean;+ /**+ * Move the cursor to the item whose `data-logical-index` — or, failing that, `data-index` — is+ * the given ABSOLUTE logical index. This is the addressing a windowed list needs, where the+ * mounted items are a slice of a much larger set and their NodeList position is not their true+ * index. The stamp is compared numerically, so a zero-padded value still matches. Returns+ * `false` when that logical index is not currently mounted (the caller must scroll it into view+ * first). When no item carries either attribute (a non-windowed group) the index is treated as+ * positional — but bounds-checked rather than clamped, so an out-of-range index reports `false`+ * and moves nothing, unlike {@link DRovingFocusApi.focusIndex}.+ */+ focusLogicalIndex(index: number): boolean;+ /**+ * Active mode only — makes assistive tech read the active item again without moving the+ * cursor, by dropping `aria-activedescendant` and restoring it a tick later. Re-asserting+ * the same value is a no-op, so a change is the only thing that can be observed.+ *+ * For when the item itself is unchanged but what it says about its context is not: a row+ * whose `aria-setsize` moved from 2 to 1 under a stationary cursor reports a different+ * position in a different set, and nothing re-reads it. Returns `false` when there is no+ * cursor to re-read.+ */+ reannounceActive(): boolean;+ /**+ * Steps the cursor one item forward, as the corresponding arrow key would. `axis` picks which+ * axis to travel in a grid; omitted, it follows the group's own orientation.+ *+ * Unlike the keyboard path this suppresses the EDGE callback — `onBoundary` announces that a+ * *reader* pushed against a boundary, which a programmatic call has not done.+ * `onActiveChange` still fires on a real move, because the cursor really did move.+ */+ focusNext(axis?: DRovingFocusAxis): DRovingFocusStepResult;+ /** The backward counterpart of {@link DRovingFocusApi.focusNext}, with the same contract. */+ focusPrevious(axis?: DRovingFocusAxis): DRovingFocusStepResult;+ /** The items the cursor may legally land on, in DOM order. */+ items(): HTMLElement[];+ /** The item the cursor currently sits on, or `null` when there is no cursor. */+ currentItem(): HTMLElement | null;+ /**+ * The position of `item` within {@link DRovingFocusApi.items}, or `-1` when it is not a member.+ *+ * Deliberately resolved against that list rather than by re-querying the DOM: raw selector+ * order counts items the cursor can never land on, so an index derived that way addresses a+ * different item than the one it names as soon as a single hidden or disabled match sits+ * earlier in the container.+ */+ indexOf(item: HTMLElement): number;+ /**+ * Moves the cursor onto a specific element, returning `false` (and moving nothing) when it is+ * not one of {@link DRovingFocusApi.items}. Addressing by element rather than by index is what+ * lets a caller hold a reference across a re-render without recomputing positions.+ */+ focusElement(item: HTMLElement): boolean;+ /**+ * Active mode only — drops the cursor entirely, so nothing is highlighted and+ * `aria-activedescendant` points at nothing until the next move seeds a new one.+ *+ * There is deliberately no focus-mode counterpart. There the cursor IS DOM focus, and the+ * cursor is resolved from `document.activeElement` first, so a clear that does not blur would+ * clear nothing — while one that did blur would strand focus on `<body>`, which is worse than+ * the state it set out to fix.+ *+ * @returns Whether there was a cursor to drop.+ */+ clear(): boolean;+}++/**+ * A single navigation axis. `"grid"` is absent by construction: it names a space that allows+ * both axes, not a direction a step can travel.+ */+export type DRovingFocusAxis = Exclude<Orientation, "grid">;++/**+ * Where the cursor goes when no surviving one can be kept. Each value names its own fallback:+ * `"selected-or-first"` prefers a marked item and settles for the first, `"selected-or-none"`+ * prefers a marked item and settles for nothing.+ */+export type DRovingFocusEntry =+ | "none"+ | "first"+ | "selected-or-first"+ | "selected-or-none";++/**+ * The outcome of an API-driven step: `"moved"` when the cursor advanced, `"edge"` when a cursor+ * exists but is already against a boundary, and `"unavailable"` when the group has no items at+ * all. Three-valued so a caller can tell "the run ended here" from "there is no run here" and+ * fall back accordingly.+ */+export type DRovingFocusStepResult = "moved" | "edge" | "unavailable";++export interface DRovingFocusArgs {+ /**+ * Which focus-management strategy the group uses. Default `"roving-tabindex"`.+ *+ * Shape dictated by: Managing Focus in Composites, which names these two strategies.+ */+ focusStrategy?: DRovingFocusStrategy;+ /**+ * Navigation axes; `"grid"` (default) allows both, `"horizontal"`/`"vertical"` one. Ignored+ * under `focusStrategy="active-descendant"`, which is single-axis by construction: it leaves the+ * horizontal arrows to its controller's caret, so the vertical axis is always the live one+ * there whatever this says.+ */+ orientation?: Orientation;+ /** CSS selector matching the navigable items within the container. */+ itemSelector: string;+ /**+ * Called when an item is activated: Enter or Space in `"roving-tabindex"` mode, Enter only in `"active-descendant"`+ * mode, where Space belongs to the controller's caret. Only fires when the key landed on the+ * item itself, so a control nested inside an item keeps its own activation.+ *+ * See {@link DRovingFocusArgs.onActiveChange} for choosing between wiring selection to this and+ * wiring it to the cursor.+ */+ onActivate?: (item: HTMLElement, event: KeyboardEvent) => void;+ /**+ * Called whenever the cursor is placed on an item, or with `null` (and no `meta`) when the+ * highlight is cleared. `meta.pointer` is `true` when a pointer press placed it, which a+ * consumer can use to move the cursor without revealing it. Fires even when the cursor is+ * re-placed on the item it already held.+ *+ * Driven by actual cursor movement, so in `"roving-tabindex"` mode it reports arrow keys, pointer+ * presses and the API — not the tab stop being seeded or re-seeded, which moves no cursor —+ * and the `null` clear is an active-mode signal only.+ *+ * With {@link DRovingFocusArgs.onActivate} this pair is the practice page's+ * selection-follows-focus switch, which is why both exist rather than one. Wire selection here+ * to have it follow the cursor, or to `onActivate` to make the reader commit deliberately. The+ * page's "Deciding When to Make Selection Automatically Follow Focus" is the guidance on which+ * to choose, and a radio group and a listbox land on opposite answers.+ */+ onActiveChange?: (+ item: HTMLElement | null,+ meta?: { pointer: boolean }+ ) => void;+ /**+ * Called when an arrow key would move the cursor past an end of the GROUP, with `wrap` false+ * and a cursor already present; wrapping suppresses it. Deliberately reports the boundary+ * rather than prescribing a response: handing off to a neighbouring control and fetching more+ * rows are both legitimate, and which one applies is the consumer's business.+ *+ * `direction` is LOGICAL — `"forward"` means past the last item in DOM order, whichever arrow+ * key produced it. In a right-to-left group the forward horizontal key is ArrowLeft, so a+ * consumer handing off to a neighbouring control must resolve the physical side itself.+ *+ * `axis` names the axis travelled, and the two are not symmetric. `"horizontal"` requires+ * `"horizontal"` or `"grid"` orientation and never fires under `focusStrategy="active-descendant"`, which+ * leaves the horizontal arrows to its controller's caret. `"vertical"` requires `"vertical"`+ * or `"grid"` in `"roving-tabindex"` mode, but fires in `"active-descendant"` mode whatever `orientation` says,+ * because there the vertical axis is always the live one. A consumer that means "leave the+ * widget" must therefore branch on `axis` rather than treat every boundary alike.+ *+ * Under a multi-column grid a ROW edge is not a group edge, so an interior row never fires+ * this — otherwise a consumer would be dragged away mid-traversal.+ */+ onBoundary?: (+ direction: "forward" | "backward",+ axis: DRovingFocusAxis+ ) => void;+ /**+ * The size of the logical index space addressed by `data-logical-index` or `data-index`,+ * including disabled rows. Setting it is what makes PageUp/PageDown page: without it those keys+ * are left alone entirely so a scrollable container pages natively, Home and End address the+ * mounted items positionally, and {@link DRovingFocusArgs.onJump} is never called.+ */+ logicalCount?: number;+ /**+ * Called when a logical jump target is outside the currently-mounted item window, so the+ * consumer can mount and focus that row. Without it an off-window jump cannot be serviced, so+ * the key is left un-prevented rather than becoming a dead key.+ */+ onJump?: (target: number, direction: "forward" | "backward") => void;+ /**+ * Registers stable controls for moving the cursor, and receives `null` on teardown or when+ * superseded by a different callback. Compared by identity, so pass a stable reference — an+ * inline arrow re-registers on every render, and would take a `null` each time first.+ */+ onRegisterApi?: (api: DRovingFocusApi | null) => void;+ /** Whether navigation wraps at the ends (default `false` = clamp). */+ wrap?: boolean;+ /**+ * Focus mode: whether one item is reachable with Tab (default `true`).+ *+ * Shape dictated by: Navigation Between Components, the single-tab-stop contract.+ */+ tabStop?: boolean;+ /**+ * Focus mode: whether removing the item that holds focus moves the cursor to the item that+ * took its place, rather than letting focus fall to `body` (default `true`).+ *+ * Only fires when focus was genuinely lost, so a reader who moved focus elsewhere before the+ * removal keeps it. When the group empties entirely nothing happens: where focus should go+ * with no items left is the consumer's decision.+ *+ * **Depends on the modifier being told the items changed.** Reconciliation runs from+ * `modify()`, which re-runs only when a named argument does, so a group whose items come from+ * state this cannot observe must pass {@link DRovingFocusArgs.itemsKey}. Without it there is+ * no failure to see: focus simply falls to `body` as though this were off. Defaulting to+ * `true` does not make it independent of that contract.+ *+ * Turn it off to place focus yourself, e.g. onto a control outside the group.+ */+ restoreLostFocus?: boolean;+ /**+ * Class toggled on the active item in `"active-descendant"` mode.+ *+ * Shape dictated by: Discernible and Predictable Focus, where the indicator must stay visible.+ */+ activeClass?: string | null;+ /**+ * A reactive key (e.g. the filter string) that re-reconciles the cursor when it changes. The+ * modifier only re-runs when a named arg does, so a group whose items change from state the+ * modifier cannot see needs this to keep its cursor and tab stop correct.+ */+ itemsKey?: unknown;+ /**+ * A reactive key identifying the *question* the items answer. Reconciling normally keeps the+ * cursor on the active item whenever it survives the change, which is right when rows are+ * appended or revised but wrong when the list becomes a different result set: a row that+ * happens to match both queries would hold the cursor deep in the new list. Change this and+ * the cursor stops tracking the survivor: in `"active-descendant"` mode it re-seeds per+ * {@link DRovingFocusArgs.entryFocus}; in `"roving-tabindex"` mode the tab stop is picked afresh rather+ * than left on a surviving row.+ *+ * Key it on the query the *rendered* items answer, not the one being typed — a list that+ * keeps its old rows visible during an async reload would otherwise re-seed against them.+ */+ resetKey?: unknown;+ /**+ * Active mode: the element that keeps DOM focus, as an `HTMLElement` or a document-wide+ * selector. Its editability changes the key contract — a text input keeps Home/End for its+ * caret, while a non-editable controller (a select-only combobox) hands them to the listbox.+ * `null` is a legitimate transient while the controller has yet to render.+ *+ * A selector is resolved when the arguments change, not continuously, so a controller that is+ * destroyed and re-created under the same selector must be signalled — pass the element itself,+ * or change another argument — or the listener stays on the detached node.+ *+ * Shape dictated by: Managing Focus in Composites Using aria-activedescendant.+ */+ controllerElement?: HTMLElement | string | null;+ /**+ * Where the cursor goes when there is no surviving one to keep. Default+ * `"selected-or-first"`.+ *+ * Each value names its own fallback, because the fallback is the whole distinction:+ *+ * - `"none"` — nothing becomes active.+ * - `"first"` — the first navigable item, whatever is marked.+ * - `"selected-or-first"` — the marked item, else the first.+ * - `"selected-or-none"` — the marked item, else nothing.+ *+ * "Marked" means `aria-selected="true"`, `aria-checked="true"` or an `aria-current` token other+ * than `"false"` or empty. The consumer owns those attributes; this only reads them.+ *+ * The two modes answer different questions with the same values. Under+ * `focusStrategy="roving-tabindex"` this is the entry convention from the keyboard-interface practice:+ * where focus lands when Tab moves into the composite. Toolbars and menubars enter on the+ * first control (`"first"`), while listboxes, radio groups, tabs and trees enter on the+ * selected one. Under `focusStrategy="active-descendant"` it is instead what is active when a popup+ * opens, which the combobox pattern leaves to the author: a list that waits for the reader to+ * type or arrow wants `"none"`, and one that should not pre-highlight an arbitrary row but+ * should still restore a held value wants `"selected-or-none"`.+ *+ * A surviving cursor always outranks this. In focus mode an established tab stop is kept, and+ * in active mode a still-present active item is kept, so this only decides the *first* entry+ * and re-entry after a {@link DRovingFocusArgs.resetKey} change.+ *+ * In focus mode the two no-fallback values leave the group with no tab stop unless the author+ * supplies one, which is a deliberate way to hand that choice back rather than an oversight.+ *+ * Shape dictated by: Navigation Inside Components, and its three entry conventions.+ */+ entryFocus?: DRovingFocusEntry;+ /**+ * Whether {@link DRovingFocusArgs.entryFocus}'s first-item fallback skips items the consumer+ * has marked. Default `false`.+ *+ * The case it exists for is a multi-select whose Enter *toggles*: seeding the fallback onto an+ * already-selected row arms the very first Enter to discard a value the reader never navigated+ * to. Arrow keys still reach those rows, where removing them is deliberate.+ *+ * Constrains the fallback only, never a restored selection: the reader chose that row+ * themselves and can see it is marked, so it is seeded even where activating it would remove+ * it.+ *+ * **Scoped to a popup that seeds itself, and deliberately NOT the listbox convention.** The+ * listbox pattern says the opposite for a multi-select group receiving focus — land on the+ * first selected option, returning the reader to their own selection — and accepts that the+ * next toggle key removes it, because they tabbed in on purpose and can see where the cursor+ * is. This exists for the case that pattern does not cover: a combobox popup where the cursor+ * is placed automatically, focus is still in the input, and Enter reads as "take this" rather+ * than "toggle this", so an auto-seeded cursor on a held row silently drops a value the reader+ * never navigated to. Reach for `entryFocus="selected-or-first"` in a listbox; reach for this+ * in a popup.+ */+ fallbackSkipsMarked?: boolean;+ /**+ * Whether the cursor may rest on an item the consumer has marked `aria-disabled="true"`.+ * Default `"skip"`, which is what a listbox or combobox wants.+ *+ * The practice page's section on the focusability of disabled controls draws a distinction+ * this collapses by default: `disabled` is for state a reader can infer from context, while+ * `aria-disabled` is for state that must stay discoverable, because moving focus to a control+ * is how a screen reader user finds out it exists at all. Toolbars and menus are the patterns+ * that need it.+ *+ * `"focusable"` widens where the cursor may LAND, and nothing else. A disabled item is still+ * never activated, so {@link DRovingFocusArgs.onActivate} does not fire on one under either+ * value. Reachable and operable are separate questions and only the first is opened here.+ *+ * Note the asymmetry with native `disabled`, which no value can override: the platform+ * refuses focus to such a control outright, so targeting one would strand focus on `body`+ * rather than move it. Only the ARIA spelling is affected.+ *+ * Shape dictated by: Focusability of disabled controls.+ */+ disabledItems?: DRovingFocusDisabledItems;+ /**+ * Called for an arrow press on the axis this group does NOT navigate, so the keys a+ * single-axis composite leaves unused become available without every consumer re-deriving+ * them. A `"vertical"` group reports the horizontal arrows and a `"horizontal"` group reports+ * the vertical ones; a `"grid"` navigates both and so never reports either.+ *+ * Deliberately reports a direction rather than prescribing a response, exactly as+ * {@link DRovingFocusArgs.onBoundary} does, because the meaning varies per pattern: expand+ * and collapse for a tree, enter and exit a cell for a treegrid, open and close a submenu for+ * a menubar. Those semantics are the consumer's; only the key handling is shared.+ *+ * `direction` is LOGICAL and already mirrored where the axis mirrors. In a right-to-left+ * group the forward horizontal key is ArrowLeft, which is what a reader expects when the+ * arrow pointing at a row's children is the one that opens them. The vertical axis does not+ * mirror, so a horizontal group reports ArrowDown as `"forward"` whatever the direction.+ *+ * Return `true` when the press was acted on and the modifier will consume it. Return nothing+ * to leave it un-prevented so it can bubble, which is what a leaf node or an+ * already-collapsed row needs. Never fires while the cursor rests nowhere, since there would+ * be no item to report it against.+ */+ onCrossAxis?: (+ direction: "forward" | "backward",+ item: HTMLElement,+ event: KeyboardEvent+ ) => boolean | void;+ /**+ * Whether typing printable characters moves the cursor to the item whose accessible NAME+ * starts with what was typed. Default `false`.+ *+ * The practice page specifies this identically for listbox, tree and menu, which is why it+ * lives here rather than in each of them. Matching is on the accessible name — what assistive+ * technology announces — rather than on text content, so an item labelled by `aria-label` or+ * by a pseudo-element is reachable exactly as it is heard.+ *+ * Comparison folds case and diacritics, so `e` finds `Éclair`. Successive characters extend+ * the query and narrow the match; the query lapses after a short pause, and Space extends it+ * rather than activating while one is under way.+ *+ * Declined when the DOM holds only part of the set — {@link DRovingFocusArgs.logicalCount}+ * exceeding the mounted count — because answering from those rows returns a nearer match+ * while a truer one sits off-window, which is worse than not answering. A consumer that wants+ * it there has to search its own data, which needs a callback this does not yet have.+ *+ * A logical count alone does not decline it: that argument also drives paging, and a+ * fully-mounted list may set it for that alone. Note the completeness test relies on the+ * consumer declaring the count honestly — a group that windows without saying so is searched+ * as though it were whole, and nothing here can detect that. The same honesty applies in+ * reverse: a selector-matched row that is not yet searchable — a placeholder awaiting its+ * content — still counts as mounted, so keep placeholders out of `itemSelector` (or out of+ * the count) while they are empty.+ */+ typeAhead?: boolean;+}++export interface DRovingFocusSignature {+ Element: HTMLElement;+ Args: {+ Named: DRovingFocusArgs;+ Positional: [];+ };+}diff --git a/frontend/discourse/package.json b/frontend/discourse/package.jsonindex 2c0e8fba141..66c175dec5d 100644--- a/frontend/discourse/package.json+++ b/frontend/discourse/package.json@@ -65,6 +65,7 @@"codemirror": "^6.0.2","decorator-transforms": "^2.3.2","diff": "^9.0.0",+ "dom-accessibility-api": "^0.7.1","ember-curry-component": "^0.5.0","ember-resolver": "^13.2.0","ember-route-template": "^1.0.3",diff --git a/frontend/discourse/tests/integration/lib/load-accessible-name-test.gjs b/frontend/discourse/tests/integration/lib/load-accessible-name-test.gjsnew file mode 100644index 00000000000..b09b8a51298--- /dev/null+++ b/frontend/discourse/tests/integration/lib/load-accessible-name-test.gjs@@ -0,0 +1,92 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import loadAccessibleName from "discourse/lib/load-accessible-name";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";++module("Integration | lib | load-accessible-name", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(async function () {+ this.accessibleName = await loadAccessibleName();+ });++ test("prefers aria-label over content, as assistive tech does", async function (assert) {+ await render(+ <template>+ <button class="a" aria-label="Save changes">Save</button>+ </template>+ );++ assert.strictEqual(+ this.accessibleName(document.querySelector(".a")),+ "Save changes",+ "matching on content rather than the name would match text nobody hears"+ );+ });++ test("resolves aria-labelledby across elements", async function (assert) {+ await render(+ <template>+ <span id="an-label">Orange</span>+ <span id="an-hint">Press Backspace to remove</span>+ <button class="a" aria-labelledby="an-label an-hint">x</button>+ </template>+ );++ assert.strictEqual(+ this.accessibleName(document.querySelector(".a")),+ "Orange Press Backspace to remove",+ "a hint folded into the NAME becomes part of what type-ahead matches, which is why it belongs in aria-describedby"+ );+ });++ test("includes text contributed by a pseudo-element", async function (assert) {+ await render(+ <template>+ {{! eslint-disable ember/template-no-forbidden-elements }}+ <style>+ .an-pseudo::before {+ content: "Bold";+ }+ </style>+ <button class="a an-pseudo"></button>+ </template>+ );++ assert.strictEqual(+ this.accessibleName(document.querySelector(".a")),+ "Bold",+ "the library drops this by default, so an item labelled through CSS would be unmatchable"+ );+ });++ test("an inert element has no name to announce", async function (assert) {+ await render(+ <template>+ <div inert>+ <button class="a">Cut</button>+ </div>+ </template>+ );++ assert.strictEqual(+ this.accessibleName(document.querySelector(".a")),+ "",+ "inert removes the subtree from the accessibility tree, and the library does not implement it"+ );+ });++ test("ignores an aria-hidden descendant", async function (assert) {+ await render(+ <template>+ <button class="a">Save<span aria-hidden="true">(icon)</span></button>+ </template>+ );++ assert.strictEqual(+ this.accessibleName(document.querySelector(".a")),+ "Save",+ "decorative content is not announced, so it must not be matchable either"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-api-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-api-test.gjsnew file mode 100644index 00000000000..39ef0fa8a2b--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-api-test.gjs@@ -0,0 +1,930 @@+import { findAll, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++module(+ "Integration | ui-kit | Modifier | dRovingFocus | api",+ function (hooks) {+ setupRenderingTest(hooks);++ test("rovingApi: focusNext seeds the first navigable item when no cursor exists", async function (assert) {+ let api = null;+ const changes = [];+ const boundaries = [];+ const register = (value) => (api = value);+ const onActiveChange = (item) => changes.push(item);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=false+ onRegisterApi=register+ onActiveChange=onActiveChange+ onBoundary=onBoundary+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option" style="display: none;">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const navigableItems = findAll(".item:not([style])");+ assert.strictEqual(+ api.focusNext(),+ "moved",+ "focusNext reports that it seeded a cursor"+ );+ assert+ .dom(navigableItems[0])+ .isFocused("focusNext seeds the first measured navigable item");+ assert.deepEqual(+ changes,+ [navigableItems[0]],+ "seeding through focusNext fires onActiveChange for the landed item"+ );+ assert.deepEqual(+ boundaries,+ [],+ "seeding through focusNext does not fire onBoundary"+ );+ });++ test("rovingApi: focusIndex clamps finite integers to the item range", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert.true(+ api.focusIndex(999),+ "an integer beyond the end still lands on a group item"+ );+ assert+ .dom(".c")+ .isFocused("an index beyond the end clamps to the last item");++ assert.true(+ api.focusIndex(-5),+ "an integer before the start still lands on a group item"+ );+ assert+ .dom(".a")+ .isFocused("an index before the start clamps to the first item");+ });++ test("rovingApi: focusNext moves once then returns edge without firing callbacks", async function (assert) {+ let api = null;+ const changes = [];+ const boundaries = [];+ const register = (value) => (api = value);+ const onActiveChange = (item) => changes.push(item);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onRegisterApi=register+ onActiveChange=onActiveChange+ onBoundary=onBoundary+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const items = findAll(".item");+ assert.true(+ api.focusIndex(0),+ "the existing api seeds the measured first item"+ );+ changes.length = 0;++ assert.strictEqual(+ api.focusNext(),+ "moved",+ "focusNext reports a real forward move"+ );+ assert+ .dom(items[1])+ .isFocused("focusNext advances to the next measured navigable item");+ assert.deepEqual(+ changes,+ [items[1]],+ "a real focusNext move fires onActiveChange exactly once"+ );++ assert.true(+ api.focusLast(),+ "the existing api places the cursor at the measured end"+ );+ changes.length = 0;+ assert.strictEqual(+ api.focusNext(),+ "edge",+ "focusNext distinguishes the end of an existing run from an unavailable group"+ );+ assert+ .dom(items[items.length - 1])+ .isFocused(+ "focusNext leaves the cursor on the measured last item at the edge"+ );+ assert.deepEqual(+ changes,+ [],+ "an edge result does not fire onActiveChange when nothing moved"+ );+ assert.deepEqual(boundaries, [], "an api edge suppresses onBoundary");+ });++ test("rovingApi: focusPrevious moves once then returns edge without firing callbacks", async function (assert) {+ let api = null;+ const changes = [];+ const boundaries = [];+ const register = (value) => (api = value);+ const onActiveChange = (item) => changes.push(item);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onRegisterApi=register+ onActiveChange=onActiveChange+ onBoundary=onBoundary+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const items = findAll(".item");+ assert.true(+ api.focusIndex(items.length - 1),+ "the existing api seeds the measured last item"+ );+ changes.length = 0;++ assert.strictEqual(+ api.focusPrevious(),+ "moved",+ "focusPrevious reports a real backward move"+ );+ assert+ .dom(items[items.length - 2])+ .isFocused(+ "focusPrevious retreats to the previous measured navigable item"+ );+ assert.deepEqual(+ changes,+ [items[items.length - 2]],+ "a real focusPrevious move fires onActiveChange exactly once"+ );++ assert.true(+ api.focusFirst(),+ "the existing api places the cursor at the measured start"+ );+ changes.length = 0;+ assert.strictEqual(+ api.focusPrevious(),+ "edge",+ "focusPrevious distinguishes the start of an existing run from an unavailable group"+ );+ assert+ .dom(items[0])+ .isFocused(+ "focusPrevious leaves the cursor on the measured first item at the edge"+ );+ assert.deepEqual(+ changes,+ [],+ "a backward edge does not fire onActiveChange when nothing moved"+ );+ assert.deepEqual(+ boundaries,+ [],+ "a backward api edge suppresses onBoundary"+ );+ });++ test("rovingApi: focusNext returns unavailable for a group with no items", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ ></div>+ </template>+ );++ assert.strictEqual(+ api.focusNext(),+ "unavailable",+ "focusNext reports that the group has no items to fall back from"+ );+ assert.deepEqual(+ boundaries,+ [],+ "an unavailable focusNext call does not fire onBoundary"+ );+ });++ test("rovingApi: focusPrevious returns unavailable for a group with no items", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ ></div>+ </template>+ );++ assert.strictEqual(+ api.focusPrevious(),+ "unavailable",+ "focusPrevious reports that the group has no items to fall back from"+ );+ assert.deepEqual(+ boundaries,+ [],+ "an unavailable focusPrevious call does not fire onBoundary"+ );+ });++ test("rovingApi: focusNext returns unavailable when every layout cell is non-navigable", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ >+ <button role="option" aria-disabled="true">ARIA disabled</button>+ <button role="option" disabled>Native disabled</button>+ <button+ role="option"+ style="visibility: hidden; width: 40px; height: 20px;"+ >Visibility hidden</button>+ </div>+ </template>+ );++ assert.deepEqual(+ api.items(),+ [],+ "items excludes every non-navigable layout cell"+ );+ assert.strictEqual(+ api.focusNext(),+ "unavailable",+ "focusNext reports that there is no navigable run to step through"+ );+ assert.strictEqual(+ api.currentItem(),+ null,+ "currentItem remains null when no navigable run exists"+ );+ assert.deepEqual(+ boundaries,+ [],+ "an unavailable focusNext call does not fire onBoundary"+ );+ });++ test("rovingApi: focusPrevious returns unavailable when every layout cell is non-navigable", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ >+ <button role="option" aria-disabled="true">ARIA disabled</button>+ <button role="option" disabled>Native disabled</button>+ <button+ role="option"+ style="visibility: hidden; width: 40px; height: 20px;"+ >Visibility hidden</button>+ </div>+ </template>+ );++ assert.deepEqual(+ api.items(),+ [],+ "items excludes every non-navigable layout cell"+ );+ assert.strictEqual(+ api.focusPrevious(),+ "unavailable",+ "focusPrevious reports that there is no navigable run to step through"+ );+ assert.strictEqual(+ api.currentItem(),+ null,+ "currentItem remains null when no navigable run exists"+ );+ assert.deepEqual(+ boundaries,+ [],+ "an unavailable focusPrevious call does not fire onBoundary"+ );+ });++ test("rovingApi: a mixed group retains its navigable run", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ tabStop=false+ onRegisterApi=register+ }}+ >+ <button role="option" aria-disabled="true">ARIA disabled</button>+ <button class="navigable" role="option">Navigable</button>+ <button role="option" disabled>Native disabled</button>+ <button+ role="option"+ style="visibility: hidden; width: 40px; height: 20px;"+ >Visibility hidden</button>+ </div>+ </template>+ );++ const navigable = findAll(".navigable")[0];+ assert.deepEqual(+ api.items(),+ [navigable],+ "items retains the navigable match among non-navigable layout cells"+ );+ assert.strictEqual(+ api.focusNext(),+ "moved",+ "focusNext seeds the mixed group's navigable run"+ );+ assert.strictEqual(+ api.currentItem(),+ navigable,+ "currentItem reports the navigable member of the mixed group"+ );+ assert.strictEqual(+ api.focusNext(),+ "edge",+ "focusNext reports the end of the mixed group's navigable run"+ );+ assert.strictEqual(+ api.focusPrevious(),+ "edge",+ "focusPrevious reports the start of the mixed group's navigable run"+ );+ });++ test("rovingApi: focusNext honors horizontal and vertical axes in a grid", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(2, 40px);"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ >+ <button+ class="cell"+ role="option"+ data-row="start"+ data-column="start"+ >A</button>+ <button+ class="cell"+ role="option"+ data-row="start"+ data-column="end"+ >B</button>+ <button+ class="cell"+ role="option"+ data-row="end"+ data-column="start"+ >C</button>+ <button+ class="cell"+ role="option"+ data-row="end"+ data-column="end"+ >D</button>+ </div>+ </template>+ );++ const cells = findAll(".cell");+ const start = cells.find(+ (item) =>+ item.dataset.row === "start" && item.dataset.column === "start"+ );+ const horizontalTarget = cells.find(+ (item) => item.dataset.row === "start" && item.dataset.column === "end"+ );+ const verticalTarget = cells.find(+ (item) => item.dataset.row === "end" && item.dataset.column === "start"+ );++ assert.true(+ api.focusIndex(cells.indexOf(start)),+ "the existing api seeds the measured grid origin"+ );+ assert.strictEqual(+ api.focusNext("horizontal"),+ "moved",+ "horizontal focusNext reports a move within the measured row"+ );+ assert+ .dom(horizontalTarget)+ .isFocused(+ "horizontal focusNext lands on the next cell in the same row"+ );+ assert.strictEqual(+ api.focusNext("horizontal"),+ "edge",+ "horizontal focusNext reports the row edge instead of drifting into the next row"+ );+ assert+ .dom(horizontalTarget)+ .isFocused(+ "the horizontal row edge leaves the cursor in its measured row"+ );++ assert.true(+ api.focusIndex(cells.indexOf(start)),+ "the existing api restores the measured grid origin"+ );+ assert.strictEqual(+ api.focusNext("vertical"),+ "moved",+ "vertical focusNext reports a move to the next measured row"+ );+ assert+ .dom(verticalTarget)+ .isFocused(+ "vertical focusNext lands in the same column of the next row"+ );+ assert.strictEqual(+ api.focusNext("vertical"),+ "edge",+ "vertical focusNext reports the measured bottom edge"+ );+ assert.deepEqual(+ boundaries,+ [],+ "grid focusNext api calls suppress onBoundary"+ );+ });++ test("rovingApi: focusPrevious honors horizontal and vertical axes in a grid", async function (assert) {+ let api = null;+ const boundaries = [];+ const register = (value) => (api = value);+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(2, 40px);"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=register+ onBoundary=onBoundary+ }}+ >+ <button+ class="cell"+ role="option"+ data-row="start"+ data-column="start"+ >A</button>+ <button+ class="cell"+ role="option"+ data-row="start"+ data-column="end"+ >B</button>+ <button+ class="cell"+ role="option"+ data-row="end"+ data-column="start"+ >C</button>+ <button+ class="cell"+ role="option"+ data-row="end"+ data-column="end"+ >D</button>+ </div>+ </template>+ );++ const cells = findAll(".cell");+ const start = cells.find(+ (item) => item.dataset.row === "end" && item.dataset.column === "end"+ );+ const horizontalTarget = cells.find(+ (item) => item.dataset.row === "end" && item.dataset.column === "start"+ );+ const verticalTarget = cells.find(+ (item) => item.dataset.row === "start" && item.dataset.column === "end"+ );++ assert.true(+ api.focusIndex(cells.indexOf(start)),+ "the existing api seeds the measured grid end"+ );+ assert.strictEqual(+ api.focusPrevious("horizontal"),+ "moved",+ "horizontal focusPrevious reports a move within the measured row"+ );+ assert+ .dom(horizontalTarget)+ .isFocused(+ "horizontal focusPrevious lands on the prior cell in the same row"+ );+ assert.strictEqual(+ api.focusPrevious("horizontal"),+ "edge",+ "horizontal focusPrevious reports the row edge instead of drifting into the prior row"+ );+ assert+ .dom(horizontalTarget)+ .isFocused(+ "the backward horizontal edge leaves the cursor in its measured row"+ );++ assert.true(+ api.focusIndex(cells.indexOf(start)),+ "the existing api restores the measured grid end"+ );+ assert.strictEqual(+ api.focusPrevious("vertical"),+ "moved",+ "vertical focusPrevious reports a move to the prior measured row"+ );+ assert+ .dom(verticalTarget)+ .isFocused(+ "vertical focusPrevious lands in the same column of the prior row"+ );+ assert.strictEqual(+ api.focusPrevious("vertical"),+ "edge",+ "vertical focusPrevious reports the measured top edge"+ );+ assert.deepEqual(+ boundaries,+ [],+ "grid focusPrevious api calls suppress onBoundary"+ );+ });++ test("rovingApi: currentItem is null before a cursor exists", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <input class="controller" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".controller"+ itemSelector="[role=option]"+ onRegisterApi=register+ }}+ >+ <button role="option">A</button>+ <button role="option">B</button>+ </div>+ </template>+ );++ assert.strictEqual(+ api.currentItem(),+ null,+ "currentItem reports null before the modifier has placed a cursor"+ );+ });++ test("rovingApi: focusElement rejects an element outside the group without moving", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <button class="outside" type="button">Outside</button>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ </div>+ </template>+ );++ const groupItems = findAll(".item");+ const cursor = groupItems[groupItems.length - 1];+ const outside = findAll(".outside")[0];+ assert.true(+ api.focusIndex(groupItems.indexOf(cursor)),+ "the existing api places the cursor on a measured group member"+ );+ assert.false(+ api.focusElement(outside),+ "focusElement rejects an element outside the group"+ );+ assert+ .dom(cursor)+ .isFocused("a rejected outside element leaves DOM focus unchanged");+ assert.strictEqual(+ api.currentItem(),+ cursor,+ "a rejected outside element leaves the api cursor unchanged"+ );+ });++ test("rovingApi: element addressing round-trips every item in DOM order", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button class="item" role="option" data-label="alpha">A</button>+ <button class="item" role="option" data-label="beta">B</button>+ <button class="item" role="option" data-label="gamma">C</button>+ </div>+ </template>+ );++ const matchedItems = findAll(".item");+ const apiItems = api.items();+ assert.deepEqual(+ apiItems,+ matchedItems,+ "items returns the measured group items in DOM order when all are navigable"+ );++ apiItems.forEach((item, index) => {+ assert.strictEqual(+ api.indexOf(item),+ index,+ `indexOf maps the ${item.dataset.label} item back to its items position`+ );+ assert.true(+ api.focusElement(item),+ `focusElement accepts the ${item.dataset.label} item returned by items`+ );+ assert.strictEqual(+ api.currentItem(),+ item,+ `currentItem returns the exact ${item.dataset.label} element focused by address`+ );+ assert.strictEqual(+ api.indexOf(api.currentItem()),+ index,+ `the current ${item.dataset.label} element round-trips to the same index`+ );+ });++ const outside = document.createElement("button");+ assert.strictEqual(+ api.indexOf(outside),+ -1,+ "indexOf returns -1 for an element that is not a group member"+ );+ });++ test("rovingApi: element addressing does not drift across interleaved non-navigable matches", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button+ class="item navigable"+ role="option"+ data-label="alpha"+ >A</button>+ <button+ class="item hidden"+ role="option"+ style="display: none;"+ data-label="hidden-one"+ >Hidden one</button>+ <button+ class="item navigable"+ role="option"+ data-label="beta"+ >B</button>+ <button+ class="item hidden"+ role="option"+ style="visibility: hidden; width: 0; height: 0; padding: 0; border: 0;"+ data-label="hidden-zero-size"+ >Hidden zero size</button>+ <button+ class="item navigable"+ role="option"+ data-label="gamma"+ >C</button>+ <button+ class="item hidden"+ role="option"+ style="display: none;"+ data-label="hidden-two"+ >Hidden two</button>+ <button+ class="item navigable"+ role="option"+ data-label="delta"+ >D</button>+ </div>+ </template>+ );++ const rawMatches = findAll(".item");+ const hiddenMatches = findAll(".hidden");+ assert.true(+ hiddenMatches.length > 1,+ "the drift fixture measures several non-navigable matches"+ );+ assert.true(+ hiddenMatches.length < rawMatches.length,+ "the drift fixture also measures navigable matches around the hidden ones"+ );++ const apiItems = api.items();+ assert.true(+ apiItems.length > 0,+ "the drift fixture exposes a non-empty api item list"+ );+ apiItems.forEach((item, index) => {+ assert.strictEqual(+ api.indexOf(item),+ index,+ `indexOf preserves the api position of ${item.dataset.label} across hidden matches`+ );+ assert.true(+ api.focusElement(item),+ `focusElement accepts ${item.dataset.label} from the api item list`+ );+ assert.strictEqual(+ api.currentItem(),+ item,+ `focusElement lands on the exact ${item.dataset.label} element without DOM-query drift`+ );+ assert.strictEqual(+ api.indexOf(api.currentItem()),+ index,+ `the focused ${item.dataset.label} element maps back to its original api index`+ );+ });+ });++ // DECISION, not an invariant: this API exposes the cursor's legal landing places rather than+ // every raw selector match. The round-trip tests above remain the governing law if this+ // product choice is renegotiated.+ test("rovingApi: items exposes navigable matches only (decision)", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button class="item navigable" role="option">A</button>+ <button+ class="item"+ role="option"+ style="display: none;"+ >Hidden</button>+ <button class="item navigable" role="option">B</button>+ <button+ class="item"+ role="option"+ aria-disabled="true"+ >Disabled</button>+ <button class="item navigable" role="option">C</button>+ </div>+ </template>+ );++ const navigableMatches = findAll(".navigable");+ assert.deepEqual(+ api.items(),+ navigableMatches,+ "DECISION: items exposes exactly the measured navigable matches in DOM order"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjsnew file mode 100644index 00000000000..8e7af13b2ad--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-control-test.gjs@@ -0,0 +1,321 @@+import { findAll, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++module(+ "Integration | ui-kit | Modifier | dRovingFocus | roving control",+ function (hooks) {+ setupRenderingTest(hooks);++ test("rovingControl clear removes every active-mode cursor effect and is idempotent", async function (assert) {+ let api;+ const changes = [];+ const register = (value) => (api = value);+ const onActiveChange = (item) => changes.push(item);++ await render(+ <template>+ <div+ class="controller"+ role="combobox"+ aria-controls="rf-lb"+ tabindex="0"+ ></div>+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ onActiveChange=onActiveChange+ onRegisterApi=register+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const items = api.items();+ const target = items[Math.floor(items.length / 2)];+ assert.true(+ api.focusIndex(api.indexOf(target)),+ "the existing API places a cursor to clear"+ );+ changes.length = 0;++ assert.true(api.clear(), "clear reports that it removed a cursor");+ assert.strictEqual(api.currentItem(), null, "the API cursor is gone");+ assert+ .dom(".controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "the controller no longer advertises a cursor"+ );+ assert+ .dom(target)+ .doesNotHaveClass("--active", "the cleared item loses activeClass");+ assert.deepEqual(+ changes,+ [null],+ "onActiveChange receives exactly the active-mode clear signal"+ );++ assert.false(api.clear(), "a second clear reports there was no cursor");+ assert.deepEqual(+ changes,+ [null],+ "an empty clear emits no duplicate change signal"+ );+ });++ test("rovingControl focusNext seeds from the start after clear", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ class="controller"+ role="combobox"+ aria-controls="rf-lb"+ tabindex="0"+ ></div>+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ onRegisterApi=register+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const items = api.items();+ const first = items[0];+ const last = items[items.length - 1];+ assert.true(+ api.focusElement(last),+ "the cursor starts at the measured end"+ );+ assert.true(api.clear(), "the end cursor is cleared");+ assert.strictEqual(+ api.focusNext(),+ "moved",+ "focusNext treats the cleared state as seedless"+ );+ assert.strictEqual(+ api.currentItem(),+ first,+ "focusNext seeds the measured first item rather than advancing from the old cursor"+ );+ assert+ .dom(".controller")+ .hasAttribute(+ "aria-activedescendant",+ first.id,+ "the controller points at the newly seeded first item"+ );+ });++ test("rovingControl clear is a focus-mode no-op that preserves DOM focus", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=register+ }}+ >+ <button class="item" role="option">A</button>+ <button class="item" role="option">B</button>+ <button class="item" role="option">C</button>+ </div>+ </template>+ );++ const items = api.items();+ const target = items[items.length - 1];+ assert.true(+ api.focusElement(target),+ "the existing API places DOM focus before clear"+ );++ // In focus mode the cursor is DOM focus. Clearing without blur would not clear it, while+ // blurring would strand keyboard users on body, so this mode deliberately does nothing.+ assert.false(api.clear(), "focus mode reports that it cleared nothing");+ assert.dom(target).isFocused("DOM focus remains on the measured item");+ assert.strictEqual(+ api.currentItem(),+ target,+ "the focus-mode cursor remains the focused item"+ );+ assert+ .dom(target)+ .hasAttribute("tabindex", "0", "the focused item remains the tab stop");+ });++ test("rovingControl tabStop=false reports truthful API movement for non-focusable items", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ tabStop=false+ onRegisterApi=register+ }}+ >+ <div class="truthful-item" role="option">A</div>+ <div class="truthful-item" role="option">B</div>+ <div class="truthful-item" role="option">C</div>+ </div>+ </template>+ );++ const items = findAll(".truthful-item");+ for (const item of items) {+ item.removeAttribute("tabindex");+ }++ let previous = api.currentItem();+ for (const [index, item] of items.entries()) {+ assert.strictEqual(+ api.focusNext(),+ "moved",+ `step ${index + 1} reports a move`+ );+ const current = api.currentItem();+ assert.notStrictEqual(+ current,+ previous,+ `step ${index + 1} changes the cursor it reports`+ );+ assert.strictEqual(+ current,+ item,+ `step ${index + 1} advances to the measured item`+ );+ assert.dom(item).isFocused(`step ${index + 1} moves DOM focus`);+ previous = current;+ }++ const edgeCursor = api.currentItem();+ assert.strictEqual(+ api.focusNext(),+ "edge",+ "a step past the final item truthfully reports the edge"+ );+ assert.strictEqual(+ api.currentItem(),+ edgeCursor,+ "an edge result leaves the cursor unchanged"+ );+ assert+ .dom(".truthful-item[tabindex='0']")+ .doesNotExist("tabStop=false leaves every item outside the Tab order");+ });++ test("rovingControl tabStop=true focuses non-focusable items as the tab stop", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ tabStop=true+ onRegisterApi=register+ }}+ >+ <div class="tab-stop-item" role="option">A</div>+ <div class="tab-stop-item" role="option">B</div>+ </div>+ </template>+ );++ const items = findAll(".tab-stop-item");+ assert.true(api.focusFirst(), "focusFirst lands on the first item");+ assert.strictEqual(api.focusNext(), "moved", "focusNext moves once");+ assert.strictEqual(+ api.currentItem(),+ items[1],+ "the cursor reaches the second non-focusable item"+ );+ assert.dom(items[1]).isFocused("DOM focus follows the cursor");+ assert+ .dom(items[1])+ .hasAttribute(+ "tabindex",+ "0",+ "the focused non-focusable item is the Tab stop"+ );+ assert+ .dom(".tab-stop-item[tabindex='0']")+ .exists({ count: 1 }, "the group retains exactly one Tab stop");+ });++ test("rovingControl registers a frozen shared API object", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button role="option">A</button>+ </div>+ </template>+ );++ const originalFocusNext = api.focusNext;+ assert.true(Object.isFrozen(api), "the shared API object is frozen");+ assert.throws(+ () => (api.focusNext = () => "moved"),+ TypeError,+ "strict-mode assignment cannot replace a shared API method"+ );+ if (api.focusNext !== originalFocusNext) {+ api.focusNext = originalFocusNext;+ }++ assert.throws(+ () => (api.injected = true),+ TypeError,+ "strict-mode assignment cannot extend the shared API object"+ );+ if ("injected" in api) {+ delete api.injected;+ }+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-cost-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-cost-test.gjsnew file mode 100644index 00000000000..4b1eed58a48--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-cost-test.gjs@@ -0,0 +1,674 @@+import { tracked } from "@glimmer/tracking";+import {+ findAll,+ focus,+ render,+ settled,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++const SMALL_GROUP_SIZE = 128;+const LARGE_GROUP_SIZE = SMALL_GROUP_SIZE * 4;+const SMALL_GROUP_ITEMS = Array.from(+ { length: SMALL_GROUP_SIZE },+ (_, index) => index+);+const LARGE_GROUP_ITEMS = Array.from(+ { length: LARGE_GROUP_SIZE },+ (_, index) => index+);++const NON_BLOCKING_INPUT_TYPES = [+ "checkbox",+ "button",+ "submit",+ "reset",+ "image",+ "file",+];++const BLOCKING_INPUT_TYPES = [+ "text",+ "search",+ "tel",+ "url",+ "email",+ "password",+ "number",+ "radio",+ "range",+ "date",+ "month",+ "week",+ "time",+ "datetime-local",+ "color",+];++function isMeasuredItem(element) {+ return element instanceof HTMLElement && element.matches(".measured-item");+}++async function measureForcedReads(callback) {+ const offsetParentDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ "offsetParent"+ );+ const clientRectsDescriptor = Object.getOwnPropertyDescriptor(+ Element.prototype,+ "getClientRects"+ );+ const computedStyleDescriptor = Object.getOwnPropertyDescriptor(+ window,+ "getComputedStyle"+ );++ if (+ !offsetParentDescriptor?.get ||+ !clientRectsDescriptor?.value ||+ !computedStyleDescriptor?.value+ ) {+ throw new Error("The browser layout/style APIs cannot be instrumented");+ }++ const reads = {+ offsetParent: 0,+ clientRects: 0,+ computedStyle: 0,+ };++ let offsetParentInstalled = false;+ let clientRectsInstalled = false;+ let computedStyleInstalled = false;+ try {+ Object.defineProperty(HTMLElement.prototype, "offsetParent", {+ ...offsetParentDescriptor,+ get() {+ if (isMeasuredItem(this)) {+ reads.offsetParent++;+ }+ return offsetParentDescriptor.get.call(this);+ },+ });+ offsetParentInstalled = true;+ Object.defineProperty(Element.prototype, "getClientRects", {+ ...clientRectsDescriptor,+ value(...args) {+ if (isMeasuredItem(this)) {+ reads.clientRects++;+ }+ return clientRectsDescriptor.value.apply(this, args);+ },+ });+ clientRectsInstalled = true;+ Object.defineProperty(window, "getComputedStyle", {+ ...computedStyleDescriptor,+ value(element, ...args) {+ if (isMeasuredItem(element)) {+ reads.computedStyle++;+ }+ return computedStyleDescriptor.value.call(this, element, ...args);+ },+ });+ computedStyleInstalled = true;++ await callback();+ } finally {+ try {+ if (computedStyleInstalled) {+ Object.defineProperty(+ window,+ "getComputedStyle",+ computedStyleDescriptor+ );+ }+ } finally {+ try {+ if (clientRectsInstalled) {+ Object.defineProperty(+ Element.prototype,+ "getClientRects",+ clientRectsDescriptor+ );+ }+ } finally {+ if (offsetParentInstalled) {+ Object.defineProperty(+ HTMLElement.prototype,+ "offsetParent",+ offsetParentDescriptor+ );+ }+ }+ }+ }++ return {+ ...reads,+ total: reads.offsetParent + reads.clientRects + reads.computedStyle,+ };+}++async function measureTabIndexWrites(callback) {+ const tabIndexDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ "tabIndex"+ );+ const setAttributeDescriptor = Object.getOwnPropertyDescriptor(+ Element.prototype,+ "setAttribute"+ );++ if (!tabIndexDescriptor?.set || !setAttributeDescriptor?.value) {+ throw new Error("The browser tabindex write APIs cannot be instrumented");+ }++ const writes = {+ property: 0,+ attribute: 0,+ };++ let tabIndexInstalled = false;+ let setAttributeInstalled = false;+ try {+ Object.defineProperty(HTMLElement.prototype, "tabIndex", {+ ...tabIndexDescriptor,+ set(value) {+ if (isMeasuredItem(this)) {+ writes.property++;+ }+ tabIndexDescriptor.set.call(this, value);+ },+ });+ tabIndexInstalled = true;+ Object.defineProperty(Element.prototype, "setAttribute", {+ ...setAttributeDescriptor,+ value(name, ...args) {+ if (isMeasuredItem(this) && String(name).toLowerCase() === "tabindex") {+ writes.attribute++;+ }+ return setAttributeDescriptor.value.call(this, name, ...args);+ },+ });+ setAttributeInstalled = true;++ await callback();+ } finally {+ try {+ if (setAttributeInstalled) {+ Object.defineProperty(+ Element.prototype,+ "setAttribute",+ setAttributeDescriptor+ );+ }+ } finally {+ if (tabIndexInstalled) {+ Object.defineProperty(+ HTMLElement.prototype,+ "tabIndex",+ tabIndexDescriptor+ );+ }+ }+ }++ return {+ ...writes,+ total: writes.property + writes.attribute,+ };+}++function authorItems(generation) {+ return [0, 1, 2, 3].map((index) => ({+ id: `${generation}-${index}`,+ label: `${generation}:${index}`,+ tabindex: index === 2 ? "-1" : "0",+ }));+}++module(+ "Integration | ui-kit | Modifier | dRovingFocus | cost oracle",+ function (hooks) {+ setupRenderingTest(hooks);++ test("rovingCost M5 tabStop=false performs no per-item forced reads on modify", async function (assert) {+ const state = new (class {+ @tracked key = 0;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ tabStop=false+ itemsKey=state.key+ }}+ >+ {{#each SMALL_GROUP_ITEMS as |index|}}+ <button class="measured-item" role="option">{{index}}</button>+ {{/each}}+ </div>+ </template>+ );++ const reads = await measureForcedReads(async () => {+ state.key++;+ await settled();+ });++ assert.strictEqual(+ reads.total,+ 0,+ `tabStop=false does not inspect item navigability during modify (${JSON.stringify(+ reads+ )})`+ );+ });++ test("rovingCost M5 modify preserves at most one tab stop with author-supplied zeros", async function (assert) {+ const state = new (class {+ @tracked items = authorItems("initial");+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.items}}+ >+ {{#each state.items key="id" as |item|}}+ <button+ class="author-item"+ role="option"+ data-id={{item.id}}+ tabindex={{item.tabindex}}+ >{{item.label}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert.strictEqual(+ findAll('.author-item[tabindex="0"]').length,+ 1,+ "initial modify collapses three author-supplied zeros to one tab stop"+ );++ state.items = authorItems("rerendered");+ await settled();++ assert.strictEqual(+ findAll('.author-item[tabindex="0"]').length,+ 1,+ "re-rendered author-supplied zeros are also collapsed to one tab stop"+ );+ });++ test("rovingCost M5 tab-stop seeding keeps established selected current first preference order", async function (assert) {+ await render(+ <template>+ <div+ data-group="established"+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button role="option">First</button>+ <button role="option" aria-current="page">Current</button>+ <button role="option" aria-selected="true">Selected</button>+ <button class="established" role="option" tabindex="0">+ Established+ </button>+ </div>+ <div+ data-group="selected"+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button role="option">First</button>+ <button role="option" aria-current="page">Current</button>+ <button class="selected" role="option" aria-selected="true">+ Selected+ </button>+ </div>+ <div+ data-group="current"+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button role="option">First</button>+ <button class="current" role="option" aria-current="page">+ Current+ </button>+ </div>+ <div+ data-group="first"+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="first" role="option">First</button>+ <button role="option">Second</button>+ </div>+ </template>+ );++ assert+ .dom('[data-group="established"] .established')+ .hasAttribute("tabindex", "0", "an established tab stop wins");+ assert+ .dom('[data-group="selected"] .selected')+ .hasAttribute(+ "tabindex",+ "0",+ "aria-selected wins when no tab stop is established"+ );+ assert+ .dom('[data-group="current"] .current')+ .hasAttribute(+ "tabindex",+ "0",+ "aria-current wins when no established or selected item exists"+ );+ assert+ .dom('[data-group="first"] .first')+ .hasAttribute("tabindex", "0", "the first item is the final fallback");+ });++ test("rovingCost M6 one API step has mounted-count-independent forced-read cost", async function (assert) {+ let smallApi;+ let largeApi;+ const registerSmall = (api) => (smallApi = api);+ const registerLarge = (api) => (largeApi = api);++ await render(+ <template>+ <div+ data-group="small"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=registerSmall+ }}+ >+ {{#each SMALL_GROUP_ITEMS as |index|}}+ <button class="measured-item" role="option">{{index}}</button>+ {{/each}}+ </div>+ <div+ data-group="large"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=registerLarge+ }}+ >+ {{#each LARGE_GROUP_ITEMS as |index|}}+ <button class="measured-item" role="option">{{index}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert.true(smallApi.focusIndex(1), "the small-group cursor is seeded");+ const smallReads = await measureForcedReads(() => {+ assert.strictEqual(+ smallApi.focusNext(),+ "moved",+ "one small-group step moves one item"+ );+ });+ assert+ .dom('[data-group="small"] [role="option"]:nth-child(3)')+ .isFocused("the small-group step lands on the adjacent item");++ assert.true(largeApi.focusIndex(1), "the large-group cursor is seeded");+ const largeReads = await measureForcedReads(() => {+ assert.strictEqual(+ largeApi.focusNext(),+ "moved",+ "one large-group step moves the same one-item distance"+ );+ });+ assert+ .dom('[data-group="large"] [role="option"]:nth-child(3)')+ .isFocused("the large-group step lands on the adjacent item");++ assert.true(+ smallReads.total > 0,+ "the small measurement observes a forced read, guarding the comparison oracle itself"+ );+ assert.strictEqual(+ largeReads.total,+ smallReads.total,+ `quadrupling mounted items from ${SMALL_GROUP_SIZE} to ${LARGE_GROUP_SIZE} does not increase forced reads (small=${JSON.stringify(+ smallReads+ )}, large=${JSON.stringify(largeReads)})`+ );+ });++ test("rovingCost M5 one API step has mounted-count-independent tabindex-write cost", async function (assert) {+ let smallApi;+ let largeApi;+ const registerSmall = (api) => (smallApi = api);+ const registerLarge = (api) => (largeApi = api);++ await render(+ <template>+ <div+ data-group="small-writes"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=registerSmall+ }}+ >+ {{#each SMALL_GROUP_ITEMS as |index|}}+ <button class="measured-item" role="option">{{index}}</button>+ {{/each}}+ </div>+ <div+ data-group="large-writes"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=registerLarge+ }}+ >+ {{#each LARGE_GROUP_ITEMS as |index|}}+ <button class="measured-item" role="option">{{index}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert.true(smallApi.focusIndex(1), "the small-group cursor is seeded");+ const smallWrites = await measureTabIndexWrites(() => {+ assert.strictEqual(+ smallApi.focusNext(),+ "moved",+ "one small-group step moves one item"+ );+ });+ assert+ .dom('[data-group="small-writes"] [role="option"]:nth-child(3)')+ .isFocused("the small-group step lands on the adjacent item");++ assert.true(largeApi.focusIndex(1), "the large-group cursor is seeded");+ const largeWrites = await measureTabIndexWrites(() => {+ assert.strictEqual(+ largeApi.focusNext(),+ "moved",+ "one large-group step moves the same one-item distance"+ );+ });+ assert+ .dom('[data-group="large-writes"] [role="option"]:nth-child(3)')+ .isFocused("the large-group step lands on the adjacent item");++ assert.true(+ smallWrites.total > 0,+ "the small measurement observes a tabindex write, guarding the comparison oracle itself"+ );+ assert.strictEqual(+ largeWrites.total,+ smallWrites.total,+ `quadrupling mounted items from ${SMALL_GROUP_SIZE} to ${LARGE_GROUP_SIZE} does not increase tabindex writes (small=${JSON.stringify(+ smallWrites+ )}, large=${JSON.stringify(largeWrites)})`+ );+ });++ test("rovingCost M5 replacement and repeated steps preserve one tab stop", async function (assert) {+ let api;+ const registerApi = (registeredApi) => (api = registeredApi);+ const state = new (class {+ @tracked items = authorItems("initial-sequence");+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ itemsKey=state.items+ onRegisterApi=registerApi+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button+ class="replacement-item"+ role="option"+ data-id={{item.id}}+ tabindex={{item.tabindex}}+ >{{item.label}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert.true(api.focusIndex(2), "the old item set establishes a holder");++ state.items = authorItems("replacement-sequence");+ await settled();++ assert.strictEqual(+ findAll('.replacement-item[tabindex="0"]').length,+ 1,+ "fresh author-supplied zeros are collapsed after replacement"+ );++ for (const index of [1, 2, 3]) {+ assert.strictEqual(+ api.focusNext(),+ "moved",+ `step ${index} moves within the replacement set`+ );+ assert+ .dom(`[data-id="replacement-sequence-${index}"]`)+ .isFocused(`step ${index} focuses the expected replacement item`);+ assert.strictEqual(+ findAll('.replacement-item[tabindex="0"]').length,+ 1,+ `step ${index} leaves exactly one tab stop`+ );+ }+ });++ test("rovingCost M7 arrow navigation proceeds from non-blocking input types", async function (assert) {+ await render(+ <template>+ <div {{dRovingFocus orientation="vertical" itemSelector=".item"}}>+ {{#each NON_BLOCKING_INPUT_TYPES as |type|}}+ <div class="item">+ <input+ data-input-type={{type}}+ type={{type}}+ alt={{type}}+ src="data:image/gif;base64,R0lGODlhAQABAAAAACw="+ />+ </div>+ <button class="item" data-target-type={{type}}>+ Target for+ {{type}}+ </button>+ {{/each}}+ </div>+ </template>+ );++ for (const type of NON_BLOCKING_INPUT_TYPES) {+ const input = `[data-input-type="${type}"]`;+ await focus(input);+ await triggerKeyEvent(input, "keydown", "ArrowDown");+ assert+ .dom(`[data-target-type="${type}"]`)+ .isFocused(+ `${type} has no native arrow behavior, so navigation proceeds`+ );+ }+ });++ test("rovingCost M7 arrow navigation is blocked by native arrow-consuming input types", async function (assert) {+ await render(+ <template>+ <div {{dRovingFocus orientation="vertical" itemSelector=".item"}}>+ {{#each BLOCKING_INPUT_TYPES as |type|}}+ <div class="item">+ <input data-input-type={{type}} type={{type}} />+ </div>+ <button class="item">Target for {{type}}</button>+ {{/each}}+ </div>+ </template>+ );++ for (const type of BLOCKING_INPUT_TYPES) {+ const input = `[data-input-type="${type}"]`;+ await focus(input);+ await triggerKeyEvent(input, "keydown", "ArrowDown");+ assert+ .dom(input)+ .isFocused(`${type} keeps ArrowDown for its native behavior`);+ }+ });++ test("rovingCost M7 textarea select and contenteditable keep their arrow keys", async function (assert) {+ await render(+ <template>+ <div {{dRovingFocus orientation="vertical" itemSelector=".item"}}>+ <div class="item"><textarea class="textarea"></textarea></div>+ <button class="item">After textarea</button>+ <div class="item">+ <select class="select"><option>Choice</option></select>+ </div>+ <button class="item">After select</button>+ <div class="item">+ <div class="contenteditable" contenteditable="true">Editable</div>+ </div>+ <button class="item">After contenteditable</button>+ </div>+ </template>+ );++ for (const selector of [".textarea", ".select", ".contenteditable"]) {+ await focus(selector);+ await triggerKeyEvent(selector, "keydown", "ArrowDown");+ assert+ .dom(selector)+ .isFocused(`${selector} keeps ArrowDown for its native behavior`);+ }+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-lifecycle-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-lifecycle-test.gjsnew file mode 100644index 00000000000..e1e090f0ed6--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-lifecycle-test.gjs@@ -0,0 +1,555 @@+import { tracked } from "@glimmer/tracking";+import {+ clearRender,+ focus,+ render,+ settled,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++module(+ "Integration | ui-kit | Modifier | dRovingFocus | lifecycle",+ function (hooks) {+ setupRenderingTest(hooks);++ test("replacing the active controller preserves the cursor and rebinds navigation", async function (assert) {+ const state = new (class {+ @tracked controller = ".first-controller";+ })();+ const changes = [];+ const onActiveChange = (item) => changes.push(item);++ await render(+ <template>+ <input+ class="first-controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <input+ class="second-controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=state.controller+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ onActiveChange=onActiveChange+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ const activeId = document.querySelector(".a").id;+ changes.length = 0;+ state.controller = ".second-controller";+ await settled();++ assert+ .dom(".first-controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "the outgoing controller releases the cursor"+ );+ assert+ .dom(".second-controller")+ .hasAttribute(+ "aria-activedescendant",+ activeId,+ "the replacement controller receives the existing cursor"+ );+ assert+ .dom(".a")+ .hasClass("--active", "the active item remains highlighted");+ assert.deepEqual(+ changes,+ [],+ "replacing the controller does not report a cursor move"+ );++ await triggerKeyEvent(".first-controller", "keydown", "ArrowDown");+ assert.dom(".a").hasClass("--active", "the old listener is removed");++ await triggerKeyEvent(".second-controller", "keydown", "ArrowDown");+ assert.dom(".b").hasClass("--active", "the new controller navigates");+ });++ test("replacing the controller cancels a pending reannouncement", async function (assert) {+ const state = new (class {+ @tracked controller = ".first-controller";+ })();+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <input+ class="first-controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <input+ class="second-controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=state.controller+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ const activeId = document.querySelector(".a").id;+ assert.true(api.reannounceActive(), "the reannouncement is scheduled");++ state.controller = ".second-controller";+ await settled();++ assert+ .dom(".first-controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "the pending callback never republishes onto the old controller"+ );+ assert+ .dom(".second-controller")+ .hasAttribute(+ "aria-activedescendant",+ activeId,+ "the current controller retains the existing cursor"+ );+ assert.dom(".a").hasClass("--active", "the cursor is not reseeded");+ });++ test("leaving active mode disarms a pending seed", async function (assert) {+ const state = new (class {+ @tracked mode = "active-descendant";+ @tracked items = [];+ })();++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy=state.mode+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ itemsKey=state.items+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button role="option" id={{item.id}}>{{item.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ state.mode = "roving-tabindex";+ await settled();+ state.items = [{ id: "a" }, { id: "b" }];+ await settled();++ assert+ .dom(".controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "rows arriving later do not revive the active cursor"+ );+ assert.dom("#a").doesNotHaveClass("--active", "no highlight is added");+ assert+ .dom("#a")+ .hasAttribute(+ "tabindex",+ "0",+ "the current roving strategy seeds normally"+ );+ assert+ .dom("#a")+ .isNotFocused("the stale observer does not move DOM focus");+ });++ test("entryFocus none disarms a pending seed", async function (assert) {+ const state = new (class {+ @tracked entryFocus = "first";+ @tracked items = [];+ })();++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus=state.entryFocus+ itemsKey=state.items+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button role="option" id={{item.id}}>{{item.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ state.entryFocus = "none";+ await settled();+ state.items = [{ id: "a" }];+ await settled();++ assert+ .dom(".controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "the pending observer respects the current entry policy"+ );+ assert.dom("#a").doesNotHaveClass("--active", "nothing is highlighted");+ });++ test("active selector replacement releases every artifact from the old scope", async function (assert) {+ const state = new (class {+ @tracked selector = ".first-item";+ })();++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector=state.selector+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <div role="option" class="first-item">A</div>+ <div role="option" class="second-item">B</div>+ <div role="option" class="author-item" id="author-id">C</div>+ </div>+ </template>+ );++ const firstId = document.querySelector(".first-item").id;+ assert.true(Boolean(firstId), "the first scope receives a minted id");++ state.selector = ".second-item";+ await settled();++ assert+ .dom(".first-item")+ .doesNotHaveClass("--active", "the old highlight is removed");+ assert+ .dom(".first-item")+ .doesNotHaveAttribute("id", "the old modifier-minted id is removed");+ assert+ .dom(".second-item")+ .hasClass("--active", "the replacement scope is seeded");+ assert+ .dom(".controller")+ .hasAttribute(+ "aria-activedescendant",+ document.querySelector(".second-item").id,+ "the controller points into the replacement scope"+ );+ assert+ .dom(".author-item")+ .hasAttribute(+ "id",+ "author-id",+ "an author-owned id remains untouched"+ );+ });++ test("a delayed seed uses the latest callback", async function (assert) {+ const firstChanges = [];+ const secondChanges = [];+ const firstCallback = (item) => firstChanges.push(item);+ const secondCallback = (item) => secondChanges.push(item);+ const state = new (class {+ @tracked callback = firstCallback;+ @tracked items = [];+ })();++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ itemsKey=state.items+ onActiveChange=state.callback+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button role="option" id={{item.id}}>{{item.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ firstChanges.length = 0;+ state.callback = secondCallback;+ await settled();+ state.items = [{ id: "a" }];+ await settled();++ assert.deepEqual(+ firstChanges,+ [],+ "the superseded callback is not retained"+ );+ assert.deepEqual(+ secondChanges,+ [null, document.querySelector("#a")],+ "the current callback receives the empty cursor and the delayed seed"+ );+ });++ test("strategy round trips leave only the current strategy artifacts", async function (assert) {+ const state = new (class {+ @tracked mode = "active-descendant";+ })();++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy=state.mode+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ state.mode = "roving-tabindex";+ await settled();+ assert.dom(".a").doesNotHaveClass("--active", "active state is released");+ assert+ .dom(".a")+ .hasAttribute("tabindex", "0", "the roving strategy owns the item");++ state.mode = "active-descendant";+ await settled();++ assert+ .dom(".a")+ .doesNotHaveAttribute("tabindex", "the roving artifact is released");+ assert.dom(".a").hasClass("--active", "active mode seeds again");+ assert+ .dom(".controller")+ .hasAttribute(+ "aria-activedescendant",+ document.querySelector(".a").id,+ "only the current active cursor remains"+ );+ });++ test("teardown cancels pending active work and preserves author ids", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <input+ class="controller"+ role="combobox"+ aria-controls="lifecycle-list"+ />+ <div+ id="lifecycle-list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ onRegisterApi=register+ }}+ >+ <button class="minted" role="option">A</button>+ <button class="authored" role="option" id="authored-id">B</button>+ </div>+ </template>+ );++ assert.true(api.reannounceActive(), "a reannouncement is pending");+ const controller = document.querySelector(".controller");+ const minted = document.querySelector(".minted");+ const authored = document.querySelector(".authored");++ await clearRender();++ assert.false(+ controller.hasAttribute("aria-activedescendant"),+ "teardown removes the controller cursor"+ );+ assert.false(+ minted.hasAttribute("id"),+ "the modifier-minted id is removed"+ );+ assert.strictEqual(+ authored.id,+ "authored-id",+ "the author-owned id is preserved"+ );+ assert.false(+ minted.classList.contains("--active"),+ "the active class is removed"+ );+ });++ test("tabStop toggles without moving the roving cursor", async function (assert) {+ const state = new (class {+ @tracked tabStop = true;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=state.tabStop+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".b");+ state.tabStop = false;+ await settled();++ assert.dom(".b").isFocused("the cursor remains on the focused item");+ assert+ .dom("[role=option][tabindex='0']")+ .doesNotExist("the group leaves the Tab sequence");++ state.tabStop = true;+ await settled();++ assert.dom(".b").isFocused("restoring the tab stop does not move focus");+ assert+ .dom(".b")+ .hasAttribute("tabindex", "0", "the cursor becomes the tab stop again");+ });++ test("restoring lost focus copes with the selector matching nothing", async function (assert) {+ const state = new (class {+ @tracked+ rows = [+ { id: "a", nav: true },+ { id: "b", nav: true },+ { id: "c", nav: true },+ ];+ @tracked key = 0;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[data-nav]" itemsKey=state.key}}+ >+ {{#each state.rows key="id" as |row|}}+ <button+ class="opt-{{row.id}}"+ role="option"+ data-nav={{if row.nav "true"}}+ >{{row.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-a");+ state.rows = [+ { id: "b", nav: false },+ { id: "c", nav: false },+ ];+ state.key++;+ await settled();++ assert.strictEqual(+ document.activeElement,+ document.body,+ "with nothing left to match, restoration declines instead of throwing"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-test.gjsnew file mode 100644index 00000000000..5acd7c2427e--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-test.gjs@@ -0,0 +1,3950 @@+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import {+ click,+ focus,+ render,+ settled,+ triggerEvent,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++module("Integration | ui-kit | Modifier | dRovingFocus", function (hooks) {+ setupRenderingTest(hooks);++ test("focus mode: arrows move focus in DOM order, one tab stop", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute("tabindex", "0", "first item is the tab stop");+ assert.dom(".b").hasAttribute("tabindex", "-1");++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert.dom(".b").isFocused("ArrowRight moves focus to the next item");+ assert.dom(".b").hasAttribute("tabindex", "0", "tab stop follows focus");+ assert.dom(".a").hasAttribute("tabindex", "-1");++ await triggerKeyEvent(".b", "keydown", "ArrowLeft");+ assert.dom(".a").isFocused("ArrowLeft moves focus to the previous item");+ });++ test("focus mode: focus on a descendant of an item resolves to that item", async function (assert) {+ // An item may contain its own focusable controls (an inline button, or the+ // trigger a closed popover just handed focus back to). Focus resting on such+ // a descendant should navigate from its containing item, not fall back to+ // the tab stop.+ await render(+ <template>+ <div+ role="tree"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=treeitem]"+ }}+ >+ <div class="a" role="treeitem">A</div>+ <div class="b" role="treeitem">+ B+ {{! Intentionally nests a focusable control in the item to exercise+ descendant-focus resolution. }}+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <span class="b-inner" tabindex="0">x</span>+ </div>+ <div class="c" role="treeitem">C</div>+ </div>+ </template>+ );++ // Focus a control *inside* item B (not B itself), then navigate.+ await focus(".b-inner");+ await triggerKeyEvent(".b-inner", "keydown", "ArrowRight");+ assert+ .dom(".c")+ .isFocused("ArrowRight navigates from the item containing the focus");+ });++ test("focus mode: grid down/up moves by the live column count", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ </div>+ </template>+ );++ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");+ assert.dom(".i3").isFocused("ArrowDown moves one row (3 columns) down");++ await triggerKeyEvent(".i3", "keydown", "ArrowUp");+ assert.dom(".i0").isFocused("ArrowUp moves one row up");++ // Ragged last row: down from index 1 (row 0) would be index 4 (exists);+ // down from index 2 would be index 5 (missing) -> clamp to last (index 4).+ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowDown");+ assert+ .dom(".i4")+ .isFocused("ArrowDown past a ragged last row clamps to last");+ });++ test("focus mode: Home/End jump, no wrap by default at edges", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "End");+ assert.dom(".c").isFocused("End jumps to the last item");++ await triggerKeyEvent(".c", "keydown", "ArrowRight");+ assert+ .dom(".c")+ .isFocused("ArrowRight at the last item does nothing (no wrap)");++ await triggerKeyEvent(".c", "keydown", "Home");+ assert.dom(".a").isFocused("Home jumps to the first item");+ });++ test("focus mode: wrap=true wraps at the edges", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ wrap=true+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert+ .dom(".b")+ .isFocused("ArrowLeft from the first item wraps to the last");+ });++ test("skips hidden and disabled items", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option" disabled>B</button>+ <button class="c" role="option" style="display: none;">C</button>+ <button class="d" role="option">D</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert.dom(".d").isFocused("disabled and hidden items are skipped");+ });++ test("focus mode: skips visibility:hidden items", async function (assert) {+ // `visibility: hidden` still participates in layout (so the offsetParent /+ // client-rects check passes) but cannot take focus — it must be skipped just+ // like `display: none`.+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option" style="visibility: hidden;">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert.dom(".c").isFocused("a visibility:hidden item is skipped");+ });++ test("focus mode: keys from an embedded editable are left alone", async function (assert) {+ // An item may embed a text field; its caret and selection keys — including+ // Home/End — must win over roving navigation. The modifier ignores keydowns+ // that originate from an editable target so the field behaves natively.+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <span class="b" role="option">+ {{! Intentionally embeds a text field in an item to exercise the+ editable-target guard. }}+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <input class="b-input" type="text" />+ </span>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".b-input");+ await triggerKeyEvent(".b-input", "keydown", "ArrowRight");+ assert+ .dom(".b-input")+ .isFocused("ArrowRight from an embedded input does not navigate");++ await triggerKeyEvent(".b-input", "keydown", "Home");+ assert+ .dom(".b-input")+ .isFocused("Home from an embedded input does not jump to the first item");+ });++ test("focus mode: arrows from a control outside any item are left alone", async function (assert) {+ // A container may hold focusable controls that are neither items nor inside+ // one: a row's own switch sitting beside the handle that is the cursor's+ // item. An arrow pressed there belongs to nothing this group owns, so the+ // cursor must stay put and focus must not be pulled onto an item.+ await render(+ <template>+ <ul {{dRovingFocus orientation="vertical" itemSelector=".handle"}}>+ <li>+ <button class="handle a" type="button">A</button>+ <button+ class="switch-a"+ type="button"+ role="switch"+ aria-checked="false"+ ></button>+ </li>+ <li>+ <button class="handle b" type="button">B</button>+ <input class="check-b" type="checkbox" />+ </li>+ </ul>+ </template>+ );++ await focus(".switch-a");+ await triggerKeyEvent(".switch-a", "keydown", "ArrowDown");+ assert+ .dom(".switch-a")+ .isFocused("ArrowDown from a switch beside an item does not navigate");++ await focus(".check-b");+ await triggerKeyEvent(".check-b", "keydown", "ArrowUp");+ assert+ .dom(".check-b")+ .isFocused("ArrowUp from a checkbox beside an item does not navigate");+ });++ test("Enter and Space activate; other keys do not", async function (assert) {+ let activated = [];+ const onActivate = (el) => activated.push(el.className);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onActivate=(fn onActivate)+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "Enter");+ await triggerKeyEvent(".a", "keydown", " ");+ assert.deepEqual(+ activated,+ ["a", "a"],+ "Enter and Space activate the current item"+ );++ await triggerKeyEvent(".a", "keydown", "Escape");+ assert.deepEqual(activated, ["a", "a"], "other keys do not activate");+ });++ // For a caller whose item is unchanged but whose context is not — a row reporting a different+ // position in a different set. Re-asserting the same `aria-activedescendant` is a no-op, so the+ // attribute has to actually change for anything to observe it.+ test("active mode: reannounceActive drops and restores the cursor", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ const search = document.querySelector(".search");+ assert.false(+ api.reannounceActive(),+ "with no cursor there is nothing to read again"+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ const activeId = search.getAttribute("aria-activedescendant");++ assert.true(api.reannounceActive(), "reports that it acted");+ assert+ .dom(".search")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "the cursor is dropped synchronously"+ );++ await settled();+ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ activeId,+ "and restored to the same row a tick later"+ );++ // A cursor id outlives its row. Acting here would drop the attribute and report success while+ // reading nothing, and a caller that treats success as "the row said it" would go silent.+ document.querySelectorAll("[role=option]").forEach((el) => el.remove());+ assert.false(+ api.reannounceActive(),+ "a cursor whose row is gone is not read again"+ );+ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ activeId,+ "and the attribute is left alone rather than dropped for nothing"+ );+ });++ // The restore is owed to the row that was active when it was requested. A reader who moves in+ // the meantime must not be dragged back.+ test("active mode: a cursor move outruns a pending reannounce", async function (assert) {+ let api;+ const register = (value) => (api = value);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ api.reannounceActive();+ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ document.querySelector(".b").id,+ "the cursor sits where the reader moved it, not where it was asked to be restored"+ );+ });++ test("active mode: focus stays on the controller, aria-activedescendant tracks", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ assert.dom(".search").isFocused("focus stays on the search input");+ const activeId = document+ .querySelector(".search")+ .getAttribute("aria-activedescendant");+ assert.true(+ Boolean(activeId),+ "the controller carries aria-activedescendant"+ );+ assert+ .dom(".a")+ .hasAttribute(+ "id",+ activeId,+ "first ArrowDown highlights the first option"+ );+ assert+ .dom(".a")+ .hasClass("--active", "the highlighted item gets the active class");+ assert.dom(".b").doesNotHaveClass("--active");+ });++ test("active mode: Enter activates the highlighted item", async function (assert) {+ let activated = null;+ const onActivate = (el) => (activated = el.className);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ onActivate=(fn onActivate)+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ await triggerKeyEvent(".search", "keydown", "Enter");+ assert.strictEqual(+ activated,+ "a",+ "Enter activates the highlighted (first) option, not the focused input"+ );+ });++ test("active mode: a changing item set clears a stale highlight", async function (assert) {+ class State {+ @tracked items = ["a", "b", "c"];+ @tracked key = 0;+ }+ const state = new State();+ const refilter = () => {+ state.items = ["x", "y"];+ state.key++;+ };++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <button+ class="refilter"+ type="button"+ {{on "click" refilter}}+ >x</button>+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ itemsKey=state.key+ activeClass="--active"+ }}+ >+ {{#each state.items as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".search");+ // Highlight the first item, then swap the whole list out via tracked state.+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ await click(".refilter");++ assert+ .dom(".search")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "a highlight whose item was filtered out is cleared, never left stale"+ );++ // A fresh ArrowDown reseeds the first option of the new list.+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ const activeId = document+ .querySelector(".search")+ .getAttribute("aria-activedescendant");+ assert+ .dom(".opt-x")+ .hasAttribute("id", activeId, "ArrowDown reseeds the first live option");+ });++ test("active mode: entryFocus=first highlights the first item on insert", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "the first item is highlighted without any keypress"+ );+ const activeId = document+ .querySelector(".search")+ .getAttribute("aria-activedescendant");+ assert.dom(".a").hasAttribute("id", activeId);+ assert.dom(".b").doesNotHaveClass("--active");+ });++ // A windowed list installs this modifier on a container that is still empty: the virtualizer+ // has not measured its viewport yet, so the rows arrive a frame later. The seed ran against+ // nothing, found nothing to activate, and no key changes when the rows land — so the list is+ // presented with no cursor at all, and the reader's first arrow press is spent putting one on+ // row one instead of moving off it.+ test("active mode: a container that gains its items after install still seeds", async function (assert) {+ const state = new (class {+ @tracked items = [];+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button+ class="opt"+ role="option"+ id={{item.id}}+ >{{item.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert.dom(".opt").doesNotExist("the container installs with no items");++ state.items = [{ id: "a" }, { id: "b" }];+ await settled();++ assert+ .dom("#a")+ .hasClass("--active", "the first item is highlighted once items arrive");+ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ "a",+ "the controller points at the first item once items arrive"+ );+ });++ // The other half of the rule above, and the reason it cannot simply re-seed whenever the item+ // set changes: a windowed list republishes its rows on every scroll, so a blanket re-seed would+ // throw a reader who has arrowed down back to the top of the list.+ test("active mode: items arriving later never move a cursor the reader has placed", async function (assert) {+ // Starts EMPTY so the pending-seed observer is genuinely armed. Starting with items+ // present means `#reconcileActive` seeds and returns before ever arming it, so no+ // modifier code runs when the set later changes and the test proves nothing about the+ // one-shot guard.+ const state = new (class {+ @tracked items = [];+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ {{#each state.items key="id" as |item|}}+ <button+ class="opt"+ role="option"+ id={{item.id}}+ >{{item.id}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".search");++ state.items = [{ id: "a" }, { id: "b" }];+ await settled();+ assert+ .dom("#a")+ .hasClass(+ "--active",+ "the armed observer seeds once the first items arrive"+ );++ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert.dom("#b").hasClass("--active", "the reader moved the cursor to b");++ state.items = [...state.items, { id: "c" }];+ await settled();++ assert+ .dom("#b")+ .hasClass("--active", "a later item set leaves the placed cursor alone");+ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ "b",+ "the controller still points at the reader's row"+ );+ });++ test("active mode: entryFocus=selected-or-first prefers the selected item over the first", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="selected-or-first"+ }}+ >+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="true">B</button>+ </div>+ </template>+ );++ assert+ .dom(".b")+ .hasClass(+ "--active",+ "the user's existing choice wins over the first row"+ );+ assert.dom(".a").doesNotHaveClass("--active");+ const activeId = document+ .querySelector(".search")+ .getAttribute("aria-activedescendant");+ assert.dom(".b").hasAttribute("id", activeId);+ });++ test("active mode: entryFocus=selected-or-none restores a selection without seeding a first item", async function (assert) {+ // A list that waits for the reader to act takes no first-item fallback. That rule exists to+ // avoid highlighting an arbitrary row; a restored selection is not arbitrary.+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="selected-or-none"+ }}+ >+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="true">B</button>+ </div>+ </template>+ );++ assert.dom(".b").hasClass("--active", "the selection is restored");+ });++ test("active mode: entryFocus=selected-or-none leaves the cursor empty when nothing is selected", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="selected-or-none"+ }}+ >+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="false">B</button>+ </div>+ </template>+ );++ assert.dom(".a").doesNotHaveClass("--active");+ assert.dom(".b").doesNotHaveClass("--active");+ assert+ .dom(".search")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "no selection and no first-item fallback means no cursor"+ );+ });++ test("active mode: entryFocus=selected-or-first does not move a cursor the user has set", async function (assert) {+ // `itemsKey` is what makes this test mean what its name says: without a reconcile after the+ // arrow key, nothing could possibly drag the cursor back and the assertion would only be+ // restating that ArrowDown moved it.+ const state = new (class {+ @tracked key = 1;+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ itemsKey=state.key+ entryFocus="selected-or-first"+ }}+ >+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="true">B</button>+ <button class="c" role="option" aria-selected="false">C</button>+ </div>+ </template>+ );++ assert.dom(".b").hasClass("--active", "seeded on the selection");++ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ assert+ .dom(".c")+ .hasClass("--active", "the user's arrow key moves off the selection");++ state.key = 2;+ await settled();++ assert+ .dom(".c")+ .hasClass("--active", "a reconcile keeps the cursor the user placed");+ assert+ .dom(".b")+ .doesNotHaveClass("--active", "and the preference does not drag it back");+ });++ test("active mode: itemsKey preserves a survivor but resetKey re-seeds the first item", async function (assert) {+ const state = new (class {+ @tracked itemsKey = 0;+ @tracked resetKey = 0;+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ itemsKey=state.itemsKey+ resetKey=state.resetKey+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert.dom(".b").hasClass("--active", "the reader placed the cursor on b");++ state.itemsKey++;+ await settled();++ assert+ .dom(".b")+ .hasClass(+ "--active",+ "an ordinary item reconciliation keeps the surviving cursor"+ );++ state.resetKey++;+ await settled();++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "a new question applies the first-item entry policy afresh"+ );+ assert+ .dom(".b")+ .doesNotHaveClass(+ "--active",+ "the survivor does not outrank an explicit reset"+ );+ });++ test("active mode: resetKey re-seeds a marked row under selected-or-first", async function (assert) {+ const state = new (class {+ @tracked resetKey = 0;+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="selected-or-first"+ resetKey=state.resetKey+ }}+ >+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="true">B</button>+ <button class="c" role="option" aria-selected="false">C</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert+ .dom(".c")+ .hasClass("--active", "the reader moved past the selection");++ state.resetKey++;+ await settled();++ assert+ .dom(".b")+ .hasClass(+ "--active",+ "a new question restores the marked row before considering the first"+ );+ assert+ .dom(".c")+ .doesNotHaveClass(+ "--active",+ "a surviving cursor does not carry across an explicit reset"+ );+ });++ test("active mode: entryFocus=first re-seeds the first item when the set changes", async function (assert) {+ class State {+ @tracked items = ["a", "b", "c"];+ @tracked key = 0;+ }+ const state = new State();+ const refilter = () => {+ state.items = ["x", "y"];+ state.key++;+ };++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <button+ class="refilter"+ type="button"+ {{on "click" refilter}}+ >x</button>+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ itemsKey=state.key+ activeClass="--active"+ entryFocus="first"+ }}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ assert+ .dom(".opt-a")+ .hasClass("--active", "first item highlighted initially");++ // Swap the whole list; the highlight re-seeds to the new first with no keypress.+ await click(".refilter");+ assert+ .dom(".opt-x")+ .hasClass("--active", "the highlight follows to the new first item");+ const activeId = document+ .querySelector(".search")+ .getAttribute("aria-activedescendant");+ assert.dom(".opt-x").hasAttribute("id", activeId);+ });++ test("active mode: entryFocus=none highlights nothing until an Arrow key", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert.dom(".--active").doesNotExist("no highlight before interaction");+ assert.dom(".search").doesNotHaveAttribute("aria-activedescendant");+ });++ test("active mode: Space does not activate and is left for the input", async function (assert) {+ let activated = false;+ let spacePrevented = null;+ const onActivate = () => (activated = true);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ onActivate=(fn onActivate)+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ // Listener registered after the modifier's, so it observes whether the modifier+ // prevented the key — proving a Space reaches the input to be typed.+ document+ .querySelector(".search")+ .addEventListener(+ "keydown",+ (e) => e.key === " " && (spacePrevented = e.defaultPrevented)+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown"); // highlight .a+ await triggerKeyEvent(".search", "keydown", " ");++ assert.false(activated, "Space does not activate in a text combobox");+ assert.false(+ spacePrevented,+ "Space is not preventDefault-ed, so the character reaches the input"+ );+ assert+ .dom(".a")+ .hasClass("--active", "the highlight does not move on Space");+ });++ test("active mode: Home/End/Left/Right are left for the text caret", async function (assert) {+ const prevented = {};++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ document+ .querySelector(".search")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown"); // highlight .a++ for (const key of ["Home", "End", "ArrowLeft", "ArrowRight"]) {+ await triggerKeyEvent(".search", "keydown", key);+ assert.false(+ prevented[key],+ `${key} is left for the caret, not intercepted`+ );+ }+ assert+ .dom(".a")+ .hasClass("--active", "the highlight does not move on caret keys");+ });++ test("active mode: Enter with no highlight does not activate", async function (assert) {+ let activated = false;+ let enterPrevented = null;+ const onActivate = () => (activated = true);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ onActivate=(fn onActivate)+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ document+ .querySelector(".search")+ .addEventListener(+ "keydown",+ (e) => e.key === "Enter" && (enterPrevented = e.defaultPrevented)+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "Enter");++ assert.false(activated, "Enter with nothing highlighted does not activate");+ assert.false(+ enterPrevented,+ "Enter falls through so the consumer can submit or create"+ );+ });++ test("active mode: first ArrowUp seeds the last option", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowUp");+ assert+ .dom(".c")+ .hasClass("--active", "ArrowUp from no highlight seeds the last option");+ });++ test("active mode: onBoundary reports only vertical group exits", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) => boundaries.push([direction, axis]);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ wrap=false+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ assert.deepEqual(+ boundaries,+ [["forward", "vertical"]],+ "leaving the last option reports a forward vertical boundary"+ );++ await triggerKeyEvent(".search", "keydown", "ArrowRight");+ await triggerKeyEvent(".search", "keydown", "ArrowLeft");++ assert.deepEqual(+ boundaries,+ [["forward", "vertical"]],+ "horizontal caret keys never masquerade as listbox boundaries"+ );+ assert+ .dom(".b")+ .hasClass("--active", "horizontal caret keys leave the cursor in place");++ await triggerKeyEvent(".search", "keydown", "ArrowUp");+ await triggerKeyEvent(".search", "keydown", "ArrowUp");++ assert.deepEqual(+ boundaries,+ [+ ["forward", "vertical"],+ ["backward", "vertical"],+ ],+ "leaving the first option reports a backward vertical boundary"+ );+ });++ test("focus mode with tabStop=false: every item is -1, never a tab stop", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=false+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute("tabindex", "-1", "the first item is not made a tab stop");+ assert.dom(".b").hasAttribute("tabindex", "-1");+ assert.dom(".c").hasAttribute("tabindex", "-1");++ // The -1 is what keeps items programmatically focusable, so arrow navigation+ // still works — but the newly-focused item never becomes tabindex 0.+ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert+ .dom(".b")+ .isFocused("ArrowRight still moves focus with tabStop=false");+ assert+ .dom(".b")+ .hasAttribute("tabindex", "-1", "the focused item stays -1, never 0");+ assert.dom(".a").hasAttribute("tabindex", "-1");+ });++ test("focus mode: entryFocus=none deliberately leaves no tab stop", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" entryFocus="none"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute(+ "tabindex",+ "-1",+ "without an entry fallback the first row stays out of the tab sequence"+ );+ assert+ .dom(".b")+ .hasAttribute(+ "tabindex",+ "-1",+ "without an entry fallback no later row becomes an accidental tab stop"+ );+ assert+ .dom('[role="option"][tabindex="0"]')+ .doesNotExist("the group deliberately contributes no tab stop");+ });++ test("focus mode: selected-or-none supplies a tab stop only for a marked row", async function (assert) {+ await render(+ <template>+ <div+ class="unmarked"+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ entryFocus="selected-or-none"+ }}+ >+ <button+ class="unmarked-a"+ role="option"+ aria-selected="false"+ >A</button>+ <button+ class="unmarked-b"+ role="option"+ aria-selected="false"+ >B</button>+ </div>+ <div+ class="marked"+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ entryFocus="selected-or-none"+ }}+ >+ <button+ class="marked-a"+ role="option"+ aria-selected="false"+ >A</button>+ <button class="marked-b" role="option" aria-selected="true">B</button>+ </div>+ </template>+ );++ assert+ .dom(".unmarked-a")+ .hasAttribute(+ "tabindex",+ "-1",+ "an unmarked first row cannot become the missing selection"+ );+ assert+ .dom(".unmarked-b")+ .hasAttribute(+ "tabindex",+ "-1",+ "no later unmarked row is used as a fallback either"+ );+ assert+ .dom('.unmarked [tabindex="0"]')+ .doesNotExist("an unmarked group deliberately contributes no tab stop");+ assert+ .dom(".marked-b")+ .hasAttribute(+ "tabindex",+ "0",+ "a real selection restores the group's tab stop"+ );+ assert+ .dom(".marked-a")+ .hasAttribute(+ "tabindex",+ "-1",+ "the first row does not outrank the restored selection"+ );+ });++ test("focus mode: onBoundary fires at a horizontal edge with the travel direction", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "ArrowRight");+ assert.deepEqual(+ boundaries,+ ["horizontal:forward"],+ "ArrowRight past the last item exits forward"+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert.deepEqual(+ boundaries,+ ["horizontal:forward", "horizontal:backward"],+ "ArrowLeft past the first item exits backward"+ );+ });++ test("focus mode: onBoundary does not fire on a vertical key or with no cursor", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onBoundary=onBoundary+ tabStop=false+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ // tabStop=false leaves no tab stop, so with nothing focused the cursor is -1.+ // Arrowing with no cursor must not report an edge exit.+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert.deepEqual(boundaries, [], "ArrowLeft with no cursor does not exit");++ // Under horizontal orientation a vertical key is not ours. A silent `onBoundary` alone would+ // hold even with the orientation gate deleted, since the group has only two items and+ // ArrowDown from the first would land on the second rather than an edge — so the+ // load-bearing assertion is that the cursor DID NOT MOVE.+ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowDown");+ assert+ .dom(".a")+ .isFocused(+ "ArrowDown under horizontal orientation does not move the cursor"+ );+ assert.deepEqual(+ boundaries,+ [],+ "and reports no boundary on an axis the group does not claim"+ );+ });++ test("focus mode: onRegisterApi yields focus controls that move focus", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=false+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert.strictEqual(+ typeof api?.focusFirst,+ "function",+ "the api is registered on insert"+ );++ assert.true(api.focusFirst(), "focusFirst reports it landed on an item");+ await settled();+ assert.dom(".a").isFocused("focusFirst moves DOM focus to the first item");++ assert.true(api.focusLast(), "focusLast reports it landed on an item");+ await settled();+ assert.dom(".c").isFocused("focusLast moves DOM focus to the last item");++ assert.true(api.focusIndex(1), "focusIndex reports it landed on an item");+ await settled();+ assert.dom(".b").isFocused("focusIndex moves DOM focus to the given index");+ });++ test("focus mode: the api is revoked and inert after teardown", async function (assert) {+ let api = null;+ let revoked = false;+ const register = (value) => {+ if (value === null) {+ revoked = true;+ } else {+ api = value;+ }+ };++ const state = new (class {+ @tracked show = true;+ })();++ await render(+ <template>+ {{#if state.show}}+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=false+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ {{/if}}+ </template>+ );++ assert.strictEqual(+ typeof api?.focusFirst,+ "function",+ "the api is registered while mounted"+ );++ state.show = false;+ await settled();++ assert.true(revoked, "onRegisterApi(null) is called on teardown");++ // The container is destroyed on every modal close on mobile; a stale api call+ // must find no items and report it never landed rather than throw on items[last].+ assert.false(api.focusFirst(), "a stale focusFirst reports no item landed");+ assert.false(api.focusLast(), "a stale focusLast reports no item landed");+ assert.false(+ api.focusIndex(0),+ "a stale focusIndex reports no item landed"+ );+ });++ test("grid: ArrowDown inside the last row reaches the edge instead of jumping sideways", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ </div>+ </template>+ );++ // A rectangular 3x2 grid: i3 is already on the last row, so there is nothing below it.+ await focus(".i3");+ await triggerKeyEvent(".i3", "keydown", "ArrowDown");++ assert.dom(".i3").isFocused("ArrowDown from the last row does not move");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "it reports the bottom edge rather than clamping laterally to the last item"+ );+ });++ test("grid: ArrowRight stops at a row edge without reporting a group exit", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ </div>+ </template>+ );++ // i2 closes row 0. A row edge is not the end of the group, so the cursor stops and+ // nothing is reported: `onBoundary` means "leaving the group", and firing it from an+ // interior row would drag a consumer's focus out mid-traversal.+ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowRight");+ assert+ .dom(".i2")+ .isFocused("ArrowRight at a row edge does not wrap onto the next row");+ assert.deepEqual(boundaries, [], "and a row edge is not a group exit");++ // The true end of the group still reports one.+ await focus(".i5");+ await triggerKeyEvent(".i5", "keydown", "ArrowRight");+ assert.deepEqual(+ boundaries,+ ["horizontal:forward"],+ "the last item still exits forward"+ );+ });++ test("horizontal orientation never row-clamps, however the items wrap visually", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ // The multi-chips shape: a horizontal group whose items wrap onto several lines. Visual+ // rows are not logical rows, so clamping must key off `orientation`, never geometry.+ await render(+ <template>+ <div+ role="listbox"+ style="display: flex; flex-wrap: wrap; width: 80px;"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onBoundary=onBoundary+ }}+ >+ <button class="i0" role="option" style="width: 30px;">0</button>+ <button class="i1" role="option" style="width: 30px;">1</button>+ <button class="i2" role="option" style="width: 30px;">2</button>+ <button class="i3" role="option" style="width: 30px;">3</button>+ </div>+ </template>+ );++ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowRight");+ assert+ .dom(".i3")+ .isFocused("a wrapped horizontal group keeps moving across lines");+ assert.deepEqual(+ boundaries,+ [],+ "and does not report an exit mid-traversal"+ );+ });++ test("grid: geometry follows the rendered cells, not the navigable ones", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option" aria-disabled="true">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ </div>+ </template>+ );++ // An `aria-disabled` cell still occupies its grid cell, so the row below i0 is i3.+ // Indexing the navigable-only set would count i1 out and land on i4 instead.+ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");+ assert+ .dom(".i3")+ .isFocused("ArrowDown lands in the same column of the next row");+ });++ test("grid: a column count derived from CSS ignores named grid lines", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: [start] 40px [mid] 40px [end];"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ </div>+ </template>+ );++ // Two tracks, three line names. Counting the names makes this read as five columns.+ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");+ assert+ .dom(".i2")+ .isFocused("ArrowDown moves by two tracks, not by the token count");+ });++ // The container is a real three-track CSS grid, so a derivation that ignored the orientation+ // would find three columns and step ArrowDown three items at a time.+ test("a non-grid orientation derives no column count", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus orientation="vertical" itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ </div>+ </template>+ );++ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");+ assert+ .dom(".i1")+ .isFocused(+ "a vertical list has no second axis, so ArrowDown steps one item"+ );+ });++ test("active mode steps one item at a time even over a grid", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ </div>+ </template>+ );++ // Active mode leaves ArrowLeft/ArrowRight to the controller's caret, so a second axis+ // would strand every item outside the first column.+ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert+ .dom(".i0")+ .hasClass("--active", "the first ArrowDown seeds the first item");++ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert+ .dom(".i1")+ .hasClass("--active", "and the next steps one item, not one row");+ });++ test("focus mode: wrapping backwards with no cursor lands on the last item", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ tabStop=false+ wrap=true+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ // `tabStop=false` with nothing focused means no cursor, so ArrowLeft seeds the far end.+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert+ .dom(".c")+ .isFocused("ArrowLeft with no cursor wraps to the last item");+ });++ test("focus mode: a chorded key is left alone", async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onActivate=onActivate+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "Enter", { metaKey: true });+ assert.deepEqual(+ activated,+ [],+ "Cmd+Enter is a submit chord, not an activation"+ );+ assert.false(prevented.Enter, "and it reaches the surrounding handler");++ await triggerKeyEvent(".a", "keydown", "ArrowDown", { altKey: true });+ assert.dom(".a").isFocused("Alt+ArrowDown does not navigate");+ });++ // While an IME is composing, the browser still reports the arrows and Enter the candidate+ // window is using to choose a character. Acting on them navigates the group out from under a+ // reader who is mid-word, and swallows the commit.+ test("focus mode: keys mid-composition are left to the IME", async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onActivate=onActivate+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".a");++ for (const key of ["ArrowDown", "ArrowUp"]) {+ await triggerEvent(".a", "keydown", { key, isComposing: true });+ assert.dom(".a").isFocused(`${key} mid-composition does not navigate`);+ assert.false(+ prevented[key],+ `${key} mid-composition is left for the candidate window`+ );+ }++ await triggerEvent(".a", "keydown", { key: "Enter", isComposing: true });+ assert.deepEqual(+ activated,+ [],+ "Enter mid-composition commits a candidate rather than activating"+ );+ assert.false(prevented.Enter, "and it reaches the IME un-prevented");+ });++ test("active mode: keys mid-composition leave the highlight alone", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert+ .dom(".a")+ .hasClass("--active", "the highlight starts on the first item");++ await triggerEvent(".search", "keydown", {+ key: "ArrowDown",+ isComposing: true,+ });++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "composing ArrowDown does not advance the highlight"+ );+ assert+ .dom(".search")+ .hasAttribute(+ "aria-activedescendant",+ document.querySelector(".a").id,+ "and the controller still points at the unmoved item"+ );+ });++ test("focus mode: wrapping onto the only navigable item is not an exit", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);+ const changes = [];+ const onActiveChange = (item) => changes.push(item?.className ?? null);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ wrap=true+ onBoundary=onBoundary+ onActiveChange=onActiveChange+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option" aria-disabled="true">B</button>+ </div>+ </template>+ );++ await focus(".a");+ changes.length = 0;+ await triggerKeyEvent(".a", "keydown", "ArrowRight");++ assert.dom(".a").isFocused("the only navigable item keeps the cursor");+ assert.deepEqual(+ boundaries,+ [],+ "a wrapping group does not report an exit, even when the wrap lands where it started"+ );+ assert.deepEqual(+ changes,+ [],+ "and a cursor that did not move reports no change"+ );+ });++ test("active mode navigates vertically whatever the orientation says", async function (assert) {+ // Active mode never claims the horizontal arrows, so honouring a horizontal orientation+ // would leave the group with no working arrow key and therefore no way to seed a cursor.+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ orientation="horizontal"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert.dom(".a").hasClass("--active", "ArrowDown still seeds the cursor");++ await triggerKeyEvent(".search", "keydown", "ArrowDown");+ assert.dom(".b").hasClass("--active", "and still advances it");+ });++ test("a superseded onRegisterApi callback is told its registration ended", async function (assert) {+ const first = [];+ const second = [];+ const registerFirst = (value) => first.push(value);+ const registerSecond = (value) => second.push(value);+ const state = new (class {+ @tracked useFirst = true;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ onRegisterApi=(if state.useFirst registerFirst registerSecond)+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ assert.strictEqual(first.length, 1, "the first callback is registered");+ assert.notStrictEqual(first[0], null, "with a live api");++ state.useFirst = false;+ await settled();++ assert.strictEqual(+ first[1],+ null,+ "the superseded callback is told the registration ended"+ );+ assert.notStrictEqual(second[0], null, "and the new one receives the api");+ });++ test("focus mode: an author-supplied tab stop survives the first render", async function (assert) {+ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="a" role="option" tabindex="-1">A</button>+ <button class="b" role="option" tabindex="-1">B</button>+ <button class="c" role="option" tabindex="0">C</button>+ </div>+ </template>+ );++ assert+ .dom(".c")+ .hasAttribute(+ "tabindex",+ "0",+ "the tab stop the author placed is preserved rather than relocated to the first item"+ );+ assert.dom(".a").hasAttribute("tabindex", "-1");+ });++ test("focus mode: re-seeding prefers the item holding DOM focus over an authored tab stop", async function (assert) {+ const state = new (class {+ @tracked showEarlier = false;+ @tracked itemsKey = 0;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.itemsKey}}+ >+ <button class="start" role="option">Start</button>+ {{#if state.showEarlier}}+ <button+ class="authored"+ role="option"+ tabindex="0"+ >Authored</button>+ {{/if}}+ <button class="middle" role="option">Middle</button>+ <button class="end" role="option">End</button>+ </div>+ </template>+ );++ await focus(".middle");+ state.showEarlier = true;+ state.itemsKey++;+ await settled();++ assert+ .dom(".middle")+ .isFocused(+ "the row containing DOM focus remains the reader's current position"+ );+ assert+ .dom(".middle")+ .hasAttribute(+ "tabindex",+ "0",+ "the tab stop follows the focused row through reconciliation"+ );+ assert+ .dom(".authored")+ .hasAttribute(+ "tabindex",+ "-1",+ "an earlier authored zero is demoted instead of stealing the established cursor"+ );+ });++ test("focus mode: itemsKey preserves a survivor but resetKey re-picks the tab stop", async function (assert) {+ const state = new (class {+ @tracked itemsKey = 0;+ @tracked resetKey = 0;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ entryFocus="first"+ itemsKey=state.itemsKey+ resetKey=state.resetKey+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".c");+ state.itemsKey++;+ await settled();++ assert+ .dom(".c")+ .hasAttribute(+ "tabindex",+ "0",+ "an ordinary item reconciliation keeps the surviving tab stop"+ );++ state.resetKey++;+ await settled();++ assert+ .dom(".a")+ .hasAttribute(+ "tabindex",+ "0",+ "a new question applies the first-item entry policy afresh"+ );+ assert+ .dom(".c")+ .hasAttribute(+ "tabindex",+ "-1",+ "the surviving row no longer owns the tab stop after a reset"+ );+ });++ test("focus mode: a shifted key is left for text selection", async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onActivate=onActivate+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowDown", { shiftKey: true });+ assert.dom(".a").isFocused("Shift+ArrowDown does not navigate");++ await triggerKeyEvent(".a", "keydown", "Enter", { shiftKey: true });+ assert.deepEqual(activated, [], "and Shift+Enter does not activate");+ });++ test("focus mode: Enter on a control inside an item is left to that control", async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onActivate=onActivate+ }}+ >+ <div class="a" role="option" tabindex="-1">+ A+ {{! Intentionally nests a real control in the item: the point of the test is that+ its own Enter handling survives. }}+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="a-remove" type="button">remove</button>+ </div>+ <div class="b" role="option" tabindex="-1">B</div>+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".a-remove");+ await triggerKeyEvent(".a-remove", "keydown", "Enter");++ assert.deepEqual(+ activated,+ [],+ "Enter on a nested button does not activate the row"+ );+ assert.false(+ prevented.Enter,+ "and the button keeps its own native activation"+ );+ });++ test("focus mode: horizontal arrows follow the writing direction", async function (assert) {+ await render(+ <template>+ <div+ dir="rtl"+ role="listbox"+ {{dRovingFocus orientation="horizontal" itemSelector="[role=option]"}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ // In RTL the visual start is the right-hand edge, so ArrowLeft advances through DOM order.+ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert.dom(".b").isFocused("ArrowLeft moves forward in an RTL group");++ await triggerKeyEvent(".b", "keydown", "ArrowRight");+ assert.dom(".a").isFocused("and ArrowRight moves back");+ });++ // The reported direction is LOGICAL, so it is derived from which key advances DOM order, not+ // from which physical arrow was pressed. An implementation keyed on "ArrowRight means forward"+ // reports "backward" here.+ test("focus mode: an RTL boundary reports the logical direction", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ dir="rtl"+ role="listbox"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[role=option]"+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "ArrowLeft");+ assert.deepEqual(+ boundaries,+ ["horizontal:forward"],+ "ArrowLeft past the last item in DOM order is a FORWARD horizontal boundary in RTL"+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert.deepEqual(+ boundaries,+ ["horizontal:forward", "horizontal:backward"],+ "and ArrowRight past the first item is backward"+ );+ });++ // The vertical axis used to be a separate callback, so a grid consumer that wired only the+ // horizontal one heard nothing at the bottom row. One callback reports both, which is why the+ // axis is not optional.+ test("grid: a vertical group edge reports the vertical axis", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ </div>+ </template>+ );++ await focus(".i4");+ await triggerKeyEvent(".i4", "keydown", "ArrowDown");+ assert.dom(".i4").isFocused("the bottom row has nowhere further to go");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "the bottom row reports a forward VERTICAL boundary, not a horizontal one"+ );++ await focus(".i1");+ await triggerKeyEvent(".i1", "keydown", "ArrowUp");+ assert.deepEqual(+ boundaries,+ ["vertical:forward", "vertical:backward"],+ "and the top row reports backward on the same axis"+ );+ });++ test("grid: a wrapping flex container warns that it has no second axis", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div+ role="listbox"+ style="display: flex; flex-wrap: wrap; width: 80px;"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ </div>+ </template>+ );++ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");++ assert.true(+ warn.calledOnce,+ "a wrapping flex group says it cannot find its second axis"+ );+ assert.true(+ warn.firstCall.args[0].includes("wrapping flex"),+ "and names the layout it could not measure"+ );++ await triggerKeyEvent(".i1", "keydown", "ArrowDown");+ assert.true(+ warn.calledOnce,+ "and does not repeat itself on every keystroke"+ );+ });++ test("grid: a real CSS grid does not warn", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(2, 40px);"+ {{dRovingFocus itemSelector="[role=option]"}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ </div>+ </template>+ );++ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");++ assert.dom(".i2").isFocused("the second axis works");+ assert.false(warn.called, "so nothing is warned about");+ });++ test("a plain one-column list does not warn", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ </div>+ </template>+ );++ await focus(".i0");+ await triggerKeyEvent(".i0", "keydown", "ArrowDown");++ assert.dom(".i1").isFocused("one column steps one item");+ assert.false(+ warn.called,+ "a block container resolving to one column is correct, not a degradation"+ );+ });++ test("focus mode: an item disabled while it holds the tab stop does not keep it", async function (assert) {+ const state = new (class {+ @tracked disabled = false;+ })();++ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="a" role="option">A</button>+ <button+ class="b"+ role="option"+ aria-disabled={{if state.disabled "true" "false"}}+ >B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert.dom(".b").hasAttribute("tabindex", "0", "b holds the tab stop");++ state.disabled = true;+ await settled();+ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");++ assert+ .dom(".b")+ .hasAttribute(+ "tabindex",+ "-1",+ "a row that left the navigable set is demoted, not left as a second tab stop"+ );+ });++ test("focus mode: the tab stop prefers the selected item over the first", async function (assert) {+ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="a" role="option" aria-selected="false">A</button>+ <button class="b" role="option" aria-selected="true">B</button>+ <button class="c" role="option" aria-selected="false">C</button>+ </div>+ </template>+ );++ // Natively-focusable elements report `tabIndex === 0` with no attribute, so reading the+ // property rather than the attribute makes this preference unreachable for buttons.+ assert+ .dom(".b")+ .hasAttribute("tabindex", "0", "the selected item is the tab stop");+ assert+ .dom(".a")+ .hasAttribute("tabindex", "-1", "and the first item is not");+ });++ test("focus mode: entryFocus=first ignores a marked item", async function (assert) {+ await render(+ <template>+ {{! Deliberately unroled: the modifier reads no roles, and the lint rule forbids+ buttons inside a toolbar role even though that is what the pattern is made of. }}+ <div+ {{dRovingFocus+ orientation="horizontal"+ itemSelector="[data-control]"+ entryFocus="first"+ }}+ >+ <button class="a" data-control>A</button>+ <button class="b" data-control aria-current="page">B</button>+ <button class="c" data-control>C</button>+ </div>+ </template>+ );++ // Toolbar and menubar enter on the first control unconditionally. A button marking the+ // current view is not a selection, and must not take the tab stop off the first one.+ assert+ .dom(".a")+ .hasAttribute("tabindex", "0", "the first control keeps the tab stop");+ assert+ .dom(".b")+ .hasAttribute("tabindex", "-1", "the marked control does not steal it");+ });++ test("focus mode: the tab stop prefers the checked radio over the first", async function (assert) {+ await render(+ <template>+ <div role="radiogroup" {{dRovingFocus itemSelector="[role=radio]"}}>+ <button class="a" role="radio" aria-checked="false">A</button>+ <button class="b" role="radio" aria-checked="true">B</button>+ <button class="c" role="radio" aria-checked="false">C</button>+ </div>+ </template>+ );++ assert+ .dom(".b")+ .hasAttribute("tabindex", "0", "the checked radio is the tab stop");+ assert+ .dom(".a")+ .hasAttribute("tabindex", "-1", "and the first radio is not");+ });++ test("focus mode: an item inside a disabled fieldset is not a target", async function (assert) {+ await render(+ <template>+ {{! An unroled container: a fieldset is the only way to inherit the disabled state,+ and it would otherwise have to sit between a listbox and its options. The predicate+ under test does not care about roles. }}+ <div {{dRovingFocus itemSelector=".opt"}}>+ <button class="opt a" type="button">A</button>+ <fieldset disabled>+ <button class="opt b" type="button">B</button>+ </fieldset>+ <button class="opt c" type="button">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ assert+ .dom(".c")+ .isFocused(+ "a button disabled through its fieldset cannot take focus, so it is skipped"+ );+ });++ test("focus mode: an inert item is not a target", async function (assert) {+ await render(+ <template>+ <div {{dRovingFocus itemSelector=".opt"}}>+ <button class="opt a" type="button">A</button>+ <button class="opt b" type="button" inert>B</button>+ <button class="opt c" type="button">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");++ assert+ .dom(".c")+ .isFocused("an inert button cannot take focus, so it is skipped");+ });++ test("focus mode: clicking an item moves the tab stop onto it", async function (assert) {+ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute("tabindex", "0", "the first item starts as the tab stop");++ await click(".c");++ assert+ .dom(".c")+ .hasAttribute("tabindex", "0", "the clicked item becomes the tab stop");+ assert+ .dom(".a")+ .hasAttribute("tabindex", "-1", "and the previous holder gives it up");+ });++ test("focus mode: focus arriving without a pointer also moves the tab stop", async function (assert) {+ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector="[role=option]"}}>+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".c");++ // Programmatic focus, with no pointer event at all: a fix that only widened the pointer+ // handler would leave the tab stop behind here.+ assert+ .dom(".c")+ .hasAttribute("tabindex", "0", "the focused item becomes the tab stop");+ assert.dom(".a").hasAttribute("tabindex", "-1");+ });++ // Focus persistence. Removals are driven straight through tracked state rather than by+ // clicking a button, because clicking one moves focus onto it and would hide the very+ // condition these tests turn on: focus falling to the body.+ class RemovableItems {+ @tracked items = ["a", "b", "c"];+ @tracked key = 0;++ remove(name) {+ this.items = this.items.filter((item) => item !== name);+ this.key++;+ }+ }++ test("focus mode: removing the focused item moves focus to the one that follows", async function (assert) {+ const state = new RemovableItems();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.key}}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-b");+ state.remove("b");+ await settled();++ assert+ .dom(".opt-c")+ .isFocused("focus lands on the item that took the removed one's place");+ });++ test("focus mode: restoreLostFocus=false leaves a removed cursor on the body", async function (assert) {+ const state = new (class {+ @tracked items = ["a", "b", "c"];+ @tracked itemsKey = 0;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ itemsKey=state.itemsKey+ restoreLostFocus=false+ }}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-b");+ state.items = state.items.filter((item) => item !== "b");+ state.itemsKey++;+ await settled();++ assert.strictEqual(+ document.activeElement,+ document.body,+ "the opt-out leaves focus lost for the consumer to place elsewhere"+ );+ });++ test("focus mode: a removal declined by the opt-out is forgotten, not deferred", async function (assert) {+ const state = new (class {+ @tracked items = ["a", "b", "c"];+ @tracked itemsKey = 0;+ @tracked restore = false;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ itemSelector="[role=option]"+ itemsKey=state.itemsKey+ restoreLostFocus=state.restore+ }}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-b");+ state.items = state.items.filter((item) => item !== "b");+ state.itemsKey++;+ await settled();++ state.restore = true;+ state.itemsKey++;+ await settled();++ assert.strictEqual(+ document.activeElement,+ document.body,+ "enabling restoration later must not act on a removal that was declined at the time"+ );+ });++ test("focus mode: removing the focused last item falls back to the previous one", async function (assert) {+ const state = new RemovableItems();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.key}}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-c");+ state.remove("c");+ await settled();++ assert+ .dom(".opt-b")+ .isFocused("there is no following item, so the cursor steps back");+ });++ test("focus mode: a removal does not reclaim focus the reader moved away", async function (assert) {+ const state = new RemovableItems();++ await render(+ <template>+ <button class="outside" type="button">outside</button>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.key}}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-b");+ await focus(".outside");+ state.remove("b");+ await settled();++ // The whole feature turns on focus having been LOST, not merely on an item disappearing.+ // Without that condition this steals focus back out of wherever the reader went.+ assert+ .dom(".outside")+ .isFocused("focus deliberately moved out of the group is left alone");+ });++ test("focus mode: removing an item the reader is not on leaves focus where it is", async function (assert) {+ const state = new RemovableItems();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.key}}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-c");+ state.remove("a");+ await settled();++ assert+ .dom(".opt-c")+ .isFocused("an unrelated removal is not an occasion to move the cursor");+ });++ test("focus mode: replacing the whole item set does not move focus", async function (assert) {+ class State {+ @tracked items = ["a", "b", "c"];+ @tracked key = 0;+ }+ const state = new State();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" itemsKey=state.key}}+ >+ {{#each state.items key="@identity" as |item|}}+ <button class="opt-{{item}}" role="option">{{item}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus(".opt-b");+ state.items = ["x", "y", "z"];+ state.key++;+ await settled();++ // Every previous item is gone, so this is a new question rather than a deletion. Seeding+ // never yanks focus on a re-render, and restoring here would drop the reader into a result+ // set they never navigated to.+ assert+ .dom(".opt-x")+ .isNotFocused("a wholesale replacement is not a removal to recover from");+ assert+ .dom(".opt-y")+ .isNotFocused("and no other member of the new set takes focus either");+ });++ test("active mode with no focus indicator at all warns", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ // In active mode DOM focus stays on the controller, so with neither activeClass nor+ // onActiveChange there is nothing drawing a focus indicator anywhere.+ assert.true(+ warn.called,+ "a group that can render no focus indicator says so"+ );+ });++ test("active mode: fallbackSkipsMarked seeds past a marked first item", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ fallbackSkipsMarked=true+ }}+ >+ <button class="a" role="option" aria-selected="true">A</button>+ <button class="b" role="option" aria-selected="false">B</button>+ </div>+ </template>+ );++ // Seeding the held row would arm the very first Enter to discard it, in a group whose+ // activation toggles.+ assert+ .dom(".b")+ .hasClass("--active", "the fallback lands past the marked row");+ assert.dom(".a").doesNotHaveClass("--active");+ });++ test("active mode warns when the cursor is unreachable from the controller", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ {{! No aria-controls and no aria-owns, so the list is a sibling the controller has no+ permitted relationship with. }}+ <input class="lonely" role="combobox" />+ <div+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".lonely"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ assert.true(+ warn.called,+ "an activedescendant that ARIA does not let the controller reach is reported"+ );+ });++ test("active mode does not warn when aria-owns reaches the cursor", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <input class="owner" role="combobox" aria-owns="owned-option" />+ <div+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".owner"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button id="owned-option" class="a" role="option">A</button>+ </div>+ </template>+ );++ // Containment is not the only permitted relationship, so a sibling list that is explicitly+ // owned must pass.+ assert.false(warn.called, "aria-owns is one of the three ARIA permits");+ });++ test("active mode does not warn when the consumer renders its own indicator", async function (assert) {+ const warn = sinon.stub(console, "warn");+ const noop = () => {};++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ onActiveChange=noop+ }}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ // Reporting the cursor is the other legitimate way to draw the indicator, so only the+ // absence of both is a problem.+ assert.false(+ warn.called,+ "reporting the cursor is indicator enough; only the absence of both is a problem"+ );+ });++ test("active mode: a changed activeClass is removed from the row that had it", async function (assert) {+ const state = new (class {+ @tracked cls = "--active";+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass=state.cls+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert.dom(".a").hasClass("--active", "seeded with the first class");++ state.cls = "--highlight";+ await settled();++ assert.dom(".a").hasClass("--highlight", "the new class is applied");+ assert+ .dom(".a")+ .doesNotHaveClass("--active", "and the previous one is swept off");+ });++ test("switching focusStrategy leaves no state from the previous mode", async function (assert) {+ const state = new (class {+ @tracked mode = "active-descendant";+ })();++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ role="listbox"+ {{dRovingFocus+ focusStrategy=state.mode+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert.dom(".a").hasClass("--active", "active mode seeded a highlight");++ state.mode = "roving-tabindex";+ await settled();++ assert+ .dom(".search")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "leaving active mode drops the controller's cursor"+ );+ assert+ .dom(".a")+ .doesNotHaveClass("--active", "and the highlight class goes with it");+ });++ test("active mode: a non-primary pointer press does not move the cursor", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ assert.dom(".a").hasClass("--active", "seeded on the first item");++ await triggerEvent(".b", "mousedown", { button: 2 });++ assert+ .dom(".a")+ .hasClass("--active", "a right-click leaves the cursor where it was");+ });++ test("active mode: onActiveChange identifies pointer and keyboard placement", async function (assert) {+ const changes = [];+ const onActiveChange = (item, meta) =>+ changes.push([item?.dataset.label ?? null, meta]);++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ onActiveChange=onActiveChange+ }}+ >+ <button class="a" role="option" data-label="a">A</button>+ <button class="b" role="option" data-label="b">B</button>+ <button class="c" role="option" data-label="c">C</button>+ </div>+ </template>+ );++ changes.length = 0;+ await focus(".search");+ await triggerEvent(".b", "mousedown", { button: 0 });+ await triggerKeyEvent(".search", "keydown", "ArrowDown");++ assert.deepEqual(+ changes,+ [+ ["b", { pointer: true }],+ ["c", { pointer: false }],+ ],+ "pointer placement can stay visually quiet while the following keyboard move is revealed"+ );+ });++ test("focusIndex reports failure for an index that is not a number", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button class="a" role="option">A</button>+ </div>+ </template>+ );++ assert.false(api.focusIndex(NaN), "NaN reports no item landed");+ assert.false(+ api.focusIndex(1.5),+ "a fractional index reports no item landed"+ );+ assert.dom(".a").isNotFocused("and neither moved the cursor");+ });++ test("active mode leaves author-supplied tabindex alone", async function (assert) {+ // The internal mode starts as focus, so an active-mode group crosses a mode boundary on its+ // very first run. Nothing may be handed back for a mode that never wrote anything, or the+ // author's own tabindex values are stripped and items they excluded become tab stops.+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ entryFocus="first"+ }}+ >+ <button class="a" role="option" tabindex="-1">A</button>+ <button class="b" role="option" tabindex="-1">B</button>+ </div>+ </template>+ );++ assert.dom(".a").hasClass("--active", "active mode seeded its highlight");+ assert+ .dom(".a")+ .hasAttribute("tabindex", "-1", "the author's tabindex survives");+ assert+ .dom(".b")+ .hasAttribute("tabindex", "-1", "on every item, not just the active one");+ });++ test("grid: a blocked column reaches the edge instead of sliding into another column", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option" aria-disabled="true">4</button>+ <button class="i5" role="option">5</button>+ <button class="i6" role="option">6</button>+ <button class="i7" role="option" aria-disabled="true">7</button>+ <button class="i8" role="option">8</button>+ </div>+ </template>+ );++ // A full 3x3 grid: every column exists in the last row, so nothing is ragged. Column 1 is+ // blocked all the way down, which is a vertical edge — not licence to land in column 2.+ await focus(".i1");+ await triggerKeyEvent(".i1", "keydown", "ArrowDown");++ assert.dom(".i1").isFocused("the cursor stays in its own column");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "and reports the bottom edge rather than moving diagonally"+ );+ });++ test("grid: a column blocked above a ragged last row does not skip into it", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option" aria-disabled="true">5</button>+ <button class="i6" role="option">6</button>+ </div>+ </template>+ );++ // Rows are [i0 i1 i2] [i3 i4 i5] [i6]. The cell below i2 is i5, which EXISTS but is blocked,+ // so the column is genuinely exhausted. The ragged fallback is for a column that ran out,+ // and must not fire here and drop the cursor two rows down into a different column.+ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowDown");++ assert.dom(".i2").isFocused("the cursor stays put");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "and reports the bottom of its column rather than skipping a row"+ );+ });++ test("grid: a last row with nothing navigable in it is an edge, not a sideways move", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(2, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option" aria-disabled="true">4</button>+ </div>+ </template>+ );++ // Rows are [i0 i1] [i2 i3] [i4]. The only cell below i2 is disabled, so there is nowhere to+ // go — and the fallback must not reach sideways to i2's own neighbour i3.+ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowDown");++ assert.dom(".i2").isFocused("the cursor stays put");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "and it reports the bottom edge rather than stepping across its own row"+ );+ });++ test("grid: a rectangular grid takes no ragged fallback when the cell below is the last one", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option" aria-disabled="true">5</button>+ </div>+ </template>+ );++ // Rows are [i0 i1 i2] [i3 i4 i5], so the grid is rectangular and i2's column DOES exist in+ // the last row, merely blocked. This sits exactly on the boundary where the ragged guard's+ // strict comparison is the only thing holding the fallback shut: relax it and the cursor+ // slides diagonally to i4.+ await focus(".i2");+ await triggerKeyEvent(".i2", "keydown", "ArrowDown");++ assert.dom(".i2").isFocused("the cursor stays in its own column");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "and a blocked cell at the end of a full grid is an edge, not a ragged row"+ );+ });++ test("grid: a ragged last row takes no fallback when the cursor's own column is merely blocked", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(3, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="i0" role="option">0</button>+ <button class="i1" role="option">1</button>+ <button class="i2" role="option">2</button>+ <button class="i3" role="option">3</button>+ <button class="i4" role="option">4</button>+ <button class="i5" role="option">5</button>+ <button class="i6" role="option">6</button>+ <button class="i7" role="option" aria-disabled="true">7</button>+ </div>+ </template>+ );++ // Rows are [i0 i1 i2] [i3 i4 i5] [i6 i7]. The last row IS ragged, but i4's column still+ // reaches it, since i7 exists and is only disabled, so the fallback must stay shut. Again on+ // the boundary: relaxing the guard walks back to i6 and changes column.+ await focus(".i4");+ await triggerKeyEvent(".i4", "keydown", "ArrowDown");++ assert.dom(".i4").isFocused("the cursor stays in its own column");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "and a ragged row only rescues a column that is absent, not one that is blocked"+ );+ });++ test("Enter does not activate a row that has become disabled under the cursor", async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);+ const state = new (class {+ @tracked disabled = false;+ })();++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onActivate=onActivate+ }}+ >+ <button+ class="a"+ role="option"+ aria-disabled={{if state.disabled "true" "false"}}+ >A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ // `aria-disabled` does not remove focusability, so the row keeps DOM focus and stays the+ // cursor's position even though it is no longer a legal target.+ state.disabled = true;+ await settled();++ await triggerKeyEvent(".a", "keydown", "Enter");+ assert.deepEqual(+ activated,+ [],+ "a disabled row is not activatable, however the cursor came to rest on it"+ );+ });++ test('disabledItems="focusable" lets the cursor reach an aria-disabled item', async function (assert) {+ await render(+ <template>+ <div+ role="toolbar"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".item"+ disabledItems="focusable"+ }}+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item a">A</button>+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item b" aria-disabled="true">B</button>+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item c">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "moving focus is how a screen reader user discovers the control is there at all"+ );+ });++ test('disabledItems="focusable" still refuses to activate the item', async function (assert) {+ const activated = [];+ const onActivate = (item) => activated.push(item.className);++ await render(+ <template>+ <div+ role="toolbar"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".item"+ disabledItems="focusable"+ onActivate=onActivate+ }}+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item a">A</button>+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item b" aria-disabled="true">B</button>+ </div>+ </template>+ );++ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "Enter");++ assert.deepEqual(+ activated,+ [],+ "reachable and activatable are separate, so the policy widens only the first"+ );+ });++ test('disabledItems="focusable" cannot resurrect a natively disabled control', async function (assert) {+ await render(+ <template>+ <div+ role="toolbar"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".item"+ disabledItems="focusable"+ }}+ >+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item a">A</button>+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item b" disabled>B</button>+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button class="item c">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasClass(+ "c",+ "the platform refuses focus to a disabled control, so no policy here can offer it"+ );+ });++ test("onCrossAxis reports the horizontal arrows a vertical group does not use", async function (assert) {+ const seen = [];+ const onCrossAxis = (direction, item) =>+ seen.push(`${direction}:${item.className}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ onCrossAxis=onCrossAxis+ }}+ >+ <button class="item a" role="option">A</button>+ <button class="item b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");++ assert.deepEqual(+ seen,+ ["forward:item a", "backward:item a"],+ "the resting item comes with the direction, so the consumer need not re-read activeElement"+ );+ });++ test("onCrossAxis mirrors its direction in a right-to-left group", async function (assert) {+ const seen = [];+ const onCrossAxis = (direction) => seen.push(direction);++ await render(+ <template>+ <div+ role="listbox"+ dir="rtl"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ onCrossAxis=onCrossAxis+ }}+ >+ <button class="item a" role="option">A</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");++ assert.deepEqual(+ seen,+ ["forward"],+ "the arrow pointing at where children would be is the forward one, whichever key that is"+ );+ });++ test("onCrossAxis reports the vertical arrows a horizontal group does not use", async function (assert) {+ const seen = [];+ const onCrossAxis = (direction) => seen.push(direction);++ await render(+ <template>+ <div+ role="listbox"+ dir="rtl"+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".item"+ onCrossAxis=onCrossAxis+ }}+ >+ <button class="item a" role="option">A</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowDown");++ assert.deepEqual(+ seen,+ ["forward"],+ "a menubar opens its submenu downward, and the vertical axis never mirrors"+ );+ });++ test("onCrossAxis prevents the default only when the consumer says it acted", async function (assert) {+ const handled = [];+ const onCrossAxis = (direction) => {+ handled.push(direction);+ return direction === "forward";+ };++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ onCrossAxis=onCrossAxis+ }}+ >+ <button class="item a" role="option">A</button>+ </div>+ </template>+ );++ await focus(".a");+ const item = document.querySelector(".a");++ const acted = new KeyboardEvent("keydown", {+ key: "ArrowRight",+ bubbles: true,+ cancelable: true,+ });+ item.dispatchEvent(acted);++ const declined = new KeyboardEvent("keydown", {+ key: "ArrowLeft",+ bubbles: true,+ cancelable: true,+ });+ item.dispatchEvent(declined);++ assert.true(acted.defaultPrevented, "a handled key is consumed");+ assert.false(+ declined.defaultPrevented,+ "an unhandled one keeps bubbling, which is what a leaf node or an already-collapsed row needs"+ );+ });++ test("onCrossAxis never fires for a grid, which navigates both axes", async function (assert) {+ const seen = [];+ const onCrossAxis = (direction) => seen.push(direction);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="grid"+ itemSelector=".item"+ onCrossAxis=onCrossAxis+ }}+ >+ <button class="item a" role="option">A</button>+ <button class="item b" role="option">B</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowRight");+ await triggerKeyEvent(".b", "keydown", "ArrowDown");++ assert.deepEqual(+ seen,+ [],+ "there is no unused axis to report, so a grid consumer never has to distinguish one"+ );+ });++ test("fallbackSkipsMarked seeds the tab stop past a marked item", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ aria-multiselectable="true"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ entryFocus="first"+ fallbackSkipsMarked=true+ }}+ >+ <button class="item a" role="option" aria-selected="true">A</button>+ <button class="item b" role="option" aria-selected="false">B</button>+ </div>+ </template>+ );++ assert+ .dom(".b")+ .hasAttribute(+ "tabindex",+ "0",+ "activation toggles in a multi-select list, so entry avoids arming the first Enter to remove a value"+ );+ });++ test("fallbackSkipsMarked does not skip a restored selection", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ aria-multiselectable="true"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ entryFocus="selected-or-first"+ fallbackSkipsMarked=true+ }}+ >+ <button class="item a" role="option" aria-selected="false">A</button>+ <button class="item b" role="option" aria-selected="true">B</button>+ </div>+ </template>+ );++ assert+ .dom(".b")+ .hasAttribute(+ "tabindex",+ "0",+ "the reader's marked row is restored before the first-item fallback is considered"+ );+ assert+ .dom(".a")+ .hasAttribute(+ "tabindex",+ "-1",+ "skipping marked fallbacks does not replace an existing selection with the first row"+ );+ });++ test("fallbackSkipsMarked still seeds when every item is marked", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ aria-multiselectable="true"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ entryFocus="first"+ fallbackSkipsMarked=true+ }}+ >+ <button class="item a" role="option" aria-selected="true">A</button>+ <button class="item b" role="option" aria-selected="true">B</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute(+ "tabindex",+ "0",+ "an empty seed would take the group out of the tab sequence entirely, which is worse than seeding a marked item"+ );+ });++ test("entry ignores aria-current tokens that mean not current", async function (assert) {+ const emptyToken = "";++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ entryFocus="selected-or-first"+ }}+ >+ <button+ class="item a"+ role="option"+ aria-current={{emptyToken}}+ >A</button>+ <button class="item b" role="option" aria-current="false">B</button>+ <button class="item c" role="option" aria-current="page">C</button>+ <button class="item d" role="option">D</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasAttribute(+ "aria-current",+ "",+ "the empty token is genuinely present on the first row"+ );+ assert+ .dom(".c")+ .hasAttribute(+ "tabindex",+ "0",+ "only a token that means current marks the row the entry seed prefers"+ );+ });++ test("fallbackSkipsMarked does not treat aria-current=false as marked", async function (assert) {+ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-current-lb" />+ <div+ id="rf-current-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".search"+ itemSelector=".item"+ activeClass="--active"+ entryFocus="first"+ fallbackSkipsMarked=true+ }}+ >+ <button class="item a" role="option" aria-current="false">A</button>+ <button class="item b" role="option" aria-current="false">B</button>+ </div>+ </template>+ );++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "rows that only say they are not current leave the fallback free to seed"+ );+ });++ test("changing itemSelector releases the items it no longer matches", async function (assert) {+ const state = new (class {+ @tracked selector = ".one";+ })();++ await render(+ <template>+ <div role="listbox" {{dRovingFocus itemSelector=state.selector}}>+ <button class="one a" role="option">A</button>+ <button class="two b" role="option">B</button>+ </div>+ </template>+ );++ assert.dom(".a").hasAttribute("tabindex", "0", "the first set is seeded");++ state.selector = ".two";+ await settled();++ assert+ .dom(".b")+ .hasAttribute("tabindex", "0", "the new set takes over the tab stop");+ assert+ .dom(".a")+ .doesNotHaveAttribute(+ "tabindex",+ "and the old set is released rather than left as a second tab stop"+ );+ });+});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-typeahead-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-typeahead-test.gjsnew file mode 100644index 00000000000..cfb4d9b3461--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-typeahead-test.gjs@@ -0,0 +1,786 @@+import { focus, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import TypeAhead from "discourse/ui-kit/modifiers/d-roving-focus/type-ahead";++/**+ * The practice page specifies type-ahead as matching the item whose accessible NAME starts with+ * what was typed, which is why these fixtures deliberately disagree with their own text content.+ */++function pressKey(selector, key, modifiers = {}) {+ const element = document.querySelector(selector);+ const event = new KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ ...modifiers,+ });+ element.dispatchEvent(event);+ return event;+}++module(+ "Integration | ui-kit | Modifier | dRovingFocus | type-ahead",+ function (hooks) {+ setupRenderingTest(hooks);++ test("moves the cursor to the next item whose accessible name matches", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ <button class="item c" role="option" aria-label="Cherry">3</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "b");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "the name is what a reader hears, so it is what they type against"+ );+ });++ test("matching ignores case and diacritics", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Éclair">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "e");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "case folding alone would leave e and E-acute as different letters"+ );+ });++ test("accumulates characters, so a longer query narrows further", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Bar">1</button>+ <button class="item b" role="option" aria-label="Baz">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "b");+ pressKey(".b", "a");+ pressKey(".b", "r");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "a",+ "the lone b walks off Bar onto Baz, so only an accumulated bar brings the cursor back"+ );+ });++ test("Shift produces a capital rather than being rejected as a chord", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "B", { shiftKey: true });+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "rejecting every shiftKey event makes capitals untypeable"+ );+ });++ test("a real shortcut is still left to whoever owns it", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".a");+ const event = pressKey(".a", "b", { ctrlKey: true });+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass("a", "Ctrl+B belongs to the page, not to the list");+ assert.false(event.defaultPrevented, "and it is not consumed");+ });++ test("an unmatched character leaves the cursor and native key behavior alone", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".a");+ const event = pressKey(".a", "z");+ await settled();++ assert+ .dom(".a")+ .isFocused("a query with no match leaves the reader's cursor in place");+ assert.false(+ event.defaultPrevented,+ "a failed match leaves the character available to native behavior"+ );+ });++ test("AltGr still types, since it sets both ctrlKey and altKey", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Łódź">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "ł", { ctrlKey: true, altKey: true });+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "an ISO layout produces this character with a modifier combination that is not a shortcut"+ );+ });++ test("Space activates on an empty query and extends a started one", async function (assert) {+ const activated = [];+ const visited = [];+ const onActivate = (item) => activated.push(item.className);+ const onActiveChange = (item) => visited.push(item.dataset.name);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ onActivate=onActivate+ onActiveChange=onActiveChange+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button+ class="item b"+ role="option"+ aria-label="Ap pie"+ data-name="Ap pie"+ >+ 2+ </button>+ <button+ class="item pear"+ role="option"+ aria-label="Pear"+ data-name="Pear"+ >3</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", " ");+ await settled();+ assert.deepEqual(+ activated,+ ["item a"],+ "with nothing typed, Space is activation"+ );++ pressKey(".a", "a");+ pressKey(".b", "p");+ pressKey(".b", " ");+ pressKey(".b", "p");+ await settled();++ assert+ .dom('[aria-label="Ap pie"]')+ .isFocused(+ "mid-query Space stays a character and keeps the full match"+ );+ assert.false(+ visited.includes("Pear"),+ "preserving the buffer keeps a fresh p query from wrapping onto Pear"+ );+ assert.deepEqual(+ activated,+ ["item a"],+ "and it did not also activate anything"+ );+ });++ test("characters typed into an embedded editable are left alone", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <div class="item b" role="option" aria-label="Banana">+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <input class="inner" type="text" />+ </div>+ </div>+ </template>+ );++ await focus(".inner");+ const event = pressKey(".inner", "b");+ await settled();++ assert.false(+ event.defaultPrevented,+ "the caret owns the character, and the listener element being non-editable is not the question"+ );+ });++ test("the query lapses, so a later character starts a new one", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ <button class="item c" role="option" aria-label="Ab">3</button>+ </div>+ </template>+ );++ await focus(".a");++ // Timestamps rather than a timer, so the lapse is expressed by the events themselves.+ const first = new KeyboardEvent("keydown", {+ key: "b",+ bubbles: true,+ cancelable: true,+ });+ Object.defineProperty(first, "timeStamp", { value: 1000 });+ document.querySelector(".a").dispatchEvent(first);+ await settled();++ const later = new KeyboardEvent("keydown", {+ key: "b",+ bubbles: true,+ cancelable: true,+ });+ Object.defineProperty(later, "timeStamp", { value: 99000 });+ document.activeElement.dispatchEvent(later);+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "a fresh single-character query re-matches rather than searching for bb"+ );+ });++ test("repeating a character walks the items sharing that initial", async function (assert) {+ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Apricot">2</button>+ <button class="item c" role="option" aria-label="Banana">3</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "a");+ await settled();+ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "the first press moves to the next item sharing the initial"+ );++ pressKey(".b", "a");+ await settled();+ assert+ .dom(document.activeElement)+ .hasClass(+ "a",+ "a repeated character cycles rather than searching for the literal run"+ );+ });++ test("still types when a logical count is set but nothing is off-window", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ logicalCount=2+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "b");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "b",+ "every row is mounted, so the search is complete and there is nothing to be wrong about"+ );+ assert.false(warn.calledWithMatch(/typeAhead/), "and no reason to warn");+ });++ test("declines to type-ahead over a windowed group", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ logicalCount=500+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "b");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "a",+ "searching only the mounted rows would answer with a nearer match while a truer one sits off-window"+ );+ assert.true(+ warn.calledWithMatch(/typeAhead/),+ "and says so rather than failing quietly"+ );+ });++ test("a fully mounted list keeps type-ahead when a row is disabled", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".item"+ typeAhead=true+ logicalCount=3+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button+ class="item b"+ role="option"+ aria-label="Banana"+ aria-disabled="true"+ >2</button>+ <button class="item c" role="option" aria-label="Cherry">3</button>+ </div>+ </template>+ );++ await focus(".a");+ pressKey(".a", "c");+ await settled();++ assert+ .dom(document.activeElement)+ .hasClass(+ "c",+ "a skipped row is not an off-window row, so the search still runs"+ );+ assert.false(+ warn.calledWithMatch(/typeAhead/),+ "and a complete window earns no windowed warning"+ );+ });++ test("with no cursor, a single character matches from the first item", async function (assert) {+ await render(+ <template>+ <div+ class="tri"+ role="combobox"+ tabindex="0"+ aria-controls="ta-lb"+ ></div>+ <div+ id="ta-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".tri"+ itemSelector=".item"+ activeClass="--active"+ entryFocus="none"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Apricot">2</button>+ <button class="item c" role="option" aria-label="Banana">3</button>+ </div>+ </template>+ );++ pressKey(".tri", "a");+ await settled();++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "an unseeded search begins at the top of the list"+ );++ pressKey(".tri", "a");+ await settled();++ assert+ .dom(".b")+ .hasClass(+ "--active",+ "repeating the character still cycles to the next match"+ );+ });++ test("an active-mode hit on the current row is reannounced", async function (assert) {+ await render(+ <template>+ <div+ class="controller"+ role="combobox"+ tabindex="0"+ aria-controls="ta-lb"+ ></div>+ <div+ id="ta-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector=".item"+ activeClass="--active"+ entryFocus="first"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ const activeId = document.querySelector(".a").id;+ pressKey(".controller", "a");++ assert+ .dom(".controller")+ .doesNotHaveAttribute(+ "aria-activedescendant",+ "matching the current row briefly drops the cursor so it can be announced again"+ );++ await settled();++ assert+ .dom(".a")+ .hasClass("--active", "reannouncing does not move the highlight");+ assert+ .dom(".controller")+ .hasAttribute(+ "aria-activedescendant",+ activeId,+ "the runloop restores the cursor to the same matching row"+ );+ });++ test("an editable active-mode controller keeps printable characters", async function (assert) {+ await render(+ <template>+ <input class="controller" role="combobox" aria-controls="ta-lb" />+ <div+ id="ta-lb"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=".controller"+ itemSelector=".item"+ activeClass="--active"+ entryFocus="first"+ typeAhead=true+ }}+ >+ <button class="item a" role="option" aria-label="Apple">1</button>+ <button class="item b" role="option" aria-label="Banana">2</button>+ </div>+ </template>+ );++ await focus(".controller");+ const event = pressKey(".controller", "b");+ await settled();++ assert+ .dom(".a")+ .hasClass(+ "--active",+ "the input's character does not move the listbox highlight"+ );+ assert+ .dom(".b")+ .doesNotHaveClass(+ "--active",+ "a matching row cannot claim text meant for the input"+ );+ assert.false(+ event.defaultPrevented,+ "the printable character remains available to the editable controller"+ );+ });++ test("a failed accessible-name load is retried by a later configure", async function (assert) {+ const loads = [];+ let outcome = "reject";+ const namer = (element) => element.dataset.name ?? "";+ const loader = () => {+ const promise =+ outcome === "reject"+ ? Promise.reject(new Error("simulated chunk failure"))+ : Promise.resolve(namer);+ loads.push(promise);+ return promise;+ };+ const typeAhead = new TypeAhead(loader);++ typeAhead.configure(true);+ assert.strictEqual(+ loads.length,+ 1,+ "the first configure starts one load"+ );+ await settled();++ outcome = "resolve";+ typeAhead.configure(true);+ assert.strictEqual(+ loads.length,+ 2,+ "a failed load leaves the next configure free to retry"+ );+ await settled();++ const apple = document.createElement("button");+ apple.dataset.name = "Apple";+ const banana = document.createElement("button");+ banana.dataset.name = "Banana";+ const activated = [];+ typeAhead.handle(+ new KeyboardEvent("keydown", { key: "b", cancelable: true }),+ {+ editableController: false,+ logicalCount: undefined,+ mountedCount: () => 2,+ items: () => [apple, banana],+ currentIndex: () => -1,+ activate: (item) => activated.push(item),+ reannounce: () => {},+ warnWindowed: () => {},+ }+ );+ assert.deepEqual(+ activated,+ [banana],+ "the retried namer serves the search"+ );+ });++ test("typing itself retries a failed name load", async function (assert) {+ const loads = [];+ let outcome = "reject";+ const namer = (element) => element.dataset.name ?? "";+ const loader = () => {+ const promise =+ outcome === "reject"+ ? Promise.reject(new Error("simulated chunk failure"))+ : Promise.resolve(namer);+ loads.push(promise);+ return promise;+ };+ const typeAhead = new TypeAhead(loader);++ typeAhead.configure(true);+ await settled();+ assert.strictEqual(loads.length, 1, "the configure-time load failed");++ const apple = document.createElement("button");+ apple.dataset.name = "Apple";+ const banana = document.createElement("button");+ banana.dataset.name = "Banana";+ const activated = [];+ const context = {+ editableController: false,+ logicalCount: undefined,+ mountedCount: () => 2,+ items: () => [apple, banana],+ currentIndex: () => -1,+ activate: (item) => activated.push(item),+ reannounce: () => {},+ warnWindowed: () => {},+ };++ outcome = "resolve";+ typeAhead.handle(+ new KeyboardEvent("keydown", { key: "b", cancelable: true }),+ context+ );+ assert.strictEqual(+ loads.length,+ 2,+ "a group that never reconfigures still recovers, because typing is the retry"+ );+ await settled();++ typeAhead.handle(+ new KeyboardEvent("keydown", { key: "b", cancelable: true }),+ context+ );+ assert.deepEqual(+ activated,+ [banana],+ "the keystroke after recovery searches normally"+ );+ });+ }+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-windowed-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-windowed-test.gjsnew file mode 100644index 00000000000..2b371fe9acd--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-roving-focus-windowed-test.gjs@@ -0,0 +1,1039 @@+import { focus, render, settled, triggerKeyEvent } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";++/** A mounted window of ten rows deep in a 5000-row logical list: data-index 100..109. */+const WINDOW_ROWS = Array.from({ length: 10 }, (_, i) => 100 + i);++/** A fully-mounted small list: data-index 0..9, logicalCount 10 (nothing off-window). */+const SMALL_ROWS = Array.from({ length: 10 }, (_, i) => i);++/**+ * The same ten-row window with one row disabled, so the rendered cell count and the navigable+ * count differ.+ */+const WINDOW_ROWS_ONE_DISABLED = WINDOW_ROWS.map((index) => ({+ index,+ disabled: index === 109 ? "true" : "false",+}));++module(+ "Integration | ui-kit | Modifier | dRovingFocus | windowed",+ function (hooks) {+ setupRenderingTest(hooks);++ test("focusLogicalIndex focuses a mounted logical index", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button role="option" data-index="100">100</button>+ <button role="option" data-index="101">101</button>+ <button role="option" data-index="102">102</button>+ <button role="option" data-index="103">103</button>+ <button role="option" data-index="104">104</button>+ <button role="option" data-index="105">105</button>+ <button role="option" data-index="106">106</button>+ <button role="option" data-index="107">107</button>+ <button role="option" data-index="108">108</button>+ <button role="option" data-index="109">109</button>+ </div>+ </template>+ );++ assert.strictEqual(+ typeof api?.focusLogicalIndex,+ "function",+ "the registered api exposes focusLogicalIndex"+ );+ assert.true(+ api?.focusLogicalIndex?.(105),+ "focusLogicalIndex reports it landed on the mounted logical item"+ );+ await settled();+ assert+ .dom('[data-index="105"]')+ .isFocused("focusLogicalIndex moves DOM focus to the logical item");+ assert+ .dom('[data-index="105"]')+ .hasAttribute("tabindex", "0", "the logical item becomes the tab stop");+ assert+ .dom('[data-index="100"]')+ .hasAttribute("tabindex", "-1", "the previous tab stop is cleared");+ });++ test("focusLogicalIndex does not move when the logical index is outside the mounted window", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ >+ <button role="option" data-index="104">104</button>+ <button role="option" data-index="105">105</button>+ <button role="option" data-index="106">106</button>+ </div>+ </template>+ );++ assert.true(api.focusIndex(1), "the existing api seeds the middle item");+ await settled();+ assert+ .dom('[data-index="105"]')+ .isFocused("the cursor starts in the window");++ assert.strictEqual(+ typeof api?.focusLogicalIndex,+ "function",+ "the registered api exposes focusLogicalIndex"+ );+ assert.false(+ api?.focusLogicalIndex?.(5000),+ "focusLogicalIndex reports no mounted logical item"+ );+ await settled();+ assert+ .dom('[data-index="105"]')+ .isFocused("a missing logical index does not move the cursor");+ assert+ .dom('[data-index="105"]')+ .hasAttribute(+ "tabindex",+ "0",+ "a missing index preserves the tab stop"+ );+ });++ test("focusLogicalIndex falls back to positional indexes without data-index", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="grid"+ {{dRovingFocus+ itemSelector="[role=gridcell]"+ onRegisterApi=register+ }}+ >+ <div role="row"><button class="a" role="gridcell">A</button></div>+ <div role="row"><button class="b" role="gridcell">B</button></div>+ <div role="row"><button class="c" role="gridcell">C</button></div>+ </div>+ </template>+ );++ assert.strictEqual(+ typeof api?.focusLogicalIndex,+ "function",+ "the registered api exposes focusLogicalIndex"+ );+ assert.true(+ api?.focusLogicalIndex?.(2),+ "focusLogicalIndex reports it landed by position"+ );+ await settled();+ assert.dom(".c").isFocused("the positional fallback focuses index 2");+ assert+ .dom(".c")+ .hasAttribute(+ "tabindex",+ "0",+ "the positional item becomes the tab stop"+ );+ });++ test("focusLogicalIndex returns false for an empty group", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus itemSelector="[role=option]" onRegisterApi=register}}+ ></div>+ </template>+ );++ assert.strictEqual(+ typeof api?.focusLogicalIndex,+ "function",+ "the registered api exposes focusLogicalIndex"+ );+ assert.false(+ api?.focusLogicalIndex?.(0),+ "focusLogicalIndex reports no item landed in an empty group"+ );+ });++ test("onBoundary fires at vertical edges and prevents the key", async function (assert) {+ const boundaries = [];+ const prevented = {};+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ document.querySelector(".list").addEventListener("keydown", (event) => {+ prevented[event.key] = event.defaultPrevented;+ });++ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "ArrowDown");+ assert.deepEqual(+ boundaries,+ ["vertical:forward"],+ "ArrowDown at the end reaches forward"+ );+ assert.true(prevented.ArrowDown, "ArrowDown at the end is prevented");+ assert.dom(".b").isFocused("the cursor stays on the last item");++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowUp");+ assert.deepEqual(+ boundaries,+ ["vertical:forward", "vertical:backward"],+ "ArrowUp at the start reaches backward exactly once"+ );+ assert.true(prevented.ArrowUp, "ArrowUp at the start is prevented");+ assert.dom(".a").isFocused("the cursor stays on the first item");+ });++ test("onBoundary does not fire without a cursor and ArrowDown seeds the first item", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ tabStop=false+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ </div>+ </template>+ );++ await triggerKeyEvent(".a", "keydown", "ArrowDown");+ assert.deepEqual(+ boundaries,+ [],+ "ArrowDown without a cursor does not reach an edge"+ );+ assert+ .dom(".a")+ .isFocused("ArrowDown without a cursor seeds the first item");+ });++ test("onBoundary does not fire while moving within the list or wrapping", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ wrap=true+ onBoundary=onBoundary+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowDown");+ assert.dom(".b").isFocused("ArrowDown moves within the list");+ assert.deepEqual(+ boundaries,+ [],+ "a non-edge move does not reach an edge"+ );++ await focus(".c");+ await triggerKeyEvent(".c", "keydown", "ArrowDown");+ assert.dom(".a").isFocused("ArrowDown wraps to the first item");++ await triggerKeyEvent(".a", "keydown", "ArrowUp");+ assert.dom(".c").isFocused("ArrowUp wraps to the last item");+ assert.deepEqual(+ boundaries,+ [],+ "wrapping suppresses the boundary callback"+ );+ });++ test("Home and End stay silent while horizontal edges fire onBoundary", async function (assert) {+ const boundaries = [];+ const onBoundary = (direction, axis) =>+ boundaries.push(`${axis}:${direction}`);++ await render(+ <template>+ <div+ role="listbox"+ style="display: grid; grid-template-columns: repeat(1, 40px);"+ {{dRovingFocus itemSelector="[role=option]" onBoundary=onBoundary}}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ // Home and End move without reporting anything, while the horizontal arrows at either end+ // report a boundary on their own axis. Each step also asserts where the cursor actually+ // landed, which is what would catch a key being mis-routed to the wrong axis.+ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "Home");+ assert.dom(".a").isFocused("Home moves to the first item");++ await triggerKeyEvent(".a", "keydown", "End");+ assert.dom(".c").isFocused("End moves to the last item");++ await triggerKeyEvent(".c", "keydown", "ArrowRight");+ assert.dom(".c").isFocused("ArrowRight at the last item does not move");++ await focus(".a");+ await triggerKeyEvent(".a", "keydown", "ArrowLeft");+ assert.dom(".a").isFocused("ArrowLeft at the first item does not move");++ assert.deepEqual(+ boundaries,+ ["horizontal:forward", "horizontal:backward"],+ "only the two horizontal ends report, and they report the horizontal axis — Home and End reach no boundary at all"+ );+ });+ }+);++// Home/End/PageUp/PageDown must target the LOGICAL row (0 / `logicalCount-1` / ±one+// page) over the ABSOLUTE `data-index` set, not the mounted slice. An in-window target+// lands locally; an off-window target fires `onJump(target, direction)` so the consumer+// scrolls it in and refocuses. `logicalCount` absent ⇒ Home/End keep their positional behavior+// and the PAGE keys are not claimed at all, so a scrollable container pages natively; no+// `onJump` either way. Direction: Home/PageUp → "backward", End/PageDown → "forward". Page size =+// the mounted navigable count. In ACTIVE mode PageUp/PageDown always navigate the+// listbox; Home/End navigate it only when the controller is NON-editable (select-only+// combobox) and are left for the caret when it is editable (editable combobox).+module(+ "Integration | ui-kit | Modifier | dRovingFocus | logical jumps",+ function (hooks) {+ setupRenderingTest(hooks);++ test("focus mode: End jumps to the last logical row when it is off-window", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "End");++ assert.deepEqual(+ jumps,+ [[4999, "forward"]],+ "End fires onJump for the last logical row (5000-1)"+ );+ assert.true(+ prevented.End,+ "End is prevented (the consumer owns the scroll)"+ );+ assert+ .dom('[data-index="105"]')+ .isFocused(+ "focus stays on the current row until the consumer refocuses post-scroll"+ );+ });++ test("focus mode: Home jumps to logical row 0 when it is off-window", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "Home");++ assert.deepEqual(+ jumps,+ [[0, "backward"]],+ "Home fires onJump for logical row 0"+ );+ assert.true(prevented.Home, "Home is prevented");+ });++ test("focus mode: PageDown pages down by the mounted count and clamps to the last logical row", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "PageDown");++ assert.deepEqual(+ jumps,+ [[115, "forward"]],+ "PageDown targets current (105) + page size (10 mounted rows)"+ );+ });++ test("focus mode: PageDown clamps to the last logical row", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ // 105 + a 10-row page overshoots a 112-row list, so this is the fixture that actually+ // reaches `Math.min`. The 5000-row case above is an ordinary increment and would still+ // pass with the clamp deleted.+ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=112+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "PageDown");++ assert.deepEqual(+ jumps,+ [[111, "forward"]],+ "PageDown clamps to the last logical row (112-1) instead of overshooting to 115"+ );+ });++ test("focus mode: PageUp pages up by the mounted count", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "PageUp");++ assert.deepEqual(+ jumps,+ [[95, "backward"]],+ "PageUp targets current (105) - page size (10)"+ );+ });++ test("focus mode: an in-window logical End lands locally without firing onJump", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=10+ onJump=onJump+ }}+ >+ {{#each SMALL_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus('[data-index="3"]');+ await triggerKeyEvent('[data-index="3"]', "keydown", "End");++ assert.deepEqual(jumps, [], "an in-window target does not fire onJump");+ assert+ .dom('[data-index="9"]')+ .isFocused("End moves the cursor to the mounted last logical row");+ });++ test("without logicalCount: Home/End stay positional over the mounted rows and never fire onJump", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onJump=onJump+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ await focus(".b");+ await triggerKeyEvent(".b", "keydown", "End");+ assert.dom(".c").isFocused("End goes to the last mounted item");++ await triggerKeyEvent(".c", "keydown", "Home");+ assert.dom(".a").isFocused("Home goes to the first mounted item");++ assert.deepEqual(+ jumps,+ [],+ "no logicalCount ⇒ no windowing ⇒ onJump never fires"+ );+ });++ test("active mode, non-editable controller: Home navigates the listbox (select-only combobox)", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);+ const prevented = {};++ await render(+ <template>+ <div+ class="ctrl"+ role="combobox"+ aria-controls="rf-lb"+ tabindex="0"+ ></div>+ <div+ id="rf-lb"+ class="list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".ctrl"+ itemSelector="[role=option]"+ activeClass="--active"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".ctrl")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".ctrl");+ await triggerKeyEvent(".ctrl", "keydown", "ArrowDown"); // seed the cursor on 100++ await triggerKeyEvent(".ctrl", "keydown", "Home");+ assert.deepEqual(+ jumps,+ [[0, "backward"]],+ "Home navigates the listbox when the controller has no caret"+ );+ assert.true(+ prevented.Home,+ "Home is prevented for a select-only combobox"+ );+ });++ test("active mode, editable controller: Home/End are left for the caret; PageDown still navigates the listbox", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);+ const prevented = {};++ await render(+ <template>+ <input class="search" role="combobox" aria-controls="rf-lb" />+ <div+ id="rf-lb"+ class="list"+ role="listbox"+ {{dRovingFocus+ focusStrategy="active-descendant"+ entryFocus="none"+ controllerElement=".search"+ itemSelector="[role=option]"+ activeClass="--active"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".search")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus(".search");+ await triggerKeyEvent(".search", "keydown", "ArrowDown"); // seed the cursor on 100++ await triggerKeyEvent(".search", "keydown", "Home");+ await triggerKeyEvent(".search", "keydown", "End");+ assert.deepEqual(+ jumps,+ [],+ "Home/End do not navigate the listbox on an editable combobox"+ );+ assert.false(prevented.Home, "Home is left for the input caret");+ assert.false(prevented.End, "End is left for the input caret");++ await triggerKeyEvent(".search", "keydown", "PageDown");+ assert.deepEqual(+ jumps,+ [[110, "forward"]],+ "PageDown pages the listbox even on an editable combobox (100 + 10)"+ );+ assert.true(prevented.PageDown, "PageDown is prevented");+ });++ test("without logicalCount the page keys are left to the scroll container", async function (assert) {+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus orientation="vertical" itemSelector="[role=option]"}}+ >+ {{#each SMALL_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus('[data-index="5"]');+ await triggerKeyEvent('[data-index="5"]', "keydown", "PageDown");+ assert+ .dom('[data-index="5"]')+ .isFocused(+ "PageDown does not move the cursor without a logical row count"+ );+ assert.false(+ prevented.PageDown,+ "and it falls through so the container can page natively"+ );++ await triggerKeyEvent('[data-index="5"]', "keydown", "PageUp");+ assert+ .dom('[data-index="5"]')+ .isFocused("PageUp does not move the cursor either");+ assert.false(prevented.PageUp, "and it falls through too");+ });++ test("a page is the mounted navigable count, not the rendered cell count", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ }}+ >+ {{#each WINDOW_ROWS_ONE_DISABLED key="index" as |row|}}+ <button+ role="option"+ data-index={{row.index}}+ aria-disabled={{row.disabled}}+ >{{row.index}}</button>+ {{/each}}+ </div>+ </template>+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "PageDown");++ // Ten rows are rendered but one is disabled, so a page is nine.+ assert.deepEqual(+ jumps,+ [[114, "forward"]],+ "a disabled placeholder does not lengthen the page"+ );+ });++ test("a page key with no cursor pages from the mounted window", async function (assert) {+ const jumps = [];+ const onJump = (target, direction) => jumps.push([target, direction]);++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onJump=onJump+ tabStop=false+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );++ // No cursor, so there is no current logical row to page from. Anchoring on -1 would+ // page to row 9 — backwards past the window on a PageDown.+ await triggerKeyEvent('[data-index="100"]', "keydown", "PageDown");++ assert.deepEqual(+ jumps,+ [[110, "forward"]],+ "PageDown pages forward from the window's first row, not from -1"+ );+ });++ test("a jump key is left alone when there is no onJump to service it", async function (assert) {+ const prevented = {};++ await render(+ <template>+ <div+ class="list"+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ }}+ >+ {{#each WINDOW_ROWS as |n|}}+ <button role="option" data-index={{n}}>{{n}}</button>+ {{/each}}+ </div>+ </template>+ );+ document+ .querySelector(".list")+ .addEventListener(+ "keydown",+ (e) => (prevented[e.key] = e.defaultPrevented)+ );++ await focus('[data-index="105"]');+ await triggerKeyEvent('[data-index="105"]', "keydown", "End");++ // The target is off-window and no consumer can scroll it in, so swallowing the key+ // would make End do nothing at all.+ assert.false(+ prevented.End,+ "an unserviceable jump falls through instead of becoming a dead key"+ );+ assert+ .dom('[data-index="105"]')+ .isFocused(+ "an unserviceable End leaves the cursor on its mounted starting row"+ );+ });++ test("focusLogicalIndex refuses an out-of-range index on an unstamped group", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ // Nothing is stamped, so the index is positional — but positional addressing must be+ // bounds-checked, not clamped: reporting success here would tell a windowed consumer the+ // jump had been serviced when the row was never reached.+ assert.false(+ api.focusLogicalIndex(4999),+ "an index past the mounted rows reports no landing"+ );+ assert+ .dom(".c")+ .isNotFocused("and the cursor is not clamped onto the last row");++ assert.true(api.focusLogicalIndex(2), "an in-range index still lands");+ assert.dom(".c").isFocused("on the row at that position");+ });++ test("a logical index prefers data-logical-index over data-index", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onRegisterApi=register+ }}+ >+ <button+ class="a"+ role="option"+ data-index="0"+ data-logical-index="40"+ >A</button>+ <button+ class="b"+ role="option"+ data-index="1"+ data-logical-index="41"+ >B</button>+ </div>+ </template>+ );++ // A windowed list with non-option rows stamps its own option ordinal, which must win over+ // the raw virtualizer index.+ assert.true(+ api.focusLogicalIndex(41),+ "the logical ordinal identifies the row"+ );+ assert.dom(".b").isFocused("and the cursor lands on it");++ assert.false(+ api.focusLogicalIndex(1),+ "the raw virtualizer index is not what is addressed"+ );+ });++ test("a logical index matches its row however the attribute is written", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ logicalCount=5000+ onRegisterApi=register+ }}+ >+ <button class="r1" role="option" data-index="0105">105</button>+ <button class="r2" role="option" data-index="106">106</button>+ </div>+ </template>+ );++ assert.true(+ api.focusLogicalIndex(105),+ "a zero-padded index still identifies its row"+ );+ assert.dom(".r1").isFocused("and the cursor lands on it");+ });++ test("focusLogicalIndex declines a fractional index on an unstamped list", async function (assert) {+ let api = null;+ const register = (value) => (api = value);++ await render(+ <template>+ <div+ role="listbox"+ {{dRovingFocus+ orientation="vertical"+ itemSelector="[role=option]"+ onRegisterApi=register+ }}+ >+ <button class="a" role="option">A</button>+ <button class="b" role="option">B</button>+ <button class="c" role="option">C</button>+ </div>+ </template>+ );++ assert.false(+ api.focusLogicalIndex(1.5),+ "a fractional index reports false instead of landing between rows"+ );+ await settled();+ assert+ .dom(".a")+ .hasAttribute(+ "tabindex",+ "0",+ "the seeded tab stop is untouched by the declined call"+ );+ });+ }+);diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/adjacent-groups.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/adjacent-groups.gjsnew file mode 100644index 00000000000..ba70cae9e6e--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/adjacent-groups.gjs@@ -0,0 +1,113 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const FILTERS = ["open", "mine", "recent"];++/**+ * A group that is NOT a tab stop, sitting beside a control that is.+ *+ * Tab reaches the field and nothing else: the filters are not in the tab sequence at all, which+ * is what `tabStop=false` means and why the whole arrangement counts as one component rather+ * than two. Reaching the filters is a step from the field, and running off their end is a step+ * back to it.+ *+ * That return trip is what the boundary report is for. The modifier says the cursor tried to+ * leave and in which direction; it does not decide where to send it, because only this component+ * knows the field is there. The direction is logical, so this keeps working in a right-to-left+ * locale. Entry resolves the field's computed direction too, so its caret-facing arrow mirrors+ * with the return trip.+ */+export default class RovingFocusAdjacentGroupsExample extends Component {+ @tracked active = ["open"];+ @tracked filterApi = null;+ @tracked field = null;++ get filters() {+ return FILTERS.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.adjacent.${id}`),+ pressed: this.active.includes(id) ? "true" : "false",+ }));+ }++ @action+ captureField(element) {+ this.field = element;+ }++ @action+ enterFilters(event) {+ const entryKey =+ getComputedStyle(event.target).direction === "rtl"+ ? "ArrowRight"+ : "ArrowLeft";++ // Only from the very start of the text, so the arrow keeps its caret meaning everywhere else.+ if (event.key === entryKey && event.target.selectionStart === 0) {+ event.preventDefault();+ this.filterApi?.focusLast();+ }+ }++ @action+ leaveFilters(direction) {+ if (direction === "forward") {+ this.field?.focus();+ }+ }++ @action+ registerFilters(api) {+ this.filterApi = api;+ }++ @action+ toggle(id) {+ this.active = this.active.includes(id)+ ? this.active.filter((entry) => entry !== id)+ : [...this.active, id];+ }++ <template>+ <div class="roving-demo__adjacent">+ <div+ class="roving-demo__filters"+ role="group"+ aria-label={{i18n "styleguide.sections.roving_focus.adjacent.label"}}+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".roving-demo__filter"+ tabStop=false+ onBoundary=this.leaveFilters+ onRegisterApi=this.registerFilters+ }}+ >+ {{#each this.filters key="id" as |filter|}}+ <button+ type="button"+ class="roving-demo__filter"+ aria-pressed={{filter.pressed}}+ {{on "click" (fn this.toggle filter.id)}}+ >{{filter.label}}</button>+ {{/each}}+ </div>++ <input+ class="roving-demo__field"+ type="text"+ aria-label={{i18n "styleguide.sections.roving_focus.adjacent.field"}}+ placeholder={{i18n+ "styleguide.sections.roving_focus.adjacent.placeholder"+ }}+ {{didInsert this.captureField}}+ {{on "keydown" this.enterFilters}}+ />+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/combobox.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/combobox.gjsnew file mode 100644index 00000000000..e747385c4ce--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/combobox.gjs@@ -0,0 +1,147 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const OPTIONS = ["daily", "weekly", "monthly", "never"];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/combobox/+ *+ * The other examples move DOM focus between items. This one does not, and that is the whole+ * point of it: focus stays on the control the reader arrived at, while a virtual cursor moves+ * through the options and the control reports where it is with `aria-activedescendant`.+ *+ * Watch the focus ring while arrowing. It never leaves the button, yet the highlight moves and+ * a screen reader announces each option, because what is announced follows the attribute rather+ * than the focus.+ *+ * The listbox is reachable from the controller through `aria-controls`, which is one of the+ * three relationships the specification permits between a control and the descendant it points+ * at. Pointing across to an unrelated element instead is the mistake the modifier warns about+ * in development, and it is easy to make once a popup is portaled somewhere else in the DOM.+ */+export default class RovingFocusComboboxExample extends Component {+ @tracked controller = null;+ @tracked expanded = false;+ @tracked selected = "weekly";++ get rows() {+ return OPTIONS.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.combobox.${id}`),+ selected: this.selected === id ? "true" : "false",+ }));+ }++ get selectedLabel() {+ return i18n(`styleguide.sections.roving_focus.combobox.${this.selected}`);+ }++ @action+ captureController(element) {+ this.controller = element;+ }++ @action+ choose(item) {+ this.selected = item.dataset.optionId;+ this.expanded = false;+ }++ @action+ handleListboxClick(event) {+ const option = event.target.closest("[data-option-id]");+ if (option) {+ this.choose(option);+ }+ }++ @action+ handleListboxMouseDown(event) {+ event.preventDefault();+ }++ @action+ handleTriggerKeydown(event) {+ if (event.key === "Escape" && this.expanded) {+ event.preventDefault();+ this.expanded = false;+ } else if (this.expanded && (event.key === " " || event.key === "Tab")) {+ // Space commits like Enter, and Tab commits on its way out; both close. Space is+ // prevented so the native button click does not reopen the popup, while Tab keeps its+ // default so focus still leaves.+ if (event.key === " ") {+ event.preventDefault();+ }+ const active = document.getElementById(+ event.target.getAttribute("aria-activedescendant") ?? ""+ );+ if (active) {+ this.choose(active);+ } else {+ this.expanded = false;+ }+ } else if (+ !this.expanded &&+ (event.key === "ArrowDown" || event.key === "ArrowUp")+ ) {+ event.preventDefault();+ this.expanded = true;+ }+ }++ @action+ toggle() {+ this.expanded = !this.expanded;+ }++ <template>+ <div class="roving-demo__combobox">+ <button+ type="button"+ class="roving-demo__combobox-trigger"+ role="combobox"+ aria-expanded={{if this.expanded "true" "false"}}+ aria-controls={{if this.expanded "roving-demo-combobox-listbox"}}+ aria-label={{i18n "styleguide.sections.roving_focus.combobox.label"}}+ {{didInsert this.captureController}}+ {{on "click" this.toggle}}+ {{on "keydown" this.handleTriggerKeydown}}+ >{{this.selectedLabel}}</button>++ {{#if this.expanded}}+ <ul+ id="roving-demo-combobox-listbox"+ class="roving-demo__combobox-listbox"+ role="listbox"+ {{on "click" this.handleListboxClick}}+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}+ {{on "mousedown" this.handleListboxMouseDown}}+ {{dRovingFocus+ focusStrategy="active-descendant"+ controllerElement=this.controller+ itemSelector=".roving-demo__combobox-option"+ activeClass="--active"+ entryFocus="selected-or-first"+ onActivate=this.choose+ }}+ >+ {{#each this.rows key="id" as |row|}}+ <li+ class="roving-demo__combobox-option"+ role="option"+ data-option-id={{row.id}}+ aria-selected={{row.selected}}+ >+ {{row.label}}+ </li>+ {{/each}}+ </ul>+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/listbox.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/listbox.gjsnew file mode 100644index 00000000000..f50a39f26b4--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/listbox.gjs@@ -0,0 +1,78 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const OPTIONS = [+ { id: "apple", count: 12 },+ { id: "apricot", count: 3 },+ { id: "banana", count: 47 },+ { id: "blackberry", count: 8 },+ { id: "cherry", count: 21 },+ { id: "coconut", count: 5 },+];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/listbox/+ *+ * The APG listbox pattern, and the only example here that types.+ *+ * The labels share initials on purpose. A single character walks the options sharing it, while a+ * longer query keeps the option under the cursor for as long as it still matches, so reaching+ * Apricot from Apple takes `apr` rather than `ap`.+ *+ * Matching is on the accessible name rather than on the text. Each row carries a decorative+ * count that belongs to its text but not to its name, so the difference between matching one+ * and matching the other is visible rather than asserted: typing a digit finds nothing.+ *+ * Entry restores the chosen row, which is the listbox convention and the opposite of the+ * toolbar's. Selection is moved by activation rather than by the cursor, so arrowing through+ * the list reads each option without committing to it.+ */+export default class RovingFocusListboxExample extends Component {+ @tracked selected = "banana";++ get rows() {+ return OPTIONS.map((option) => ({+ ...option,+ label: i18n(`styleguide.sections.roving_focus.listbox.${option.id}`),+ selected: this.selected === option.id ? "true" : "false",+ }));+ }++ @action+ select(item) {+ this.selected = item.dataset.optionId;+ }++ <template>+ <ul+ class="roving-demo__listbox"+ role="listbox"+ aria-label={{i18n "styleguide.sections.roving_focus.listbox.label"}}+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".roving-demo__option"+ entryFocus="selected-or-first"+ typeAhead=true+ onActivate=this.select+ }}+ >+ {{#each this.rows key="id" as |row|}}+ <li+ class="roving-demo__option"+ role="option"+ data-option-id={{row.id}}+ aria-selected={{row.selected}}+ >+ {{row.label}}+ <span+ class="roving-demo__count"+ aria-hidden="true"+ >{{row.count}}</span>+ </li>+ {{/each}}+ </ul>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/multi-select.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/multi-select.gjsnew file mode 100644index 00000000000..cd7b933062e--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/multi-select.gjs@@ -0,0 +1,71 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const OPTIONS = ["keyboard", "contrast", "captions", "motion", "labels"];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/listbox/ in its multi-select form.+ *+ * Entry lands on the first chosen row, which is what the pattern asks for: if one or more+ * options are selected before the listbox receives focus, focus is set on the first selected+ * one. The reader is returned to their own selection rather than to the top. The first option+ * is chosen on purpose so that is visible.+ *+ * This accepts a hazard knowingly, because the pattern does. Space toggles the focused option,+ * so starting on a chosen one means the next Space removes it. A combobox popup, where a cursor+ * is seeded automatically and Enter reads as "take this", has better reason to avoid that and+ * can, but a listbox the reader tabbed into deliberately and can see is not that case.+ *+ * Wrapping is on, so passing the last row returns to the first instead of stopping. A list this+ * short makes that worth having; a very long one usually does not, which is why it is a choice+ * rather than a default.+ */+export default class RovingFocusMultiSelectExample extends Component {+ @tracked chosen = ["keyboard"];++ get rows() {+ return OPTIONS.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.multi.${id}`),+ selected: this.chosen.includes(id) ? "true" : "false",+ }));+ }++ @action+ toggle(item) {+ const id = item.dataset.optionId;+ this.chosen = this.chosen.includes(id)+ ? this.chosen.filter((chosen) => chosen !== id)+ : [...this.chosen, id];+ }++ <template>+ <ul+ class="roving-demo__listbox"+ role="listbox"+ aria-multiselectable="true"+ aria-label={{i18n "styleguide.sections.roving_focus.multi.label"}}+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".roving-demo__option"+ entryFocus="selected-or-first"+ wrap=true+ onActivate=this.toggle+ }}+ >+ {{#each this.rows key="id" as |row|}}+ <li+ class="roving-demo__option"+ role="option"+ data-option-id={{row.id}}+ aria-selected={{row.selected}}+ >+ {{row.label}}+ </li>+ {{/each}}+ </ul>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/radio-group.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/radio-group.gjsnew file mode 100644index 00000000000..418b174fa8a--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/radio-group.gjs@@ -0,0 +1,67 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const CHOICES = ["left", "center", "right"];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/radio/+ *+ * The APG radio group pattern, and the one place selection is meant to follow the cursor.+ *+ * A radio group states which member it is checked on with `aria-checked` rather than+ * `aria-selected`, so this is the example that covers that spelling: entry lands on the checked+ * member, not the first, which is what a reader returning to the group expects.+ *+ * Unlike the listbox, moving the cursor also moves the checked state. The practice page treats+ * that as the consumer's call rather than the modifier's, so it is wired here through the+ * callback that reports cursor movement. No activation handler is needed as a result: the+ * member under the cursor is always the checked one, leaving Space nothing to do.+ */+export default class RovingFocusRadioGroupExample extends Component {+ @tracked checked = "center";++ get choices() {+ return CHOICES.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.radio.${id}`),+ checked: this.checked === id ? "true" : "false",+ }));+ }++ @action+ check(item) {+ // The null argument is an active-mode signal, so a roving-tabindex group never sees one; the+ // guard keeps the callback honest against its own contract rather than against this group.+ if (item) {+ this.checked = item.dataset.choiceId;+ }+ }++ <template>+ <div+ class="roving-demo__radios"+ role="radiogroup"+ aria-label={{i18n "styleguide.sections.roving_focus.radio.label"}}+ {{dRovingFocus+ itemSelector=".roving-demo__radio"+ entryFocus="selected-or-first"+ onActiveChange=this.check+ wrap=true+ }}+ >+ {{#each this.choices key="id" as |choice|}}+ <span+ class="roving-demo__radio"+ role="radio"+ data-choice-id={{choice.id}}+ aria-checked={{choice.checked}}+ >+ {{choice.label}}+ </span>+ {{/each}}+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/removable-tags.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/removable-tags.gjsnew file mode 100644index 00000000000..9bd7108b373--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/removable-tags.gjs@@ -0,0 +1,88 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const TAGS = ["design", "keyboard", "release", "support"];++/**+ * The one example built from a real component rather than from bare markup, and the only one+ * where items are destroyed under the cursor.+ *+ * Two things only show up in this combination. Removing the focused tag unmounts the element+ * holding the cursor, so focus falls to the document body unless the modifier moves it, which+ * is the persistence behaviour the practice page calls essential. And the button defers its+ * action through the runloop, so the removal lands a tick after the key that asked for it,+ * which is the ordering a hand-written fixture does not reproduce.+ *+ * `itemsKey` is load-bearing here rather than an optimisation. The tags are component state the+ * modifier cannot observe, and it only reconciles when a named argument changes, so without the+ * key it never learns the item is gone and focus is left on the page. Persistence is on by+ * default but still depends on being told.+ *+ * When the last tag goes there is nothing left to hold a cursor, and the modifier deliberately+ * does nothing rather than inventing a destination. Landing somewhere sensible from there is+ * the consumer's decision, because only it knows what sits outside the group.+ */+export default class RovingFocusRemovableTagsExample extends Component {+ @tracked tags = TAGS;++ get rows() {+ return this.tags.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.tags.${id}`),+ }));+ }++ @action+ remove(id) {+ this.tags = this.tags.filter((tag) => tag !== id);+ }++ @action+ reset() {+ this.tags = TAGS;+ }++ <template>+ <div class="roving-demo__tags">+ <div+ class="roving-demo__tag-bar"+ role="toolbar"+ aria-label={{i18n "styleguide.sections.roving_focus.tags.label"}}+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".roving-demo__tag"+ entryFocus="first"+ itemsKey=this.tags+ }}+ >+ {{#each this.rows key="id" as |row|}}+ <DButton+ class="roving-demo__tag"+ @icon="xmark"+ @translatedLabel={{row.label}}+ @translatedAriaLabel={{i18n+ "styleguide.sections.roving_focus.tags.remove"+ tag=row.label+ }}+ @action={{fn this.remove row.id}}+ />+ {{/each}}+ </div>++ {{#unless this.tags.length}}+ <DButton+ class="roving-demo__reset"+ @translatedLabel={{i18n+ "styleguide.sections.roving_focus.tags.reset"+ }}+ @action={{this.reset}}+ />+ {{/unless}}+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/toolbar.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/toolbar.gjsnew file mode 100644index 00000000000..7c6dd6c31e3--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/toolbar.gjs@@ -0,0 +1,105 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const TOGGLES = ["bold", "italic", "underline"];++const COMMANDS = [+ { id: "copy" },+ { id: "cut", disabled: true },+ { id: "paste", ariaDisabled: true },+];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/+ *+ * The APG toolbar pattern in plain semantic HTML: the whole bar is one tab stop, the arrows move+ * between controls, and Home/End reach the ends.+ *+ * Activation is deliberately not wired. The modifier only calls preventDefault on Enter and+ * Space when a consumer passes onActivate, so leaving it off lets the native buttons keep their+ * own activation, which is what a real toolbar wants.+ *+ * Entry is pinned to the first control because that is the toolbar convention, and it is the one+ * pattern where a marked item must NOT win: a button marking the current view would otherwise+ * take the tab stop away from the first.+ *+ * The last two commands spell disabled differently on purpose, and under this policy they behave+ * differently: the natively disabled one is skipped because the platform will not focus it,+ * while the aria-disabled one keeps its place in the sequence. Moving focus to a control is how+ * a screen reader user discovers it exists, so the second stays reachable without ever becoming+ * operable.+ */+export default class RovingFocusToolbarExample extends Component {+ @tracked pressed = {};++ get toggles() {+ return TOGGLES.map((id) => ({+ id,+ label: i18n(`styleguide.sections.roving_focus.toolbar.${id}`),+ pressed: this.pressed[id] ? "true" : "false",+ }));+ }++ get commands() {+ return COMMANDS.map((command) => ({+ ...command,+ label: i18n(`styleguide.sections.roving_focus.toolbar.${command.id}`),+ ariaDisabled: command.ariaDisabled ? "true" : undefined,+ }));+ }++ @action+ toggle(id) {+ this.pressed = { ...this.pressed, [id]: !this.pressed[id] };+ }++ <template>+ <div+ class="roving-demo__toolbar"+ role="toolbar"+ aria-label={{i18n "styleguide.sections.roving_focus.toolbar.label"}}+ {{dRovingFocus+ orientation="horizontal"+ itemSelector=".roving-demo__item"+ entryFocus="first"+ disabledItems="focusable"+ }}+ >+ {{#each this.toggles key="id" as |item|}}+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button+ type="button"+ class="roving-demo__item"+ aria-pressed={{item.pressed}}+ {{on "click" (fn this.toggle item.id)}}+ >{{item.label}}</button>+ {{/each}}++ <span+ class="roving-demo__separator"+ role="separator"+ aria-orientation="vertical"+ ></span>++ {{#each this.commands key="id" as |command|}}+ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <button+ type="button"+ class="roving-demo__item"+ disabled={{command.disabled}}+ aria-disabled={{command.ariaDisabled}}+ >{{command.label}}</button>+ {{/each}}++ {{! eslint-disable-next-line ember/template-no-nested-interactive }}+ <a class="roving-demo__item" href="https://www.w3.org/WAI/ARIA/apg/">+ {{i18n "styleguide.sections.roving_focus.toolbar.docs"}}+ </a>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/tree.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/tree.gjsnew file mode 100644index 00000000000..92ae044af20--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/roving-focus/tree.gjs@@ -0,0 +1,154 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import dRovingFocus from "discourse/ui-kit/modifiers/d-roving-focus";+import { i18n } from "discourse-i18n";++const NODES = [+ { id: "components", level: 1 },+ { id: "button", level: 2, parent: "components" },+ { id: "select", level: 2, parent: "components" },+ { id: "modifiers", level: 1 },+ { id: "roving_focus", level: 2, parent: "modifiers" },+ { id: "auto_focus", level: 2, parent: "modifiers" },+];++/**+ * Mirrors https://www.w3.org/WAI/ARIA/apg/patterns/treeview/+ *+ * The APG tree pattern in plain semantic HTML. The modifier runs vertically over the visible+ * rows, which is the whole of what it claims here: hierarchy is the consumer's.+ *+ * The cross-axis event implements the tree's four-way contract: forward opens a closed parent+ * or enters an open parent's first child, while backward closes an open parent or returns a+ * child to its parent. The modifier resolves which physical arrow is forward.+ *+ * The consequence is visible in the right-to-left copy: the arrow that points at a row's+ * children is the one that opens them, without this component knowing that writing directions+ * exist.+ *+ * @param dir - Writing direction to render under, either ltr or rtl.+ */+export default class RovingFocusTreeExample extends Component {+ @tracked expanded = { components: true };++ #api = null;++ get rows() {+ return NODES.filter(+ (node) => node.level === 1 || this.expanded[node.parent]+ ).map((node) => ({+ ...node,+ label: i18n(`styleguide.sections.roving_focus.tree.${node.id}`),+ isParent: this.#isParent(node.id),+ expanded: this.expanded[node.id] ? "true" : "false",+ }));+ }++ /**+ * Enter and Space on a parent toggle it. Unlike the cross-axis keys this is safe to route+ * through the modifier, since a row is not a native control and has no activation of its own+ * to lose.+ */+ @action+ activateRow(item) {+ this.#toggle(item.dataset.nodeId);+ }++ @action+ handleClick(event) {+ const row = event.target.closest("[data-node-id]");+ if (row) {+ this.#toggle(row.dataset.nodeId);+ }+ }++ @action+ handleCrossAxis(direction, item) {+ const id = item.dataset.nodeId;+ const isParent = this.#isParent(id);+ const isOpen = Boolean(this.expanded[id]);++ if (direction === "forward") {+ if (isParent && !isOpen) {+ this.#setExpanded(id, true);+ return true;+ }++ if (isParent) {+ const child = this.#api+ ?.items()+ .find((row) => row.dataset.parent === id);+ return child ? this.#api.focusElement(child) : false;+ }++ return false;+ }++ if (isParent && isOpen) {+ this.#setExpanded(id, false);+ return true;+ }++ const parentId = item.dataset.parent;+ if (parentId) {+ const parent = this.#api+ ?.items()+ .find((row) => row.dataset.nodeId === parentId);+ return parent ? this.#api.focusElement(parent) : false;+ }++ return false;+ }++ @action+ registerApi(api) {+ this.#api = api;+ }++ #isParent(id) {+ return NODES.some((node) => node.parent === id);+ }++ #setExpanded(id, next) {+ this.expanded = { ...this.expanded, [id]: next };+ }++ #toggle(id) {+ if (this.#isParent(id)) {+ this.#setExpanded(id, !this.expanded[id]);+ }+ }++ <template>+ <ul+ class="roving-demo__tree"+ dir={{@dir}}+ role="tree"+ aria-label={{i18n "styleguide.sections.roving_focus.tree.label"}}+ {{on "click" this.handleClick}}+ {{dRovingFocus+ orientation="vertical"+ itemSelector=".roving-demo__row"+ entryFocus="selected-or-first"+ onActivate=this.activateRow+ onCrossAxis=this.handleCrossAxis+ onRegisterApi=this.registerApi+ }}+ >+ {{#each this.rows key="id" as |row|}}+ <li+ class="roving-demo__row"+ role="treeitem"+ data-node-id={{row.id}}+ data-parent={{row.parent}}+ aria-level={{row.level}}+ aria-expanded={{if row.isParent row.expanded}}+ >+ {{row.label}}+ </li>+ {{/each}}+ </ul>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/roving-focus.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/roving-focus.gjsnew file mode 100644index 00000000000..9451329ba43--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/roving-focus.gjs@@ -0,0 +1,176 @@+import Component from "@glimmer/component";+import { i18n } from "discourse-i18n";+import RovingFocusAdjacentGroupsExample from "../../examples/molecules/roving-focus/adjacent-groups";+import rovingFocusAdjacentGroupsSource from "../../examples/molecules/roving-focus/adjacent-groups?source=file";+import RovingFocusComboboxExample from "../../examples/molecules/roving-focus/combobox";+import rovingFocusComboboxSource from "../../examples/molecules/roving-focus/combobox?source=file";+import RovingFocusListboxExample from "../../examples/molecules/roving-focus/listbox";+import rovingFocusListboxSource from "../../examples/molecules/roving-focus/listbox?source=file";+import RovingFocusMultiSelectExample from "../../examples/molecules/roving-focus/multi-select";+import rovingFocusMultiSelectSource from "../../examples/molecules/roving-focus/multi-select?source=file";+import RovingFocusRadioGroupExample from "../../examples/molecules/roving-focus/radio-group";+import rovingFocusRadioGroupSource from "../../examples/molecules/roving-focus/radio-group?source=file";+import RovingFocusRemovableTagsExample from "../../examples/molecules/roving-focus/removable-tags";+import rovingFocusRemovableTagsSource from "../../examples/molecules/roving-focus/removable-tags?source=file";+import RovingFocusToolbarExample from "../../examples/molecules/roving-focus/toolbar";+import rovingFocusToolbarSource from "../../examples/molecules/roving-focus/toolbar?source=file";+import RovingFocusTreeExample from "../../examples/molecules/roving-focus/tree";+import rovingFocusTreeSource from "../../examples/molecules/roving-focus/tree?source=file";+import StyleguideExample from "../../styleguide-example";+import StyleguideGroups from "../../styleguide-groups";++const GROUPS = [+ "toolbar",+ "listbox",+ "combobox",+ "radio",+ "tree",+ "adjacent",+ "components",+];++/**+ * Conformance demos for the roving-focus modifier, mirroring the interactive examples in the+ * WAI-ARIA Authoring Practices at+ * https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/+ *+ * Deliberately plain semantic HTML rather than shared components. A failure here is+ * unambiguously the modifier's, which is the point of this tier; the same patterns built from+ * real components belong beside it later, where the interesting failures actually live.+ */+export default class RovingFocus extends Component {+ get groups() {+ return GROUPS.map((id) => ({+ id,+ title: i18n(`styleguide.sections.roving_focus.groups.${id}.title`),+ description: i18n(+ `styleguide.sections.roving_focus.groups.${id}.description`+ ),+ }));+ }++ <template>+ <p class="section-description">+ {{i18n "styleguide.sections.roving_focus.description"}}+ </p>++ <StyleguideGroups+ @groups={{this.groups}}+ @section={{@section}}+ @active={{@group}}+ @ariaLabel={{i18n "styleguide.sections.roving_focus.groups.aria_label"}}+ as |Group|+ >+ <Group @id="toolbar">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.toolbar.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.toolbar.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.toolbar.try_this"}}+ @code={{rovingFocusToolbarSource}}+ >+ <RovingFocusToolbarExample />+ </StyleguideExample>+ </Group>++ <Group @id="listbox">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.multi.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.multi.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.multi.try_this"}}+ @code={{rovingFocusMultiSelectSource}}+ >+ <RovingFocusMultiSelectExample />+ </StyleguideExample>+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.listbox.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.listbox.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.listbox.try_this"}}+ @code={{rovingFocusListboxSource}}+ >+ <RovingFocusListboxExample />+ </StyleguideExample>+ </Group>++ <Group @id="combobox">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.combobox.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.combobox.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.combobox.try_this"}}+ @code={{rovingFocusComboboxSource}}+ >+ <RovingFocusComboboxExample />+ </StyleguideExample>+ </Group>++ <Group @id="radio">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.radio.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.radio.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.radio.try_this"}}+ @code={{rovingFocusRadioGroupSource}}+ >+ <RovingFocusRadioGroupExample />+ </StyleguideExample>+ </Group>++ <Group @id="tree">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.tree.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.tree.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.tree.try_this"}}+ @code={{rovingFocusTreeSource}}+ >+ <RovingFocusTreeExample @dir="ltr" />+ </StyleguideExample>++ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.tree.rtl_example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.tree.rtl_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.tree.rtl_try_this"}}+ >+ <RovingFocusTreeExample @dir="rtl" />+ </StyleguideExample>+ </Group>++ <Group @id="adjacent">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.adjacent.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.adjacent.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.adjacent.try_this"}}+ @code={{rovingFocusAdjacentGroupsSource}}+ >+ <RovingFocusAdjacentGroupsExample />+ </StyleguideExample>+ </Group>++ <Group @id="components">+ <StyleguideExample+ @title={{i18n "styleguide.sections.roving_focus.tags.example"}}+ @description={{i18n+ "styleguide.sections.roving_focus.tags.example_description"+ }}+ @tryThis={{i18n "styleguide.sections.roving_focus.tags.try_this"}}+ @code={{rovingFocusRemovableTagsSource}}+ >+ <RovingFocusRemovableTagsExample />+ </StyleguideExample>+ </Group>+ </StyleguideGroups>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.jsindex f2dd54bc566..ccd8afdf67e 100644--- a/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js+++ b/plugins/styleguide/assets/javascripts/discourse/lib/styleguide.js@@ -22,6 +22,7 @@ import multiselect from "../components/sections/molecules/multi-select";import navigationBar from "../components/sections/molecules/navigation-bar";import navigationStacked from "../components/sections/molecules/navigation-stacked";import postMenu from "../components/sections/molecules/post-menu";+import rovingFocus from "../components/sections/molecules/roving-focus";import segmentedControl from "../components/sections/molecules/segmented-control";import signupCta from "../components/sections/molecules/signup-cta";import toasts from "../components/sections/molecules/toasts";@@ -85,6 +86,7 @@ const SECTIONS = [id: "navigation-stacked",},{ component: postMenu, category: "molecules", id: "post-menu" },+ { component: rovingFocus, category: "molecules", id: "roving-focus" },{ component: tooltips, category: "molecules", id: "tooltips" },{ component: menus, category: "molecules", id: "menus" },{ component: multiselect, category: "molecules", id: "multi-select" },diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scssindex b8ec188f3da..25195282c15 100644--- a/plugins/styleguide/assets/stylesheets/styleguide.scss+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss@@ -759,6 +759,203 @@}}+.roving-demo {+ &__toolbar {+ display: flex;+ align-items: center;+ gap: 0.25em;+ padding: 0.5em;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__separator {+ width: 1px;+ align-self: stretch;+ margin: 0 0.5em;+ background: var(--primary-low);+ }++ &__item {+ padding: 0.25em 0.75em;+ border: 1px solid transparent;+ border-radius: var(--d-border-radius);+ background: none;+ color: var(--primary);+ cursor: pointer;++ &[aria-pressed="true"] {+ background: var(--tertiary-low);+ border-color: var(--tertiary);+ }++ &:disabled,+ &[aria-disabled="true"] {+ color: var(--primary-medium);+ cursor: not-allowed;+ }+ }++ &__tag-bar {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ min-height: 2.5em;+ align-items: center;+ }++ &__adjacent {+ display: flex;+ align-items: center;+ gap: 0.75em;+ flex-wrap: wrap;+ }++ &__filters {+ display: flex;+ gap: 0.25em;+ }++ &__filter {+ padding: 0.25em 0.75em;+ border: 1px solid var(--primary-low);+ border-radius: 2em;+ background: none;+ color: var(--primary);+ cursor: pointer;++ &[aria-pressed="true"] {+ background: var(--tertiary-low);+ border-color: var(--tertiary);+ }+ }++ &__combobox {+ position: relative;+ width: fit-content;+ }++ &__combobox-trigger {+ padding: 0.35em 0.75em;+ border: 1px solid var(--primary-medium);+ border-radius: var(--d-border-radius);+ background: var(--secondary);+ color: var(--primary);+ cursor: pointer;+ min-width: 10em;+ text-align: start;+ }++ &__combobox-listbox {+ position: absolute;+ top: 100%;+ inset-inline-start: 0;+ z-index: z("dropdown");+ margin: 0.25em 0 0;+ padding: 0.25em;+ list-style: none;+ min-width: 100%;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ background: var(--secondary);+ }++ &__combobox-option {+ padding: 0.25em 0.5em;+ cursor: pointer;++ // The highlight is drawn from a class the modifier toggles, not from focus, because focus+ // never arrives here.+ &.--active {+ background: var(--tertiary-low);+ }++ &[aria-selected="true"]::after {+ content: "✓";+ float: inline-end;+ }+ }++ &__listbox {+ margin: 0;+ padding: 0.5em;+ list-style: none;+ max-width: 20em;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__option {+ display: flex;+ justify-content: space-between;+ gap: 1em;+ padding: 0.25em 0.5em;+ cursor: pointer;++ &[aria-selected="true"] {+ background: var(--tertiary-low);+ }+ }++ &__count {+ color: var(--primary-medium);+ font-variant-numeric: tabular-nums;+ }++ &__radios {+ display: flex;+ gap: 0.25em;+ padding: 0.5em;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ width: fit-content;+ }++ &__radio {+ padding: 0.25em 0.75em;+ border: 1px solid transparent;+ border-radius: var(--d-border-radius);+ cursor: pointer;++ &[aria-checked="true"] {+ background: var(--tertiary-low);+ border-color: var(--tertiary);+ }+ }++ &__tree {+ margin: 0;+ padding: 0.5em;+ list-style: none;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__row {+ padding: 0.25em 0.5em;+ cursor: pointer;++ // The rows are a flat list, so depth has to be drawn from aria-level rather than from nesting.+ &[aria-level="2"] {+ padding-inline-start: 2em;+ }++ &[aria-expanded]::before {+ content: "▸";+ display: inline-block;+ width: 1em;+ }++ &[aria-expanded="false"]:dir(rtl)::before {+ content: "◂";+ }++ &[aria-expanded="true"]::before {+ content: "▾";+ }+ }+}+.styleguide-shortcut-spellings {th,td {diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.ymlindex 16e95842d53..6f868006dd9 100644--- a/plugins/styleguide/config/locales/client.en.yml+++ b/plugins/styleguide/config/locales/client.en.yml@@ -261,6 +261,117 @@ en:title: "More Topics"post_menu:title: "Post Menu"+ roving_focus:+ title: "Roving focus"+ description: "Keyboard navigation inside a composite widget, built from plain semantic HTML so that anything that misbehaves here is the modifier rather than a component wrapped around it. The patterns mirror the interactive examples in the WAI-ARIA Authoring Practices."+ groups:+ aria_label: "Roving focus patterns"+ toolbar:+ title: "Toolbar"+ description: "A single tab stop holding controls of mixed kinds, entered on the first one."+ listbox:+ title: "Listbox"+ description: "A vertical cursor with type-ahead, entered on the option already chosen."+ combobox:+ title: "Combobox"+ description: "A cursor that moves without focus moving, reported by aria-activedescendant."+ radio:+ title: "Radio group"+ description: "A group whose checked member is where the cursor starts, and follows."+ tree:+ title: "Tree"+ description: "A vertical cursor over the visible rows, with hierarchy left to the consumer."+ adjacent:+ title: "Beside a control"+ description: "A group that Tab never reaches, entered and left through its edges."+ components:+ title: "With components"+ description: "The same cursor over real buttons, where items are destroyed under it."+ toolbar:+ label: "Text formatting"+ example: "Toolbar"+ example_description: "The whole bar is one tab stop. Activation is left to the native buttons rather than routed through the modifier, so Enter and Space behave exactly as they would without it. Cut and Paste are disabled in the two different ways the practice page distinguishes, and the cursor treats them differently as a result."+ try_this: "Tab in, then arrow along the bar. Home and End reach the ends. Arrow past Cut and Paste: Cut is stepped over, while Paste can be reached and read out but does nothing when activated."+ bold: "Bold"+ italic: "Italic"+ underline: "Underline"+ copy: "Copy"+ cut: "Cut"+ paste: "Paste"+ docs: "Authoring practices"+ tags:+ label: "Applied tags"+ example: "Removing the item under the cursor"+ example_description: "Each tag is a real button, so removing one destroys the element holding the cursor and the button runs its action a tick later than the key that asked for it. The cursor moves to the next tag rather than letting focus fall to the page."+ try_this: "Arrow to a tag in the middle and press Enter to remove it, then check where the cursor went. Remove the last tag in the row and it moves backwards instead. Remove them all and it stops rather than guessing."+ remove: "Remove %{tag}"+ reset: "Start over"+ design: "Design"+ keyboard: "Keyboard"+ release: "Release"+ support: "Support"+ multi:+ label: "Accessibility checks"+ example: "Multi-select entry"+ example_description: "Entry lands on the first chosen row, returning the reader to their own selection rather than to the top. That knowingly starts the cursor where the next Space would remove something, which is the trade the pattern makes. Arrows wrap, so passing the last row returns to the first."+ try_this: "Note that the cursor starts on the chosen row rather than the first one, then arrow past the last row to come back around to the top."+ keyboard: "Keyboard navigable"+ contrast: "Sufficient contrast"+ captions: "Captions provided"+ motion: "Reduced motion honored"+ labels: "Fields are labelled"+ adjacent:+ label: "Filters"+ field: "Search"+ placeholder: "Search topics"+ example: "A group Tab does not reach"+ example_description: "The filters are not in the tab sequence, so Tab goes straight to the field and the pair counts as one component rather than two. The filters are reached with an arrow from the start of the field, and running off their end returns there. The modifier reports the edge and the direction; where to go next is this example's decision, because only it knows the field exists."+ try_this: "Tab in and notice you land on the field, not the filters. With the caret at the start, press the left arrow to step into them, arrow between them, then continue past the last to return to the field."+ open: "Open"+ mine: "Mine"+ recent: "Recent"+ listbox:+ label: "Fruit"+ example: "Listbox with type-ahead"+ example_description: "Typing moves the cursor to the option whose name starts with what was typed, which is what the practice page specifies and what a screen reader reads out. The count beside each option is decorative, so it belongs to the row's text but not to its name."+ try_this: "Arrow through the options, then type a letter such as b. Press a repeatedly to walk the options sharing that initial, then pause and type apr to land on Apricot directly. Typing a digit matches nothing, because the counts are not part of any name."+ apple: "Apple"+ apricot: "Apricot"+ banana: "Banana"+ blackberry: "Blackberry"+ cherry: "Cherry"+ coconut: "Coconut"+ combobox:+ label: "Email digest"+ example: "Cursor without focus"+ example_description: "The control keeps focus while the arrows move a highlight through the options, and the control reports where that highlight is rather than the browser moving to it. This is the second of the two strategies the practice page describes, and the one a combobox needs so the reader can keep typing."+ try_this: "Open the list and arrow through it while watching the focus ring: it stays on the button. Press Enter to choose, and Escape or another click to close."+ daily: "Daily"+ weekly: "Weekly"+ monthly: "Monthly"+ never: "Never"+ radio:+ label: "Alignment"+ example: "Radio group"+ example_description: "A radio group marks its choice with aria-checked rather than aria-selected, and entering the group lands on that member instead of the first one. Moving the cursor moves the choice with it, which is the one pattern where that is expected."+ try_this: "Tab into the group and notice it enters on the checked member. Arrow along it and watch the choice follow. Tab away and back to return to the new choice."+ left: "Left"+ center: "Center"+ right: "Right"+ tree:+ label: "Source tree"+ example: "Tree"+ example_description: "The cursor runs over the rows that are visible right now, so collapsing a parent removes its children from the sequence. Expand and collapse come from the cross-axis event, which reports the arrows this group does not navigate as a direction, leaving what that direction means to the example."+ try_this: "Arrow up and down the rows, then use the right and left arrows on a parent to open and close it. Collapse a parent and notice that its children leave the cursor with it."+ rtl_example: "Tree, right to left"+ rtl_description: "The same component under a right-to-left direction, from the same source. The arrows swap with the writing direction, so the one pointing at a row's children is still the one that opens them, and the example itself never mentions direction."+ rtl_try_this: "Open and close a parent, then compare with the copy above: the children sit on the other side, and the arrow that reaches them has swapped to match."+ components: "Components"+ button: "Button"+ select: "Select"+ modifiers: "Modifiers"+ roving_focus: "Roving focus"+ auto_focus: "Auto focus"docked_composer:title: "Docked Composer"modal:diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rbindex f1083acd455..636cf7a7aa5 100644--- a/plugins/styleguide/spec/system/smoke_test_spec.rb+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb@@ -35,6 +35,7 @@ RSpec.describe "Styleguide Smoke Test" do{ href: "/molecules/navigation-bar", title: "Navigation Bar" },{ href: "/molecules/navigation-stacked", title: "Navigation Stacked" },{ href: "/molecules/post-menu", title: "Post Menu" },+ { href: "/molecules/roving-focus", title: "Roving focus" },{ href: "/molecules/signup-cta", title: "Signup CTA" },{ href: "/molecules/multi-select", title: "Multi select" },{ href: "/molecules/toasts", title: "Toasts" },diff --git a/plugins/styleguide/test/javascripts/integration/components/roving-focus-examples-test.gjs b/plugins/styleguide/test/javascripts/integration/components/roving-focus-examples-test.gjsnew file mode 100644index 00000000000..3f890a381be--- /dev/null+++ b/plugins/styleguide/test/javascripts/integration/components/roving-focus-examples-test.gjs@@ -0,0 +1,847 @@+import {+ click,+ findAll,+ render,+ settled,+ triggerKeyEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import RovingFocusAdjacentGroupsExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/adjacent-groups";+import RovingFocusComboboxExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/combobox";+import RovingFocusListboxExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/listbox";+import RovingFocusMultiSelectExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/multi-select";+import RovingFocusRadioGroupExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/radio-group";+import RovingFocusRemovableTagsExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/removable-tags";+import RovingFocusToolbarExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/toolbar";+import RovingFocusTreeExample from "discourse/plugins/styleguide/discourse/components/examples/molecules/roving-focus/tree";++/**+ * The tier-1 conformance fixtures are plain semantic HTML, so anything that fails here is the+ * modifier rather than a component wrapped around it.+ */++function pressKey(element, key) {+ const event = new KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ });+ element.dispatchEvent(event);+ return event;+}++function labels(selector) {+ return findAll(selector).map((el) => el.textContent.trim());+}++function tabStop() {+ return findAll(".roving-demo__item").find(+ (el) => el.getAttribute("tabindex") === "0"+ );+}++module(+ "Integration | Component | roving-focus examples | toolbar",+ function (hooks) {+ setupRenderingTest(hooks);++ test("enters on the first control", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ assert+ .dom(tabStop())+ .hasText(+ "Bold",+ "the toolbar convention is the first control unconditionally"+ );+ });++ test("a pointer press moves the tab stop it lands on", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ await click(findAll(".roving-demo__item")[1]);++ assert+ .dom(findAll(".roving-demo__item")[1])+ .hasAttribute(+ "aria-pressed",+ "true",+ "the native button activated on its own"+ );+ assert+ .dom(tabStop())+ .hasText(+ "Italic",+ "so Tab out and back returns to where the reader last was, not to where the cursor was seeded"+ );+ });++ test("arrows walk the bar, telling the two spellings of disabled apart", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ const first = findAll(".roving-demo__item")[0];+ first.focus();++ const visited = [document.activeElement.textContent.trim()];+ for (let i = 0; i < 5; i++) {+ await triggerKeyEvent(document.activeElement, "keydown", "ArrowRight");+ visited.push(document.activeElement.textContent.trim());+ }++ assert.deepEqual(+ visited,+ ["Bold", "Italic", "Underline", "Copy", "Paste", "Authoring practices"],+ "Cut is skipped because the platform will not focus a disabled button, while Paste stays reachable so it can be discovered"+ );+ });++ test("the reachable disabled command is still not operable", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ const paste = findAll(".roving-demo__item").find(+ (el) => el.textContent.trim() === "Paste"+ );+ paste.focus();++ const event = new KeyboardEvent("keydown", {+ key: "Enter",+ bubbles: true,+ cancelable: true,+ });+ paste.dispatchEvent(event);++ assert.false(+ event.defaultPrevented,+ "the modifier declines to activate it, so nothing consumes the key on its behalf"+ );+ });++ test("End and Home reach the ends of the bar", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ findAll(".roving-demo__item")[0].focus();++ await triggerKeyEvent(document.activeElement, "keydown", "End");+ assert+ .dom(document.activeElement)+ .hasText("Authoring practices", "End reaches the last navigable item");++ await triggerKeyEvent(document.activeElement, "keydown", "Home");+ assert+ .dom(document.activeElement)+ .hasText("Bold", "Home reaches the first");+ });++ test("Space is left to the native button", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ const first = findAll(".roving-demo__item")[0];+ first.focus();++ const event = new KeyboardEvent("keydown", {+ key: " ",+ bubbles: true,+ cancelable: true,+ });+ first.dispatchEvent(event);++ assert.false(+ event.defaultPrevented,+ "no onActivate is passed, so the modifier does not claim Space and the button keeps its own activation"+ );+ });++ test("the separator states its orientation", async function (assert) {+ await render(<template><RovingFocusToolbarExample /></template>);++ assert+ .dom(".roving-demo__separator")+ .hasAttribute(+ "aria-orientation",+ "vertical",+ "a separator announces horizontal unless told otherwise, and this one stands upright"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | tree",+ function (hooks) {+ setupRenderingTest(hooks);++ test("the cursor covers only the rows that are visible", async function (assert) {+ await render(<template><RovingFocusTreeExample @dir="ltr" /></template>);++ assert.deepEqual(+ labels(".roving-demo__row"),+ ["Components", "Button", "Select", "Modifiers"],+ "the collapsed parent contributes no rows"+ );++ const rows = findAll(".roving-demo__row");+ rows[0].focus();+ await triggerKeyEvent(document.activeElement, "keydown", "ArrowDown");++ assert+ .dom(document.activeElement)+ .hasText("Button", "the next visible row takes the cursor");+ });++ test("collapsing a parent takes its children out of the sequence", async function (assert) {+ await render(<template><RovingFocusTreeExample @dir="ltr" /></template>);++ const parent = findAll(".roving-demo__row")[0];+ parent.focus();+ await triggerKeyEvent(parent, "keydown", "ArrowLeft");++ assert.deepEqual(+ labels(".roving-demo__row"),+ ["Components", "Modifiers"],+ "the children are gone"+ );++ await triggerKeyEvent(document.activeElement, "keydown", "ArrowDown");+ assert+ .dom(document.activeElement)+ .hasText("Modifiers", "the cursor steps to what is left");+ });++ test("the cross-axis keys mirror under rtl", async function (assert) {+ await render(<template><RovingFocusTreeExample @dir="rtl" /></template>);++ const parent = findAll(".roving-demo__row")[0];+ parent.focus();+ assert+ .dom(parent)+ .hasAttribute("aria-expanded", "true", "it starts expanded");++ await triggerKeyEvent(parent, "keydown", "ArrowRight");+ assert+ .dom(findAll(".roving-demo__row")[0])+ .hasAttribute(+ "aria-expanded",+ "false",+ "the arrow pointing away from the children closes them, which is ArrowRight here"+ );++ await triggerKeyEvent(+ findAll(".roving-demo__row")[0],+ "keydown",+ "ArrowLeft"+ );+ assert+ .dom(findAll(".roving-demo__row")[0])+ .hasAttribute(+ "aria-expanded",+ "true",+ "and the one pointing at them opens them, without the example resolving direction itself"+ );+ });++ test("the forward arrow steps into an open parent", async function (assert) {+ await render(<template><RovingFocusTreeExample @dir="ltr" /></template>);++ const parent = findAll(".roving-demo__row")[0];+ parent.focus();+ await triggerKeyEvent(parent, "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasText(+ "Button",+ "an open parent has nothing left to open, so forward reaches its first child"+ );+ assert+ .dom(findAll(".roving-demo__row")[0])+ .hasAttribute(+ "aria-expanded",+ "true",+ "and stepping in is not a toggle"+ );+ });++ test("the backward arrow returns a child to its parent", async function (assert) {+ await render(<template><RovingFocusTreeExample @dir="ltr" /></template>);++ const child = findAll(".roving-demo__row")[1];+ child.focus();+ await triggerKeyEvent(child, "keydown", "ArrowLeft");++ assert+ .dom(document.activeElement)+ .hasText(+ "Components",+ "a child has nothing to close, so backward climbs to the parent"+ );+ assert+ .dom(findAll(".roving-demo__row")[0])+ .hasAttribute(+ "aria-expanded",+ "true",+ "and climbing does not collapse on the way"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | listbox",+ function (hooks) {+ setupRenderingTest(hooks);++ test("enters on the option already chosen, not the first", async function (assert) {+ await render(<template><RovingFocusListboxExample /></template>);++ const seeded = findAll(".roving-demo__option").find(+ (el) => el.getAttribute("tabindex") === "0"+ );++ assert+ .dom(seeded)+ .hasAttribute(+ "data-option-id",+ "banana",+ "a listbox returns a reader to their own choice, which is the opposite of the toolbar convention"+ );+ });++ test("typing matches the name, and the decorative count is not part of it", async function (assert) {+ await render(<template><RovingFocusListboxExample /></template>);++ const rows = findAll(".roving-demo__option");+ rows[0].focus();++ pressKey(document.activeElement, "c");+ await settled();+ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-option-id",+ "cherry",+ "one character finds the first C"+ );++ const digit = pressKey(document.activeElement, "1");+ await settled();+ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-option-id",+ "cherry",+ "the counts belong to the text but not to any name, so a digit matches nothing"+ );+ assert.false(digit.defaultPrevented, "and the key is not consumed");+ });++ test("a single character walks the rows sharing an initial", async function (assert) {+ await render(<template><RovingFocusListboxExample /></template>);++ findAll(".roving-demo__option")[0].focus();++ pressKey(document.activeElement, "a");+ await settled();++ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-option-id",+ "apricot",+ "a lone character passes over the row it starts on, so repeating it walks the group"+ );+ });++ test("a longer query addresses a row a single character cannot reach", async function (assert) {+ await render(<template><RovingFocusListboxExample /></template>);++ findAll(".roving-demo__option")[1].focus();++ pressKey(document.activeElement, "a");+ pressKey(document.activeElement, "p");+ pressKey(document.activeElement, "r");+ await settled();++ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-option-id",+ "apricot",+ "the lone a lands on Apple, and only the accumulated apr names Apricot from there"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | radio group",+ function (hooks) {+ setupRenderingTest(hooks);++ test("enters on the checked member", async function (assert) {+ await render(<template><RovingFocusRadioGroupExample /></template>);++ const seeded = findAll(".roving-demo__radio").find(+ (el) => el.getAttribute("tabindex") === "0"+ );++ assert+ .dom(seeded)+ .hasAttribute(+ "data-choice-id",+ "center",+ "aria-checked is the radio group spelling, and seeding has to read it"+ );+ });++ test("the choice follows the cursor", async function (assert) {+ await render(<template><RovingFocusRadioGroupExample /></template>);++ const center = findAll(".roving-demo__radio")[1];+ center.focus();+ await triggerKeyEvent(center, "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasAttribute("data-choice-id", "right", "the cursor moved");+ assert+ .dom(document.activeElement)+ .hasAttribute(+ "aria-checked",+ "true",+ "and the choice came with it, which is what this pattern expects"+ );+ });++ test("the vertical arrows move the choice too", async function (assert) {+ await render(<template><RovingFocusRadioGroupExample /></template>);++ const center = findAll(".roving-demo__radio")[1];+ center.focus();+ await triggerKeyEvent(center, "keydown", "ArrowDown");++ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-choice-id",+ "right",+ "the pattern requires both arrow pairs, whatever the visual axis"+ );+ assert+ .dom(document.activeElement)+ .hasAttribute(+ "aria-checked",+ "true",+ "and the choice follows here too"+ );+ });++ test("the arrows wrap at the ends", async function (assert) {+ await render(<template><RovingFocusRadioGroupExample /></template>);++ const center = findAll(".roving-demo__radio")[1];+ center.focus();+ await triggerKeyEvent(center, "keydown", "ArrowRight");+ await triggerKeyEvent(document.activeElement, "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-choice-id",+ "left",+ "past the last member the pattern comes back around rather than stopping"+ );+ assert+ .dom(document.activeElement)+ .hasAttribute("aria-checked", "true", "with the choice still attached");+ });+ }+);++module(+ "Integration | Component | roving-focus examples | removable tags",+ function (hooks) {+ setupRenderingTest(hooks);++ test("removing the focused tag hands the cursor to the next one", async function (assert) {+ await render(<template><RovingFocusRemovableTagsExample /></template>);++ const tags = findAll(".roving-demo__tag");+ assert.strictEqual(tags.length, 4, "four to begin with");++ tags[1].focus();+ await click(tags[1]);++ assert.strictEqual(+ findAll(".roving-demo__tag").length,+ 3,+ "the tag is gone"+ );+ assert+ .dom(document.activeElement)+ .hasText(+ "Release",+ "focus followed to what took its place rather than falling to the page"+ );+ });++ test("removing the last tag hands the cursor backwards", async function (assert) {+ await render(<template><RovingFocusRemovableTagsExample /></template>);++ const tags = findAll(".roving-demo__tag");+ const last = tags[tags.length - 1];+ last.focus();+ await click(last);++ assert+ .dom(document.activeElement)+ .hasText(+ "Release",+ "there is nothing after it, so the item before takes the cursor"+ );+ });++ test("emptying the group leaves focus alone rather than guessing", async function (assert) {+ await render(<template><RovingFocusRemovableTagsExample /></template>);++ for (let i = 0; i < 4; i++) {+ const remaining = findAll(".roving-demo__tag");+ remaining[0].focus();+ await click(remaining[0]);+ }++ assert.strictEqual(+ findAll(".roving-demo__tag").length,+ 0,+ "every tag is gone"+ );+ assert+ .dom(".roving-demo__reset")+ .exists("and the group offers a way back");+ });++ test("a tag's button says it removes", async function (assert) {+ await render(<template><RovingFocusRemovableTagsExample /></template>);++ assert+ .dom(findAll(".roving-demo__tag")[0])+ .hasAttribute(+ "aria-label",+ "Remove Design",+ "hearing only the tag's own name invites pressing Enter to inspect, which destroys it"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | combobox",+ function (hooks) {+ setupRenderingTest(hooks);++ test("the cursor moves while focus stays on the control", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ const trigger = document.querySelector(".roving-demo__combobox-trigger");++ assert+ .dom(".roving-demo__combobox-option.--active")+ .hasAttribute(+ "data-option-id",+ "weekly",+ "opening highlights the option already chosen"+ );++ await triggerKeyEvent(trigger, "keydown", "ArrowDown");++ assert+ .dom(".roving-demo__combobox-option.--active")+ .hasAttribute("data-option-id", "monthly", "the highlight moved");+ assert.strictEqual(+ document.activeElement,+ trigger,+ "and focus never left the control, which is the whole distinction from the other examples"+ );+ assert+ .dom(trigger)+ .hasAttribute(+ "aria-activedescendant",+ document.querySelector(".roving-demo__combobox-option.--active").id,+ "the control reports where the cursor is, since the browser cannot"+ );+ });++ test("Enter chooses the highlighted option", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ const trigger = document.querySelector(".roving-demo__combobox-trigger");+ await triggerKeyEvent(trigger, "keydown", "ArrowDown");+ await triggerKeyEvent(trigger, "keydown", "Enter");++ assert.dom(trigger).hasText("Monthly", "the choice is committed");+ assert+ .dom(".roving-demo__combobox-listbox")+ .doesNotExist("and the list closed");+ });++ test("the control can legally reach the option it points at", async function (assert) {+ const warn = sinon.stub(console, "warn");++ await render(<template><RovingFocusComboboxExample /></template>);+ await click(".roving-demo__combobox-trigger");+ await triggerKeyEvent(+ document.querySelector(".roving-demo__combobox-trigger"),+ "keydown",+ "ArrowDown"+ );++ assert.false(+ warn.calledWithMatch(/aria-activedescendant/),+ "aria-controls is one of the three permitted relationships, so no warning is raised"+ );+ });++ test("a pointer press chooses without stealing focus", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ const monthly = document.querySelector('[data-option-id="monthly"]');+ const mousedown = new MouseEvent("mousedown", {+ bubbles: true,+ cancelable: true,+ button: 0,+ });+ monthly.dispatchEvent(mousedown);++ assert.true(+ mousedown.defaultPrevented,+ "preventing the press is how the control keeps focus through the choice"+ );++ await click('[data-option-id="monthly"]');++ assert+ .dom(".roving-demo__combobox-trigger")+ .hasText("Monthly", "the click committed the option it landed on");+ assert+ .dom(".roving-demo__combobox-listbox")+ .doesNotExist("and the list closed");+ });++ test("Escape closes the popup", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ assert.dom(".roving-demo__combobox-listbox").exists("the list is open");++ await triggerKeyEvent(+ document.querySelector(".roving-demo__combobox-trigger"),+ "keydown",+ "Escape"+ );++ assert+ .dom(".roving-demo__combobox-listbox")+ .doesNotExist("dismissal is part of the pattern, not an extra");+ });++ test("the closed control opens from the arrows", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await triggerKeyEvent(+ document.querySelector(".roving-demo__combobox-trigger"),+ "keydown",+ "ArrowDown"+ );++ assert+ .dom(".roving-demo__combobox-listbox")+ .exists("the arrow is an opening gesture on a collapsed control");+ assert+ .dom(".roving-demo__combobox-option.--active")+ .hasAttribute(+ "data-option-id",+ "weekly",+ "and the highlight enters on the option already chosen"+ );+ });++ test("Space commits the highlighted option", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ const trigger = document.querySelector(".roving-demo__combobox-trigger");+ await triggerKeyEvent(trigger, "keydown", "ArrowDown");+ await triggerKeyEvent(trigger, "keydown", " ");++ assert+ .dom(trigger)+ .hasText("Monthly", "Space commits like Enter in a select-only popup");+ assert+ .dom(".roving-demo__combobox-listbox")+ .doesNotExist("and the list closed with the choice");+ });++ test("Tab commits the highlight on its way out", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ await click(".roving-demo__combobox-trigger");+ const trigger = document.querySelector(".roving-demo__combobox-trigger");+ await triggerKeyEvent(trigger, "keydown", "ArrowDown");+ await triggerKeyEvent(trigger, "keydown", "Tab");++ assert+ .dom(trigger)+ .hasText(+ "Monthly",+ "leaving the control keeps the reader's last highlight"+ );+ assert+ .dom(".roving-demo__combobox-listbox")+ .doesNotExist("rather than stranding an open popup behind them");+ });++ test("aria-controls resolves exactly while the popup exists", async function (assert) {+ await render(<template><RovingFocusComboboxExample /></template>);++ assert+ .dom(".roving-demo__combobox-trigger")+ .doesNotHaveAttribute(+ "aria-controls",+ "collapsed, there is nothing for the reference to resolve to"+ );++ await click(".roving-demo__combobox-trigger");+ const listbox = document.querySelector(".roving-demo__combobox-listbox");++ assert+ .dom(".roving-demo__combobox-trigger")+ .hasAttribute(+ "aria-controls",+ listbox.id,+ "open, the reference names the listbox it actually controls"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | multi-select",+ function (hooks) {+ setupRenderingTest(hooks);++ test("entry lands on the row already chosen", async function (assert) {+ await render(<template><RovingFocusMultiSelectExample /></template>);++ const seeded = findAll(".roving-demo__option").find(+ (el) => el.getAttribute("tabindex") === "0"+ );++ assert+ .dom(findAll(".roving-demo__option")[0])+ .hasAttribute("aria-selected", "true", "the first row is chosen");+ assert+ .dom(seeded)+ .hasAttribute(+ "data-option-id",+ "keyboard",+ "the pattern returns a reader to their own selection rather than to the top of the list"+ );+ });++ test("arrows wrap past the last row", async function (assert) {+ await render(<template><RovingFocusMultiSelectExample /></template>);++ const rows = findAll(".roving-demo__option");+ rows[rows.length - 1].focus();+ await triggerKeyEvent(document.activeElement, "keydown", "ArrowDown");++ assert+ .dom(document.activeElement)+ .hasAttribute(+ "data-option-id",+ "keyboard",+ "passing the end returns to the top rather than stopping"+ );+ });+ }+);++module(+ "Integration | Component | roving-focus examples | adjacent groups",+ function (hooks) {+ setupRenderingTest(hooks);++ test("the filters are not in the tab sequence", async function (assert) {+ await render(<template><RovingFocusAdjacentGroupsExample /></template>);++ const tabbable = findAll(".roving-demo__filter").filter(+ (el) => el.getAttribute("tabindex") !== "-1"+ );++ assert.strictEqual(+ tabbable.length,+ 0,+ "every filter is out of the tab order, so Tab reaches the field instead"+ );+ });++ test("an arrow from the start of the field steps into the filters", async function (assert) {+ await render(<template><RovingFocusAdjacentGroupsExample /></template>);++ const field = document.querySelector(".roving-demo__field");+ field.focus();+ field.setSelectionRange(0, 0);+ await triggerKeyEvent(field, "keydown", "ArrowLeft");++ assert+ .dom(document.activeElement)+ .hasText("Recent", "the nearest filter takes the cursor");+ });++ test("running off the end of the filters returns to the field", async function (assert) {+ await render(<template><RovingFocusAdjacentGroupsExample /></template>);++ const filters = findAll(".roving-demo__filter");+ const last = filters[filters.length - 1];+ last.focus();+ await triggerKeyEvent(last, "keydown", "ArrowRight");++ assert.strictEqual(+ document.activeElement,+ document.querySelector(".roving-demo__field"),+ "the boundary report is what sends it back, since the modifier does not know the field is there"+ );+ });++ test("the entry gesture mirrors under rtl", async function (assert) {+ await render(+ <template>+ <div dir="rtl"><RovingFocusAdjacentGroupsExample /></div>+ </template>+ );++ const field = document.querySelector(".roving-demo__field");+ field.focus();+ await triggerKeyEvent(field, "keydown", "ArrowLeft");++ assert.strictEqual(+ document.activeElement,+ field,+ "the left arrow is a live caret key here, so it must stay with the text"+ );++ await triggerKeyEvent(field, "keydown", "ArrowRight");++ assert+ .dom(document.activeElement)+ .hasClass(+ "roving-demo__filter",+ "the arrow pointing at the filters is the one that steps into them"+ );+ });+ }+);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9c40abcf7fb..9d3e8834b29 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -321,6 +321,9 @@ importers:diff:specifier: ^9.0.0version: 9.0.0+ dom-accessibility-api:+ specifier: ^0.7.1+ version: 0.7.1ember-curry-component:specifier: ^0.5.0version: 0.5.0(@babel/[email protected])(@glint/[email protected])@@ -4321,6 +4324,9 @@ packages:resolution: {integrity: sha512-NqTbaYeE4gA/wU1hdKFdU+AFahpDOpgGLzHP42k6H6DKExJd0A55KEVWYhL9FEmHmgeLvEU2vuKXDuU+4yToOw==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-vdnCeZD+3wZ+8h8xXL/ZtBlvvoobOFyPzSiIfO6sGOZDqjFx4aLMAjZhl4rawj5xYz3UwP6Tgvyh0iH4IOCVnQ==}+resolution: {integrity: sha512-DLayMRQ+yJaziF4JJX1FMjwjdr7wdTr1y9XvZ+NfHELfOMcYDnCHneAYXAS4FT1gLILh4V0juMZohhH1N5FsoQ==}@@ -12403,6 +12409,8 @@ snapshots:+ [email protected]: {}+