Skip to content

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

TypeScript

feat(theme): make the focus outline a token (#4973)

Cindy Zhangc6a994e777df
diff --git a/.changeset/focus-outline-tokens.md b/.changeset/focus-outline-tokens.md
new file mode 100644
index 0000000000..2286074890
--- /dev/null
+++ b/.changeset/focus-outline-tokens.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] The keyboard focus ring is now a theme token. `--focus-outline-width`, `--focus-outline-style`, `--focus-outline-color` and `--focus-outline-offset` drive every ring in core and lab, so one override in a theme's `tokens` restyles focus system-wide; the color tracks `--color-accent` unless a theme sets it. The `:focus-visible` condition is not themeable, so a themed ring still cannot appear for pointer users.
+
+Every ring is now drawn from the shared focus-outline utility rather than written out per component, and a lint rule keeps it that way. Two corrections come with that: the rings that had drifted to a 2px offset (Slider, Switch, Lightbox, ProgressBar, and lab's InfoTip, Step and LogStream) now sit at the documented 3px, and the buttons inside a field — the Date, DateRange and DateTime calendar toggles, the DateRange presets, and the Selector and MultiSelector status buttons — draw the standard 2px ring instead of a 1px one.
+
+@cixzhang
diff --git a/.github/a11y-baseline.json b/.github/a11y-baseline.json
index e3ebd4ad2e..1666760822 100644
--- a/.github/a11y-baseline.json
+++ b/.github/a11y-baseline.json
@@ -903,6 +903,11 @@
"impact": "serious",
"helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"
},
+ {
+ "key": "Stepper::Slots — endContent (trailing badges)::color-contrast",
+ "impact": "serious",
+ "helpUrl": "https://dequeuniversity.com/rules/axe/4.12/color-contrast?application=playwright"
+ },
{
"key": "TabList::Divider Gap (sm / md / lg)::landmark-unique",
"impact": "moderate",
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 70d11db1a1..f0c2719773 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -297,3 +297,32 @@ 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.
+
+### `@astryx/focus-outline-shared`
+
+Flags a focus ring written out inside `stylex.create()` instead of taken from the shared utility. There is one ring in the system and it is themeable through the `--focus-outline-*` tokens; a component that spells out its own gets those values by accident and drifts the moment either side moves — which is what happened before this rule existed (offsets wandered between 1px, 2px and 3px, and one ring was a border-width thick).
+
+**Bad:**
+
+```ts
+const styles = stylex.create({
+ base: {
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ },
+});
+```
+
+**Good:**
+
+```ts
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+
+stylex.props(focusOutlineStyles.focusVisible, styles.base);
+```
+
+**Scope:** only what the ring LOOKS like — the `outline` shorthand, `outlineWidth`, `outlineStyle` — under a literal `:focus-visible` condition. Not flagged: `outlineOffset` (where the ring sits is a local constraint — inset into a tight grid, or held clear of a field border — and such a component still follows the theme's width, style and color), `outlineColor` (re-coloring per variant is the documented override), and a computed condition key such as `stylex.when.ancestor(':has(:focus-visible)', scope)`, which a shared style cannot express because a scope marker cannot be shared between components.
+
+Ships as an **error in both tiers**: core and lab are clean, and this keeps them that way.
diff --git a/internal/eslint-plugin-astryx/focus-outline-shared.js b/internal/eslint-plugin-astryx/focus-outline-shared.js
new file mode 100644
index 0000000000..847e8a2489
--- /dev/null
+++ b/internal/eslint-plugin-astryx/focus-outline-shared.js
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file focus-outline-shared.js
+ * @description A keyboard focus ring must come from the shared utility, not be
+ * written out again in a component.
+ *
+ * There is exactly one focus ring in the system, and it is themeable through
+ * the `--focus-outline-*` tokens. A component that writes its own
+ * `2px solid accent` gets the tokens' values by accident at best, and drifts
+ * the moment either side changes — which is what happened: offsets wandered
+ * between 1px, 2px and 3px, and one ring was a border-width thick.
+ *
+ * BAD
+ * outline: {default: 'none', ':focus-visible': `2px solid ${accent}`}
+ * outlineWidth: {default: '0', ':has(:focus-visible)': '2px'}
+ *
+ * GOOD
+ * stylex.props(focusOutlineStyles.focusVisible, styles.base)
+ * focusOutlineProps.focusWithin(styles.base)
+ *
+ * SCOPE: only the parts that say what the ring LOOKS like — the `outline`
+ * shorthand, `outlineWidth`, `outlineStyle` — and only under a literal
+ * `:focus-visible` condition.
+ *
+ * Deliberately NOT flagged:
+ * - `outlineOffset`. Where the ring sits is a local constraint (a ring inset
+ * into a tight grid, or held clear of a field border), and a component that
+ * overrides only the offset still follows the theme's width, style and color.
+ * - `outlineColor`. Re-coloring the ring per variant is the documented override
+ * — destructive buttons ring in error red.
+ * - A computed condition key, e.g.
+ * `stylex.when.ancestor(':has(:focus-visible)', scope)`. A scope marker
+ * cannot be shared between components without leaking focus state, so Switch
+ * composes the tokens itself; the exception is recorded there.
+ */
+
+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';
+
+function isFocusVisibleKey(key) {
+ return typeof key === 'string' && key.includes(':focus-visible');
+}
+
+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 take one away? */
+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';
+ }
+ 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 rings must be drawn from the shared focusOutline utility',
+ category: 'Consistency',
+ recommended: true,
+ },
+ messages: {
+ handRolledRing:
+ "'{{property}}' paints a focus ring under '{{key}}'. Use the shared " +
+ 'focusOutlineStyles / focusOutlineProps from utils/focusOutline.stylex ' +
+ 'so one theme override reaches every ring — a local outlineOffset is ' +
+ 'still fine when the ring has to sit somewhere else.',
+ },
+ schema: [],
+ },
+ create(context) {
+ if (context.filename?.includes(UTILITY_FILE)) return {};
+
+ return {
+ Property(node) {
+ if (!isInsideStylexCreate(node)) return;
+
+ const property = keyOf(node);
+ if (!RING_APPEARANCE.has(property)) return;
+ if (node.value?.type !== 'ObjectExpression') return;
+
+ for (const condition of node.value.properties) {
+ const key = keyOf(condition);
+ if (isFocusVisibleKey(key) && drawsARing(condition.value)) {
+ context.report({
+ node: condition,
+ messageId: 'handRolledRing',
+ data: {property, key},
+ });
+ }
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs b/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs
new file mode 100644
index 0000000000..e033d4dcfc
--- /dev/null
+++ b/internal/eslint-plugin-astryx/focus-outline-shared.test.mjs
@@ -0,0 +1,134 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file focus-outline-shared.test.mjs
+ */
+
+import {RuleTester} from 'eslint';
+import rule from './focus-outline-shared.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ },
+});
+
+ruleTester.run('focus-outline-shared', rule, {
+ valid: [
+ // The shared utility, applied at the call site.
+ {
+ code: `
+ import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+ stylex.props(focusOutlineStyles.focusVisible, styles.base);
+ `,
+ },
+ // A local offset: where the ring sits is a local constraint.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ cell: {outlineOffset: {default: '0', ':focus-visible': -2}},
+ });
+ `,
+ },
+ // Re-coloring the ring per variant is the documented override.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ destructive: {
+ outlineColor: {default: null, ':focus-visible': colorVars['--color-error']},
+ },
+ });
+ `,
+ },
+ // Suppressing a ring is not painting one.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ bare: {outline: {default: 'none', ':focus-visible': 'none'}},
+ });
+ `,
+ },
+ // A computed condition key — Switch's scope marker, which cannot be shared.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ track: {
+ outline: {
+ default: 'none',
+ [stylex.when.ancestor(':has(:focus-visible)', switchScope)]: RING,
+ },
+ },
+ });
+ `,
+ },
+ // Outside stylex.create this rule has nothing to say.
+ {
+ code: `const doc = {outline: {':focus-visible': '2px solid blue'}};`,
+ },
+ // The utility itself is the one place the ring is written.
+ {
+ filename: '/repo/packages/core/src/utils/focusOutline.stylex.ts',
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ focusVisible: {
+ outlineWidth: {default: '0', ':focus-visible': WIDTH},
+ outlineStyle: {default: 'none', ':focus-visible': STYLE},
+ },
+ });
+ `,
+ },
+ ],
+ invalid: [
+ // The shorthand, written out by hand.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outline: {default: 'none', ':focus-visible': '2px solid blue'},
+ },
+ });
+ `,
+ errors: [{messageId: 'handRolledRing'}],
+ },
+ // Longhands, on a wrapper.
+ {
+ 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'},
+ },
+ });
+ `,
+ errors: [
+ {messageId: 'handRolledRing'},
+ {messageId: 'handRolledRing'},
+ ],
+ },
+ // Reading the tokens directly is still a second definition of the ring.
+ {
+ code: `
+ import * as stylex from '@stylexjs/stylex';
+ const styles = stylex.create({
+ base: {
+ outline: {
+ default: 'none',
+ ':focus-visible': \`\${focusVars['--focus-outline-width']} solid red\`,
+ },
+ },
+ });
+ `,
+ errors: [{messageId: 'handRolledRing'}],
+ },
+ ],
+});
+
+console.log('✅ focus-outline-shared tests passed');
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index 0134ced0b7..61682542ae 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -31,6 +31,7 @@ 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 focusOutlineSharedRule from './focus-outline-shared.js';
import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';
import copyrightHeaderRule from './copyright-header.js';
import noRawConsoleCliRule from './no-raw-console-cli.js';
@@ -252,6 +253,7 @@ const plugin = {
'no-border-shorthand': noBorderShorthandRule,
'no-physical-properties': noPhysicalPropertiesRule,
'focus-outline-keyboard-only': focusOutlineKeyboardOnlyRule,
+ 'focus-outline-shared': focusOutlineSharedRule,
'no-react-namespace-hooks': noReactNamespaceHooksRule,
'require-base-props': requireBasePropsRule,
'require-ref-prop': requireRefPropRule,
@@ -296,6 +298,9 @@ plugin.configs.strict = {
// 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',
+ // Core and lab draw every ring from the shared utility; error so the one
+ // themeable definition stays the only one.
+ '@astryx/focus-outline-shared': 'error',
'@astryx/no-react-namespace-hooks': 'error',
'@astryx/require-base-props': 'error',
'@astryx/require-ref-prop': 'error',
@@ -329,6 +334,9 @@ plugin.configs.recommended = {
// 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',
+ // Core and lab draw every ring from the shared utility; error so the one
+ // themeable definition stays the only one.
+ '@astryx/focus-outline-shared': 'error',
'@astryx/no-react-namespace-hooks': 'error',
'@astryx/require-base-props': 'warn',
'@astryx/require-ref-prop': 'warn',
diff --git a/packages/cli/assets/docs/tokens.doc.mjs b/packages/cli/assets/docs/tokens.doc.mjs
index a1b5b9989d..8991ae4734 100644
--- a/packages/cli/assets/docs/tokens.doc.mjs
+++ b/packages/cli/assets/docs/tokens.doc.mjs
@@ -3,7 +3,7 @@
// AUTO-GENERATED — do not edit manually.
// Source: packages/core/src/theme/tokens.stylex.ts
// Run: node scripts/generate-token-docs.mjs
-// Total: 184 tokens across 12 categories.
+// Total: 188 tokens across 13 categories.
/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
@@ -561,6 +561,40 @@ export const docs = {
],
"previewType": "border-line"
},
+ {
+ "title": "Focus Tokens",
+ "content": [
+ {
+ "type": "prose",
+ "text": "The keyboard focus ring, shared by every component that draws one. Override these to restyle focus across the system."
+ },
+ {
+ "type": "table",
+ "headers": [
+ "Token",
+ "Value"
+ ],
+ "rows": [
+ [
+ "--focus-outline-width",
+ "2px"
+ ],
+ [
+ "--focus-outline-style",
+ "solid"
+ ],
+ [
+ "--focus-outline-color",
+ "var(--color-accent)"
+ ],
+ [
+ "--focus-outline-offset",
+ "3px"
+ ]
+ ]
+ }
+ ]
+ },
{
"title": "Radius Tokens",
"content": [
diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs
index 9d67e04058..9768468110 100644
--- a/packages/core/src/Button/Button.doc.mjs
+++ b/packages/core/src/Button/Button.doc.mjs
@@ -163,7 +163,7 @@ export const docs = {
],
vars: [
{name: '--_button-radius', description: 'Border radius', default: 'var(--radius-element)', private: true},
- {name: '--button-focus-offset', description: 'Focus ring outline offset', default: '3px'},
+ {name: '--button-focus-offset', description: 'Focus ring outline offset', default: 'var(--focus-outline-offset)'},
{name: '--button-icon-only-aspect', description: 'Aspect ratio for icon-only buttons', default: '1 / 1'},
],
derived: [
@@ -245,7 +245,7 @@ export const docsZh = {
],
vars: [
{name: '--_button-radius', description: '圆角半径', default: 'var(--radius-element)', private: true},
- {name: '--button-focus-offset', description: '焦点环轮廓偏移', default: '3px'},
+ {name: '--button-focus-offset', description: '焦点环轮廓偏移', default: 'var(--focus-outline-offset)'},
{name: '--button-icon-only-aspect', description: '纯图标按钮的宽高比', default: '1 / 1'},
],
derived: [
diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx
index e67a7a8e7c..88191f9821 100644
--- a/packages/core/src/Button/Button.tsx
+++ b/packages/core/src/Button/Button.tsx
@@ -34,6 +34,7 @@ import {
fontWeightVars,
typeScaleVars,
shadowVars,
+ focusVars,
} from '../theme/tokens.stylex';
import {Spinner} from '../Spinner';
import {VisuallyHidden} from '../VisuallyHidden';
@@ -57,10 +58,10 @@ import type {ButtonVariantMap} from './index';
const styles = stylex.create({
base: {
// Kept as a public themeable var (documented in Button.doc.mjs) even though
- // its default now matches the shared outline: removing it would break any
- // theme setting it, for no gain. It overrides the shared offset, so a theme
- // can still tune the ring distance on buttons specifically.
- '--button-focus-offset': '3px',
+ // it now defaults to the shared token: removing it would break any theme
+ // setting it, for no gain. It overrides the shared offset, so a theme can
+ // still tune the ring distance on buttons specifically.
+ '--button-focus-offset': focusVars['--focus-outline-offset'],
outlineOffset: {
default: '0',
':focus-visible': 'var(--button-focus-offset)',
diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
index ddd879f47f..77969bbd94 100644
--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx
@@ -17,6 +17,7 @@ import {Theme} from '../theme/Theme';
import {defineTheme} from '../theme/defineTheme';
import {getForcedColorsRules} from '../__tests__/forcedColors';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {FOCUS_OUTLINE_PARTS} from '../utils/focusOutline.stylex';
afterEach(() => {
__resetLiveRegionsForTest();
@@ -686,7 +687,9 @@ describe('focus ring ownership (WCAG 2.4.7)', () => {
<CheckboxInput label="Accept" value={false} onChange={() => {}} />,
);
focusInput(container);
- expect(indicatorOf(container).style.outlineStyle).toBe('solid');
+ expect(indicatorOf(container).style.outlineStyle).toBe(
+ FOCUS_OUTLINE_PARTS.outlineStyle,
+ );
});
it('paints it on a replacement that forwards nothing', () => {
@@ -701,7 +704,7 @@ describe('focus ring ownership (WCAG 2.4.7)', () => {
expect(replaced.className).toBe('');
// ...and it still gets a ring, because the owner drew it.
focusInput(container);
- expect(replaced.style.outlineStyle).toBe('solid');
+ expect(replaced.style.outlineStyle).toBe(FOCUS_OUTLINE_PARTS.outlineStyle);
});
it('clears the ring on blur', () => {
@@ -709,7 +712,9 @@ describe('focus ring ownership (WCAG 2.4.7)', () => {
<CheckboxInput label="Accept" value={false} onChange={() => {}} />,
);
const input = focusInput(container);
- expect(indicatorOf(container).style.outlineStyle).toBe('solid');
+ expect(indicatorOf(container).style.outlineStyle).toBe(
+ FOCUS_OUTLINE_PARTS.outlineStyle,
+ );
fireEvent.blur(input);
expect(indicatorOf(container).style.outlineStyle).toBe('');
});
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index 2c68e197ce..d4ec8f41c5 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -80,11 +80,6 @@ const styles = stylex.create({
backgroundColor: 'transparent',
cursor: 'pointer',
borderRadius: radiusVars['--radius-element'],
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 1,
},
iconButtonDisabled: {
cursor: 'not-allowed',
@@ -163,6 +158,7 @@ import {mergeProps, mergeRefs, isFocusDetached} from '../utils';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
import {useTranslator} from '../i18n';
@@ -694,6 +690,7 @@ export function DateInput({
: t('@astryx.dateInput.openCalendar')
}
{...stylex.props(
+ focusOutlineStyles.focusVisible,
styles.iconButton,
isEffectivelyDisabled && styles.iconButtonDisabled,
)}>
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx
index 9195b36b85..090d509666 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx
@@ -61,6 +61,7 @@ import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
import {useTranslator} from '../i18n';
@@ -118,11 +119,6 @@ const styles = stylex.create({
backgroundColor: 'transparent',
cursor: 'pointer',
borderRadius: radiusVars['--radius-element'],
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 1,
},
iconButtonDisabled: {
cursor: 'not-allowed',
@@ -160,10 +156,6 @@ const styles = stylex.create({
color: colorVars['--color-text-primary'],
cursor: 'pointer',
textAlign: 'start',
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
},
presetButtonActive: {
backgroundColor: colorVars['--color-accent-muted'],
@@ -592,6 +584,7 @@ export function DateRangeInput({
}
tabIndex={-1}
{...stylex.props(
+ focusOutlineStyles.focusVisible,
styles.iconButton,
isEffectivelyDisabled && styles.iconButtonDisabled,
)}>
@@ -661,6 +654,7 @@ export function DateRangeInput({
aria-current={isActive ? 'true' : undefined}
onClick={() => handlePresetClick(preset)}
{...stylex.props(
+ focusOutlineStyles.focusVisible,
styles.presetButton,
isActive && styles.presetButtonActive,
)}>
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx
index 20dd2437f9..0722d31c40 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx
@@ -84,6 +84,7 @@ import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {useTranslator} from '../i18n';
export type ISODateTimeString = string & {
@@ -118,11 +119,6 @@ const styles = stylex.create({
backgroundColor: 'transparent',
cursor: 'pointer',
borderRadius: radiusVars['--radius-element'],
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 1,
},
iconButtonDisabled: {
cursor: 'not-allowed',
@@ -941,6 +937,7 @@ export function DateTimeInput({
: t('@astryx.dateInput.openCalendar')
}
{...stylex.props(
+ focusOutlineStyles.focusVisible,
styles.iconButton,
isEffectivelyDisabled && styles.iconButtonDisabled,
)}>
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index f84d5c6bc1..12470b1d66 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -35,6 +35,7 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {mergeProps, mergeRefs, rtlStyles} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {useTranslator} from '../i18n';
/**
@@ -158,16 +159,6 @@ const styles = stylex.create({
'@media (hover: hover)': 'zoom-in',
},
},
- zoomTarget: {
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- },
imageWrapperZoomed: {
cursor: 'grab',
},
@@ -641,7 +632,7 @@ export function Lightbox({
aria-label={isZoomTarget ? t('@astryx.lightbox.zoom') : undefined}
{...stylex.props(
styles.imageWrapper,
- isZoomTarget && styles.zoomTarget,
+ isZoomTarget && focusOutlineStyles.focusVisible,
!isVideo && hasZoom && !isZoomed && styles.imageWrapperZoomable,
!isVideo && isZoomed && styles.imageWrapperZoomed,
!isVideo && isDragging && styles.imageWrapperDragging,
diff --git a/packages/core/src/MultiSelector/MultiSelector.tsx b/packages/core/src/MultiSelector/MultiSelector.tsx
index 1b7e790e50..f59572e98f 100644
--- a/packages/core/src/MultiSelector/MultiSelector.tsx
+++ b/packages/core/src/MultiSelector/MultiSelector.tsx
@@ -76,6 +76,7 @@ import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
import {groupStyles} from '../InputGroup/groupStyles';
import {useInputGroup} from '../InputGroup/InputGroupContext';
@@ -200,14 +201,6 @@ const styles = stylex.create({
':focus-within': 'none',
},
fontWeight: fontWeightVars['--font-weight-medium'],
- outline: {
- default: 'none',
- ':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':has(:focus-visible)': '3px',
- },
transitionProperty:
'background-image, background-color, color, opacity, transform',
transform: {
@@ -236,11 +229,6 @@ const styles = stylex.create({
color: 'inherit',
cursor: 'pointer',
borderRadius: radiusVars['--radius-element'],
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 1,
},
// Dropdown container
@@ -1453,6 +1441,7 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
styles.triggerContainer,
sizeStyles[size],
variant === 'ghost' && styles.triggerGhost,
+ variant === 'ghost' && focusOutlineStyles.focusWithin,
isDisabled && inputWrapperStyles.disabled,
variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,
optimisticValue.length === 0 && styles.triggerPlaceholder,
@@ -1541,7 +1530,10 @@ export function MultiSelector<T extends MultiSelectorOptionType>({
aria-label={t(STATUS_BUTTON_LABEL_KEY[status.type])}
aria-describedby={statusTooltip.describedBy}
onClick={e => e.stopPropagation()}
- {...stylex.props(styles.statusButton)}>
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.statusButton,
+ )}>
<Icon
icon={STATUS_ICON_MAP[status.type]}
size="sm"
diff --git a/packages/core/src/ProgressBar/ProgressBar.tsx b/packages/core/src/ProgressBar/ProgressBar.tsx
index 78406b3727..10831b671b 100644
--- a/packages/core/src/ProgressBar/ProgressBar.tsx
+++ b/packages/core/src/ProgressBar/ProgressBar.tsx
@@ -30,6 +30,7 @@ import {
typeScaleVars,
} from '../theme/tokens.stylex';
import {mergeProps} from '../utils';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {VisuallyHidden} from '../VisuallyHidden';
@@ -282,14 +283,6 @@ const styles = stylex.create({
top: '50%',
width: 'var(--_progressbar-mark-width, 2px)',
height: 'var(--_progressbar-mark-height, 8px)',
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
transform: {
default: 'translate(-50%, -50%)',
':is([dir="rtl"] *)': 'translate(50%, -50%)',
@@ -581,6 +574,7 @@ export function ProgressBar({
placement: mark.isOnFill ? 'fill' : 'track',
}),
stylex.props(
+ focusOutlineStyles.focusVisible,
styles.mark,
mark.isOnFill
? markOnFillStyles[fillVariant]
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index 8f0a5f8423..0546b8185e 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -76,6 +76,7 @@ import {useSize} from '../SizeContext/SizeContext';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
import {groupStyles} from '../InputGroup/groupStyles';
import {useInputGroup} from '../InputGroup/InputGroupContext';
@@ -179,14 +180,6 @@ const styles = stylex.create({
':focus-within': 'none',
},
fontWeight: fontWeightVars['--font-weight-medium'],
- outline: {
- default: 'none',
- ':has(:focus-visible)': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':has(:focus-visible)': '3px',
- },
transitionProperty:
'background-image, background-color, color, opacity, transform',
transform: {
@@ -215,11 +208,6 @@ const styles = stylex.create({
color: 'inherit',
cursor: 'pointer',
borderRadius: radiusVars['--radius-element'],
- outline: {
- default: 'none',
- ':focus-visible': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 1,
},
// Dropdown container
@@ -1251,6 +1239,7 @@ export function Selector<T extends SelectorOptionType>(
styles.triggerContainer,
sizeStyles[size],
variant === 'ghost' && styles.triggerGhost,
+ variant === 'ghost' && focusOutlineStyles.focusWithin,
isDisabled && inputWrapperStyles.disabled,
variant === 'ghost' && isDisabled && styles.triggerGhostDisabled,
!selectedItem && styles.triggerPlaceholder,
@@ -1338,7 +1327,10 @@ export function Selector<T extends SelectorOptionType>(
aria-label={t(STATUS_BUTTON_LABEL_KEY[status.type])}
aria-describedby={statusTooltip.describedBy}
onClick={e => e.stopPropagation()}
- {...stylex.props(styles.statusButton)}>
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.statusButton,
+ )}>
<Icon
icon={STATUS_ICON_MAP[status.type]}
size="sm"
diff --git a/packages/core/src/Slider/Slider.tsx b/packages/core/src/Slider/Slider.tsx
index b6a44a4b98..f0496614b1 100644
--- a/packages/core/src/Slider/Slider.tsx
+++ b/packages/core/src/Slider/Slider.tsx
@@ -41,6 +41,7 @@ import {useTooltip} from '../Tooltip';
import {VisuallyHidden} from '../VisuallyHidden';
import type {InputStatus} from '../Field/types';
import {mergeProps, mergeRefs, rtlStyles} from '../utils';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {isRtlElement} from '../hooks/isRtlElement';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -253,16 +254,6 @@ const styles = stylex.create({
},
},
},
- thumbFocusVisible: {
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- },
thumbDisabled: {
backgroundColor: colorVars['--color-background-muted'],
cursor: 'not-allowed',
@@ -792,7 +783,7 @@ export function Slider({ref, ...props}: SliderProps) {
? styles.thumbHorizontal
: rtlStyles.centerInline('50%'),
!isDisabled && styles.thumbHover,
- !isDisabled && styles.thumbFocusVisible,
+ !isDisabled && focusOutlineStyles.focusVisible,
isDisabled && styles.thumbDisabled,
),
undefined,
diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsx
index f02a73b5dd..afa92bdec6 100644
--- a/packages/core/src/Switch/Switch.tsx
+++ b/packages/core/src/Switch/Switch.tsx
@@ -33,6 +33,7 @@ import {
easeVars,
typographyVars,
typeScaleVars,
+ focusVars,
} from '../theme/tokens.stylex';
import {FieldLabel} from '../Field/FieldLabel';
import {FieldStatus} from '../FieldStatus/FieldStatus';
@@ -189,15 +190,22 @@ const styles = stylex.create({
'@media (forced-colors: active)': 'CanvasText',
},
},
+ // The one ring in the system not drawn by focusOutlineStyles. The focusable
+ // input is a sibling of the track, so the condition has to reach the shared
+ // scope marker — and a marker cannot be shared across components without
+ // leaking focus state from an outer one, so it cannot live in the utility.
+ // StyleX also cannot inline a constant imported from another module, so the
+ // values are read from the tokens the utility reads.
trackFocus: {
outline: {
default: 'none',
[stylex.when.ancestor(':has(:focus-visible)', switchScope)]:
- `2px solid ${colorVars['--color-accent']}`,
+ `${focusVars['--focus-outline-width']} ${focusVars['--focus-outline-style']} ${focusVars['--focus-outline-color']}`,
},
outlineOffset: {
default: null,
- [stylex.when.ancestor(':has(:focus-visible)', switchScope)]: '2px',
+ [stylex.when.ancestor(':has(:focus-visible)', switchScope)]:
+ focusVars['--focus-outline-offset'],
},
},
// State-dependent colors with ancestor hover behavior
diff --git a/packages/core/src/TreeList/TreeList.test.tsx b/packages/core/src/TreeList/TreeList.test.tsx
index e5892698b5..d8a19543cf 100644
--- a/packages/core/src/TreeList/TreeList.test.tsx
+++ b/packages/core/src/TreeList/TreeList.test.tsx
@@ -16,6 +16,7 @@ import {TreeList} from './TreeList';
import type {TreeListItemData} from './TreeListTypes';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
+import {FOCUS_OUTLINE} from '../utils/focusOutline.stylex';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
@@ -299,8 +300,8 @@ describe('TreeList', () => {
expect(root).toHaveFocus();
expect(
- getComputedStyle(root).getPropertyValue('--_focus-outline'),
- ).toContain('solid');
+ getComputedStyle(root).getPropertyValue('--_focus-outline').trim(),
+ ).toBe(FOCUS_OUTLINE);
// Mid and Leaf are DOM descendants of Root's <li> (nested <ul role="group">
// subtrees) — their own outline var must stay unset, not inherit Root's.
expect(getComputedStyle(mid).getPropertyValue('--_focus-outline')).toBe(
diff --git a/packages/core/src/hooks/useInputStatusIcon.tsx b/packages/core/src/hooks/useInputStatusIcon.tsx
index 7b68ca5bf7..5068730489 100644
--- a/packages/core/src/hooks/useInputStatusIcon.tsx
+++ b/packages/core/src/hooks/useInputStatusIcon.tsx
@@ -40,8 +40,9 @@ import type {FieldStatusVariant} from '../FieldStatus/FieldStatus';
import type {InputStatus, InputStatusType} from '../Field/types';
import {useTooltip} from '../Tooltip';
import {useTranslator} from '../i18n';
-import {colorVars, radiusVars} from '../theme/tokens.stylex';
+import {radiusVars} from '../theme/tokens.stylex';
import {themeProps} from '../utils/themeProps';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
/**
* Maps each status type to its glyph. Shared so every input shows the same icon
@@ -82,12 +83,8 @@ const styles = stylex.create({
color: 'inherit',
cursor: 'pointer',
borderRadius: radiusVars['--radius-full'],
- outlineWidth: {default: null, ':focus-visible': '2px'},
- outlineStyle: {default: null, ':focus-visible': 'solid'},
- outlineColor: {
- default: null,
- ':focus-visible': colorVars['--color-accent'],
- },
+ // Not the shared offset: this button sits inside the field, and measured at
+ // the standard 3px its ring crosses the field border.
outlineOffset: {default: null, ':focus-visible': '2px'},
},
});
@@ -224,7 +221,10 @@ export function useInputStatusIcon({
aria-describedby={tooltip.describedBy}
onClick={handleButtonClick}
onBlur={handleButtonBlur}
- {...stylex.props(styles.statusButton)}>
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.statusButton,
+ )}>
{icon}
</button>
{tooltip.renderTooltip(status.message)}
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index d670cea31f..e557c4998a 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -42,6 +42,7 @@ import {
colorDefaults,
spacingDefaults,
sizeDefaults,
+ focusDefaults,
radiusDefaults,
shadowDefaults,
durationDefaults,
@@ -74,6 +75,7 @@ export type CoreTokenName =
| keyof typeof colorDefaults
| keyof typeof spacingDefaults
| keyof typeof sizeDefaults
+ | keyof typeof focusDefaults
| keyof typeof radiusDefaults
| keyof typeof shadowDefaults
| keyof typeof durationDefaults
@@ -377,6 +379,7 @@ export const tokenDefaults: Record<string, string> = {
...colorDefaults,
...spacingDefaults,
...sizeDefaults,
+ ...focusDefaults,
...radiusDefaults,
...shadowDefaults,
...durationDefaults,
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 4c58efba1e..091bc3897d 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -23,6 +23,23 @@ const defaultInput = {
},
};
+describe('focus outline tokens', () => {
+ it('emits a focus ring override into the theme scope', () => {
+ const theme = defineTheme({
+ name: 'brand',
+ tokens: {
+ '--focus-outline-color': '#FF00FF',
+ '--focus-outline-width': '4px',
+ },
+ });
+
+ const {component} = generateThemeCSS(theme);
+
+ expect(component).toContain('--focus-outline-color: #FF00FF;');
+ expect(component).toContain('--focus-outline-width: 4px;');
+ });
+});
+
describe('generateThemeRules', () => {
const theme = defineTheme(defaultInput);
const rules = generateThemeRules(theme);
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 90b6d3bbf4..86c5270204 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -90,6 +90,7 @@ export {
spacingDefaults,
sizeDefaults,
borderDefaults,
+ focusDefaults,
radiusDefaults,
shadowDefaults,
durationDefaults,
@@ -102,6 +103,7 @@ export {
spacingVars,
sizeVars,
borderVars,
+ focusVars,
radiusVars,
shadowVars,
durationVars,
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index 9db606ac29..d0c93be655 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -193,6 +193,24 @@ export const borderVars = stylex.defineVars(borderDefaults);
export type BorderVarName = keyof typeof borderDefaults;
+// =============================================================================
+// Focus Tokens
+// =============================================================================
+// The keyboard focus ring, as one definition for the whole system. Values come
+// from Design Conventions §User Interaction States: 2px --color-accent at 3px
+// offset. Components read these through utils/focusOutline.stylex.ts; the
+// `:focus-visible` condition stays in core, so a theme can restyle the ring
+// but cannot show it to pointer users.
+
+export const focusDefaults = {
+ '--focus-outline-width': '2px',
+ '--focus-outline-style': 'solid',
+ '--focus-outline-color': 'var(--color-accent)',
+ '--focus-outline-offset': '3px',
+} as const;
+
+export const focusVars = stylex.defineVars(focusDefaults);
+
// =============================================================================
// Radius Tokens
// =============================================================================
diff --git a/packages/core/src/theme/tokens.test.ts b/packages/core/src/theme/tokens.test.ts
index 1dc7808dd5..f586d3026f 100644
--- a/packages/core/src/theme/tokens.test.ts
+++ b/packages/core/src/theme/tokens.test.ts
@@ -280,3 +280,40 @@ describe('resolveThemeTokens — generated themes end to end', () => {
expect(light['--color-icon-accent']).toBe(light['--color-accent']);
});
});
+
+describe('focus outline tokens', () => {
+ it('default to the accent ring from Design Conventions', () => {
+ const tokens = resolveThemeTokens(null, {mode: 'light'});
+
+ expect(tokens['--focus-outline-width']).toBe('2px');
+ expect(tokens['--focus-outline-style']).toBe('solid');
+ expect(tokens['--focus-outline-offset']).toBe('3px');
+ // Tracks the theme's accent unless a theme says otherwise.
+ expect(tokens['--focus-outline-color']).toBe(tokens['--color-accent']);
+ });
+
+ it('follows a theme accent without an explicit focus override', () => {
+ const theme = defineTheme({name: 'brand', color: {accent: '#AA0000'}});
+ const tokens = resolveThemeTokens(theme, {mode: 'light'});
+
+ expect(tokens['--focus-outline-color']).toBe(tokens['--color-accent']);
+ expect(tokens['--focus-outline-color']).not.toContain('var(');
+ });
+
+ it('takes an explicit ring over the accent', () => {
+ const theme = defineTheme({
+ name: 'brand',
+ color: {accent: '#AA0000'},
+ tokens: {
+ '--focus-outline-color': '#00FF00',
+ '--focus-outline-width': '4px',
+ '--focus-outline-offset': '0px',
+ },
+ });
+ const tokens = resolveThemeTokens(theme, {mode: 'light'});
+
+ expect(tokens['--focus-outline-color']).toBe('#00FF00');
+ expect(tokens['--focus-outline-width']).toBe('4px');
+ expect(tokens['--focus-outline-offset']).toBe('0px');
+ });
+});
diff --git a/packages/core/src/utils/focusOutline.stylex.ts b/packages/core/src/utils/focusOutline.stylex.ts
index 9b32dababa..b7ccead6df 100644
--- a/packages/core/src/utils/focusOutline.stylex.ts
+++ b/packages/core/src/utils/focusOutline.stylex.ts
@@ -7,28 +7,42 @@
* @position Internal utility for consistent keyboard focus outlines across core components
*
* Centralizes the standard Astryx focus outline, shown only for keyboard focus.
- * Every focusable surface drew the same 2px accent ring at 2px offset already;
- * writing it per component meant five identical definitions to keep in step.
+ * Every focusable surface drew the same 2px accent ring already; writing it per
+ * component meant dozens of identical definitions to keep in step, and they did
+ * not stay in step — offsets drifted and one ring was a border-width thick.
*
- * These are utility styles, deliberately NOT a theme target. A shared
- * `astryx-focus-outline` class was tried and pulled: a theme can only override
- * the ring unconditionally through it (`generateThemeRules` mangles
- * `:focus-visible` into `.focus-visible` and truncates `:has(:focus-visible)`
- * at the paren), so the one thing such a target exists for — restyling a
- * STATE — is exactly what it cannot express. Making focus outlines themeable
- * is worth doing on top of this consolidation, once that is fixed.
+ * Every ring in core and lab is drawn from here, with one exception recorded in
+ * Switch: its condition is a component-scoped ancestor marker, which cannot be
+ * shared without leaking focus state between components. A component may still
+ * override the OFFSET (a ring that must sit inset, or clear of a field border);
+ * width, style and color are not restated anywhere.
+ *
+ * Every value comes from the `--focus-outline-*` tokens, which is how a theme
+ * restyles the ring: one override reaches every component at once. The
+ * `:focus-visible` condition is not themeable and stays here, so a theme can
+ * change what the ring looks like but cannot show it to pointer users.
*/
import * as stylex from '@stylexjs/stylex';
-import {colorVars} from '../theme/tokens.stylex';
+import {focusVars} from '../theme/tokens.stylex';
+
+const FOCUS_OUTLINE_WIDTH = focusVars['--focus-outline-width'];
+const FOCUS_OUTLINE_STYLE = focusVars['--focus-outline-style'];
+const FOCUS_OUTLINE_COLOR = focusVars['--focus-outline-color'];
+
+const FOCUS_OUTLINE_OFFSET = focusVars['--focus-outline-offset'];
-const FOCUS_OUTLINE_WIDTH = '2px';
-// 3px, per Design Conventions §User Interaction States: "2px --color-accent
-// outline at 3px offset". Most components had drifted to 2px; Button, Calendar,
-// Dialog and Pagination were the ones matching the spec, so the consolidation
-// takes their value rather than the majority's.
-const FOCUS_OUTLINE_OFFSET = '3px';
-const FOCUS_OUTLINE_COLOR = colorVars['--color-accent'];
+/**
+ * The ring as a single `outline` value, for reading it at runtime — an
+ * assertion, or an element styled imperatively.
+ *
+ * NOT usable inside another file's `stylex.create`: StyleX resolves imported
+ * `defineVars` and nothing else, so a component whose condition
+ * {@link focusOutlineStyles} cannot express (Switch, whose ring keys off a
+ * component-scoped ancestor marker) has to compose the `focusVars` tokens
+ * itself.
+ */
+export const FOCUS_OUTLINE = `${FOCUS_OUTLINE_WIDTH} ${FOCUS_OUTLINE_STYLE} ${FOCUS_OUTLINE_COLOR}`;
/**
* Written as longhands rather than the `outline` shorthand.
@@ -40,7 +54,7 @@ const FOCUS_OUTLINE_COLOR = colorVars['--color-accent'];
*/
const focusOutlineLonghands = {
outlineWidth: FOCUS_OUTLINE_WIDTH,
- outlineStyle: 'solid',
+ outlineStyle: FOCUS_OUTLINE_STYLE,
outlineColor: FOCUS_OUTLINE_COLOR,
} as const;
@@ -53,8 +67,8 @@ const focusOutlineLonghands = {
* Longhands, not the `outline` shorthand, for the same reason the styles are:
* a shorthand resets every longhand it covers, so a caller could not re-color
* the ring without restating its width and style. Split, each part is
- * independently overridable — and `--color-accent` stays a var, so a theme's
- * accent still flows through.
+ * independently overridable — and every part stays a var, so a theme's
+ * `--focus-outline-*` overrides still flow through.
*
* Keys are camelCase to match `HTMLElement.style`, so this spreads straight
* onto an element:
@@ -66,7 +80,7 @@ const focusOutlineLonghands = {
*/
export const FOCUS_OUTLINE_PARTS = {
outlineWidth: FOCUS_OUTLINE_WIDTH,
- outlineStyle: 'solid',
+ outlineStyle: FOCUS_OUTLINE_STYLE,
outlineColor: FOCUS_OUTLINE_COLOR,
outlineOffset: FOCUS_OUTLINE_OFFSET,
} as const;
@@ -113,7 +127,7 @@ export const focusOutlineStyles = stylex.create({
publishFocusVisibleVars: {
'--_focus-outline': {
default: 'none',
- ':focus-visible': `${FOCUS_OUTLINE_WIDTH} solid ${FOCUS_OUTLINE_COLOR}`,
+ ':focus-visible': FOCUS_OUTLINE,
},
'--_focus-outline-offset': {
default: '0',
@@ -123,7 +137,7 @@ export const focusOutlineStyles = stylex.create({
focusWithinOrPublished: {
outline: {
default: 'var(--_focus-outline, none)',
- ':has(:focus-visible)': `${FOCUS_OUTLINE_WIDTH} solid ${FOCUS_OUTLINE_COLOR}`,
+ ':has(:focus-visible)': FOCUS_OUTLINE,
},
outlineOffset: {
default: 'var(--_focus-outline-offset, 0)',
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index 9e2abdce09..1c77663a63 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -101,3 +101,7 @@ export type {RGBA} from './color';
export {devWarn, devError, warnOnce, formatDevMessage} from './devWarning';
export {rtlStyles} from './rtlStyles';
+
+// The shared focus ring, exported for @astryxdesign/lab — same reason
+// rtlStyles is: a style that must be identical across packages, not copied.
+export {focusOutlineStyles, focusOutlineProps} from './focusOutline.stylex';
diff --git a/packages/lab/src/Chat/ChatEmojiPicker.tsx b/packages/lab/src/Chat/ChatEmojiPicker.tsx
index efa5a7579b..ccabc2621f 100644
--- a/packages/lab/src/Chat/ChatEmojiPicker.tsx
+++ b/packages/lab/src/Chat/ChatEmojiPicker.tsx
@@ -34,7 +34,7 @@ import {
typeScaleVars,
} from '@astryxdesign/core/theme/tokens.stylex';
import type {BaseProps} from '@astryxdesign/core';
-import {mergeProps} from '@astryxdesign/core/utils';
+import {focusOutlineStyles, mergeProps} from '@astryxdesign/core/utils';
import {themeProps} from '@astryxdesign/core/utils';
import {Popover} from '@astryxdesign/core/Popover';
import {TextInput} from '@astryxdesign/core/TextInput';
@@ -148,11 +148,9 @@ const styles = stylex.create({
cursor: 'pointer',
fontSize: 18,
lineHeight: typeScaleVars['--text-body-leading'],
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: -2,
+ // Inset, not the shared offset: the cells sit in a tight 8-across grid, so
+ // an outset ring would overlap its neighbors.
+ outlineOffset: {default: '0', ':focus-visible': -2},
transitionProperty: 'background-color',
transitionDuration: {
default: durationVars['--duration-fast'],
@@ -271,7 +269,10 @@ export function ChatEmojiPicker({
data-emoji={option.emoji}
aria-label={`React with ${option.name}`}
onClick={() => handleSelect(option.emoji)}
- {...stylex.props(styles.cell)}>
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.cell,
+ )}>
<span aria-hidden="true">{option.emoji}</span>
</button>
))}
diff --git a/packages/lab/src/InfoTip/InfoTip.tsx b/packages/lab/src/InfoTip/InfoTip.tsx
index b208041807..83100cbf7e 100644
--- a/packages/lab/src/InfoTip/InfoTip.tsx
+++ b/packages/lab/src/InfoTip/InfoTip.tsx
@@ -26,6 +26,7 @@ import {
radiusVars,
spacingVars,
} from '@astryxdesign/core/theme/tokens.stylex';
+import {focusOutlineStyles} from '@astryxdesign/core/utils';
/**
* Size of the info icon. Maps 1:1 to Icon sizes
@@ -70,14 +71,6 @@ const styles = stylex.create({
'@media (hover: hover)': colorVars['--color-icon-primary'],
},
},
- outline: {
- default: null,
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
transitionProperty: 'color',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
@@ -145,7 +138,7 @@ export function InfoTip({
onKeyDown={handleKeyDown}
onBlur={handleReset}
onMouseLeave={handleReset}
- {...stylex.props(styles.trigger)}>
+ {...stylex.props(focusOutlineStyles.focusVisible, styles.trigger)}>
<Icon icon="info" size={size} />
</button>
</Tooltip>
diff --git a/packages/lab/src/LogStream/LogStream.tsx b/packages/lab/src/LogStream/LogStream.tsx
index 5b2475c366..9c41879ec0 100644
--- a/packages/lab/src/LogStream/LogStream.tsx
+++ b/packages/lab/src/LogStream/LogStream.tsx
@@ -34,7 +34,11 @@ import {
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
-import {mergeProps, themeProps} from '@astryxdesign/core/utils';
+import {
+ focusOutlineStyles,
+ mergeProps,
+ themeProps,
+} from '@astryxdesign/core/utils';
import {
borderVars,
colorVars,
@@ -288,11 +292,6 @@ const styles = stylex.create({
fontWeight: fontWeightVars['--font-weight-medium'],
cursor: 'pointer',
boxShadow: shadowVars['--shadow-med'],
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: 2,
},
jumpToLatestTerminal: {
borderColor: TERM.border,
@@ -561,6 +560,7 @@ export function LogStream({
type="button"
onClick={handleJumpToLatest}
{...stylex.props(
+ focusOutlineStyles.focusVisible,
styles.jumpToLatest,
isTerminal && styles.jumpToLatestTerminal,
)}>
diff --git a/packages/lab/src/Stepper/Step.tsx b/packages/lab/src/Stepper/Step.tsx
index bb046ed3ae..fd6a58f9b0 100644
--- a/packages/lab/src/Stepper/Step.tsx
+++ b/packages/lab/src/Stepper/Step.tsx
@@ -28,7 +28,7 @@ import {
durationVars,
easeVars,
} from '@astryxdesign/core/theme/tokens.stylex';
-import {mergeProps} from '@astryxdesign/core/utils';
+import {focusOutlineStyles, mergeProps} from '@astryxdesign/core/utils';
import type {BaseProps} from '@astryxdesign/core';
import {Icon} from '@astryxdesign/core/Icon';
import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
@@ -440,17 +440,6 @@ const styles = stylex.create({
},
},
- focusRing: {
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: {
- default: '0',
- ':focus-visible': '2px',
- },
- },
-
// ===================== ON-TRACK LAYOUT =====================
// Indicator is slotted into the connector line as a node on the track.
// Each step draws the connector segments that flank its own indicator; the
@@ -1109,7 +1098,7 @@ export function Step({
styles.otInteractive,
styles.otRowWrap,
styles.otRowPadV(densitySpace),
- styles.focusRing,
+ focusOutlineStyles.focusVisible,
)}>
{inner}
</button>
@@ -1187,7 +1176,7 @@ export function Step({
styles.otInteractive,
styles.otColWrap,
styles.otPadBlock(densitySpace),
- styles.focusRing,
+ focusOutlineStyles.focusVisible,
)}>
{innerH}
</button>
@@ -1239,7 +1228,7 @@ export function Step({
aria-label={stepAriaLabel}
{...stylex.props(
styles.buttonReset,
- styles.focusRing,
+ focusOutlineStyles.focusVisible,
density === 'compact' && styles.densityCompact,
density === 'balanced' && styles.densityBalanced,
density === 'spacious' && styles.densitySpacious,
@@ -1295,7 +1284,7 @@ export function Step({
aria-label={stepAriaLabel}
{...stylex.props(
styles.buttonReset,
- styles.focusRing,
+ focusOutlineStyles.focusVisible,
density === 'compact' && styles.densityCompact,
density === 'balanced' && styles.densityBalanced,
density === 'spacious' && styles.densitySpacious,
diff --git a/packages/lab/src/TransferList/TransferList.tsx b/packages/lab/src/TransferList/TransferList.tsx
index 8e13c09fac..c07ba80f30 100644
--- a/packages/lab/src/TransferList/TransferList.tsx
+++ b/packages/lab/src/TransferList/TransferList.tsx
@@ -44,7 +44,12 @@ import {
spacingVars,
typeScaleVars,
} from '@astryxdesign/core/theme/tokens.stylex';
-import {mergeProps, mergeRefs, themeProps} from '@astryxdesign/core/utils';
+import {
+ focusOutlineStyles,
+ mergeProps,
+ mergeRefs,
+ themeProps,
+} from '@astryxdesign/core/utils';
import {reorderStyles} from '../reorderStyles';
import {transferListVars} from './tokens.stylex';
@@ -234,11 +239,9 @@ const styles = stylex.create({
flexDirection: 'column',
minWidth: 0,
overflow: 'hidden',
- outline: {
- default: 'none',
- ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
- },
- outlineOffset: -2,
+ // Inset, not the shared offset: the panel's own edge is the container
+ // boundary, so an outset ring would fall outside the component.
+ outlineOffset: {default: '0', ':focus-visible': -2},
},
panelDivider: {
borderInlineStartWidth: {
@@ -1180,7 +1183,7 @@ export function TransferList<T extends string = string>({
tabIndex={-1}
{...mergeProps(
themeProps('transfer-list-panel', {side: 'selected'}),
- stylex.props(styles.panel),
+ stylex.props(focusOutlineStyles.focusVisible, styles.panel),
)}>
<div {...stylex.props(styles.panelHeader)}>
<Text id={selectedHeadingId} type="label" color="secondary">
@@ -1233,7 +1236,11 @@ export function TransferList<T extends string = string>({
tabIndex={-1}
{...mergeProps(
themeProps('transfer-list-panel', {side: 'available'}),
- stylex.props(styles.panel, styles.panelDivider),
+ stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.panel,
+ styles.panelDivider,
+ ),
)}>
<div {...stylex.props(styles.panelHeader)}>
<Text id={availableHeadingId} type="label" color="secondary">
diff --git a/scripts/generate-token-docs.mjs b/scripts/generate-token-docs.mjs
index 19973490ad..84015cbd21 100644
--- a/scripts/generate-token-docs.mjs
+++ b/scripts/generate-token-docs.mjs
@@ -106,6 +106,15 @@ const groups = [
headers: ['Token', 'Value'],
formatRow: (name, value) => [name, value],
},
+ {
+ key: 'focus',
+ exportName: 'focusDefaults',
+ title: 'Focus Tokens',
+ description:
+ 'The keyboard focus ring, shared by every component that draws one. Override these to restyle focus across the system.',
+ headers: ['Token', 'Value'],
+ formatRow: (name, value) => [name, value],
+ },
{
key: 'radius',
previewType: 'radius-box',