Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix: focus outlines are keyboard-only (:focus-visible), and a lint rule to keep them that way (#4935)

Cindy Zhangee705d83bdcb
diff --git a/.changeset/complexselector-focus-visible-ring.md b/.changeset/complexselector-focus-visible-ring.md
new file mode 100644
index 0000000000..2889a58c92
--- /dev/null
+++ b/.changeset/complexselector-focus-visible-ring.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] ComplexSelector: the trigger's focus ring is now keyboard-only. It was drawn from `:focus-within`, which also matches a mouse click — open the popover with the mouse, dismiss it with the mouse, and the restored focus left a pointer user staring at a keyboard affordance. It now uses the shared `:has(:focus-visible)` ring, which also brings the outline to the documented 3px offset.
+
+@cixzhang
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 25c7b19f93..70d11db1a1 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -261,3 +261,39 @@ import {isRenderable} from '@astryxdesign/core/utils';
Ships as a **warning in both tiers** while core migrates its existing call sites; promote to `error` in strict mode once migrated. Provides an ESLint suggestion that rewrites the comparison to `isRenderable(value)` (add the import manually).
See: https://github.com/facebook/astryx/issues/2538
+
+### `@astryx/focus-outline-keyboard-only`
+
+Flags a focus outline written against `:focus` or `:focus-within` inside `stylex.create()`. A focus outline is a **keyboard** affordance; both of those selectors also match a plain mouse click, so the ring gets shown to pointer users too — most easily missed on the paths where focus is restored programmatically (an overlay that returns focus to its trigger after a click-to-dismiss puts the ring back up with no keyboard involved).
+
+Use `:focus-visible`, or `:has(:focus-visible)` when the ring is drawn on a wrapper around the focusable element. A text input still matches `:focus-visible` when clicked, so nothing is lost.
+
+**Bad:**
+
+```ts
+const styles = stylex.create({
+ base: {
+ outline: {
+ default: 'none',
+ ':focus': `2px solid ${colorVars['--color-accent']}`,
+ },
+ },
+ wrapper: {
+ ':focus-within': {outline: `2px solid ${colorVars['--color-accent']}`},
+ },
+});
+```
+
+**Good:**
+
+```ts
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+
+// Preferred — the shared ring: .focusVisible on the focusable element,
+// .focusWithin (`:has(:focus-visible)`) on a wrapper around it.
+stylex.props(focusOutlineStyles.focusVisible);
+```
+
+**Scope:** `outline` and its longhands only, and only where the ring is drawn — suppressing one on a broader selector (`outline: {':focus': 'none'}`) is legitimate and is not flagged. A field's `:focus-within` border and inset box-shadow (`Field/inputStyles.stylex.ts`) are a different treatment — "you are typing here" — and are deliberately not policed by this rule.
+
+Ships as an **error in both tiers**: core is clean, and this keeps it that way.
diff --git a/internal/eslint-plugin-astryx/focus-outline-keyboard-only.js b/internal/eslint-plugin-astryx/focus-outline-keyboard-only.js
new file mode 100644
index 0000000000..f9b55cc14e
--- /dev/null
+++ b/internal/eslint-plugin-astryx/focus-outline-keyboard-only.js
@@ -0,0 +1,170 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file focus-outline-keyboard-only.js
+ * @description Focus outlines must key off `:focus-visible`, never `:focus` or
+ * `:focus-within`.
+ *
+ * A focus outline is a KEYBOARD affordance. `:focus` and `:focus-within` also
+ * match a plain mouse click, so a ring written against them is shown to
+ * pointer users who never asked for it — and on the paths where it is easy to
+ * miss in review: an overlay that restores focus to its trigger after a
+ * click-to-dismiss puts the ring back up with no keyboard involved (this is
+ * exactly what ComplexSelector shipped).
+ *
+ * `:focus-visible` asks the browser instead of guessing, and a text input
+ * still matches it when clicked — so nothing is lost by using it.
+ *
+ * BAD
+ * outline: {default: 'none', ':focus': '2px solid …'}
+ * ':focus-within': {outline: '2px solid …'}
+ *
+ * GOOD
+ * outline: {default: 'none', ':focus-visible': '2px solid …'}
+ * outlineWidth: {default: '0', ':has(:focus-visible)': '2px'} // ring on a
+ * // wrapper
+ * focusOutlineStyles.focusVisible / .focusWithin // preferred:
+ * // the shared
+ * // utility
+ *
+ * SCOPE: `outline` and its longhands only, and only where the ring is DRAWN.
+ * Suppressing an outline on a broader selector (`outline: {':focus': 'none'}`,
+ * as AppShell does for the skip link's programmatic target) is legitimate and
+ * is not flagged. A field's `:focus-within` border and inset box-shadow (see
+ * `Field/inputStyles.stylex.ts`) are a different treatment with a different
+ * rule — the field says "you are typing here" — so this rule deliberately does
+ * not police `borderColor` or `boxShadow`.
+ */
+
+const OUTLINE_PROPERTIES = new Set([
+ 'outline',
+ 'outlineWidth',
+ 'outlineStyle',
+ 'outlineColor',
+ 'outlineOffset',
+]);
+
+/**
+ * Does this StyleX condition key match pointer focus as well as keyboard
+ * focus?
+ *
+ * `:focus-visible` in any form is fine, including `:has(:focus-visible)`.
+ * A `:not(:focus-within)` segment is an exclusion, not a focus state — it is
+ * how hover styles step aside for a focused field — so drop `:not(…)` before
+ * looking.
+ */
+function isPointerFocusKey(key) {
+ if (typeof key !== 'string' || !key.includes('focus')) return false;
+ const withoutNegations = key.replace(/:not\([^)]*\)/g, '');
+ if (withoutNegations.includes('focus-visible')) return false;
+ return /:focus(-within)?(?![-\w])/.test(withoutNegations);
+}
+
+function keyOf(property) {
+ if (!property || property.type !== 'Property') return null;
+ if (property.key?.type === 'Literal') return String(property.key.value);
+ if (property.key?.type === 'Identifier' && !property.computed) {
+ return property.key.name;
+ }
+ return null;
+}
+
+/**
+ * Does this value PAINT a ring, or does it take one away?
+ *
+ * Only the painting case is a defect. Suppressing an outline on a broader
+ * selector is legitimate and sometimes the point: AppShell's `<main>` is
+ * focusable only as the skip link's programmatic target, and it kills the UA
+ * ring with `outline: {default: null, ':focus': 'none'}` — deliberately for
+ * every kind of focus, not just the keyboard kind.
+ */
+function drawsARing(valueNode) {
+ if (!valueNode) return false;
+ if (valueNode.type === 'Literal') {
+ const value = valueNode.value;
+ if (value == null) return false;
+ const text = String(value).trim();
+ return text !== '' && text !== 'none' && text !== '0' && text !== '0px';
+ }
+ // A template literal, a token lookup, a variable — assume it paints.
+ return true;
+}
+
+function isInsideStylexCreate(node) {
+ let current = node;
+ while (current) {
+ if (
+ current.type === 'CallExpression' &&
+ current.callee?.type === 'MemberExpression' &&
+ current.callee.object?.name === 'stylex' &&
+ current.callee.property?.name === 'create'
+ ) {
+ return true;
+ }
+ current = current.parent;
+ }
+ return false;
+}
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Focus outlines must use :focus-visible (keyboard), not :focus or :focus-within',
+ category: 'Accessibility',
+ recommended: true,
+ },
+ messages: {
+ pointerFocusOutline:
+ "Focus outline keyed off '{{key}}', which also matches a mouse click. " +
+ 'Use \':focus-visible\' (or \':has(:focus-visible)\' when the ring is on a wrapper) — ' +
+ 'better still, the shared focusOutlineStyles from utils/focusOutline.stylex.',
+ },
+ schema: [],
+ },
+ create(context) {
+ return {
+ Property(node) {
+ if (!isInsideStylexCreate(node)) return;
+
+ const key = keyOf(node);
+ if (key == null) return;
+
+ // Shape 1 — outline property, focus condition inside:
+ // outline: {default: 'none', ':focus': '…'}
+ if (OUTLINE_PROPERTIES.has(key) && node.value?.type === 'ObjectExpression') {
+ for (const condition of node.value.properties) {
+ const conditionKey = keyOf(condition);
+ if (isPointerFocusKey(conditionKey) && drawsARing(condition.value)) {
+ context.report({
+ node: condition,
+ messageId: 'pointerFocusOutline',
+ data: {key: conditionKey},
+ });
+ }
+ }
+ return;
+ }
+
+ // Shape 2 — focus condition, outline properties inside:
+ // ':focus-within': {outline: '…', outlineOffset: '2px'}
+ if (isPointerFocusKey(key) && node.value?.type === 'ObjectExpression') {
+ const drawsOutline = node.value.properties.some(
+ inner =>
+ OUTLINE_PROPERTIES.has(keyOf(inner)) && drawsARing(inner.value),
+ );
+ if (drawsOutline) {
+ context.report({
+ node,
+ messageId: 'pointerFocusOutline',
+ data: {key},
+ });
+ }
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-astryx/focus-outline-keyboard-only.test.mjs b/internal/eslint-plugin-astryx/focus-outline-keyboard-only.test.mjs
new file mode 100644
index 0000000000..68ba5e0c32
--- /dev/null
+++ b/internal/eslint-plugin-astryx/focus-outline-keyboard-only.test.mjs
@@ -0,0 +1,178 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file focus-outline-keyboard-only.test.mjs
+ */
+
+import {RuleTester} from 'eslint';
+import rule from './focus-outline-keyboard-only.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ },
+});
+
+ruleTester.run('focus-outline-keyboard-only', rule, {
+ valid: [
+ // The standard shape.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outline: {default: 'none', ':focus-visible': '2px solid blue'},
+ outlineOffset: {default: '0', ':focus-visible': '3px'},
+ },
+ });
+ `,
+ },
+ // A ring drawn on a wrapper around the focusable element.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ wrapper: {
+ outlineWidth: {default: '0', ':has(:focus-visible)': '2px'},
+ outlineStyle: {default: 'none', ':has(:focus-visible)': 'solid'},
+ },
+ });
+ `,
+ },
+ // :focus-within on something that is not an outline — the field border and
+ // its inset ring are out of scope for this rule.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ field: {
+ borderColor: {default: 'gray', ':focus-within': 'blue'},
+ boxShadow: {default: 'none', ':focus-within': 'inset 0 0 0 2px blue'},
+ },
+ });
+ `,
+ },
+ // A hover style stepping aside for a focused field is an exclusion, not a
+ // focus state.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outlineColor: {
+ default: null,
+ ':hover:not(:focus-within)': 'gray',
+ ':focus-visible': 'blue',
+ },
+ },
+ });
+ `,
+ },
+ // Menu rows highlight roving focus with a background, not a ring.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ item: {
+ backgroundColor: {default: 'transparent', ':focus': 'gray'},
+ outline: 'none',
+ },
+ });
+ `,
+ },
+ // Outside stylex.create() this rule says nothing.
+ {
+ code: `
+ const notStyles = {
+ base: {outline: {default: 'none', ':focus': '2px solid blue'}},
+ };
+ `,
+ },
+ // SUPPRESSING a ring on a broader selector is legitimate — AppShell kills
+ // the UA ring on its programmatic focus target for every kind of focus.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ mainFocusTarget: {
+ outline: {default: null, ':focus': 'none'},
+ },
+ });
+ `,
+ },
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outlineWidth: {default: '2px', ':focus-within': '0'},
+ },
+ });
+ `,
+ },
+ ],
+ invalid: [
+ // Shape 1: :focus condition on an outline property.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outline: {default: 'none', ':focus': '2px solid blue'},
+ },
+ });
+ `,
+ errors: [{messageId: 'pointerFocusOutline', data: {key: ':focus'}}],
+ },
+ // Shape 1, longhand + :focus-within.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outlineWidth: {default: '0', ':focus-within': '2px'},
+ },
+ });
+ `,
+ errors: [{messageId: 'pointerFocusOutline'}],
+ },
+ // Shape 2: outline nested inside a :focus-within block — what
+ // ComplexSelector shipped.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ focusRing: {
+ ':focus-within': {
+ outline: '2px solid blue',
+ outlineOffset: '2px',
+ },
+ },
+ });
+ `,
+ errors: [{messageId: 'pointerFocusOutline'}],
+ },
+ // Every offending condition is reported, not just the first.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outline: {
+ default: 'none',
+ ':focus': '2px solid blue',
+ ':focus-within': '2px solid blue',
+ },
+ },
+ });
+ `,
+ errors: [
+ {messageId: 'pointerFocusOutline'},
+ {messageId: 'pointerFocusOutline'},
+ ],
+ },
+ ],
+});
+
+console.log('✅ focus-outline-keyboard-only tests passed');
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index a74614ff33..0134ced0b7 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -30,6 +30,7 @@ import noRawParagraphRule from './no-raw-paragraph.js';
import noNullishJsxGuardRule from './no-nullish-jsx-guard.js';
import noBorderShorthandRule from './no-border-shorthand.js';
import noPhysicalPropertiesRule from './no-physical-properties.js';
+import focusOutlineKeyboardOnlyRule from './focus-outline-keyboard-only.js';
import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';
import copyrightHeaderRule from './copyright-header.js';
import noRawConsoleCliRule from './no-raw-console-cli.js';
@@ -250,6 +251,7 @@ const plugin = {
'no-nullish-jsx-guard': noNullishJsxGuardRule,
'no-border-shorthand': noBorderShorthandRule,
'no-physical-properties': noPhysicalPropertiesRule,
+ 'focus-outline-keyboard-only': focusOutlineKeyboardOnlyRule,
'no-react-namespace-hooks': noReactNamespaceHooksRule,
'require-base-props': requireBasePropsRule,
'require-ref-prop': requireRefPropRule,
@@ -291,6 +293,9 @@ plugin.configs.strict = {
'@astryx/no-border-shorthand': 'error',
// RTL physical→logical migration complete; errors to prevent regressions.
'@astryx/no-physical-properties': 'error',
+ // A focus outline drawn for pointer users is an accessibility defect, and
+ // core is clean — error in both tiers so it stays that way.
+ '@astryx/focus-outline-keyboard-only': 'error',
'@astryx/no-react-namespace-hooks': 'error',
'@astryx/require-base-props': 'error',
'@astryx/require-ref-prop': 'error',
@@ -321,6 +326,9 @@ plugin.configs.recommended = {
'@astryx/no-border-shorthand': 'warn',
// RTL physical→logical migration complete; errors to prevent regressions.
'@astryx/no-physical-properties': 'error',
+ // A focus outline drawn for pointer users is an accessibility defect, and
+ // core is clean — error in both tiers so it stays that way.
+ '@astryx/focus-outline-keyboard-only': 'error',
'@astryx/no-react-namespace-hooks': 'error',
'@astryx/require-base-props': 'warn',
'@astryx/require-ref-prop': 'warn',
diff --git a/packages/core/src/ComplexSelector/ComplexSelector.tsx b/packages/core/src/ComplexSelector/ComplexSelector.tsx
index 171f6058c7..d6b043541e 100644
--- a/packages/core/src/ComplexSelector/ComplexSelector.tsx
+++ b/packages/core/src/ComplexSelector/ComplexSelector.tsx
@@ -43,6 +43,7 @@ import {
} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
import {composeEventHandlers} from '../utils/composeEventHandlers';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
@@ -147,12 +148,6 @@ const styles = stylex.create({
disabled: {
cursor: 'not-allowed',
},
- focusRing: {
- ':focus-within': {
- outline: `2px solid ${colorVars['--color-accent']}`,
- outlineOffset: '2px',
- },
- },
});
export type ComplexSelectorSize = 'sm' | 'md' | 'lg';
@@ -356,7 +351,11 @@ export function ComplexSelector<Value>({
inputWrapperStyles.base,
styles.triggerContainer,
styles[size],
- styles.focusRing,
+ // The ring belongs to the wrapper (the focusable `<button>` sits
+ // inside it), but it must still be a KEYBOARD ring: `:focus-within`
+ // matched a mouse click on the trigger and drew the outline for
+ // pointer users too. `focusWithin` here is `:has(:focus-visible)`.
+ focusOutlineStyles.focusWithin,
isDisabled && inputWrapperStyles.disabled,
isDisabled && styles.disabled,
triggerLabel == null && styles.placeholder,