Skip to content

Commit 1632191

Browse files
committed
feat(SegmentedControl): under a finger the selection slides on UIKit's spring
On touch screens the selected surface slides from the old segment to the new one on the compositor (spring response 0.40 s, damping ratio 0.85, read from UISegmentedControl on iOS 26.2) and the two titles that change cross-fade over 200 ms on Core Animation's default curve, for taps, arrow keys and programmatic changes alike. A proxy copies the selected segment's computed surface for the slide and hands it back pixel for pixel; a change mid-flight keeps position and velocity; Reduce Motion drops the travel, as UIKit does. The proxy sits at z-index -1 in an isolated track, under every segment's content whatever the engine composites. Values live in motion/uikit/segmented.ts; the presentation comes from the shared touch presentation resolver.
1 parent 1092994 commit 1632191

14 files changed

Lines changed: 2132 additions & 12 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[feat] SegmentedControl: on touch screens the selection slides to the new segment on UIKit's spring and the labels cross-fade, whether a tap, an arrow key or a new `value` moved it. The motion runs on the compositor and keeps moving while the main thread is busy; with Reduce Motion the selection moves without travel.
6+
@vjeux

‎apps/storybook/stories/SegmentedControl.stories.tsx‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
SegmentedControl,
77
SegmentedControlItem,
88
} from '@astryxdesign/core/SegmentedControl';
9+
import {Button} from '@astryxdesign/core/Button';
910
import {Card} from '@astryxdesign/core/Card';
1011
import {Heading} from '@astryxdesign/core/Heading';
1112
import {Icon} from '@astryxdesign/core/Icon';
@@ -356,3 +357,55 @@ export const PressedState: Story = {
356357
);
357358
},
358359
};
360+
361+
const PERIODS = [
362+
{value: 'day', label: 'Day'},
363+
{value: 'week', label: 'Week'},
364+
{value: 'month', label: 'Month'},
365+
{value: 'year', label: 'Year to date'},
366+
];
367+
368+
/**
369+
* On a touch screen the selection slides from one segment to the next on
370+
* UIKit's spring and the titles cross-fade, whether a finger, a key or the app
371+
* changed the value. Segments keep their width when the selection moves: each
372+
* reserves its title's selected width. With a mouse the selection changes in
373+
* place, as before.
374+
*/
375+
export const SelectionMotion: Story = {
376+
name: 'Selection motion',
377+
parameters: {
378+
docs: {
379+
description: {
380+
story:
381+
'On a touch screen the selection slides between segments on UIKit’s spring and the titles cross-fade, for taps, arrow keys and programmatic changes alike (the button changes the value from outside). Under Reduce Motion the selection moves without travel. Segments never change width when the selection moves.',
382+
},
383+
},
384+
},
385+
render: () => {
386+
const [value, setValue] = useState('day');
387+
const next = () => {
388+
const index = PERIODS.findIndex(period => period.value === value);
389+
setValue(PERIODS[(index + 1) % PERIODS.length].value);
390+
};
391+
return (
392+
<VStack gap={4} width="100%">
393+
<SegmentedControl value={value} onChange={setValue} label="Period">
394+
{PERIODS.map(period => (
395+
<SegmentedControlItem key={period.value} {...period} />
396+
))}
397+
</SegmentedControl>
398+
<SegmentedControl
399+
value={value}
400+
onChange={setValue}
401+
label="Period, filling the row"
402+
layout="fill">
403+
{PERIODS.map(period => (
404+
<SegmentedControlItem key={period.value} {...period} />
405+
))}
406+
</SegmentedControl>
407+
<Button label="Next period" onClick={next} />
408+
</VStack>
409+
);
410+
},
411+
};

‎packages/core/src/SegmentedControl/SegmentedControl.doc.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ function WorkspaceCard() {
168168
usage: {
169169
anatomy,
170170
description:
171-
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation.',
171+
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation. On touch screens the selection slides to the new segment and the labels cross-fade, as on iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel.',
172172
accessibility: [
173173
{
174174
name: 'Text label',
@@ -240,7 +240,7 @@ export const docsZh = {
240240
usage: {
241241
anatomy,
242242
description:
243-
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation.',
243+
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation. On touch screens the selection slides to the new segment and the labels cross-fade, as on iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel.',
244244
bestPractices: [
245245
{guidance: true, description: 'Use for switching between 2–5 mutually exclusive views or modes where all options should be visible.'},
246246
{guidance: true, description: 'Provide a descriptive label for the control to ensure the group is accessible to screen readers.'},
@@ -256,7 +256,7 @@ export const docsDense = {
256256
usage: {
257257
anatomy,
258258
description:
259-
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation.',
259+
'A segmented button group that allows users to make a single selection from a small set of mutually exclusive options. Use SegmentedControl when all options should be visible at once and the selection controls a value or mode, not page navigation. On touch screens the selection slides to the new segment and the labels cross-fade, as on iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel.',
260260
bestPractices: [
261261
{guidance: true, description: 'Use for switching between 2–5 mutually exclusive views or modes where all options should be visible.'},
262262
{guidance: true, description: 'Provide a descriptive label for the control to ensure the group is accessible to screen readers.'},

‎packages/core/src/SegmentedControl/SegmentedControl.test.tsx‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* SYNC: When SegmentedControl components change, update tests to match new behavior
1313
*/
1414

15+
import {StrictMode} from 'react';
1516
import {describe, it, expect, vi, beforeEach} from 'vitest';
1617
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
1718
import userEvent from '@testing-library/user-event';
@@ -882,3 +883,115 @@ describe('segment width', () => {
882883
).toBeNull();
883884
});
884885
});
886+
887+
describe('selection motion', () => {
888+
/** A finger is the primary pointer: the touch presentation. */
889+
function mockCoarsePointer() {
890+
return vi.spyOn(window, 'matchMedia').mockImplementation(
891+
(query: string) =>
892+
({
893+
matches: query === '(pointer: coarse)',
894+
media: query,
895+
onchange: null,
896+
addListener: () => {},
897+
removeListener: () => {},
898+
addEventListener: () => {},
899+
removeEventListener: () => {},
900+
dispatchEvent: () => false,
901+
}) as MediaQueryList,
902+
);
903+
}
904+
905+
function renderControl(onChange = vi.fn()) {
906+
return render(
907+
<SegmentedControl value="grid" onChange={onChange} label="View mode">
908+
<SegmentedControlItem value="grid" label="Grid" />
909+
<SegmentedControlItem value="list" label="List" />
910+
<SegmentedControlItem
911+
value="icon"
912+
label="Icon"
913+
icon={<span>*</span>}
914+
isLabelHidden
915+
/>
916+
</SegmentedControl>,
917+
);
918+
}
919+
920+
it('keeps the pointer presentation as it was: no proxy, the theme’s transitions', () => {
921+
renderControl();
922+
expect(
923+
screen.getByRole('radiogroup').querySelector('[data-selection-proxy]'),
924+
).toBeNull();
925+
expect(
926+
getComputedStyle(screen.getByRole('radio', {name: 'List'}))
927+
.transitionProperty,
928+
).toContain('background-color');
929+
});
930+
931+
it('touch presentation: an aria-hidden proxy behind the segments; selection unchanged', async () => {
932+
const spy = mockCoarsePointer();
933+
try {
934+
const onChange = vi.fn();
935+
renderControl(onChange);
936+
const group = screen.getByRole('radiogroup');
937+
const proxy = group.querySelector('[data-selection-proxy]');
938+
expect(group.firstElementChild).toBe(proxy);
939+
expect(proxy).toHaveAttribute('aria-hidden', 'true');
940+
await userEvent.setup().click(screen.getByRole('radio', {name: 'List'}));
941+
expect(onChange).toHaveBeenCalledWith('list');
942+
} finally {
943+
spy.mockRestore();
944+
}
945+
});
946+
947+
it('touch presentation: a value change starts the slide, StrictMode included', () => {
948+
const spy = mockCoarsePointer();
949+
const boxes: Record<string, [number, number]> = {
950+
grid: [2, 96],
951+
list: [102, 96],
952+
};
953+
const rects = vi
954+
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
955+
.mockImplementation(function (this: HTMLElement) {
956+
const [left, width] =
957+
this.getAttribute('role') === 'radiogroup'
958+
? [0, 200]
959+
: (boxes[this.dataset.value ?? ''] ?? [0, 0]);
960+
return {
961+
left,
962+
top: 2,
963+
width,
964+
height: 28,
965+
right: left + width,
966+
bottom: 30,
967+
x: left,
968+
y: 2,
969+
toJSON: () => ({}),
970+
};
971+
});
972+
try {
973+
const ui = (value: string) => (
974+
<StrictMode>
975+
<SegmentedControl value={value} onChange={() => {}} label="View">
976+
<SegmentedControlItem value="grid" label="Grid" />
977+
<SegmentedControlItem value="list" label="List" />
978+
</SegmentedControl>
979+
</StrictMode>
980+
);
981+
const {rerender} = render(ui('grid'));
982+
rerender(ui('list'));
983+
const proxy = screen
984+
.getByRole('radiogroup')
985+
.querySelector<HTMLElement>('[data-selection-proxy]')!;
986+
// After StrictMode's extra unmount and remount, the proxy still takes
987+
// the destination's box and its animator still drives it (jsdom has no
988+
// Web Animations, so the animator writes the landing value inline).
989+
expect(proxy.style.visibility).toBe('visible');
990+
expect(proxy.style.width).toBe('96px');
991+
expect(proxy.style.translate).toMatch(/^102px/);
992+
} finally {
993+
rects.mockRestore();
994+
spy.mockRestore();
995+
}
996+
});
997+
});

‎packages/core/src/SegmentedControl/SegmentedControl.tsx‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,24 @@
44

55
/**
66
* @file SegmentedControl.tsx
7-
* @input Uses React, StyleX, SegmentedControlContext, useListFocus, useKeyboardHint
7+
* @input Uses React, StyleX, SegmentedControlContext, useListFocus,
8+
* useKeyboardHint, useMotionPresentation (the shared touch presentation),
9+
* useSegmentedSelectionMotion
810
* @output Exports SegmentedControl component and SegmentedControlProps type
9-
* @position Container wrapper; provides context to SegmentedControlItem children
11+
* @position Container wrapper; provides context to SegmentedControlItem
12+
* children. In the touch presentation it also renders the proxy that carries
13+
* the selected surface while the selection slides (see
14+
* useSegmentedSelectionMotion.ts).
1015
*
1116
* SYNC: When modified, update:
1217
* - /packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
1318
* - /packages/core/src/SegmentedControl/index.ts
1419
* - /packages/core/src/SegmentedControl/SegmentedControl.test.tsx
20+
* - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
1521
* - /packages/cli/assets/templates/blocks/components/SegmentedControl/ (showcase blocks)
1622
*/
1723

18-
import React, {useMemo, useCallback, type ReactNode} from 'react';
24+
import React, {useMemo, useCallback, useRef, type ReactNode} from 'react';
1925
import * as stylex from '@stylexjs/stylex';
2026
import {colorVars, spacingVars, radiusVars} from '../theme/tokens.stylex';
2127
import {SegmentedControlContext} from './SegmentedControlContext';
@@ -32,6 +38,9 @@ import type {BaseProps} from '../BaseProps';
3238
import {themeProps} from '../utils/themeProps';
3339

3440
import {useMergedRefs} from '../hooks/useMergedRefs';
41+
import {useMotionPresentation} from '../utils/touchPresentation';
42+
import {useSegmentedSelectionMotion} from './useSegmentedSelectionMotion';
43+
3544
export interface SegmentedControlProps extends Omit<
3645
BaseProps<HTMLDivElement>,
3746
'onChange'
@@ -90,6 +99,11 @@ export interface SegmentedControlProps extends Omit<
9099

91100
const styles = stylex.create({
92101
container: {
102+
// The containing block and stacking context of the selection proxy
103+
// (touch presentation), which sits at z-index -1 inside it: above the
104+
// track's own background, below every segment.
105+
position: 'relative',
106+
isolation: 'isolate',
93107
display: 'inline-flex',
94108
alignItems: 'center',
95109
width: 'fit-content',
@@ -127,6 +141,27 @@ const styles = stylex.create({
127141
disabledWithMessage: {
128142
opacity: 0.5,
129143
},
144+
// The touch presentation's selection proxy: a copy of the selected
145+
// segment's surface that springs from the old segment to the new one, then
146+
// hands the surface back (useSegmentedSelectionMotion). A negative z-index
147+
// keeps it under every segment's content however the engine composites
148+
// it: WebKit's overlap test misses segments the moving layer will cover,
149+
// so DOM order alone let it paint over their titles mid-slide on iOS.
150+
// Its paint and box are written when a slide starts; at rest it is hidden.
151+
thumb: {
152+
position: 'absolute',
153+
zIndex: -1,
154+
top: 0,
155+
// eslint-disable-next-line @astryx/no-physical-properties -- intentional: the proxy is placed by a physical translate measured from client rects (useSegmentedSelectionMotion), in both directions; a logical anchor would start it at the right edge under RTL.
156+
left: 0,
157+
boxSizing: 'border-box',
158+
transformOrigin: '0 0',
159+
pointerEvents: 'none',
160+
visibility: 'hidden',
161+
// It carries a copy of an already resolved surface, forced colors
162+
// included (Highlight), so the UA must not remap it again.
163+
forcedColorAdjust: 'none',
164+
},
130165
});
131166

132167
const sizeStyles = stylex.create({
@@ -176,6 +211,15 @@ export function SegmentedControl({
176211
...rest
177212
}: SegmentedControlProps) {
178213
const size = useSize(sizeProp, 'md');
214+
// UIKit's motion under a finger (the selection slides on a spring and the
215+
// titles cross-fade), the theme's transitions under a mouse.
216+
const isTouchPresentation = useMotionPresentation() === 'uikit';
217+
const trackRef = useRef<HTMLDivElement | null>(null);
218+
const {thumbRef} = useSegmentedSelectionMotion(
219+
trackRef,
220+
value,
221+
isTouchPresentation,
222+
);
179223

180224
// Disabled-reason tooltip. Applies to the whole-group disabled state. Disabled
181225
// controls swallow pointer events, so the tooltip listeners attach to the
@@ -269,14 +313,23 @@ export function SegmentedControl({
269313
layout,
270314
isDisabled,
271315
hasDisabledMessage: showsDisabledMessage,
316+
isTouchPresentation,
272317
}),
273-
[value, onChange, size, layout, isDisabled, showsDisabledMessage],
318+
[
319+
value,
320+
onChange,
321+
size,
322+
layout,
323+
isDisabled,
324+
showsDisabledMessage,
325+
isTouchPresentation,
326+
],
274327
);
275328

276329
return (
277330
<SegmentedControlContext value={contextValue}>
278331
<div
279-
ref={useMergedRefs(ref, listRef, disabledMessageTooltip.ref)}
332+
ref={useMergedRefs(ref, listRef, trackRef, disabledMessageTooltip.ref)}
280333
{...rest}
281334
role="radiogroup"
282335
aria-label={label}
@@ -302,6 +355,14 @@ export function SegmentedControl({
302355
className,
303356
style,
304357
)}>
358+
{isTouchPresentation && (
359+
<span
360+
ref={thumbRef}
361+
aria-hidden="true"
362+
data-selection-proxy=""
363+
{...stylex.props(styles.thumb)}
364+
/>
365+
)}
305366
{children}
306367
{hint.hintElement}
307368
</div>

‎packages/core/src/SegmentedControl/SegmentedControlContext.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,12 @@ export interface SegmentedControlContextValue {
3030
* tooltip is keyboard-discoverable; selection is still blocked.
3131
*/
3232
hasDisabledMessage?: boolean;
33+
/**
34+
* True in the touch presentation (the shared resolver's UIKit motion): the
35+
* control animates selection changes itself (the surface slides, the titles
36+
* cross-fade), so segments drop their CSS transitions.
37+
*/
38+
isTouchPresentation?: boolean;
3339
}
3440

3541
export const SegmentedControlContext =

0 commit comments

Comments
 (0)