An open source design system that's fully customizable and agent ready
TypeScript
fix(RadioList): the pressed circle reads the row's press through a custom property, not a :has() scan (#8424)
Cindy Zhangf57df18221eb
diff --git a/.changeset/radio-list-press-no-descendant-has.md b/.changeset/radio-list-press-no-descendant-has.mdnew file mode 100644index 0000000000..b82842f46f--- /dev/null+++ b/.changeset/radio-list-press-no-descendant-has.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `RadioList`'s pressed circle no longer comes from a `:has()` check that reached every element under the row, so a large page no longer restyles everything under each row whenever anything inside it changes. The row is pressed and the circle shows it exactly as before, and a link or button inside the row still keeps its own press.++@cixzhangdiff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsxindex 5d5b4ae986..0c1956141b 100644--- a/packages/core/src/RadioList/RadioList.test.tsx+++ b/packages/core/src/RadioList/RadioList.test.tsx@@ -16,9 +16,10 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {- hasPressedArm,hasReleaseFade,readsPressStrength,+ rulesDeclaredFor,+ rulesWithSelector,} from '../__tests__/pressState';import {RadioList} from './RadioList';import {RadioListItem} from './RadioListItem';@@ -884,6 +885,26 @@ describe('forced colors (WCAG 1.4.11)', () => {});});+/** Does the element's own CSS paint the row's mouse press (`--_radio-row-press`)? */+function readsRowPress(el: Element): boolean {+ return rulesDeclaredFor(el).some(rule =>+ rule.includes('var(--_radio-row-press'),+ );+}++/**+ * Does the row declare the mouse press's paint while pressed, but not while a+ * nested link or button is the pressed one?+ */+function declaresRowPress(el: Element): boolean {+ return rulesWithSelector(el, ':active').some(+ rule =>+ rule.includes('--_radio-row-press:') &&+ rule.includes('var(--color-overlay-pressed)') &&+ /:not\(:has\(a:active, ?button:active/.test(rule),+ );+}+describe('pressed state', () => {it('paints the pressed overlay over the radio indicator while the row is pressed', () => {const {container} = render(@@ -894,10 +915,14 @@ describe('pressed state', () => {);const circle = container.querySelector('.astryx-radio-indicator');const wrapper = circle?.parentElement?.parentElement;- if (wrapper == null) {- throw new Error('the radio has no indicator wrapper to press');+ const row = circle?.closest('[data-astryx-pressable]');+ if (wrapper == null || row == null) {+ throw new Error('the radio has no pressable row or indicator wrapper');}- expect(hasPressedArm(wrapper)).toBe(true);+ // The row declares the mouse press's paint while it is pressed, and the+ // layer over the circle reads it.+ expect(declaresRowPress(row)).toBe(true);+ expect(readsRowPress(wrapper)).toBe(true);});it('does not expose a pressed arm on a disabled radio', () => {@@ -908,10 +933,12 @@ describe('pressed state', () => {);const circle = container.querySelector('.astryx-radio-indicator');const wrapper = circle?.parentElement?.parentElement;- if (wrapper == null) {- throw new Error('the radio has no indicator wrapper');+ const row = wrapper?.closest('.astryx-item');+ if (wrapper == null || row == null) {+ throw new Error('the radio has no row or indicator wrapper');}- expect(hasPressedArm(wrapper)).toBe(false);+ expect(declaresRowPress(row)).toBe(false);+ expect(readsRowPress(wrapper)).toBe(false);});it('fades the touch press out from the row, with the overlay reading its strength', () => {diff --git a/packages/core/src/RadioList/RadioListItem.press.source-build.test.mjs b/packages/core/src/RadioList/RadioListItem.press.source-build.test.mjsnew file mode 100644index 0000000000..a2d1b1ca71--- /dev/null+++ b/packages/core/src/RadioList/RadioListItem.press.source-build.test.mjs@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file RadioListItem.press.source-build.test.mjs+ * @input Uses Babel, the StyleX plugin as the package stylesheet compiles it,+ * and the RadioListItem source+ * @output Verifies the shipped mouse press reaches the radio circle through an+ * inherited custom property, with no `:has()` ancestor scan+ * @position Regression test for the compiled CSS of the RadioListItem module+ *+ * The circle's pressed layer once read the row through+ * `.layer:where(.row:active:not(:has(...)) *)`. That shape makes the browser+ * restyle everything under the row on every DOM change. The row now declares+ * the press's paint under a `:has()` on itself, and the layer reads it.+ */++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 RadioListItem mouse press', () => {+ it('ships no :has() followed by a descendant *', async () => {+ const selectors = selectorsOf(await compiledCss('RadioListItem.tsx'));+ expect(+ selectors.filter(selector => /:has\([^{]*\)[^{,]* \*/.test(selector)),+ ).toEqual([]);+ });++ it('keeps the nested-control exclusion on the row itself', async () => {+ const css = await compiledCss('RadioListItem.tsx');+ const press = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter(match =>+ match[2].includes('--_radio-row-press:'),+ );+ expect(press.length).toBeGreaterThan(0);+ for (const [, selector] of press) {+ expect(selector).toMatch(/:active:not\(:has\(a:active/);+ expect(selector).not.toMatch(/ \*/);+ }+ });+});diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 7df2df5245..683f7dbee9 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -38,6 +38,10 @@ import {themeProps} from '../utils/themeProps';// that paints it. See interactionOverlay.stylex.ts.const pressedOverlayImage = 'var(--_press-paint-image)';+// The mouse press's paint, declared on the row and inherited by the layer+// over the circle. Internal: not a theme hook.+const ROW_PRESS = '--_radio-row-press';+const styles = stylex.create({radioWrapper: {position: 'relative',@@ -48,8 +52,10 @@ const styles = stylex.create({isolation: 'isolate',},// The row remains the large press target, but nested links and buttons keep- // their independent action and do not make the radio appear pressed. This- // owner-drawn layer also survives a theme replacing the indicator component.+ // their independent action and do not make the radio appear pressed: the+ // row declares the mouse press's paint (`rowStyles.press`) and this layer+ // reads it. This owner-drawn layer also survives a theme replacing the+ // indicator component.// Two pointers, two press models (see interactionOverlay.stylex.ts): a// mouse keeps `:active`; under a coarse pointer that arm is dropped and the// touch press controller writes `data-astryx-press` on the row, which this layer@@ -63,16 +69,7 @@ const styles = stylex.create({inset: 0,borderRadius: radiusVars['--radius-full'],pointerEvents: 'none',- backgroundColor: {- default: 'transparent',- [stylex.when.ancestor(- ':active:not(:has(a:active,button:active,[role="button"]:active,[role="link"]:active))',- indicatorScope,- )]: {- default: colorVars['--color-overlay-pressed'],- '@media (pointer: coarse)': 'transparent',- },- },+ backgroundColor: `var(${ROW_PRESS}, transparent)`,// The touch press, as an image layer over the colour: an image change is// discrete, so no transition can delay the onset, and the strength the// row's `pressedAlpha` arms own (1 while on, 1 → 0 over the release) is@@ -152,6 +149,22 @@ const rowStyles = stylex.create({// circle reads it.backgroundImage: 'none',},+ // The mouse press (a finger's lives on `data-astryx-press`): the row is+ // pressed, but not through a nested link or button, which keep their own+ // action. The `:has()` is on the row itself and reaches no descendant+ // selector, so a change inside the row re-checks the row alone; the circle's+ // layer reads the paint through inheritance rather than a relation that+ // would restyle everything under the row.+ press: {+ [ROW_PRESS]: {+ default: null,+ ':active:not(:has(a:active,button:active,[role="button"]:active,[role="link"]:active))':+ {+ default: colorVars['--color-overlay-pressed'],+ '@media (pointer: coarse)': 'transparent',+ },+ },+ },});export interface RadioListItemProps extends BaseProps<HTMLDivElement> {@@ -387,6 +400,7 @@ export function RadioListItem({// styles so it wins within the base layer; a `radio-list-item` theme// still overrides it from the higher `astryx-theme` layer.rowStyles.root,+ !isDisabled && rowStyles.press,xstyle,] as StyleXStyles}