Skip to content

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

TypeScript

fix(Switch): the focus ring follows the input through a sibling, not a :has() scan (#8415)

Cindy Zhangd695efb568bf
diff --git a/.changeset/switch-focus-ring-sibling.md b/.changeset/switch-focus-ring-sibling.md
new file mode 100644
index 0000000000..9a2607db8d
--- /dev/null
+++ b/.changeset/switch-focus-ring-sibling.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Switch`'s focus ring now follows the switch's own input through a sibling selector instead of a `:has()` check on the whole row, so a switch whose row holds large content (a long description, for example) no longer restyles everything in that row whenever something inside it changes. The ring looks and behaves the same. One edge changes: a focusable link inside the switch's label or description keeps its own focus ring and no longer also rings the switch.
+
+@cixzhang
diff --git a/internal/a11y-spec/src/patterns/switch.ts b/internal/a11y-spec/src/patterns/switch.ts
index 8d8e3d28f1..5298650e2f 100644
--- a/internal/a11y-spec/src/patterns/switch.ts
+++ b/internal/a11y-spec/src/patterns/switch.ts
@@ -765,7 +765,7 @@ export const SWITCH_PATTERN: PatternContract<SwitchStateFacts> =
verifiedBy:
"the repository visual gate and the component's own focus-ring styling",
reason:
- 'A focus indicator is a painted result. Astryx switches draw theirs on the track through an ancestor `:has(:focus-visible)` condition, so proving it means comparing pixels, which is the visual layer.',
+ "A focus indicator is a painted result. Astryx switches draw theirs on the track when the switch's own input, the track's preceding sibling, matches `:focus-visible`, so proving it means comparing pixels, which is the visual layer.",
},
'2.4.11-focus-not-obscured': {
owner: 'the composing page',
diff --git a/packages/core/src/Switch/Switch.focusRing.source-build.test.mjs b/packages/core/src/Switch/Switch.focusRing.source-build.test.mjs
new file mode 100644
index 0000000000..cb53dbaa95
--- /dev/null
+++ b/packages/core/src/Switch/Switch.focusRing.source-build.test.mjs
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Switch.focusRing.source-build.test.mjs
+ * @input Uses Babel, the StyleX plugin as the package stylesheet compiles it,
+ * and the Switch source
+ * @output Verifies the shipped focus ring follows the switch's own input
+ * through a sibling relation, with no `:has()` ancestor scan
+ * @position Regression test for the compiled CSS of the Switch module
+ *
+ * The ring's condition once read `:has(:focus-visible)` on an ancestor of the
+ * track (`.track:where(.scope:has(:focus-visible) *)`). That shape makes the
+ * browser restyle everything under the ancestor on every DOM change. The
+ * track's preceding sibling is the focusable input, so the ring reads that
+ * input directly.
+ */
+
+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';
+import stylexResolution from '../../../../scripts/stylex-module-resolution.cjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+
+async function compiledCss(fileName) {
+ const file = path.join(__dirname, fileName);
+ const result = await transformAsync(await fs.readFile(file, 'utf8'), {
+ babelrc: false,
+ configFile: false,
+ filename: file,
+ presets: [
+ ['@babel/preset-typescript', {isTSX: true, allExtensions: true}],
+ ['@babel/preset-react', {runtime: 'automatic'}],
+ ],
+ plugins: [
+ [
+ stylexBabelPlugin,
+ {
+ dev: false,
+ runtimeInjection: false,
+ genConditionalClasses: true,
+ treeshakeCompensation: true,
+ unstable_moduleResolution: stylexResolution.stylexModuleResolution,
+ },
+ ],
+ ],
+ });
+ return stylexBabelPlugin.processStylexRules(
+ result?.metadata?.stylex ?? [],
+ false,
+ );
+}
+
+/** Every selector in `css`, one per rule. */
+function selectorsOf(css) {
+ return [...css.matchAll(/([^{}]+)\{[^{}]*\}/g)].map(match => match[1].trim());
+}
+
+describe('the shipped Switch focus ring', () => {
+ it('reads the input as the track\u2019s preceding sibling, never through :has()', async () => {
+ const selectors = selectorsOf(await compiledCss('Switch.tsx'));
+ const ring = selectors.filter(selector =>
+ selector.includes(':focus-visible'),
+ );
+ expect(ring.length).toBeGreaterThan(0);
+ for (const selector of ring) {
+ expect(selector).toMatch(/:focus-visible ~ \*/);
+ expect(selector).not.toContain(':has(');
+ }
+ });
+
+ it('ships no :has() followed by a descendant *', async () => {
+ const selectors = selectorsOf(await compiledCss('Switch.tsx'));
+ expect(
+ selectors.filter(selector => /:has\([^{]*\)[^{,]* \*/.test(selector)),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsx
index 022504b8d4..d3249eb9b3 100644
--- a/packages/core/src/Switch/Switch.tsx
+++ b/packages/core/src/Switch/Switch.tsx
@@ -44,7 +44,7 @@ import type {InputStatus} from '../Field/types';
import {Spinner} from '../Spinner';
import {useTooltip} from '../Tooltip';
import {mergeProps, mergeRefs, rtlStyles} from '../utils';
-import {switchFocusScope, switchScope} from './switch.markers.stylex';
+import {switchFocusInput, switchScope} from './switch.markers.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
@@ -258,20 +258,22 @@ const styles = stylex.create({
},
},
// 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.
+ // input is the track's preceding sibling, so the condition reads that input
+ // through its own marker: a sibling relation, never a `:has()` scan of the
+ // row, which would restyle everything under it on any change. 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)', switchFocusScope)]:
+ [stylex.when.siblingBefore(':focus-visible', switchFocusInput)]:
`${focusVars['--focus-outline-width']} ${focusVars['--focus-outline-style']} ${focusVars['--focus-outline-color']}`,
},
outlineOffset: {
default: null,
- [stylex.when.ancestor(':has(:focus-visible)', switchFocusScope)]:
+ [stylex.when.siblingBefore(':focus-visible', switchFocusInput)]:
focusVars['--focus-outline-offset'],
},
},
@@ -686,6 +688,7 @@ export function Switch({
inputSizeStyles[size],
isDisabled && styles.inputDisabled,
isBusy && styles.inputBusy,
+ switchFocusInput,
)}
/>
<div
@@ -773,7 +776,6 @@ export function Switch({
isLabelHidden && styles.containerLabelHidden,
labelSpacing === 'spread' && styles.containerSpread,
!isDisabled && switchScope,
- switchFocusScope,
// The touch press's strength and release live on the row the
// controller writes to; the track and thumb inherit and paint it.
!isDisabled && interactionOverlayStyles.pressedAlpha,
diff --git a/packages/core/src/Switch/switch.markers.stylex.ts b/packages/core/src/Switch/switch.markers.stylex.ts
index e8a4634723..0c7f44c997 100644
--- a/packages/core/src/Switch/switch.markers.stylex.ts
+++ b/packages/core/src/Switch/switch.markers.stylex.ts
@@ -9,6 +9,11 @@ import * as stylex from '@stylexjs/stylex';
export const switchScope: ReturnType<typeof stylex.defineMarker> =
stylex.defineMarker();
-/** Focus-ring marker; unlike `switchScope`, it stays on while disabled. */
-export const switchFocusScope: ReturnType<typeof stylex.defineMarker> =
+/**
+ * Marks the switch's own focusable input, the track's preceding sibling, so
+ * the track's focus ring follows that input's `:focus-visible` alone. Unlike
+ * `switchScope`, it stays on while disabled (a focusable-disabled switch
+ * still shows the ring).
+ */
+export const switchFocusInput: ReturnType<typeof stylex.defineMarker> =
stylex.defineMarker();