An open source design system that's fully customizable and agent ready
TypeScript
fix(core): center coarse-pointer touch targets in RTL for Checkbox, Radio, and Switch (#5170) (#5177)
Geervan0d6dc2099bb6
diff --git a/apps/storybook/rtl-audit/rtl-audit.mjs b/apps/storybook/rtl-audit/rtl-audit.mjsindex 6ffd662077..f9b2a7c9f5 100644--- a/apps/storybook/rtl-audit/rtl-audit.mjs+++ b/apps/storybook/rtl-audit/rtl-audit.mjs@@ -126,8 +126,13 @@ function serve(root) {});}-const storyUrl = (port, id, rtl) =>- `http://127.0.0.1:${port}/iframe.html?id=${id}&viewMode=story${rtl ? '&globals=direction:rtl' : ''}`;+const storyUrl = (port, id, rtl, args = {}) => {+ const argQuery = Object.entries(args)+ .map(([name, value]) => `${name}:${value}`)+ .join(';');+ const argsParam = argQuery ? `&args=${encodeURIComponent(argQuery)}` : '';+ return `http://127.0.0.1:${port}/iframe.html?id=${id}&viewMode=story${rtl ? '&globals=direction:rtl' : ''}${argsParam}`;+};async function settle(page) {// Wait for the story to render (load event + fonts), but do NOT block on@@ -710,13 +715,81 @@ async function checkD4(page, port, t, card) {card.notes.push(`D4 overlay side frac: LTR ${sideL.toFixed(2)} RTL ${sideR.toFixed(2)} flipped=${flipped}`);}-async function scoreCurated(page, port, t) {+async function checkD7CoarseHit(page, port, t, card) {+ const wrapperSel = t.selectors?.wrapperSelector;+ const sizes = t.sizes || ['md'];++ const testDir = async (rtl, size) => {+ const inputSel = t.selectors?.inputSelectorBySize?.[size] ||+ t.selectors?.inputSelector || 'input[type="checkbox"], input[type="radio"]';+ await page.goto(storyUrl(port, t.storyId, rtl, {size}), {waitUntil: 'domcontentloaded'});+ await settle(page);+ await doSetup(page, t);++ return page.evaluate(({inputSel, wrapperSel, size, rtl}) => {+ const coarse = window.matchMedia('(pointer: coarse)').matches;+ const touchPoints = navigator.maxTouchPoints;+ const inputs = Array.from(document.querySelectorAll(inputSel));+ if (inputs.length === 0) return {coarse, touchPoints, size, rtl, count: 0, allHitsOk: false};++ let allHitsOk = true;+ let count = 0;+ const centers = [];+ for (const input of inputs) {+ const wrapper = wrapperSel ? input.closest(wrapperSel) : input.parentElement;+ if (!wrapper) continue;+ const b = wrapper.getBoundingClientRect();+ const inputBox = input.getBoundingClientRect();+ if (b.width < 1 || b.height < 1) continue;+ const cx = b.x + b.width / 2;+ const cy = b.y + b.height / 2;+ const hit = document.elementFromPoint(cx, cy);+ const isHit = hit === input || input.contains(hit);+ const isCentered = Math.abs(inputBox.x + inputBox.width / 2 - cx) < 0.5 &&+ Math.abs(inputBox.y + inputBox.height / 2 - cy) < 0.5;+ if (!isHit || !isCentered) allHitsOk = false;+ centers.push({+ wrapper: {x: b.x, y: b.y, width: b.width, height: b.height},+ hit: isHit,+ centered: isCentered,+ });+ count++;+ }+ return {coarse, touchPoints, size, rtl, count, allHitsOk, centers};+ }, {inputSel, wrapperSel, size, rtl}).catch(() => null);+ };++ const results = [];+ for (const size of sizes) {+ results.push(await testDir(false, size));+ results.push(await testDir(true, size));+ }++ if (results.some(result => result === null || !result.coarse || result.touchPoints < 1 || result.count === 0)) {+ card.dims.D7 = 'N-A';+ card.notes.push('D7: coarse-pointer context or input/wrapper targets not verified');+ return;+ }++ const pass = results.every(result => result.allHitsOk);+ card.dims.D7 = pass ? 'pass' : 'fail';+ const formatTarget = target => {+ const {width, height} = target.wrapper;+ const cx = target.wrapper.x + width / 2;+ const cy = target.wrapper.y + height / 2;+ return `${width}x${height}@(${cx.toFixed(0)},${cy.toFixed(0)})->${target.hit && target.centered ? 'HIT' : 'MISS'}`;+ };+ card.notes.push(`D7 coarse hit-target center: ${results.map(result => `${result.rtl ? 'RTL' : 'LTR'} ${result.size}:${result.centers.map(formatTarget).join(',')}`).join('; ')}`);+}++async function scoreCurated(page, coarsePage, port, t) {const card = {component: t.component, storyId: t.storyId, dims: {}, notes: []};for (const dim of t.dims) {try {if (dim === 'D2') await checkD2(page, port, t, card);else if (dim === 'D3') await checkD3Scroll(page, port, t, card);else if (dim === 'D4') await checkD4(page, port, t, card);+ else if (dim === 'D7') await checkD7CoarseHit(coarsePage, port, t, card);// D1 is handled by auto-discovery; ignore any stray D1 in curated entries.} catch (e) {card.dims[dim] = 'ERROR';@@ -770,6 +843,13 @@ async function mapPool(items, pages, fn) {),);const page = pages[0]; // curated dims run serially on the first page+ const coarseContext = await browser.newContext({+ viewport: {width: 1100, height: 760},+ deviceScaleFactor: 1,+ hasTouch: true,+ isMobile: true,+ });+ const coarsePage = await coarseContext.newPage();let entries = {};try {@@ -890,7 +970,7 @@ async function mapPool(items, pages, fn) {const dims = (t.dims || []).filter(d => d !== 'D1');if (dims.length === 0) continue;try {- const card = await scoreCurated(page, port, {...t, component, dims});+ const card = await scoreCurated(page, coarsePage, port, {...t, component, dims});curatedResults.push(card);console.error(`CUR ${card.rollup.padEnd(10)} ${component.padEnd(20)} ${JSON.stringify(card.dims)}`);} catch (e) {@@ -923,6 +1003,7 @@ async function mapPool(items, pages, fn) {if (verifiedNaError) coverage.registryError = verifiedNaError;await Promise.all(pages.map(p => p.close().catch(() => {})));+ await coarseContext.close().catch(() => {});await browser.close();server.close();diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex fe712ca7e8..c56e2f46e0 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -21,6 +21,20 @@"next": "[role=\"group\"] button:last-child"}},+ {+ "component": "CheckboxInput",+ "storyId": "core-checkboxinput--size-comparison",+ "dims": [+ "D7"+ ],+ "sizes": ["sm", "md"],+ "selectors": {+ "inputSelectorBySize": {+ "sm": "[data-testid=\"checkbox-sm\"]",+ "md": "[data-testid=\"checkbox-md\"]"+ }+ }+ },{"component": "CheckboxList","storyId": "core-checkboxlist--rich-descriptions",@@ -36,11 +50,25 @@"component": "RadioList","storyId": "core-radiolist--rich-content","dims": [- "D2"+ "D2",+ "D7"],+ "sizes": ["sm", "md"],"selectors": {"prev": "input[aria-label=\"Pro\"]",- "next": "[data-testid=\"radio-end-content\"]"+ "next": "[data-testid=\"radio-end-content\"]",+ "inputSelector": "input[type=\"radio\"]"+ }+ },+ {+ "component": "Switch",+ "storyId": "core-switch--default",+ "dims": [+ "D7"+ ],+ "sizes": ["sm", "md"],+ "selectors": {+ "inputSelector": "input[type=\"checkbox\"]"}},{diff --git a/apps/storybook/stories/CheckboxInput.stories.tsx b/apps/storybook/stories/CheckboxInput.stories.tsxindex fa2fff2a71..a7bb3d63c9 100644--- a/apps/storybook/stories/CheckboxInput.stories.tsx+++ b/apps/storybook/stories/CheckboxInput.stories.tsx@@ -278,24 +278,28 @@ export const SizeComparison: Story = {}}><CheckboxInputlabel="Medium size (default)"+ data-testid="checkbox-md"value={value1}onChange={setValue1}size="md"/><CheckboxInputlabel="Small size"+ data-testid="checkbox-sm"value={value2}onChange={setValue2}size="sm"/><CheckboxInputlabel="Medium size checked"+ data-testid="checkbox-md"value={value3}onChange={setValue3}size="md"/><CheckboxInputlabel="Small size checked"+ data-testid="checkbox-sm"value={value4}onChange={setValue4}size="sm"diff --git a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx b/packages/core/src/CheckboxInput/CheckboxInput.test.tsxindex f2ac19f4e0..96759a3e15 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.test.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.test.tsx@@ -19,6 +19,30 @@ import {getForcedColorsRules} from '../__tests__/forcedColors';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {FOCUS_OUTLINE_PARTS} from '../utils/focusOutline.stylex';+interface InjectedRule {+ selector: string;+ text: string;+ media: string | null;+}++function injectedRules(): InjectedRule[] {+ const walk = (rules: CSSRuleList, condition: string | null): InjectedRule[] =>+ [...rules].flatMap((rule): InjectedRule[] => {+ const {selectorText} = rule as CSSStyleRule;+ if (typeof selectorText === 'string') {+ return [{selector: selectorText, text: rule.cssText, media: condition}];+ }+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested == null) {+ return [];+ }+ const own = (rule as CSSMediaRule).media?.mediaText;+ return walk(nested, own != null && own !== '' ? own : condition);+ });++ return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));+}+afterEach(() => {__resetLiveRegionsForTest();});@@ -611,6 +635,35 @@ describe('CheckboxInput', () => {]).toEqual([]);});});++ describe('coarse pointer and RTL hit-target positioning', () => {+ it.each([+ ['sm', 'ltr'],+ ['sm', 'rtl'],+ ['md', 'ltr'],+ ['md', 'rtl'],+ ] as const)(+ 'applies centerInline styling to native input (size: %s, dir: %s)',+ (size, dir) => {+ const {container} = render(+ <div dir={dir}>+ <CheckboxInput+ label="Option"+ size={size}+ value={false}+ onChange={() => {}}+ />+ </div>,+ );++ const input = container.querySelector(+ 'input[type="checkbox"]',+ ) as HTMLInputElement;+ expect(input).toBeInTheDocument();+ expect(input.className).toContain('centerInline');+ },+ );+ });});// jsdom cannot emulate forced-colors rendering, so this asserts that thediff --git a/packages/core/src/CheckboxInput/CheckboxInput.tsx b/packages/core/src/CheckboxInput/CheckboxInput.tsxindex 73abae279a..345e038b43 100644--- a/packages/core/src/CheckboxInput/CheckboxInput.tsx+++ b/packages/core/src/CheckboxInput/CheckboxInput.tsx@@ -44,7 +44,7 @@ import type {IconType} from '../Icon';import type {InputStatus} from '../Field/types';import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';-import {mergeProps} from '../utils';+import {mergeProps, rtlStyles} from '../utils';import {indicatorScope} from '../Indicator/indicator.markers.stylex';import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';import {useResolvedRequired} from '../hooks/useResolvedRequired';@@ -78,6 +78,7 @@ const styles = stylex.create({},input: {position: 'absolute',+ top: '50%',margin: 0,padding: 0,opacity: 0,@@ -86,25 +87,11 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},zIndex: 1,- minInlineSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- minBlockSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- insetBlockStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- insetInlineStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- transform: {- default: null,- '@media (pointer: coarse)': 'translate(-50%, -50%)',+ },+ inputCoarse: {+ '@media (pointer: coarse)': {+ minInlineSize: 24,+ minBlockSize: 24,},},inputDisabled: {@@ -452,6 +439,8 @@ export function CheckboxInput({aria-busy={isBusy || undefined}{...stylex.props(styles.input,+ rtlStyles.centerInline('-50%'),+ styles.inputCoarse,wrapperSizeStyles[size],isDisabled && styles.inputDisabled,)}diff --git a/packages/core/src/RadioList/RadioList.test.tsx b/packages/core/src/RadioList/RadioList.test.tsxindex 01a41ac0fa..882eee2b2d 100644--- a/packages/core/src/RadioList/RadioList.test.tsx+++ b/packages/core/src/RadioList/RadioList.test.tsx@@ -15,6 +15,29 @@ import userEvent from '@testing-library/user-event';import {RadioList} from './RadioList';import {RadioListItem} from './RadioListItem';import {getForcedColorsRules} from '../__tests__/forcedColors';+interface InjectedRule {+ selector: string;+ text: string;+ media: string | null;+}++function injectedRules(): InjectedRule[] {+ const walk = (rules: CSSRuleList, condition: string | null): InjectedRule[] =>+ [...rules].flatMap((rule): InjectedRule[] => {+ const {selectorText} = rule as CSSStyleRule;+ if (typeof selectorText === 'string') {+ return [{selector: selectorText, text: rule.cssText, media: condition}];+ }+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested == null) {+ return [];+ }+ const own = (rule as CSSMediaRule).media?.mediaText;+ return walk(nested, own != null && own !== '' ? own : condition);+ });++ return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));+}// Mock showPopover/hidePopover (not implemented in jsdom) so the tooltip layer// reflects its open state via a `popover-open` attribute the tests can assert.@@ -949,6 +972,32 @@ describe('RadioList', () => {);});});++ describe('coarse pointer and RTL hit-target positioning', () => {+ it.each([+ ['sm', 'ltr'],+ ['sm', 'rtl'],+ ['md', 'ltr'],+ ['md', 'rtl'],+ ] as const)(+ 'applies centerInline styling to native input (size: %s, dir: %s)',+ (size, dir) => {+ const {container} = render(+ <div dir={dir}>+ <RadioList size={size} label="Choice" value="" onChange={() => {}}>+ <RadioListItem label="Option A" value="a" />+ </RadioList>+ </div>,+ );++ const input = container.querySelector(+ 'input[type="radio"]',+ ) as HTMLInputElement;+ expect(input).toBeInTheDocument();+ expect(input.className).toContain('centerInline');+ },+ );+ });});// jsdom cannot emulate forced-colors rendering, so this asserts that thediff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsxindex 6a01e4b5a5..8faf9145a3 100644--- a/packages/core/src/RadioList/RadioListItem.tsx+++ b/packages/core/src/RadioList/RadioListItem.tsx@@ -23,7 +23,7 @@ import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import type {BaseProps} from '../BaseProps';import {RadioListContext} from './RadioList';-import {mergeProps, isRenderable} from '../utils';+import {mergeProps, isRenderable, rtlStyles} from '../utils';import {indicatorScope} from '../Indicator/indicator.markers.stylex';import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';import {useIndicator} from '../Indicator';@@ -41,6 +41,7 @@ const styles = stylex.create({},input: {position: 'absolute',+ top: '50%',margin: 0,padding: 0,opacity: 0,@@ -49,25 +50,11 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},zIndex: 1,- minInlineSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- minBlockSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- insetBlockStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- insetInlineStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- transform: {- default: null,- '@media (pointer: coarse)': 'translate(-50%, -50%)',+ },+ inputCoarse: {+ '@media (pointer: coarse)': {+ minInlineSize: 24,+ minBlockSize: 24,},},inputDisabled: {@@ -268,6 +255,8 @@ export function RadioListItem({aria-describedby={hasDescription ? descriptionID : undefined}{...stylex.props(styles.input,+ rtlStyles.centerInline('-50%'),+ styles.inputCoarse,wrapperSizeStyles[size],isDisabled && styles.inputDisabled,)}diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsxindex 2571402e30..d352513110 100644--- a/packages/core/src/Switch/Switch.test.tsx+++ b/packages/core/src/Switch/Switch.test.tsx@@ -19,6 +19,30 @@ import {} from '../__tests__/forcedColors';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';+interface InjectedRule {+ selector: string;+ text: string;+ media: string | null;+}++function injectedRules(): InjectedRule[] {+ const walk = (rules: CSSRuleList, condition: string | null): InjectedRule[] =>+ [...rules].flatMap((rule): InjectedRule[] => {+ const {selectorText} = rule as CSSStyleRule;+ if (typeof selectorText === 'string') {+ return [{selector: selectorText, text: rule.cssText, media: condition}];+ }+ const nested = (rule as CSSGroupingRule).cssRules;+ if (nested == null) {+ return [];+ }+ const own = (rule as CSSMediaRule).media?.mediaText;+ return walk(nested, own != null && own !== '' ? own : condition);+ });++ return [...document.styleSheets].flatMap(sheet => walk(sheet.cssRules, null));+}+afterEach(() => {__resetLiveRegionsForTest();});@@ -789,6 +813,35 @@ describe('Switch', () => {expect(root).toHaveAttribute('aria-label', 'Toggle notifications');});});++ describe('coarse pointer and RTL hit-target positioning', () => {+ it.each([+ ['sm', 'ltr'],+ ['sm', 'rtl'],+ ['md', 'ltr'],+ ['md', 'rtl'],+ ] as const)(+ 'applies centerInline styling to native input (size: %s, dir: %s)',+ (size, dir) => {+ const {container} = render(+ <div dir={dir}>+ <Switch+ label="Dark mode"+ size={size}+ value={false}+ onChange={() => {}}+ />+ </div>,+ );++ const input = container.querySelector(+ 'input[type="checkbox"]',+ ) as HTMLInputElement;+ expect(input).toBeInTheDocument();+ expect(input.className).toContain('centerInline');+ },+ );+ });});// jsdom cannot emulate forced-colors rendering, so these assert that thediff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsxindex 91c8b54ccd..7e52e8f929 100644--- a/packages/core/src/Switch/Switch.tsx+++ b/packages/core/src/Switch/Switch.tsx@@ -41,7 +41,7 @@ import type {IconType} from '../Icon';import type {InputStatus} from '../Field/types';import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';-import {mergeProps} from '../utils';+import {mergeProps, mergeRefs, rtlStyles} from '../utils';import {switchScope} from './switch.markers.stylex';import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';@@ -159,6 +159,7 @@ const styles = stylex.create({},input: {position: 'absolute',+ top: '50%',margin: 0,padding: 0,opacity: 0,@@ -167,25 +168,11 @@ const styles = stylex.create({':is(:disabled,[aria-disabled="true"])': 'default',},zIndex: 1,- minInlineSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- minBlockSize: {- default: null,- '@media (pointer: coarse)': '24px',- },- insetBlockStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- insetInlineStart: {- default: null,- '@media (pointer: coarse)': '50%',- },- transform: {- default: null,- '@media (pointer: coarse)': 'translate(-50%, -50%)',+ },+ inputCoarse: {+ '@media (pointer: coarse)': {+ minInlineSize: 24,+ minBlockSize: 24,},},inputDisabled: {@@ -589,6 +576,8 @@ export function Switch({aria-busy={isBusy || undefined}{...stylex.props(styles.input,+ rtlStyles.centerInline('-50%'),+ styles.inputCoarse,inputSizeStyles[size],isDisabled && styles.inputDisabled,isBusy && styles.inputBusy,