Skip to content

Commit 4d9e0cb

Browse files
committed
fix(SegmentedControl): under Reduce Motion the selection fades and scales in at its new segment
UIKit's Reduce Motion substitution for the lens is not an instant move. When the selection changes (a tap, a drag's lift, a programmatic set) the lens jumps to the destination and fades and scales in place there: opacity from 0 and a uniform scale from 0.88 about its centre, on one clock and curve, UIKit's 0.2 s block with Core Animation's default curve (F4's per-frame read under Reduce Motion, Prefer Cross-Fade off and on: opacity and scale share one progress at every frame; the 0.2 s curve-5 block fits all four cases within 0.041, rms 0.012). The table entry segmentedControl.reducedMotion carries the clock and curve as theme roles and the starting scale; the controller plays the fade itself (the substitution is the motion), and the titles still cross-fade. Tests sample the fade against the curve in jsdom, Chromium and WebKit, and check the table against UIKit's frames.
1 parent b53773b commit 4d9e0cb

10 files changed

Lines changed: 418 additions & 44 deletions

File tree

‎.changeset/segmented-control-selection-slide.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@
22
'@astryxdesign/core': patch
33
---
44

5-
[feat] SegmentedControl: on iPhone and iPad 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. The spring and the cross-fade are motion roles (`segmentedControl.*`) a theme can retune; UIKit's measured values are the default theme's. Other touch screens and desktops keep the color fade.
5+
[feat] SegmentedControl: on iPhone and iPad 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 it doesn't travel: it fades and scales in at the new segment, as iOS does. The spring, the cross-fade and the Reduce Motion fade are motion roles (`segmentedControl.*`) a theme can retune; UIKit's measured values are the default theme's. Other touch screens and desktops keep the color fade.
66
@vjeux

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ export const SelectionMotion: Story = {
378378
docs: {
379379
description: {
380380
story:
381-
'On iPhone and iPad 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; other touch screens and desktops keep the color fade. Segments never change width when the selection moves.',
381+
'On iPhone and iPad 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 fades and scales in at the new segment instead; other touch screens and desktops keep the color fade. Segments never change width when the selection moves.',
382382
},
383383
},
384384
},

‎packages/cli/assets/docs/motion.doc.mjs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,18 @@ const calmTheme = defineTheme({
209209
'duration',
210210
'200ms',
211211
],
212+
[
213+
'segmentedControl.reducedMotion.curve',
214+
'--motion-segmented-control-reduced-motion-curve',
215+
'curve',
216+
'cubic-bezier(0.25, 0.1, 0.25, 1)',
217+
],
218+
[
219+
'segmentedControl.reducedMotion.fadeMs',
220+
'--motion-segmented-control-reduced-motion-fade-ms',
221+
'duration',
222+
'200ms',
223+
],
212224
[
213225
'segmentedControl.selectionSpring',
214226
'--motion-segmented-control-selection-spring',

‎packages/cli/test/__golden__/no-icon-set/docs-topics.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@
201201
"touch-motion",
202202
"best-practices"
203203
],
204-
"skeleton": "59bab6689e5f3b7c6b0bea2c1b452fa9ff5fc487f250a4e88ee59e89af4f62cb",
204+
"skeleton": "a3f6842429ab578145467f46e8a55acab18ca3c1bcfd778ae523c5d417f0f523",
205205
"mentions": []
206206
},
207207
"principles": {

‎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. On iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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 iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it fades and scales in at the new segment instead of travelling. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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. On iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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 iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it fades and scales in at the new segment instead of travelling. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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. On iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it moves without travel. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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 iPhone and iPad the selection slides to the new segment and the labels cross-fade, as in iOS, whether a tap, an arrow key or a new value moved it; with Reduce Motion it fades and scales in at the new segment instead of travelling. Other touch screens and desktops keep the color fade. A theme can retune the slide and the cross-fade through their motion roles.',
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/__tests__/SegmentedControl.interaction.browser.spec.ts‎

Lines changed: 114 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ const SLIDE = {response: 0.4, dampingFraction: 0.85} as const;
6666
/** UIKit's title cross-fade. */
6767
const TITLE_FADE_MS = 200;
6868
const TITLE_EASE = cubicBezier(0.25, 0.1, 0.25, 1);
69+
/** Reduce Motion: the in-place fade and scale-in (motion/uikit/segmented.ts). */
70+
const RM_FADE_MS = 200;
71+
const RM_EASE = cubicBezier(0.25, 0.1, 0.25, 1);
72+
const RM_SCALE_FROM = 0.88;
6973

7074
interface SegmentBox {
7175
value: string;
@@ -445,30 +449,128 @@ test('an arrow key and a programmatic change slide the selection too', async ({
445449
expect(animations.length).toBeGreaterThan(0);
446450
});
447451

448-
test('Reduce Motion: the selection moves without travel; the titles still cross-fade', async ({
452+
test('Reduce Motion: no travel; the surface fades and scales in at the new segment on UIKit’s 0.2 s block; the titles still cross-fade', async ({
449453
page,
450454
}) => {
451455
await page.emulateMedia({reducedMotion: 'reduce'});
452456
const control = await openControl(page);
457+
const table = boxOf(await control.boxes(), 'table');
458+
// Hold the clock, and the proxy's animations from their birth: the fade is
459+
// 200 ms, sooner over than a slow engine reaches a hold after the fact.
460+
await installTimerGate(page);
461+
await holdLensAnimationsAtBirth(page);
453462
await control.tapSegment('table');
454-
await expect(control.segment('table')).toHaveAttribute(
455-
'aria-checked',
456-
'true',
463+
await expect
464+
.poll(async () =>
465+
page.evaluate(
466+
() =>
467+
(window as unknown as {__harnessHeld: Animation[]}).__harnessHeld
468+
.length,
469+
),
470+
)
471+
.toBeGreaterThan(0);
472+
await freezeTimers(page);
473+
await page.evaluate(() => {
474+
(window as unknown as {__restoreAnimate: () => void}).__restoreAnimate();
475+
});
476+
const samples = await control.proxy.evaluate(
477+
(element, ts) => {
478+
const held = (window as unknown as {__harnessHeld: Animation[]})
479+
.__harnessHeld;
480+
return ts.map(t => {
481+
for (const animation of held) {
482+
const end = Number(
483+
animation.effect?.getComputedTiming().endTime ?? 0,
484+
);
485+
animation.currentTime = Math.min(t, Math.max(0, end - 0.5));
486+
}
487+
const style = getComputedStyle(element);
488+
const [sx, sy = sx] =
489+
style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
490+
return {
491+
t,
492+
opacity: Number(style.opacity),
493+
sx,
494+
sy,
495+
x: style.translate === 'none' ? 0 : parseFloat(style.translate),
496+
origin: style.transformOrigin.split(' ').map(parseFloat),
497+
visible: style.visibility === 'visible',
498+
};
499+
});
500+
},
501+
timeline(RM_FADE_MS - 1),
457502
);
458-
const title = control.segment('table').locator('[data-segment-title="text"]');
459-
const fades = await waitForAnimation(title);
460-
expect(fades[0].durationMs).toBe(TITLE_FADE_MS);
461-
// No travel: the proxy runs nothing and the segment paints its own surface.
462-
expect(
463-
await control.proxy.evaluate(element => element.getAnimations().length),
464-
).toBe(0);
465-
await expect(control.proxy).toHaveCSS('visibility', 'hidden');
503+
// The titles still cross-fade (held by their own fill until the hand-back).
504+
const titleFades = await control
505+
.segment('table')
506+
.locator('[data-segment-title="text"]')
507+
.evaluate(element =>
508+
element
509+
.getAnimations()
510+
.map(a => Number(a.effect?.getComputedTiming().duration)),
511+
);
512+
await releaseAnimations(page);
513+
await thawTimers(page);
514+
expect(titleFades).toContain(TITLE_FADE_MS);
515+
for (const sample of samples) {
516+
const p = RM_EASE(sample.t / RM_FADE_MS);
517+
expect(sample.visible).toBe(true);
518+
// At the new segment from the first frame: no travel...
519+
expect(Math.abs(sample.x - table.x)).toBeLessThan(0.5);
520+
// ...scaled about its center...
521+
expect(Math.abs(sample.origin[0] - table.width / 2)).toBeLessThan(0.5);
522+
expect(Math.abs(sample.origin[1] - table.height / 2)).toBeLessThan(0.5);
523+
// ...fading in from 0 and growing from 0.88, on one curve.
524+
expect(Math.abs(sample.opacity - p), JSON.stringify(sample)).toBeLessThan(
525+
0.02,
526+
);
527+
expect(
528+
Math.abs(sample.sx - (RM_SCALE_FROM + (1 - RM_SCALE_FROM) * p)),
529+
JSON.stringify(sample),
530+
).toBeLessThan(0.005);
531+
expect(sample.sy).toBeCloseTo(sample.sx, 4);
532+
}
533+
// Then the segment paints its own surface again.
534+
await expect(control.proxy).toHaveCSS('visibility', 'hidden', {
535+
timeout: 3000,
536+
});
466537
await expect(control.segment('table')).not.toHaveCSS(
467538
'background-color',
468539
'rgba(0, 0, 0, 0)',
469540
);
470541
});
471542

543+
/**
544+
* Pauses every animation started on the lens (the proxy and anything inside
545+
* it) the moment it is created, into the harness's held set;
546+
* `__restoreAnimate` puts `Element.animate` back.
547+
*/
548+
async function holdLensAnimationsAtBirth(page: Page): Promise<void> {
549+
await page.evaluate(() => {
550+
const original = Element.prototype.animate;
551+
const held: Animation[] = [];
552+
const w = window as unknown as {
553+
__harnessHeld: Animation[];
554+
__restoreAnimate: () => void;
555+
};
556+
w.__harnessHeld = held;
557+
w.__restoreAnimate = () => {
558+
Element.prototype.animate = original;
559+
};
560+
Element.prototype.animate = function (
561+
this: Element,
562+
...args: Parameters<Element['animate']>
563+
): Animation {
564+
const animation = original.apply(this, args);
565+
if (this.closest('[data-selection-proxy]') != null) {
566+
animation.pause();
567+
held.push(animation);
568+
}
569+
return animation;
570+
};
571+
});
572+
}
573+
472574
test('Android and other non-iOS touch screens keep today’s presentation: no slide, the tap selects', async ({
473575
page,
474576
}) => {

‎packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts‎

Lines changed: 54 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717

1818
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
1919
import {createAnimator, type Animator} from '../motion/animator';
20+
import {cubicBezier} from '../motion/bezier';
21+
import {segmentedControl} from '../motion/uikit';
2022
import {
2123
SegmentedSelectionMotion,
2224
TITLE_SELECTOR,
@@ -86,7 +88,10 @@ function setup(selected: string) {
8688
now: () => clock,
8789
prefersReducedMotion: () => reduceMotion,
8890
});
89-
const motion = new SegmentedSelectionMotion(animator, {now: () => clock});
91+
const motion = new SegmentedSelectionMotion(animator, {
92+
now: () => clock,
93+
prefersReducedMotion: () => reduceMotion,
94+
});
9095
motion.attachProxy(proxy);
9196
paint(segments, selected);
9297
motion.rememberTitles(track);
@@ -129,6 +134,13 @@ function select(ctx: ReturnType<typeof setup>, from: string, to: string): void {
129134

130135
const xOf = (value: string) => SEGMENTS[value].left - TRACK.left;
131136

137+
/** The proxy carries this segment's surface: hidden on the segment, inline. */
138+
function expectHidden(segment: HTMLElement): void {
139+
expect(segment.style.getPropertyValue('background-color')).toBe(
140+
'transparent',
141+
);
142+
}
143+
132144
/** The segment paints its own surface again: nothing inline, the stylesheet's paint. */
133145
function expectOwnSurface(segment: HTMLElement): void {
134146
expect(segment.style.getPropertyValue('background-color')).toBe('');
@@ -280,18 +292,53 @@ describe('the selection slide', () => {
280292
expect(ctx.animator.get('x', 5000)).toBeCloseTo(xOf('table'), 6);
281293
});
282294

283-
it('Reduced Motion: no travel, the surface is at the destination in the same frame', async () => {
295+
it('Reduced Motion: no travel; the surface fades and scales in at the destination on UIKit’s 0.2 s block', async () => {
284296
reduceMotion = true;
285297
const ctx = setup('grid');
286298
select(ctx, 'grid', 'table');
299+
// At the destination from the first frame, scaled about its center.
287300
expect(ctx.animator.get('x')).toBe(xOf('table'));
288-
// Handed back before the next frame (a microtask, not a timer).
289-
await Promise.resolve();
290-
await Promise.resolve();
301+
expect(ctx.proxy.style.width).toBe('106px');
302+
expect(ctx.proxy.style.transformOrigin).toBe('50% 50%');
303+
expectHidden(ctx.segments.table);
304+
const {reducedMotion} = segmentedControl;
305+
const ease = cubicBezier(reducedMotion.curve);
306+
for (const t of [0, 16, 50, 100, 150, 199]) {
307+
const p = ease(t / reducedMotion.fadeMs);
308+
expect(ctx.animator.get('opacity', clock + t)).toBeCloseTo(p, 4);
309+
expect(ctx.animator.get('scaleX', clock + t)).toBeCloseTo(
310+
reducedMotion.scaleFrom + (1 - reducedMotion.scaleFrom) * p,
311+
4,
312+
);
313+
expect(ctx.animator.get('scaleY', clock + t)).toBeCloseTo(
314+
ctx.animator.get('scaleX', clock + t),
315+
6,
316+
);
317+
// No travel at any point.
318+
expect(ctx.animator.get('x', clock + t)).toBe(xOf('table'));
319+
}
320+
await advance(1000);
291321
expect(ctx.motion.isSliding).toBe(false);
292322
expect(ctx.proxy.style.visibility).toBe('hidden');
323+
expect(ctx.proxy.style.transformOrigin).toBe('');
293324
expectOwnSurface(ctx.segments.table);
294325
});
326+
327+
it('Reduced Motion off again: the next change slides at full size and opacity', async () => {
328+
reduceMotion = true;
329+
const ctx = setup('grid');
330+
select(ctx, 'grid', 'table');
331+
await advance(50);
332+
// Turned off mid-fade: the next change travels, opaque and unscaled.
333+
reduceMotion = false;
334+
ctx.motion.settle();
335+
select(ctx, 'table', 'list');
336+
expect(ctx.animator.get('opacity')).toBe(1);
337+
expect(ctx.animator.get('scaleY')).toBe(1);
338+
expect(ctx.proxy.style.transformOrigin).toBe('');
339+
await advance(3000);
340+
expect(ctx.animator.get('x')).toBe(xOf('list'));
341+
});
295342
});
296343

297344
describe('the title cross-fade', () => {
@@ -394,11 +441,10 @@ describe('the title cross-fade', () => {
394441
});
395442

396443
it('with no slide running, the twin is hidden again as soon as the fade ends', async () => {
397-
reduceMotion = true;
398444
const ctx = setup('grid');
399445
select(ctx, 'grid', 'table');
400-
await Promise.resolve();
401-
await Promise.resolve();
446+
// The surface handed back before the titles finish (a resize, say).
447+
ctx.motion.settle();
402448
expect(ctx.motion.isSliding).toBe(false);
403449
for (const r of recorded) {
404450
r.finish();

0 commit comments

Comments
 (0)