An open source design system that's fully customizable and agent ready
TypeScript
fix(Selector): a ghost or secondary trigger's clear and status buttons ring themselves, not the trigger too (#8874)
Cindy Zhang841bcb8daddc
diff --git a/.changeset/focus-ring-one-owner-selector.md b/.changeset/focus-ring-one-owner-selector.mdnew file mode 100644index 0000000000..ff00a433f0--- /dev/null+++ b/.changeset/focus-ring-one-owner-selector.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Focusing the clear or status button of a ghost or secondary `Selector` no longer also rings the whole trigger: each tab stop shows one focus ring.++@cixzhangdiff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.mdindex ca42a633a9..4ddfafdd2b 100644--- a/docs/architecture/interaction-modality.md+++ b/docs/architecture/interaction-modality.md@@ -145,9 +145,9 @@ work.`privateAttributes/focusOwner.stylex.ts`, so the wrapper rings only while that controlhas keyboard focus, and a nested owner or a sibling control rings itself;no component writes the attribute or its selector itself. Implementation- gap: the module does not exist yet, and Item, Token, the clickable and- selectable cards, Thumbnail, the Selectors, SideNavItem, and ChatComposer's- body write their own ring conditions.+ gap: Item, Token, the clickable and selectable cards, Thumbnail,+ MultiSelector, SideNavItem, and ChatComposer's body write their own ring+ conditions.- **INV4 — Every modality has an operable path.** Keyboard, pointer, and touch orpen can reach each supported interaction. Hover is never the only discovery oractivation path. A tooltip's scrolling overflow is the one exception, as@@ -327,20 +327,20 @@ reachability, newer-intent precedence, and the evidence/scope guard were approve## Verification-| Invariant | Evidence | Failure signal |-| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| INV1, INV2 | Programmatic-focus cases after keyboard and pointer input in representative component tests | Programmatic focus invents a modality, or pointer history paints the keyboard indicator |-| INV3 | Direct-owner, wrapper-owner, replaceable-indicator, and nested-action cases, including a Token inside an Item and a control inside a card; evidence gap for the shared-module cases: the module does not exist yet | No indicator, two indicators, replacement content that can opt out, or a component that writes the focus-owner attribute or selector itself |-| INV4 | Keyboard, mouse, touch, and pen browser paths where applicable; tap cases on an action trigger with a label tooltip and on a hint-only trigger under `touchTrigger="auto"` | Hover-only behavior, sticky touch hover, unreachable action, a tap on an action trigger that opens its label tooltip, or hint-only information with no touch path |-| INV5 | Disabled, busy, and read-only DOM and activation assertions | Inactive control reacts, eligible control loses focus, or state changes with modality |-| INV6 | Public API review and representative source inspection | A component adds caller-controlled modality without a separate API decision |-| INV7 | Rendered-browser affected-state checks across geometry, clipping, scrolling, hit testing, built-in and custom-renderer paths | At an offered interaction point one modality loses every essential path, or evidence substitutes class equality for reachability/perceptibility |-| INV8 | Owner-defined intent order, pending, close, cancellation, disablement, and unmount mutations | Older work changes current content, selection, status or announcement, visibility, focus, or activation after owner-defined supersession |-| INV9 | Concrete-harm reproduction, representative normal/legacy/no-new-prop paths, and coincident public-delta inventory | Unsupported or aesthetic preference is treated as harm, unaffected behavior changes, or an API, layout, sizing, default, sticky, or exception delta escapes direct authority |-| INV10 | Source boundary check over Core and Lab, a Lab-to-Core comparison on one recorded stream, and release-filter unit tests over recorded iOS pan and scroll-view streams | A Core component with its own sample buffer, velocity math, or release filter; a Lab component with its own sample buffer, velocity math, or release filter; a Lab component reporting a different velocity than Core for the same stream; an export of the tracker; a non-zero release after a still pause |-| INV11 | Evidence gap: not implemented yet; the shared hover recognizer and its adopters' move onto it are pending. Then: unit tests of the hover recognizer's intent and browser tests of its adopters with a mouse, a pen, a finger, and the keyboard | A show without the owner's entry delay, a missed handoff within a group, a delayed keyboard show, a hover-shown surface that closes before the pointer reaches it, a finger served by it, or a second hover-timing implementation fails |-| INV12 | Unit tests of native scroll's progress and real-browser proofs of its adopters | Progress routed through React state, a missing edge, travel under Reduce Motion, use where native scroll-driven animation is supported, or a public export fails |-| INV13 | Source boundary check over Core and each family member's pointer-stream tests | A member outside menus and Selector's and MultiSelector's options that tracks a held pointer across its actions with its own code, or a public export of the tracker, fails |+| Invariant | Evidence | Failure signal |+| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| INV1, INV2 | Programmatic-focus cases after keyboard and pointer input in representative component tests | Programmatic focus invents a modality, or pointer history paints the keyboard indicator |+| INV3 | Direct-owner, wrapper-owner, replaceable-indicator, and nested-action cases, including a Token inside an Item and a control inside a card; `FocusRingOwner.a11y.chromium.spec.ts` covers the shared module in Selector, and the other wrappers that the gap names are not covered yet | No indicator, two indicators, replacement content that can opt out, or a component that writes the focus-owner attribute or selector itself |+| INV4 | Keyboard, mouse, touch, and pen browser paths where applicable; tap cases on an action trigger with a label tooltip and on a hint-only trigger under `touchTrigger="auto"` | Hover-only behavior, sticky touch hover, unreachable action, a tap on an action trigger that opens its label tooltip, or hint-only information with no touch path |+| INV5 | Disabled, busy, and read-only DOM and activation assertions | Inactive control reacts, eligible control loses focus, or state changes with modality |+| INV6 | Public API review and representative source inspection | A component adds caller-controlled modality without a separate API decision |+| INV7 | Rendered-browser affected-state checks across geometry, clipping, scrolling, hit testing, built-in and custom-renderer paths | At an offered interaction point one modality loses every essential path, or evidence substitutes class equality for reachability/perceptibility |+| INV8 | Owner-defined intent order, pending, close, cancellation, disablement, and unmount mutations | Older work changes current content, selection, status or announcement, visibility, focus, or activation after owner-defined supersession |+| INV9 | Concrete-harm reproduction, representative normal/legacy/no-new-prop paths, and coincident public-delta inventory | Unsupported or aesthetic preference is treated as harm, unaffected behavior changes, or an API, layout, sizing, default, sticky, or exception delta escapes direct authority |+| INV10 | Source boundary check over Core and Lab, a Lab-to-Core comparison on one recorded stream, and release-filter unit tests over recorded iOS pan and scroll-view streams | A Core component with its own sample buffer, velocity math, or release filter; a Lab component with its own sample buffer, velocity math, or release filter; a Lab component reporting a different velocity than Core for the same stream; an export of the tracker; a non-zero release after a still pause |+| INV11 | Evidence gap: not implemented yet; the shared hover recognizer and its adopters' move onto it are pending. Then: unit tests of the hover recognizer's intent and browser tests of its adopters with a mouse, a pen, a finger, and the keyboard | A show without the owner's entry delay, a missed handoff within a group, a delayed keyboard show, a hover-shown surface that closes before the pointer reaches it, a finger served by it, or a second hover-timing implementation fails |+| INV12 | Unit tests of native scroll's progress and real-browser proofs of its adopters | Progress routed through React state, a missing edge, travel under Reduce Motion, use where native scroll-driven animation is supported, or a public export fails |+| INV13 | Source boundary check over Core and each family member's pointer-stream tests | A member outside menus and Selector's and MultiSelector's options that tracks a held pointer across its actions with its own code, or a public export of the tracker, fails |Real-browser evidence is required when the behavior depends on`:focus-visible`, pointer capability, touch or pen synthesis, rendered focusdiff --git a/internal/eslint-plugin-astryx/focus-outline-shared.js b/internal/eslint-plugin-astryx/focus-outline-shared.jsindex 847e8a2489..81520fd85b 100644--- a/internal/eslint-plugin-astryx/focus-outline-shared.js+++ b/internal/eslint-plugin-astryx/focus-outline-shared.js@@ -37,8 +37,16 @@const RING_APPEARANCE = new Set(['outline', 'outlineWidth', 'outlineStyle']);-/** The file that owns the ring is the one place allowed to write it. */-const UTILITY_FILE = 'focusOutline.stylex';+/**+ * The files that own a ring are the only places allowed to write it: the+ * shared utility, and the focus-owner attribute's owner module, which holds+ * the wrapper ring keyed to that private attribute+ * (`architecture:public-component-api` INV23).+ */+const RING_OWNER_FILES = [+ 'focusOutline.stylex',+ 'privateAttributes/focusOwner.stylex',+];function isFocusVisibleKey(key) {return typeof key === 'string' && key.includes(':focus-visible');@@ -100,7 +108,8 @@ const rule = {schema: [],},create(context) {- if (context.filename?.includes(UTILITY_FILE)) return {};+ const filename = context.filename?.replaceAll('\\', '/') ?? '';+ if (RING_OWNER_FILES.some(owner => filename.includes(owner))) return {};return {Property(node) {diff --git a/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs b/internal/eslint-plugin-astryx/focus-outline-shared.test.mjsindex e033d4dcfc..fd5e9d9de0 100644--- a/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs+++ b/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs@@ -70,6 +70,22 @@ ruleTester.run('focus-outline-shared', rule, {{code: `const doc = {outline: {':focus-visible': '2px solid blue'}};`,},+ // The focus-owner attribute's owner module writes the wrapper ring.+ {+ filename:+ '/repo/packages/core/src/privateAttributes/focusOwner.stylex.ts',+ code: `+ import * as stylex from '@stylexjs/stylex';+ const styles = stylex.create({+ focusWithinOwner: {+ outlineWidth: {+ default: '0',+ ':has(> [data-astryx-focus-owner]:focus-visible)': WIDTH,+ },+ },+ });+ `,+ },// The utility itself is the one place the ring is written.{filename: '/repo/packages/core/src/utils/focusOutline.stylex.ts',@@ -108,10 +124,7 @@ ruleTester.run('focus-outline-shared', rule, {},});`,- errors: [- {messageId: 'handRolledRing'},- {messageId: 'handRolledRing'},- ],+ errors: [{messageId: 'handRolledRing'}, {messageId: 'handRolledRing'}],},// Reading the tokens directly is still a second definition of the ring.{diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsxindex 5ff337841c..458adc9eca 100644--- a/packages/core/src/Selector/Selector.tsx+++ b/packages/core/src/Selector/Selector.tsx@@ -96,6 +96,10 @@ import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import type {SizeValue} from '../utils/types';import {themeProps} from '../utils/themeProps';import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {+ focusOwnerProps,+ focusWithinOwner,+} from '../privateAttributes/focusOwner.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';import {usePressFeedback} from '../hooks/usePressFeedback';import {groupStyles, inputGroupItemProps} from '../InputGroup/groupStyles';@@ -2152,7 +2156,11 @@ export function Selector<T extends SelectorOptionType>(variant === 'ghost' && styles.triggerGhost,variant === 'secondary' && styles.triggerSecondary,variant !== 'input' && interactionOverlayStyles.backgroundImage,- variant !== 'input' && focusOutlineStyles.focusWithin,+ // Rings for the trigger button only. The clear and status+ // buttons ring themselves.+ variant !== 'input' &&+ !surface.isTriggerFocusRingSuppressed &&+ focusWithinOwner,surface.isTriggerFocusRingSuppressed &&selectorPresentationStyles.pointerRestoredFocus,isDisabled && inputWrapperStyles.disabled,@@ -2195,6 +2203,7 @@ export function Selector<T extends SelectorOptionType>(<button{...triggerSharedProps}ref={triggerButtonRef}+ {...focusOwnerProps}type="button"// The read-only trigger stays a combobox even when hasSearch is set:// no search input is rendered in that state, and preserving the rolediff --git a/packages/core/src/__tests__/FocusRingOwner.a11y.chromium.spec.ts b/packages/core/src/__tests__/FocusRingOwner.a11y.chromium.spec.tsnew file mode 100644index 0000000000..a6e2a65626--- /dev/null+++ b/packages/core/src/__tests__/FocusRingOwner.a11y.chromium.spec.ts@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/Selector/ ^packages/core/src/privateAttributes/focusOwner ^packages/core/src/utils/focusOutline ^apps/storybook/stories/Selector++/**+ * @file FocusRingOwner.a11y.chromium.spec.ts+ * @input The built ghost and secondary Selector "Clearable" stories in real+ * Chromium, focus moved with Tab, at desktop and phone widths+ * @output Browser evidence for `architecture:interaction-modality` INV3: each+ * tab stop in a Selector trigger shows exactly one focus ring. The trigger+ * box rings for the trigger button only; the clear button rings itself, and+ * the box stays unringed+ * @position Regression proof for focusWithinOwner in Selector+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';+import {ringedElements} from './focusRings';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function open(page: Page, story: string, width: number, args = '') {+ await page.setViewportSize({width, height: 600});+ await page.goto(+ `${storybook.origin}/iframe.html?id=${story}&viewMode=story${args}`,+ );+ await page+ .locator('#storybook-root button, #storybook-root a')+ .first()+ .waitFor();+}++/** Tabs through every stop, returning the rings painted at each. */+async function ringsAtEachStop(page: Page, stops: number) {+ const out: {focused: string; rings: string[]}[] = [];+ for (let i = 0; i < stops; i += 1) {+ await page.keyboard.press('Tab');+ const focused = await page.evaluate(+ () =>+ document.activeElement?.getAttribute('aria-label') ??+ (document.activeElement?.textContent ?? '').trim().slice(0, 30),+ );+ const rings = (await ringedElements(page)).map(ring => ring.description);+ out.push({focused, rings});+ }+ return out;+}++for (const width of [1280, 390]) {+ for (const variant of ['ghost', 'secondary']) {+ for (const component of ['selector']) {+ test(`at ${width} px, each tab stop in a ${variant} ${component} with a clear button shows one ring`, async ({+ page,+ }) => {+ await open(+ page,+ `core-${component}--clearable`,+ width,+ `&args=variant:${variant}`,+ );+ // The trigger, then its clear button.+ for (const {focused, rings} of await ringsAtEachStop(page, 2)) {+ expect(rings, `rings while "${focused}" is focused`).toHaveLength(1);+ }+ });+ }+ }+}diff --git a/packages/core/src/__tests__/focusOwner.source-build.test.mjs b/packages/core/src/__tests__/focusOwner.source-build.test.mjsnew file mode 100644index 0000000000..cde39ff941--- /dev/null+++ b/packages/core/src/__tests__/focusOwner.source-build.test.mjs@@ -0,0 +1,52 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file focusOwner.source-build.test.mjs+ * @input Uses Babel, the core StyleX build config, the StyleX rule processor,+ * and privateAttributes/focusOwner.stylex.ts+ * @output Verifies the shared focus-owner ring compiles to a ring on the+ * wrapper itself, keyed to its marked control's `:focus-visible`, and never+ * to a rule that reaches every descendant (`:has(...) *`)+ * @position Regression test for the focus-owner wrapper ring+ * (`architecture:interaction-modality` INV3)+ */++import fs from 'node:fs/promises';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {transformAsync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';+import {describe, expect, it} from 'vitest';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const SRC = path.resolve(__dirname, '..');+const CORE_ROOT = path.resolve(SRC, '..');++async function compile(relative) {+ const filename = path.join(SRC, relative);+ const result = await transformAsync(await fs.readFile(filename, 'utf8'), {+ babelrc: false,+ configFile: path.join(CORE_ROOT, 'babel.config.json'),+ filename,+ });+ return stylexBabelPlugin.processStylexRules(+ result?.metadata?.stylex ?? [],+ false,+ );+}++describe('focus-owner wrapper ring', () => {+ it('rings the wrapper for its own marked control only', async () => {+ const css = await compile('privateAttributes/focusOwner.stylex.ts');+ const ringRules = css+ .split('}')+ .filter(rule => rule.includes('var(--focus-outline-'));+ expect(ringRules.length).toBeGreaterThan(0);+ for (const rule of ringRules) {+ // On the wrapper, while its marked control shows keyboard focus.+ expect(rule).toMatch(/:has\(> \[data-astryx-focus-owner\]:focus-visible/);+ // Never every descendant.+ expect(rule).not.toMatch(/:has\([^{]*\)\)?\s+\*/);+ }+ });+});diff --git a/packages/core/src/__tests__/focusRings.ts b/packages/core/src/__tests__/focusRings.tsnew file mode 100644index 0000000000..3146700171--- /dev/null+++ b/packages/core/src/__tests__/focusRings.ts@@ -0,0 +1,62 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file focusRings.ts+ * @input A Playwright page showing a built story+ * @output `ringedElements`: every element under a root that paints an outline+ * right now, for browser specs proving `architecture:interaction-modality`+ * INV3 (one focus move has one owning indicator)+ * @position Shared helper for focus-ring browser specs+ */++import type {Page} from '@playwright/test';++export interface RingedElement {+ /** The element's tag, its accessible label or text, and its role. */+ readonly description: string;+ /** Whether it is the focused element itself. */+ readonly isFocused: boolean;+}++/**+ * Every element under `root` whose computed outline paints (a style other+ * than `none` and a width above zero) on a box a person can see. Read after+ * moving focus with the keyboard, so `:focus-visible` applies.+ */+export async function ringedElements(+ page: Page,+ root = '#storybook-root',+): Promise<RingedElement[]> {+ return page.evaluate(rootSelector => {+ const scope = document.querySelector(rootSelector) ?? document.body;+ const out: {description: string; isFocused: boolean}[] = [];+ for (const element of [scope, ...scope.querySelectorAll('*')]) {+ const style = getComputedStyle(element);+ if (+ style.outlineStyle === 'none' ||+ Number.parseFloat(style.outlineWidth) <= 0+ ) {+ continue;+ }+ // A visually hidden control (a card's screen-reader-only link) paints+ // nothing a person can see, whatever its outline says.+ const box = element.getBoundingClientRect();+ if (+ box.width <= 1 ||+ box.height <= 1 ||+ style.clipPath === 'inset(50%)' ||+ style.clip === 'rect(0px, 0px, 0px, 0px)'+ ) {+ continue;+ }+ const label =+ element.getAttribute('aria-label') ??+ (element.textContent ?? '').trim().slice(0, 30);+ out.push({+ description: `${element.tagName.toLowerCase()} "${label}"`,+ isFocused: element === document.activeElement,+ });+ }+ return out;+ }, root);+}diff --git a/packages/core/src/privateAttributes/focusOwner.stylex.ts b/packages/core/src/privateAttributes/focusOwner.stylex.tsnew file mode 100644index 0000000000..d9a9195415--- /dev/null+++ b/packages/core/src/privateAttributes/focusOwner.stylex.ts@@ -0,0 +1,51 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/focusOwner.stylex.ts+ * @input focus ring tokens+ * @output focusWithinOwner, the ring a wrapper draws only while its primary+ * control has keyboard focus, and focusOwnerProps, which mark that control+ * @position Owner module of the private focus-owner attribute: the only file+ * that writes its name or its selector. Core wrappers spread these exports.+ * No package entry exports it.+ */++import * as stylex from '@stylexjs/stylex';+import {focusVars} from '../theme/tokens.stylex';++/** Spread on the wrapper's primary control: the control the ring is for. */+export const focusOwnerProps = {'data-astryx-focus-owner': ''} as const;++// Rings only for the wrapper's own marked control, a direct child, so every+// other control inside rings itself and a nested component's owner never rings+// this wrapper. Every condition of each+// property, rest state included, is here: a caller spreading this style does+// not set these properties again on the same element. Written as longhands,+// like focusOutlineStyles, so a base style cannot erase them through `outline`.+const styles = stylex.create({+ focusWithinOwner: {+ outlineWidth: {+ default: '0',+ ':has(> [data-astryx-focus-owner]:focus-visible)':+ focusVars['--focus-outline-width'],+ },+ outlineStyle: {+ default: 'none',+ ':has(> [data-astryx-focus-owner]:focus-visible)':+ focusVars['--focus-outline-style'],+ },+ outlineColor: {+ default: null,+ ':has(> [data-astryx-focus-owner]:focus-visible)':+ focusVars['--focus-outline-color'],+ },+ outlineOffset: {+ default: '0',+ ':has(> [data-astryx-focus-owner]:focus-visible)':+ focusVars['--focus-outline-offset'],+ },+ },+});++/** The wrapper's focus ring. */+export const focusWithinOwner = styles.focusWithinOwner;