Skip to content

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

TypeScript

fix(SegmentedControl): a segment's touch target grows toward 44 px without growing its box (#10137)

Cindy Zhang2c66211e83be
diff --git a/.changeset/segmented-touch-target.md b/.changeset/segmented-touch-target.md
new file mode 100644
index 0000000000..8fad47a0f6
--- /dev/null
+++ b/.changeset/segmented-touch-target.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Under a coarse pointer, a `SegmentedControl` segment's touch target grows toward 44 px through an invisible hit area, stopping halfway to a neighbor. No segment changes size, and nothing changes under a mouse.
+
+@cixzhang
diff --git a/apps/storybook/stories/SegmentedControl.stories.tsx b/apps/storybook/stories/SegmentedControl.stories.tsx
index 67c37f6856..6355daaa4d 100644
--- a/apps/storybook/stories/SegmentedControl.stories.tsx
+++ b/apps/storybook/stories/SegmentedControl.stories.tsx
@@ -291,6 +291,46 @@ export const Disabled: Story = {
},
};
+export const BelowAButton: Story = {
+ name: 'Below a button',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A large segmented control 8 px below a button. Under a coarse pointer each segment’s invisible hit area grows toward 44 px tall, but stops halfway to the button, so a tap on the button stays the button’s and nothing changes size.',
+ },
+ },
+ },
+ render: () => {
+ const [value, setValue] = useState('month');
+ const [refreshes, setRefreshes] = useState(0);
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'start',
+ gap: 8,
+ }}>
+ <Button
+ label="Refresh"
+ onClick={() => setRefreshes(count => count + 1)}
+ />
+ <SegmentedControl
+ value={value}
+ onChange={setValue}
+ label="Range"
+ size="lg">
+ <SegmentedControlItem value="day" label="Day" />
+ <SegmentedControlItem value="week" label="Week" />
+ <SegmentedControlItem value="month" label="Month" />
+ </SegmentedControl>
+ <Text type="supporting">Refreshed {refreshes} times</Text>
+ </div>
+ );
+ },
+};
+
export const DisabledItem: Story = {
render: () => {
const [value, setValue] = useState('hourly');
diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
index 43dad60424..a866ad5332 100644
--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
@@ -40,6 +40,9 @@ import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
import {isRenderable} from '../utils/isRenderable';
+import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useTouchHitArea} from '../utils/touchHitArea';
+import {touchHitAreaStyles} from '../utils/touchHitArea.stylex';
export interface SegmentedControlItemProps extends BaseProps<HTMLButtonElement> {
ref?: React.Ref<HTMLButtonElement>;
@@ -228,13 +231,17 @@ export function SegmentedControlItem({
},
);
+ // A disabled segment takes no taps, so it gets no band.
+ const hasHitArea = !isItemDisabled;
+ const segmentRef = useMergedRefs(ref, useTouchHitArea(hasHitArea));
+
const iconElement = isRenderable(icon) ? (
<span {...stylex.props(styles.icon, iconSizeStyles[size])}>{icon}</span>
) : null;
return (
<button
- ref={ref}
+ ref={segmentRef}
{...rest}
type="button"
role="radio"
@@ -271,6 +278,7 @@ export function SegmentedControlItem({
!isItemDisabled &&
interactionOverlayStyles.backgroundColor,
isItemDisabled && styles.disabled,
+ hasHitArea && touchHitAreaStyles.layer,
ctx.isTouchPresentation === true && styles.touchPresentation,
xstyle,
),
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
index b71ea0db95..fbad9c1937 100644
--- a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
@@ -59,6 +59,17 @@ import {
const storybook = withStorybook(test);
+/**
+ * A segment's inline style without the touch hit insets utils/hitArea writes
+ * under a coarse pointer: only what the selection motion writes.
+ */
+function motionStyle(element: HTMLElement): string {
+ return [...element.style]
+ .filter(property => !property.startsWith('--astryx-hit-inset-'))
+ .map(property => `${property}: ${element.style.getPropertyValue(property)}`)
+ .join('; ');
+}
+
/** UIKit's slide, from the constants table (motion/uikit/segmented.ts). */
const SLIDE = {response: 0.4, dampingFraction: 0.85} as const;
/** How far past the end segments the lens follows a finger. */
@@ -508,9 +519,7 @@ test('the surface lands exactly where the segment paints it', async ({
).toBe('transparent');
await thawTimers(page);
await expectLensHidden(control);
- expect(
- await control.segment('list').evaluate(el => el.getAttribute('style')),
- ).toBeFalsy();
+ expect(await control.segment('list').evaluate(motionStyle)).toBe('');
const rest = await control.group.screenshot({animations: 'allow'});
const a = PNG.sync.read(landed);
const b = PNG.sync.read(rest);
@@ -738,9 +747,7 @@ test('a change mid-flight paints no press over the lens on the segment it leaves
// Once the lens lands, Table gets its own styles back.
await expectLensHidden(control);
await expect
- .poll(async () =>
- control.segment('table').evaluate(element => element.style.cssText),
- )
+ .poll(async () => control.segment('table').evaluate(motionStyle))
.toBe('');
});
@@ -2082,7 +2089,12 @@ test('a vetoed tap selects nothing, and the lens goes back to the selection', as
expect(
await control.group.evaluate(group =>
[...group.querySelectorAll<HTMLElement>('[role="radio"]')]
- .map(segment => segment.style.cssText)
+ .flatMap(segment =>
+ // Only what the motion writes: not utils/hitArea's touch insets.
+ [...segment.style].filter(
+ property => !property.startsWith('--astryx-hit-inset-'),
+ ),
+ )
.join(''),
),
).toBe('');
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts
new file mode 100644
index 0000000000..3be6a50fae
--- /dev/null
+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControlHitArea.interaction.browser.spec.ts
@@ -0,0 +1,167 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SegmentedControlHitArea.interaction.browser.spec.ts
+ * @input The built "Below a button" SegmentedControl story and real touch
+ * input on a phone-sized touch context
+ * @output Browser proofs that a segment's touch target grows toward 44 px
+ * through an invisible band, stops halfway to a neighbor, and changes no
+ * box (spec:AST-094 FR42)
+ * @position Browser layer of SegmentedControlItem's hit band and
+ * useSegmentedTouchTracking's lift bounds; the band itself is
+ * utils/touchHitArea.stylex.ts
+ */
+
+import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ openStory,
+ tap,
+ touchDriver,
+ withStorybook,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+interface Box {
+ left: number;
+ top: number;
+ right: number;
+ bottom: number;
+}
+
+async function tapAt(
+ driver: TouchDriver,
+ at: {x: number; y: number},
+): Promise<void> {
+ if (driver.engine === 'webkit') {
+ await driver.tap(at);
+ } else {
+ await driver.play(tap(at, {holdMs: 50}));
+ }
+}
+
+/** Waits until utils/hitArea has written every enabled segment's insets. */
+async function waitForHitArea(page: Page): Promise<void> {
+ await page.waitForFunction(() =>
+ [
+ ...document.querySelectorAll<HTMLElement>(
+ '#storybook-root [role="radio"]',
+ ),
+ ].every(
+ segment =>
+ segment.style.getPropertyValue('--astryx-hit-inset-top') !== '',
+ ),
+ );
+}
+
+async function measure(page: Page) {
+ return page.evaluate(() => {
+ const box = (element: Element) => {
+ const r = element.getBoundingClientRect();
+ return {left: r.left, top: r.top, right: r.right, bottom: r.bottom};
+ };
+ const inset = (element: HTMLElement, side: string) =>
+ Number.parseFloat(
+ element.style.getPropertyValue(`--astryx-hit-inset-${side}`) || '0',
+ );
+ // The first segment sits under the button, so a tap between them is
+ // a tap between two targets.
+ const segment = document.querySelector<HTMLElement>(
+ '#storybook-root [data-value="day"]',
+ )!;
+ const button = [
+ ...document.querySelectorAll<HTMLElement>('#storybook-root button'),
+ ].find(element => element.textContent?.includes('Refresh'))!;
+ return {
+ segment: box(segment),
+ button: box(button),
+ insets: {top: inset(segment, 'top'), bottom: inset(segment, 'bottom')},
+ };
+ });
+}
+
+const centerX = (box: Box) => (box.left + box.right) / 2;
+
+test.describe('SegmentedControl touch target (spec:AST-094 FR42), under a finger', () => {
+ test('a segment’s hit area grows toward 44 px tall without growing its box', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-segmentedcontrol--below-a-button');
+ await waitForHitArea(page);
+ const {segment, button, insets} = await measure(page);
+ // The theme sets the segment's height; the band adds none to its box.
+ const height = segment.bottom - segment.top;
+ expect(height).toBeLessThan(44);
+ // Below: nothing near, so the band reaches the full 44 px share.
+ expect(insets.bottom).toBe((44 - height) / 2);
+ // Above: the band stops at half the gap to the button.
+ expect(insets.top).toBeLessThanOrEqual((segment.top - button.bottom) / 2);
+ expect(insets.top).toBeGreaterThan(0);
+ });
+
+ test('a drag that lifts past a segment’s band, in the button’s half of the gap, commits nothing', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-segmentedcontrol--below-a-button');
+ await waitForHitArea(page);
+ const driver = await touchDriver(page);
+ const {segment, button, insets} = await measure(page);
+ const month$ = page.locator('#storybook-root [data-value="month"]');
+ const x = Math.min(centerX(segment), (button.left + button.right) / 2);
+ const from = {x, y: (segment.top + segment.bottom) / 2};
+ const to = {x, y: segment.top - insets.top - 2};
+ await driver.play(drag(from, to, {durationMs: 160}));
+ await page.waitForTimeout(400);
+ await expect(month$).toHaveAttribute('aria-checked', 'true');
+ });
+
+ test('a tap on the band below a segment selects it', async ({page}) => {
+ await openStory(page, storybook(), 'core-segmentedcontrol--below-a-button');
+ await waitForHitArea(page);
+ const driver = await touchDriver(page);
+ const {segment, insets} = await measure(page);
+ const segment$ = page.locator('#storybook-root [data-value="day"]');
+ await expect(segment$).toHaveAttribute('aria-checked', 'false');
+ await tapAt(driver, {
+ x: centerX(segment),
+ y: segment.bottom + insets.bottom - 2,
+ });
+ await expect(segment$).toHaveAttribute('aria-checked', 'true');
+ });
+
+ test('a tap on the band above a segment selects it; a tap past the band, nearer the button, is not the segment’s; a tap on the button is the button’s', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-segmentedcontrol--below-a-button');
+ await waitForHitArea(page);
+ const driver = await touchDriver(page);
+ const {segment, button, insets} = await measure(page);
+ const day$ = page.locator('#storybook-root [data-value="day"]');
+ const month$ = page.locator('#storybook-root [data-value="month"]');
+ const refreshed = page.getByText(/Refreshed \d+ times/);
+ // Under the button and over the first segment, so both are near.
+ const x = Math.min(centerX(segment), (button.left + button.right) / 2);
+
+ // Past the band, in the button's half of the gap: the segment does not
+ // take it.
+ await tapAt(driver, {x, y: segment.top - insets.top - 2});
+ await page.waitForTimeout(400);
+ await expect(day$).toHaveAttribute('aria-checked', 'false');
+ await expect(month$).toHaveAttribute('aria-checked', 'true');
+
+ // On the button: the button's tap, and the selection does not move.
+ const before = Number(
+ (await refreshed.textContent())?.match(/\d+/)?.[0] ?? '0',
+ );
+ await tapAt(driver, {x, y: button.bottom - 4});
+ await expect(refreshed).toHaveText(`Refreshed ${before + 1} times`);
+ await expect(month$).toHaveAttribute('aria-checked', 'true');
+
+ // On the band above the segment: the segment's tap.
+ await tapAt(driver, {x, y: segment.top - insets.top + 1});
+ await expect(day$).toHaveAttribute('aria-checked', 'true');
+ await expect(refreshed).toHaveText(`Refreshed ${before + 1} times`);
+ });
+});
diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts
index b62b5b0fe8..abdef649f6 100644
--- a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts
+++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts
@@ -78,7 +78,7 @@ describe('liftTargetAt', () => {
['table', 210, 314],
];
const liftAt = (x: number, y: number, segments: SegmentSpan[]) =>
- liftTargetAt(x, y, bounds, segments)?.dataset.value ?? null;
+ liftTargetAt(x, y, [bounds], segments)?.dataset.value ?? null;
it('commits the segment a lift inside the control counts for, the padding included', () => {
const segments = spans(layout);
@@ -100,4 +100,21 @@ describe('liftTargetAt', () => {
it('commits nothing over a disabled segment', () => {
expect(liftAt(150, 35, spans(layout, ['list']))).toBeNull();
});
+
+ it("commits on a segment's own touch band, never on the box around every band", () => {
+ const segments = spans(layout);
+ // Grid's band stops 4 px above the control (a neighbor clamped it);
+ // Table's reaches 8 px above.
+ const area = [
+ bounds,
+ {left: 12, top: 18 - 4, right: 108, bottom: 49},
+ {left: 210, top: 18 - 8, right: 314, bottom: 49},
+ ];
+ const lift = (x: number, y: number) =>
+ liftTargetAt(x, y, area, segments)?.dataset.value ?? null;
+ expect(lift(60, 15)).toBe('grid');
+ expect(lift(250, 11)).toBe('table');
+ // Above Grid, past its band but within Table's reach: nothing.
+ expect(lift(60, 11)).toBeNull();
+ });
});
diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
index 41ccdc7b47..e5fe6ffb3b 100644
--- a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
+++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
@@ -7,8 +7,8 @@
* @input The radiogroup element, the selection motion controller and whether
* the control is enabled
* @output useSegmentedTouchTracking (a press of any pointer, landing to
- * lift, and its ClickWait), and segmentTargetAt, measureSegments and
- * liftTargetAt, the segment a pointer counts for
+ * lift, and its ClickWait), and segmentTargetAt, measureSegments,
+ * measureLiftArea and liftTargetAt, the segment a pointer counts for
* @position Internal to SegmentedControl; drives useSegmentedSelectionMotion.ts
*
* SYNC: When modified, update:
@@ -28,6 +28,7 @@ import {
import {lockSelection} from '../gestures/selectionLock';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {awaitBrowserClick, clickForLift} from '../utils/browserClickWait';
+import {HIT_INSET_PROPERTIES, type HitInsets} from '../utils/hitArea';
import {
SEGMENT_SELECTOR,
type SegmentedSelectionMotion,
@@ -101,29 +102,58 @@ export function segmentTargetAt(
}
/**
- * The segment a lift at viewport (`x`, `y`) commits: inside the control's
- * `bounds`, the one `segmentTargetAt` counts it for; outside them, none. A
- * press that slides off cancels, because the control selects rather than
- * toggles: a second press would not undo it.
+ * The segment a lift at viewport (`x`, `y`) commits: inside any box of the
+ * control's lift `area`, the one `segmentTargetAt` counts it for; outside
+ * them, none. A press that slides off cancels, because the control selects
+ * rather than toggles: a second press would not undo it.
*/
export function liftTargetAt(
x: number,
y: number,
- bounds: ControlBounds,
+ area: ReadonlyArray<ControlBounds>,
segments: ReadonlyArray<SegmentSpan>,
): HTMLElement | null {
- if (
- x < bounds.left ||
- x > bounds.right ||
- y < bounds.top ||
- y > bounds.bottom
- ) {
- return null;
- }
- return segmentTargetAt(x, segments);
+ const isInside = area.some(
+ box => x >= box.left && x <= box.right && y >= box.top && y <= box.bottom,
+ );
+ return isInside ? segmentTargetAt(x, segments) : null;
+}
+
+const NO_AREA: ReadonlyArray<ControlBounds> = [];
+
+/** A measured hit inset on `element`, px (0 when none is written). */
+function hitInset(element: HTMLElement, side: keyof HitInsets): number {
+ const value = Number.parseFloat(
+ element.style.getPropertyValue(HIT_INSET_PROPERTIES[side]),
+ );
+ return Number.isFinite(value) ? value : 0;
}
-const NO_BOUNDS: ControlBounds = {left: 0, top: 0, right: -1, bottom: -1};
+/**
+ * The boxes a lift may commit in: the control's own box, and each segment's
+ * box grown by its own touch hit band (utils/hitArea), so a tap on a band
+ * selects its segment. Each band is kept apart: a band a neighbor clamped
+ * stays clamped, though another segment's band reaches further. Under a fine
+ * pointer no band is written, and the segments sit inside the control's box.
+ */
+export function measureLiftArea(
+ track: HTMLElement,
+ segments: ReadonlyArray<SegmentSpan>,
+): ReadonlyArray<ControlBounds> {
+ const {left, top, right, bottom} = track.getBoundingClientRect();
+ return [
+ {left, top, right, bottom},
+ ...segments.map(({element}) => {
+ const box = element.getBoundingClientRect();
+ return {
+ left: box.left - hitInset(element, 'left'),
+ top: box.top - hitInset(element, 'top'),
+ right: box.right + hitInset(element, 'right'),
+ bottom: box.bottom + hitInset(element, 'bottom'),
+ };
+ }),
+ ];
+}
/**
* Tracks a press on the control as UIKit's segmented control does. The press
@@ -133,8 +163,8 @@ const NO_BOUNDS: ControlBounds = {left: 0, top: 0, right: -1, bottom: -1};
* still ends the press.
*
* The lift decides the segment, wherever the press began. Inside the control,
- * the segment under the pointer counts, else the nearest one. Outside the
- * control, nothing counts.
+ * or on a segment's touch hit band, the segment under the pointer counts,
+ * else the nearest one. Outside them, nothing counts.
*
* A tap gets the browser's own click. A drag gets no click from the browser,
* so the tracker clicks the segment at the lift. Either way the item's
@@ -150,8 +180,8 @@ export function useSegmentedTouchTracking(
const isDraggingRef = useRef(false);
/** The segments as the finger found them (disabled ones too). */
const segmentsRef = useRef<SegmentSpan[]>([]);
- /** The control's box as the finger found it: a lift outside it cancels. */
- const boundsRef = useRef<ControlBounds>(NO_BOUNDS);
+ /** The lift area as the finger found it: a lift outside it cancels. */
+ const areaRef = useRef<ReadonlyArray<ControlBounds>>(NO_AREA);
const trackerRef = useRef<ActionGroupTracker | null>(null);
const tracker = (trackerRef.current ??= createActionGroupTracker(() => ({
roots: () => [trackRef.current],
@@ -165,7 +195,7 @@ export function useSegmentedTouchTracking(
x: number,
y: number,
_targets: ReadonlyArray<ActionGroupTarget>,
- ) => liftTargetAt(x, y, boundsRef.current, segmentsRef.current),
+ ) => liftTargetAt(x, y, areaRef.current, segmentsRef.current),
onActivated: (item, cancelled) => {
const track = trackRef.current;
const value = item.dataset.value;
@@ -215,13 +245,7 @@ export function useSegmentedTouchTracking(
clickWait.end();
isDraggingRef.current = false;
segmentsRef.current = measureSegments(track);
- const rect = track.getBoundingClientRect();
- boundsRef.current = {
- left: rect.left,
- top: rect.top,
- right: rect.right,
- bottom: rect.bottom,
- };
+ areaRef.current = measureLiftArea(track, segmentsRef.current);
tracker.begin(touch.x, touch.y);
motion.begin(track, tracker.beganOn, touch.pointerType === 'touch');
break;
diff --git a/packages/core/src/utils/touchHitArea.stylex.ts b/packages/core/src/utils/touchHitArea.stylex.ts
index cbbf93b929..1a7a2de2f2 100644
--- a/packages/core/src/utils/touchHitArea.stylex.ts
+++ b/packages/core/src/utils/touchHitArea.stylex.ts
@@ -7,8 +7,8 @@
* under a coarse pointer, and `touchHitAreaStyles.layerBelowChildren`, the
* same band drawn below the host's children
* @position Internal styling utility for CheckboxInput, RadioListItem, List
- * rows, InfoTip and the press-tracking groups. Each keeps its insets live
- * with `useTouchHitArea` (utils/touchHitArea.ts).
+ * rows, InfoTip, SegmentedControl segments and the press-tracking groups.
+ * Each keeps its insets live with `useTouchHitArea` (utils/touchHitArea.ts).
*
* The band is the host's `::after`, grown past each edge by the measured
* inset. A clip path cuts out the host's box, so its content keeps its taps.
diff --git a/packages/core/src/utils/touchHitArea.ts b/packages/core/src/utils/touchHitArea.ts
index 32fe6fbc21..48aa997412 100644
--- a/packages/core/src/utils/touchHitArea.ts
+++ b/packages/core/src/utils/touchHitArea.ts
@@ -9,8 +9,9 @@
* @output `useTouchHitArea`, a callback ref that keeps an element's hit insets
* live for its invisible layer (`touchHitAreaStyles.layer`)
* @position Core-internal hook for the coarse-only 44 px target. List rows,
- * InfoTip, CheckboxInput, RadioListItem and the press-tracking groups use
- * it, and so can any control whose target outgrows its box under a finger.
+ * InfoTip, CheckboxInput, RadioListItem, SegmentedControl segments and the
+ * press-tracking groups use it, and so can any control whose target outgrows
+ * its box under a finger.
*
* SYNC: When modified, update utils/touchHitArea.stylex.ts and
* touchHitArea.test.tsx.