Skip to content

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

TypeScript

feat(SegmentedControl): the selection slides on every change and drags with any pointer (#9632)

Christopher Chedeau95438ffaf99a
diff --git a/.changeset/segmented-control-drag-to-select.md b/.changeset/segmented-control-drag-to-select.md
new file mode 100644
index 0000000000..aff6a1255c
--- /dev/null
+++ b/.changeset/segmented-control-drag-to-select.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] SegmentedControl: under a finger, on a touch device (a coarse primary pointer), the control tracks the touch. Dragging the selected segment carries the selection along with the finger, and the segment under the finger is chosen when it lets go (`onChange` fires once, at the lift); letting go outside the control selects nothing. While the selection is dragged, the selected label's colour follows it, with a margin around each boundary so a finger resting on one never flickers; label weights change only at the lift, so nothing reflows under the finger. A tap selects through the browser's own click, and a pressed segment shows the shared pressed overlay; nothing lifts or dims. A vertical drag that starts on the control still scrolls the page. A commit the item's `onClick` vetoes sends the selection back at once; one a controlled parent adopts later lands without a bounce. With Reduce Motion the selection still follows the finger, with no chase, and only the lift cross-fades. Keyboard and assistive technology keep the click; no element is added.
+
+@vjeux
diff --git a/.changeset/segmented-control-every-pointer.md b/.changeset/segmented-control-every-pointer.md
new file mode 100644
index 0000000000..2dfd93695d
--- /dev/null
+++ b/.changeset/segmented-control-every-pointer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] SegmentedControl: a mouse or a pen drags the selection as a finger does. A drag from the selected segment carries it with the pointer, and the release commits the segment under the pointer (`onChange` fires once, at the release). A release outside the control selects nothing, and a drag that starts on another segment commits where it lifts. Under a mouse or a pen, every change slides the selection on the theme's duration and easing, not UIKit's spring, and a click slides it too. With Reduce Motion, a mouse's or a pen's drag still carries the selection, and its release lands at once. Keyboard and assistive technology keep the click.
+
+@vjeux
diff --git a/.changeset/segmented-control-selection-slide.md b/.changeset/segmented-control-selection-slide.md
new file mode 100644
index 0000000000..d3201787fe
--- /dev/null
+++ b/.changeset/segmented-control-selection-slide.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] SegmentedControl: under a finger the selection slides to the new segment on UIKit's spring, whether a tap, an arrow key or a new `value` moved it. The selection indicator is the control's own pseudo-element, so no element is added. The motion runs on the compositor and keeps moving while the main thread is busy. With Reduce Motion nothing travels or scales: the old selection fades out where it is as the new one fades in. The spring is UIKit's measured one, an internal motion role no theme retunes, and no theme value lengthens the Reduce Motion fade. With a mouse or a pen it slides on the theme's duration and easing instead.
+@vjeux
diff --git a/.changeset/use-media-query-no-match-media.md b/.changeset/use-media-query-no-match-media.md
new file mode 100644
index 0000000000..4ab8cd50f8
--- /dev/null
+++ b/.changeset/use-media-query-no-match-media.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `useMediaQuery` returns its server default where the window has no `matchMedia`, as in a test DOM, instead of throwing. Components that read it, such as Slider, now render in such a DOM; SegmentedControl, which reads it from this release, keeps rendering there.
+
+@vjeux
diff --git a/apps/storybook/stories/SegmentedControl.stories.tsx b/apps/storybook/stories/SegmentedControl.stories.tsx
index 7a5ea9e0de..67c37f6856 100644
--- a/apps/storybook/stories/SegmentedControl.stories.tsx
+++ b/apps/storybook/stories/SegmentedControl.stories.tsx
@@ -6,6 +6,7 @@ import {
SegmentedControl,
SegmentedControlItem,
} from '@astryxdesign/core/SegmentedControl';
+import {Button} from '@astryxdesign/core/Button';
import {Card} from '@astryxdesign/core/Card';
import {Heading} from '@astryxdesign/core/Heading';
import {Icon} from '@astryxdesign/core/Icon';
@@ -356,3 +357,54 @@ export const PressedState: Story = {
);
},
};
+
+const PERIODS = [
+ {value: 'day', label: 'Day'},
+ {value: 'week', label: 'Week'},
+ {value: 'month', label: 'Month'},
+ {value: 'year', label: 'Year to date'},
+];
+
+/**
+ * On a touch screen the selection slides from one segment to the next on
+ * UIKit's spring, whether a finger, a key or the app changed the value. With a
+ * mouse or a pen every change, a click included, slides on the theme's
+ * duration and easing, and a drag carries it as a finger does.
+ */
+export const SelectionMotion: Story = {
+ name: 'Selection motion',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Under a finger the selection slides between segments on UIKit’s spring, for taps, arrow keys and programmatic changes alike (the button changes the value from outside). Drag the selected segment to another one and let go: the segment under the finger is chosen, and letting go outside the control selects nothing. Under Reduce Motion nothing travels: the old selection fades out as the new one fades in. With a mouse or a pen every change, a click included, slides on the theme’s duration and easing, and a drag carries the selection as a finger does.',
+ },
+ },
+ },
+ render: () => {
+ const [value, setValue] = useState('day');
+ const next = () => {
+ const index = PERIODS.findIndex(period => period.value === value);
+ setValue(PERIODS[(index + 1) % PERIODS.length].value);
+ };
+ return (
+ <VStack gap={4} width="100%">
+ <SegmentedControl value={value} onChange={setValue} label="Period">
+ {PERIODS.map(period => (
+ <SegmentedControlItem key={period.value} {...period} />
+ ))}
+ </SegmentedControl>
+ <SegmentedControl
+ value={value}
+ onChange={setValue}
+ label="Period, filling the row"
+ layout="fill">
+ {PERIODS.map(period => (
+ <SegmentedControlItem key={period.value} {...period} />
+ ))}
+ </SegmentedControl>
+ <Button label="Next period" onClick={next} />
+ </VStack>
+ );
+ },
+};
diff --git a/docs/specs/AST-094-touch-presentations/motion-roles.md b/docs/specs/AST-094-touch-presentations/motion-roles.md
index e234a8db04..901a50eefd 100644
--- a/docs/specs/AST-094-touch-presentations/motion-roles.md
+++ b/docs/specs/AST-094-touch-presentations/motion-roles.md
@@ -9,6 +9,7 @@ Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind
| `progress.curves.fill` | curve | cubic-bezier(0, 0, 1, 1) | `component:ProgressBar` |
| `progress.fillTrackMs` | duration | 1000 ms | `component:ProgressBar` |
| `progress.reducedMotionPulseMs` | duration | 2000 ms | `component:ProgressBar` |
+| `segmented.selectionSpring` | spring | response 0.4 s, damping ratio 0.85 | `spec:AST-094` FR4 |
| `springs.contextMenuDismiss` | spring | response 0.35 s, damping ratio 0.85 | `spec:AST-094` FR4 |
| `springs.contextMenuLift` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 |
| `springs.contextMenuMorph` | spring | response 0.3 s, damping ratio 0.8 | `spec:AST-094` FR4 |
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 1a1cb7e695..f913d5fb0e 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -27,7 +27,10 @@ affects_consumer_docs: []
```json
{
- "paths": ["packages/core/src/motion/uikit/slider.ts"]
+ "paths": [
+ "packages/core/src/motion/uikit/segmented.ts",
+ "packages/core/src/motion/uikit/slider.ts"
+ ]
}
```
@@ -166,6 +169,7 @@ a measured, sourced difference exists.
| `springs.contextMenuLift` | damping ratio 0.8, response 0.32 s | measured: UIContextMenuInteraction's preview lift, iOS 26.2 simulator, 2026-10-23 |
| `springs.contextMenuDismiss` | damping ratio 0.85, response 0.35 s | measured: UIContextMenuInteraction's dismissal, iOS 26.2 simulator, 2026-10-23 |
| `springs.contextMenuMorph` | damping ratio 0.8, response 0.3 s | measured: UIContextMenuInteraction's menu entrance and preview shadow, iOS 26.2 simulator, 2026-10-23 |
+ | `segmented.selectionSpring` | response 0.4 s, damping ratio 0.85 | measured: UISegmentedControl's selection slide, iOS 26.2 simulator, 2026-10-23 |
| `timing.stateChangeMs` | 250 ms | measured: Core Animation's implicit transaction, iOS 26.2 simulator, 2026-10-23 |
| `timing.curves.viewChange` | cubic-bezier(0.25, 0.1, 0.25, 1) | Apple: `CAMediaTimingFunctionName.default` |
| `timing.curves.exit` | cubic-bezier(0.42, 0, 1, 1) | measured: UIKit's ease-in, iOS 26.2 simulator, 2026-10-23 |
@@ -233,7 +237,7 @@ a measured, sourced difference exists.
activation stays the browser's click, except that an action a
`family:action-groups` member tracks activates at the lift (FR26), and a toggle
under `spec:AST-020` FR9's slide-off exception (Switch, Checkbox,
- CheckboxListItem) may also complete on a lift after the finger slid off; and a Switch completes its own toggle at the lift of a finger hold or a flipping drag, rather than through the browser's click (`component:Switch` FR15). Where the engine hit-tests an element a compositor animation moves at the motion's start (iOS WebKit), a touch on moving content goes to what was drawn under the finger at touch-down, and a tap there (no recognizer claimed it, the browser did not take it, and it stayed within 45 pt) MUST activate it: the browser's own click for that touch is cancelled or swallowed, and that element receives one click, an editable focused first.
+ CheckboxListItem) may also complete on a lift after the finger slid off; and a Switch completes its own toggle at the lift of a finger hold or a flipping drag, rather than through the browser's click (`component:Switch` FR15); and a SegmentedControl drag commits at the lift on the segment nearest the pointer, wherever it began (`component:SegmentedControl` FR13). Where the engine hit-tests an element a compositor animation moves at the motion's start (iOS WebKit), a touch on moving content goes to what was drawn under the finger at touch-down, and a tap there (no recognizer claimed it, the browser did not take it, and it stayed within 45 pt) MUST activate it: the browser's own click for that touch is cancelled or swallowed, and that element receives one click, an editable focused first.
Under a fine pointer a control uses a third profile with no delay: its
press paint starts at once on `pointerdown`, through the same press
controller and release fade as a finger's, in place of CSS `:active`; the
diff --git a/docs/specs/components/SegmentedControl/SegmentedControl.spec.md b/docs/specs/components/SegmentedControl/SegmentedControl.spec.md
index c5b26a983f..328e583546 100644
--- a/docs/specs/components/SegmentedControl/SegmentedControl.spec.md
+++ b/docs/specs/components/SegmentedControl/SegmentedControl.spec.md
@@ -26,6 +26,9 @@ review_triggers:
verified_by:
[
packages/core/src/SegmentedControl/SegmentedControl.test.tsx,
+ packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts,
+ packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts,
+ packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts,
packages/core/src/RadioList/__tests__/RadioGroup.a11y.test.tsx,
packages/core/src/RadioList/__tests__/RadioGroup.a11y.chromium.spec.ts,
packages/core/src/theme/themingTargets.test.ts,
@@ -33,31 +36,43 @@ verified_by:
]
modules: []
families: []
-design_specs: [design:user-states, design:bidirectionality]
+design_specs:
+ [design:user-states, design:bidirectionality, design:reduced-motion]
architecture:
[
architecture:component-size-cascade,
+ architecture:component-style-authoring,
architecture:component-theming-surface,
architecture:interaction-modality,
architecture:public-component-api,
]
contributing: []
-system_specs: [spec:AST-020, spec:AST-085]
+system_specs:
+ [
+ spec:AST-020,
+ spec:AST-020/FR9,
+ spec:AST-085,
+ spec:AST-094,
+ spec:AST-094/FR4,
+ spec:AST-094/FR11,
+ spec:AST-094/FR13,
+ spec:AST-094/FR43,
+ ]
---
# SegmentedControl component contract
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | None changes. SegmentedControl takes `label`, `value`, `onChange`, `size`, `layout`, `isDisabled`, `disabledMessage`, base props, and SegmentedControlItem children. |
-| Behavior | A `role="radiogroup"` named by `label` with one Tab stop; arrow keys, Home, and End move focus between enabled segments, wrap, and select the segment they land on. Tabbing in never changes the value. |
-| End-user impact | People switch between a few modes with one click or arrow press, and the control shrinks with its row by truncating labels. A disabled control keeps one Tab stop. |
-| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A press while focused selects before any click, a caller `onFocus` or `onBlur` can cancel built-in focus behavior, caller handlers run while disabled, and a caller `aria-describedby` is dropped; all are listed under Current-state impact. |
-| Review checks | Reject more than one Tab stop, a value change on Tab entry, arrows that land on a disabled segment, a control that overflows its container when segments have labels, or a selection while disabled. |
-| Governing rules | WAI-ARIA radio group pattern; `spec:AST-020` FR9, FR15, DEC-5; `spec:AST-085` FR1, FR2, FR5, FR7; `design:user-states` DR1–DR3 (through SegmentedControlItem); `design:bidirectionality` DR6; `architecture:component-size-cascade` INV3–INV5; `architecture:interaction-modality` INV1; `architecture:public-component-api` INV5, INV7. |
+| Area | Contract |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | None changes. SegmentedControl takes `label`, `value`, `onChange`, `size`, `layout`, `isDisabled`, `disabledMessage`, base props, and SegmentedControlItem children. |
+| Behavior | A `role="radiogroup"` named by `label` with one Tab stop; arrow keys, Home, and End move focus between enabled segments, wrap, and select the segment they land on. Tabbing in never changes the value. Every change of selection slides the selected surface, and a drag from the selected segment carries it with any pointer until the lift commits. |
+| End-user impact | People switch between a few modes with one click or arrow press, and the control shrinks with its row by truncating labels. A disabled control keeps one Tab stop. |
+| Builder impact | None. |
+| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A drag now commits at the lift on the nearest segment, where a press used to select only on a click inside a segment; `onChange` still fires once per commit, and a lift outside the control still selects nothing (patch, the touch presentation batch). A caller `onFocus` or `onBlur` can cancel built-in focus behavior, caller handlers run while disabled, and a caller `aria-describedby` is dropped; all are listed under Current-state impact. |
+| Review checks | Reject more than one Tab stop, a value change on Tab entry, arrows that land on a disabled segment, a control that overflows its container when segments have labels, or a selection while disabled. |
+| Governing rules | WAI-ARIA radio group pattern; `spec:AST-020` FR9, FR15, DEC-5; `spec:AST-094` FR4, FR11, FR13, FR43; `design:reduced-motion`; `spec:AST-085` FR1, FR2, FR5, FR7; `design:user-states` DR1–DR3 (through SegmentedControlItem); `design:bidirectionality` DR6; `architecture:component-size-cascade` INV3–INV5; `architecture:interaction-modality` INV1; `architecture:public-component-api` INV5, INV7. |
This table is a review projection; the body below is authoritative.
@@ -112,16 +127,21 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
-| FR1 | The radiogroup container carries the current `segmented-control` target with `data-size`, sets `aria-label` to `label`, and renders its supplied children. | Current source, docs, and tests |
-| FR2 | The group is one Tab stop: the selected segment, or, when the value matches no segment, the first segment not disabled by its own `isDisabled` (in a disabled group that segment keeps the stop, FR7); a disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1). ArrowLeft and ArrowRight move focus between enabled segments in the visual direction, flipping in right-to-left layouts (`design:bidirectionality` DR6), and wrap; Home and End jump to the ends; ArrowUp and ArrowDown do nothing. Disabled segments are skipped. | WAI-ARIA radio group pattern; current tests; `design:bidirectionality` DR6 |
-| FR3 | When arrow, Home, or End navigation moves focus to an enabled segment, that segment's value is passed to `onChange` if it differs. A pointer press MUST select only on a click whose lift lands inside the segment (`spec:AST-020` FR9, DEC-5). Implementation gap: while focus is already in the group, a pointer press on another segment moves focus there and selects before any click, so a press that slides off still selects. Focus entering the group from outside never changes the value. | WAI-ARIA radio group pattern; current tests; `spec:AST-020` FR9, DEC-5 |
-| FR4 | A caller `onKeyDown` runs before built-in navigation and can cancel it with `preventDefault()`; a caller `onFocus` runs before selection-follows-focus. On first keyboard focus an ephemeral hint naming the arrow keys appears at the focused segment and dismisses on the first arrow press, a timeout, or blur. Built-in focus behavior MUST NOT be cancellable except where the public API promises it (`architecture:public-component-api` INV7). Implementation gap: a caller `onFocus` that calls `preventDefault()` also cancels the hint, the Tab-stop sync, and selection-follows-focus, and a caller `onBlur` that does so cancels the hint's blur dismissal. | Current source and tests; `architecture:public-component-api` INV7 |
-| FR5 | `hug` sizes the control to its segments; when any segment shows a visible label, the control never exceeds its container and labelled segments shrink and truncate. A control of only icon-only segments keeps its size. `fill` stretches the control to its container and gives segments equal shares that can shrink and truncate. | Current tests |
-| FR6 | Size resolves from an explicit `size`, then the nearest size provider, then `md`, and reaches every segment. | `architecture:component-size-cascade` INV3–INV5; current source |
-| FR7 | `isDisabled` sets `aria-disabled` on the radiogroup, disables every segment, dims the control to half opacity, and blocks selection. The group MUST keep a Tab stop while disabled, placed as in FR2, and pointer events stay on (`spec:AST-085` FR1, FR7). With `disabledMessage`, a reason tooltip opens on hover and keyboard focus; the reason MUST describe the focusable segment (`spec:AST-085` FR5, FR7). Implementation gap: caller handlers on the radiogroup, such as `onKeyDown`, still run while disabled (`spec:AST-085` FR2). | `spec:AST-085`; current tests |
-| FR8 | The radiogroup owns `role`, `aria-label` (from `label`), `aria-disabled`, and `data-size`; a caller value for any of them is replaced. Other base props reach the radiogroup, and `ref` reaches it. Implementation gap: a caller `aria-describedby` is replaced, by the disabled-reason id or by nothing, against `architecture:public-component-api` INV5. | `architecture:public-component-api` INV5; current source and tests |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
+| FR1 | The radiogroup container carries the current `segmented-control` target with `data-size`, sets `aria-label` to `label`, and renders its supplied children. | Current source, docs, and tests |
+| FR2 | The group is one Tab stop: the selected segment, or, when the value matches no segment, the first segment not disabled by its own `isDisabled` (in a disabled group that segment keeps the stop, FR7); a disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1). ArrowLeft and ArrowRight move focus between enabled segments in the visual direction, flipping in right-to-left layouts (`design:bidirectionality` DR6), and wrap; Home and End jump to the ends; ArrowUp and ArrowDown do nothing. Disabled segments are skipped. | WAI-ARIA radio group pattern; current tests; `design:bidirectionality` DR6 |
+| FR3 | When arrow, Home, or End navigation moves focus to an enabled segment, that segment's value is passed to `onChange` if it differs. A tap selects through the segment's click when its lift lands on that segment; a drag commits at the lift on the segment nearest the pointer, its padding and the gaps between segments included (FR13); a lift outside the control selects nothing (`spec:AST-020` FR9, DEC-5). Focus entering the group from outside never changes the value. | WAI-ARIA radio group pattern; current tests; `spec:AST-020` FR9, DEC-5 |
+| FR4 | A caller `onKeyDown` runs before built-in navigation and can cancel it with `preventDefault()`; a caller `onFocus` runs before selection-follows-focus. On first keyboard focus an ephemeral hint naming the arrow keys appears at the focused segment and dismisses on the first arrow press, a timeout, or blur. Built-in focus behavior MUST NOT be cancellable except where the public API promises it (`architecture:public-component-api` INV7). Implementation gap: a caller `onFocus` that calls `preventDefault()` also cancels the hint, the Tab-stop sync, and selection-follows-focus, and a caller `onBlur` that does so cancels the hint's blur dismissal. | Current source and tests; `architecture:public-component-api` INV7 |
+| FR5 | `hug` sizes the control to its segments; when any segment shows a visible label, the control never exceeds its container and labelled segments shrink and truncate. A control of only icon-only segments keeps its size. `fill` stretches the control to its container and gives segments equal shares that can shrink and truncate. | Current tests |
+| FR6 | Size resolves from an explicit `size`, then the nearest size provider, then `md`, and reaches every segment. | `architecture:component-size-cascade` INV3–INV5; current source |
+| FR7 | `isDisabled` sets `aria-disabled` on the radiogroup, disables every segment, dims the control to half opacity, and blocks selection. The group MUST keep a Tab stop while disabled, placed as in FR2, and pointer events stay on (`spec:AST-085` FR1, FR7). With `disabledMessage`, a reason tooltip opens on hover and keyboard focus; the reason MUST describe the focusable segment (`spec:AST-085` FR5, FR7). Implementation gap: caller handlers on the radiogroup, such as `onKeyDown`, still run while disabled (`spec:AST-085` FR2). | `spec:AST-085`; current tests |
+| FR8 | The radiogroup owns `role`, `aria-label` (from `label`), `aria-disabled`, and `data-size`; a caller value for any of them is replaced. Other base props reach the radiogroup, and `ref` reaches it. Implementation gap: a caller `aria-describedby` is replaced, by the disabled-reason id or by nothing, against `architecture:public-component-api` INV5. | `architecture:public-component-api` INV5; current source and tests |
+| FR9 | Under a finger (`spec:AST-094` FR13), a change of selection slides the selected surface from the old segment to the new one as one surface, the radiogroup's `::before`, animating transform and opacity only; under a fine pointer it slides on the theme's duration and easing. | Owner direction; `spec:AST-094` FR13; current source and tests |
+| FR10 | The slide plays on the internal `segmented.*` motion roles with UIKit's measured values (`spec:AST-094` FR4, DEC-11; thresholds internal under `spec:AST-002` FR3); under Reduce Motion the old surface fades out in place as the new one fades in (`design:reduced-motion` DR1–DR3). With a fine pointer under Reduce Motion, the theme's transition shows the change. | UIKit measurements (iOS 26.2); `design:reduced-motion` DR1–DR3; current tests |
+| FR11 | Under a finger, a held unselected segment paints the pressed overlay on its part, as under a mouse (`design:user-states` DR1); no theme role changes or dims it. | `design:user-states` DR1; current tests |
+| FR12 | During a drag of the selected surface, the selected label's colour follows the surface, with an internal hysteresis around each boundary; the weights change at the lift. A tap selects through the browser's click (`spec:AST-094` FR11). | Owner decision (weights at the lift); current tests |
+| FR13 | Under a finger, a drag from the selected segment carries the selected surface with the finger, within an internal overshoot past the end segments, and the lift commits the segment nearest the finger through that segment's click; a drag that starts on another segment leaves the surface in place and commits where it lifts, as a menu's press-tracking slide commits where it lifts (`spec:AST-094` FR26–FR28). A mouse and a pen drag the same way (`spec:AST-094` FR43). Under Reduce Motion the surface still follows the pointer, as direct movement (`design:reduced-motion`), and a finger's release cross-fades; under a fine pointer a mouse's or a pen's release lands at once (DR3). A lift outside the control commits nothing (FR3). | `spec:AST-094` FR26–FR28, FR43; `design:reduced-motion`; current tests |
### Allowed variation
@@ -158,6 +178,10 @@ Consumer migration instructions belong in consumer docs and release notes.
control, plus, through the tooltip's layer, the shared gesture counter's
document listeners, installed once per page; segments share the press
controller's window and document listeners.
+- **PR2 — The touch presentation adds no element.** SegmentedControl is a
+ repeated control, so it keeps the strict element budget
+ (`architecture:component-style-authoring` INV7): the slide uses the
+ radiogroup's `::before`.
## Accessibility contract
@@ -205,24 +229,24 @@ segment parts as well.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
-| FR1, AR1 | `SegmentedControl.test.tsx` rendering, size, and data-testid cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states | Control with several segments; sizes | Lost group semantics or name fails. Evidence gap: no test asserts the `segmented-control` target or `data-size`. | `audit:SegmentedControl/anatomy` |
-| FR2, FR3, ORD2, AR2 | `SegmentedControl.test.tsx` keyboard-navigation, unmatched-value and Tab-stop cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states; the radio-group pattern's aborted-press check on `segmented-option-unselected`; the `segmented-group-selected-rtl` state's arrow round trip under `dir="rtl"` | Arrows, wrap, Home, End; Tab-in with an unmatched or disabled selection | A value change on Tab entry, no wrap, or landing on a disabled segment fails. A press that slides off with focus outside the group and still selects fails. Evidence gap: no test covers a slide-off press while focus is already in the group. | `audit:SegmentedControl/accessibility` |
-| FR4, ORD1 | `SegmentedControl.test.tsx` container handler forwarding cases | Caller `onKeyDown`, with and without `preventDefault` | A caller key handler that cannot cancel navigation fails. Evidence gap: no test asserts the caller `onFocus` order or the keyboard hint. | `audit:SegmentedControl/behavior` |
-| FR5 | `SegmentedControl.test.tsx` layout cases | Hug, fill, narrow row, icon-only | A control that overflows, or squeezes icon-only segments, fails. | `audit:SegmentedControl/layout` |
-| FR6 | Evidence gap: no test asserts size precedence or its propagation | — | — | `audit:SegmentedControl/layout` |
-| FR7, AR3 | `SegmentedControl.test.tsx` disabled and disabledMessage cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-disabled` and `segmented-group-disabled-with-message` states | Group and item disabled; with reason | A selection while disabled, or a missing reason tooltip, fails. Evidence gap: no test asserts the half opacity, or caller handlers while disabled. The `segmented-group-disabled` state declares a Tab stop. | `audit:SegmentedControl/accessibility` |
-| FR8 | `SegmentedControl.test.tsx` role-override and data-testid cases | Forwarded role | A forwarded prop that overrides the role fails. Evidence gap: no test asserts `ref` or a caller `aria-describedby`. | `audit:SegmentedControl/api` |
-| PR1 | Evidence gap: no test asserts the absence of global listeners | — | — | `audit:SegmentedControl/behavior` |
-| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Control and item targets | A rendered class absent from the documented targets fails. | `audit:SegmentedControl/theming` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and both current targets | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:SegmentedControl/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
+| FR1, AR1 | `SegmentedControl.test.tsx` rendering, size, and data-testid cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states | Control with several segments; sizes | Lost group semantics or name fails. Evidence gap: no test asserts the `segmented-control` target or `data-size`. | `audit:SegmentedControl/anatomy` |
+| FR2, FR3, ORD2, AR2 | `SegmentedControl.test.tsx` keyboard-navigation, unmatched-value and Tab-stop cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states; the radio-group pattern's aborted-press check on `segmented-option-unselected`; the `segmented-group-selected-rtl` state's arrow round trip under `dir="rtl"`; `SegmentedControl.interaction.browser.spec.ts` slide-off cases for a finger and a mouse, with focus in the group or not | Arrows, wrap, Home, End; Tab-in with an unmatched or disabled selection | A value change on Tab entry, no wrap, or landing on a disabled segment fails. A press that slides off with focus outside the group and still selects fails. A press with focus already in the group that selects before its lift fails. | `audit:SegmentedControl/accessibility` |
+| FR4, ORD1 | `SegmentedControl.test.tsx` container handler forwarding cases | Caller `onKeyDown`, with and without `preventDefault` | A caller key handler that cannot cancel navigation fails. Evidence gap: no test asserts the caller `onFocus` order or the keyboard hint. | `audit:SegmentedControl/behavior` |
+| FR5 | `SegmentedControl.test.tsx` layout cases | Hug, fill, narrow row, icon-only | A control that overflows, or squeezes icon-only segments, fails. | `audit:SegmentedControl/layout` |
+| FR6 | Evidence gap: no test asserts size precedence or its propagation | — | — | `audit:SegmentedControl/layout` |
+| FR7, AR3 | `SegmentedControl.test.tsx` disabled and disabledMessage cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-disabled` and `segmented-group-disabled-with-message` states | Group and item disabled; with reason | A selection while disabled, or a missing reason tooltip, fails. Evidence gap: no test asserts the half opacity, or caller handlers while disabled. The `segmented-group-disabled` state declares a Tab stop. | `audit:SegmentedControl/accessibility` |
+| FR8 | `SegmentedControl.test.tsx` role-override and data-testid cases | Forwarded role | A forwarded prop that overrides the role fails. Evidence gap: no test asserts `ref` or a caller `aria-describedby`. | `audit:SegmentedControl/api` |
+| FR9, FR10, PR2 | `useSegmentedSelectionMotion.test.ts` slide, retarget, keyboard, Reduce Motion and fine-pointer cases; `SegmentedControl.interaction.browser.spec.ts` slide, measured-spring, Reduce Motion, busy-main-thread and mouse-click proofs in Chromium and WebKit | a tap, a retarget, keyboard selection, Reduce Motion, a mouse | a second surface or added element, a Layout or Paint per frame, a curve off its role, travel under Reduce Motion, or a mouse slide off the theme's timing fails | `audit:SegmentedControl/theming` |
+| FR11 | `SegmentedControl.interaction.browser.spec.ts` pressed-overlay proofs; `PressedState.a11y.chromium.spec.ts` segmented-control cases | a held unselected segment, a held selected segment | an unselected segment without the pressed overlay, or a dim under the default theme fails | `audit:SegmentedControl/theming` |
+| FR12, FR13 | `useSegmentedSelectionMotion.test.ts` and `useSegmentedTouchTracking.test.ts` drag, face and lift cases; `SegmentedControl.interaction.browser.spec.ts` drag, overshoot, hysteresis, tap-click, slide-off, Reduce Motion drag, mouse and pen proofs | a hold, a drag, a release between segments, the end overshoot, a slow dither, a tap, a drag from another segment, a lift outside, Reduce Motion | a weight change mid-drag, a label that flips twice in a small dither, a commit anywhere but the segment nearest the finger, a commit after a lift outside, or a surface that stays put under Reduce Motion fails | `audit:SegmentedControl/anatomy` |
+| PR1 | Evidence gap: no test asserts the absence of global listeners | — | — | `audit:SegmentedControl/behavior` |
+| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Control and item targets | A rendered class absent from the documented targets fails. | `audit:SegmentedControl/theming` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and both current targets | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:SegmentedControl/theming` |
## Current-state impact
-- **Press while focused (FR3).** A pointer press on another segment while focus
- is in the group selects before any click, so a slide-off still selects,
- against `spec:AST-020` FR9 and DEC-5.
- **Focus handler cancellation (FR4).** A caller `onFocus` or `onBlur` that
calls `preventDefault()` cancels built-in focus behavior the public API does
not promise to expose, against `architecture:public-component-api` INV7.
diff --git a/docs/specs/components/SegmentedControl/SegmentedControlItem.spec.md b/docs/specs/components/SegmentedControl/SegmentedControlItem.spec.md
index 04e9016a6a..899f1e46fa 100644
--- a/docs/specs/components/SegmentedControl/SegmentedControlItem.spec.md
+++ b/docs/specs/components/SegmentedControl/SegmentedControlItem.spec.md
@@ -26,6 +26,7 @@ review_triggers:
verified_by:
[
packages/core/src/SegmentedControl/SegmentedControl.test.tsx,
+ packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts,
packages/core/src/RadioList/__tests__/RadioGroup.a11y.test.tsx,
packages/core/src/RadioList/__tests__/RadioGroup.a11y.chromium.spec.ts,
packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts,
@@ -54,7 +55,7 @@ system_specs: [spec:AST-020, spec:AST-085, spec:AST-102]
| Behavior | One segment: a `<button role="radio">` with `aria-checked`. A click, or Space or Enter on the focused segment, selects it unless it is selected, disabled, or the caller's `onClick` prevents default. |
| End-user impact | People see the selected segment raised and bold, and pick another with one click. Icon-only segments are still named. A disabled selected segment keeps the Tab stop. |
| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A caller `onClick` runs while disabled or cannot veto a press while focused, a caller `className` is replaced, segments hold a fixed height, and a truncated `sm` segment can be under 24 px wide; all are listed under Current-state impact. |
+| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A caller `onClick` runs while disabled, a caller `className` is replaced, segments hold a fixed height, and a truncated `sm` segment can be under 24 px wide; all are listed under Current-state impact. |
| Review checks | Reject a segment without a name, a click that selects a disabled segment, press paint on the selected or a disabled segment, or a lost forced-colors selected state. |
| Governing rules | `component:SegmentedControl`; WAI-ARIA radio pattern; `spec:AST-020` FR9, FR15, DEC-5; `spec:AST-085` FR1, FR2; `spec:AST-102` FR4; `design:user-states` DR1–DR3 (pressed overlay, disabled non-response, and selected-segment exception); `architecture:public-component-api` INV5, INV6; WCAG 1.4.11. |
@@ -107,7 +108,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| ID | Invariant | Basis |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| FR1 | Each segment renders one `<button type="button" role="radio">` with `aria-checked` true when its `value` equals the group value, `data-value`, and the `segmented-control-item` target reflecting `data-size`, `data-selected`, and `data-disabled`. A forwarded prop cannot override the role. | WAI-ARIA radio pattern; current source and tests |
-| FR2 | A click, including one from Space or Enter on the focused segment (native button activation; `spec:AST-020` FR15), runs the caller `onClick` first; unless it prevents default, an enabled, unselected segment passes its value to the group's `onChange`. Clicking the selected segment does nothing. The caller's `preventDefault()` MUST veto every press. Implementation gap: a press while focus is already in the group selects through `component:SegmentedControl` FR3 before the click, so the veto does not apply to it. | `spec:AST-020` FR15; current tests |
+| FR2 | A click, including one from Space or Enter on the focused segment (native button activation; `spec:AST-020` FR15), runs the caller `onClick` first; unless it prevents default, an enabled, unselected segment passes its value to the group's `onChange`. Clicking the selected segment does nothing. The caller's `preventDefault()` MUST veto every press. | `spec:AST-020` FR15; current tests |
| FR3 | The segment renders its icon (sized to the segment size) followed by its label. With `isLabelHidden`, the label is not rendered and becomes `aria-label`, and the segment does not shrink. A visible label truncates with an ellipsis when the segment is narrower than it. | Current tests |
| FR4 | A segment disabled by its own `isDisabled` or by the group sets `aria-disabled`, refuses selection, shows disabled text color, and shows no hover or press paint. A disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1); for a value that matches no segment, `component:SegmentedControl` FR2 places the stop. Implementation gap: a caller `onClick` still runs on a disabled segment (`spec:AST-085` FR2). | `spec:AST-085` FR1, FR2; current tests |
| FR5 | The selected segment paints a raised surface with a low shadow and semibold primary text; under forced colors it paints `Highlight` with `HighlightText`. Unselected enabled segments paint the shared hover tint and, under `design:user-states` DR1 and DR2, the pressed overlay; the selected segment keeps its raised surface during a press (DR3). | WCAG 1.4.11; `design:user-states` DR1–DR3; current tests |
@@ -130,8 +131,7 @@ Consumer migration instructions belong in consumer docs and release notes.
### Transformation and precedence order
- **ORD1 — Click.** Caller `onClick`, then selection unless prevented,
- disabled, or already selected; today a press while focus is in the group
- selects through focus first (FR2 gap).
+ disabled, or already selected.
### Performance and resources
@@ -170,7 +170,7 @@ theming anatomy.
| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| FR1 | `SegmentedControl.test.tsx` aria-checked and data-testid cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-option-*` states | Selection change; data-testid | Stale `aria-checked` fails. Evidence gap: no test passes `role` to a segment; the role-override case covers the radiogroup. | `audit:SegmentedControlItem/accessibility` |
-| FR2 | `SegmentedControl.test.tsx` click and onClick-composition cases | Click; selected click; prevented click | A selected or prevented click that selects fails. Evidence gap: no test covers a press while focus is already in the group. | `audit:SegmentedControlItem/behavior` |
+| FR2 | `SegmentedControl.test.tsx` click and onClick-composition cases; `SegmentedControl.interaction.browser.spec.ts` click-commit and veto cases for a tap and a drag | Click; selected click; prevented click | A selected or prevented click that selects fails. A press with focus already in the group that selects past a veto fails. | `audit:SegmentedControlItem/behavior` |
| FR3 | `SegmentedControl.test.tsx` icon, icon-only, and truncation cases | Icon and label; icon-only; long label | A missing name, or an icon that truncates, fails. | `audit:SegmentedControlItem/anatomy` |
| FR4 | `SegmentedControl.test.tsx` disabled cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-option-disabled` and `segmented-option-group-disabled*` states | Item and group disabled | A disabled segment that selects fails. Evidence gap: no test asserts the disabled text color, absent hover paint, or the caller `onClick` while disabled. The `segmented-option-group-disabled` state declares a checked, group-disabled segment that keeps the Tab stop. | `audit:SegmentedControlItem/accessibility` |
| FR5 | `SegmentedControl.test.tsx` forced-colors and pressed-state cases; `PressedState.a11y.chromium.spec.ts` segmented-control cases | Selected under forced colors; press; disabled | Lost forced-colors state, or press paint on a disabled segment, fails. Evidence gap: no test asserts the raised selected surface or the hover tint. | `audit:SegmentedControlItem/visual` |
@@ -181,8 +181,6 @@ theming anatomy.
- **Narrow target (AR2).** A labelled `sm` segment that truncates can shrink
below 24 CSS px wide, short of WCAG 2.5.8.
-- **Press veto (FR2).** A caller `onClick` cannot veto a press made while focus
- is already in the group, which selects before the click.
- **Caller className (FR7).** A caller `className` on a segment is replaced by
the component's class, against `architecture:public-component-api` INV5 and
INV6.
diff --git a/docs/specs/components/Switch/Switch.spec.md b/docs/specs/components/Switch/Switch.spec.md
index 1e6f2570d4..e1bca13301 100644
--- a/docs/specs/components/Switch/Switch.spec.md
+++ b/docs/specs/components/Switch/Switch.spec.md
@@ -214,10 +214,11 @@ measured on UISwitch, iOS 26.2 (`motion/uikit/switch.ts`).
gesture counter's document listeners, installed once per page; it owns no
observer, and the busy announcement fires once per busy period. An enabled
switch also adds one consumer to the shared gesture host, whose listeners
- are installed once per page, and a `click` listener to the element around
- its track: at once under a coarse primary
- pointer, and only during a press under a fine one, where the host arms one
- passive `pointerdown` listener on that element (`spec:AST-094` FR24).
+ are installed once per page; under a fine primary pointer the host arms one
+ passive `pointerdown` listener on the element around its track
+ (`spec:AST-094` FR24). The switch adds no `click` listener of its own: a
+ lift that waits for the browser's click subscribes to the window's shared
+ input stream until that click comes or the wait runs out.
## Accessibility contract
diff --git a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
index 45a2a8adc3..803a6a1850 100644
--- a/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
+++ b/packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
@@ -168,7 +168,7 @@ function WorkspaceCard() {
usage: {
anatomy,
description:
- '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.',
+ '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. Under a finger, on a touch device (a coarse primary pointer), the selection slides to the new segment, whether a tap, an arrow key or a new value moved it; with Reduce Motion nothing travels: the old selection fades out as the new one fades in. There, dragging the selected segment carries the selection along with the selected label’s colour following it, and the segment under the finger is chosen when it lets go (letting go outside the control selects nothing); a tap selects through the browser’s click; a pressed segment shows the shared pressed overlay, and nothing lifts or dims. With a mouse or a pen every change, a click included, slides on the theme’s duration and easing, and dragging the selected segment carries it as a finger does.',
accessibility: [
{
name: 'Text label',
@@ -240,7 +240,7 @@ export const docsZh = {
usage: {
anatomy,
description:
- '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.',
+ '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. Under a finger, on a touch device (a coarse primary pointer), the selection slides to the new segment, whether a tap, an arrow key or a new value moved it; with Reduce Motion nothing travels: the old selection fades out as the new one fades in. There, dragging the selected segment carries the selection along with the selected label’s colour following it, and the segment under the finger is chosen when it lets go (letting go outside the control selects nothing); a tap selects through the browser’s click; a pressed segment shows the shared pressed overlay, and nothing lifts or dims. With a mouse or a pen every change, a click included, slides on the theme’s duration and easing, and dragging the selected segment carries it as a finger does.',
bestPractices: [
{guidance: true, description: 'Use for switching between 2–5 mutually exclusive views or modes where all options should be visible.'},
{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 = {
usage: {
anatomy,
description:
- '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.',
+ '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. Under a finger, on a touch device (a coarse primary pointer), the selection slides to the new segment, whether a tap, an arrow key or a new value moved it; with Reduce Motion nothing travels: the old selection fades out as the new one fades in. There, dragging the selected segment carries the selection along with the selected label’s colour following it, and the segment under the finger is chosen when it lets go (letting go outside the control selects nothing); a tap selects through the browser’s click; a pressed segment shows the shared pressed overlay, and nothing lifts or dims. With a mouse or a pen every change, a click included, slides on the theme’s duration and easing, and dragging the selected segment carries it as a finger does.',
bestPractices: [
{guidance: true, description: 'Use for switching between 2–5 mutually exclusive views or modes where all options should be visible.'},
{guidance: true, description: 'Provide a descriptive label for the control to ensure the group is accessible to screen readers.'},
diff --git a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
index 0e234adf36..17fe825221 100644
--- a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx
@@ -12,8 +12,15 @@
* SYNC: When SegmentedControl components change, update tests to match new behavior
*/
+import {StrictMode} from 'react';
import {describe, it, expect, vi, beforeEach} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {
+ cleanup,
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {hasPressedArm} from '../__tests__/pressState';
import {__resetInteractionModalityForTest} from '../utils/interactionModality';
@@ -1159,6 +1166,176 @@ describe('pressed state', () => {
});
});
+describe('selection motion', () => {
+ /** A finger is the primary pointer: a touch device. */
+ function mockCoarsePointer() {
+ return vi.spyOn(window, 'matchMedia').mockImplementation(
+ (query: string) =>
+ ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }) as MediaQueryList,
+ );
+ }
+
+ function renderControl(onChange = vi.fn()) {
+ return render(
+ <SegmentedControl value="grid" onChange={onChange} label="View mode">
+ <SegmentedControlItem value="grid" label="Grid" />
+ <SegmentedControlItem value="list" label="List" />
+ <SegmentedControlItem
+ value="icon"
+ label="Icon"
+ icon={<span>*</span>}
+ isLabelHidden
+ />
+ </SegmentedControl>,
+ );
+ }
+
+ it('keeps the pointer presentation as it was: no lens, the theme’s transitions', () => {
+ renderControl();
+ expect(
+ screen
+ .getByRole('radiogroup')
+ .style.getPropertyValue('--_segmented-lens-visibility'),
+ ).toBe('');
+ expect(
+ getComputedStyle(screen.getByRole('radio', {name: 'List'}))
+ .transitionProperty,
+ ).toContain('background-color');
+ });
+
+ it('one touch model: a finger on any engine (no iOS check) gets the touch presentation, and a tap still selects', async () => {
+ const spy = mockCoarsePointer();
+ try {
+ const onChange = vi.fn();
+ renderControl(onChange);
+ // The lens is the radiogroup's own pseudo-elements, so the touch
+ // presentation shows as its styles: no CSS transition on the segments.
+ expect(
+ getComputedStyle(screen.getByRole('radio', {name: 'List'}))
+ .transitionProperty,
+ ).toBe('none');
+ await userEvent.setup().click(screen.getByRole('radio', {name: 'List'}));
+ expect(onChange).toHaveBeenCalledWith('list');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('touch presentation: as many elements as under a mouse; selection unchanged', async () => {
+ // A fine pointer for the first render.
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
+ const mouse = renderControl().container.querySelectorAll('*').length;
+ cleanup();
+ const spy = mockCoarsePointer();
+ try {
+ const onChange = vi.fn();
+ const {container} = renderControl(onChange);
+ expect(container.querySelectorAll('*').length).toBe(mouse);
+ await userEvent.setup().click(screen.getByRole('radio', {name: 'List'}));
+ expect(onChange).toHaveBeenCalledWith('list');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('touch presentation: the segments a press can change keep the shared press paint, and nothing dims (the record owner’s decision)', () => {
+ const spy = mockCoarsePointer();
+ try {
+ renderControl();
+ for (const name of ['List', 'Icon']) {
+ const segment = screen.getByRole('radio', {name});
+ expect(segment).toHaveAttribute('data-astryx-pressable');
+ expect(hasPressedArm(segment)).toBe(true);
+ }
+ // The selected segment never paints a press.
+ expect(screen.getByRole('radio', {name: 'Grid'})).not.toHaveAttribute(
+ 'data-astryx-pressable',
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('a mouse keeps the shared press paint on the segments a press can change', () => {
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
+ renderControl();
+ for (const name of ['List', 'Icon']) {
+ expect(screen.getByRole('radio', {name})).toHaveAttribute(
+ 'data-astryx-pressable',
+ );
+ }
+ // The selected segment never paints a press.
+ expect(screen.getByRole('radio', {name: 'Grid'})).not.toHaveAttribute(
+ 'data-astryx-pressable',
+ );
+ });
+
+ it('touch presentation: a value change starts the slide, StrictMode included', () => {
+ const spy = mockCoarsePointer();
+ const boxes: Record<string, [number, number]> = {
+ grid: [2, 96],
+ list: [102, 96],
+ };
+ const rects = vi
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ const [left, width] =
+ this.getAttribute('role') === 'radiogroup'
+ ? [0, 200]
+ : (boxes[this.dataset.value ?? ''] ?? [0, 0]);
+ return {
+ left,
+ top: 2,
+ width,
+ height: 28,
+ right: left + width,
+ bottom: 30,
+ x: left,
+ y: 2,
+ toJSON: () => ({}),
+ };
+ });
+ try {
+ const ui = (value: string) => (
+ <StrictMode>
+ <SegmentedControl value={value} onChange={() => {}} label="View">
+ <SegmentedControlItem value="grid" label="Grid" />
+ <SegmentedControlItem value="list" label="List" />
+ </SegmentedControl>
+ </StrictMode>
+ );
+ const {rerender} = render(ui('grid'));
+ rerender(ui('list'));
+ const group = screen.getByRole('radiogroup');
+ // After StrictMode's extra unmount and remount, the lens (the
+ // radiogroup's ::before) still takes the destination's box, painted
+ // from the selected surface.
+ expect(group.style.getPropertyValue('--_segmented-lens-visibility')).toBe(
+ 'visible',
+ );
+ expect(group.style.getPropertyValue('--_segmented-lens-width')).toBe(
+ '96px',
+ );
+ // Laid out on the destination's box, where it lands centered.
+ expect(group.style.getPropertyValue('--_segmented-lens-left')).toBe(
+ '102px',
+ );
+ } finally {
+ rects.mockRestore();
+ spy.mockRestore();
+ }
+ });
+});
+
describe("SegmentedControl keeps a caller's aria-describedby", () => {
it('describes the radiogroup by the caller ids', () => {
render(
diff --git a/packages/core/src/SegmentedControl/SegmentedControl.tsx b/packages/core/src/SegmentedControl/SegmentedControl.tsx
index 51a429daab..47a0884d98 100644
--- a/packages/core/src/SegmentedControl/SegmentedControl.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControl.tsx
@@ -4,7 +4,8 @@
/**
* @file SegmentedControl.tsx
- * @input Uses React, StyleX, SegmentedControlContext, useListFocus, useKeyboardHint
+ * @input Uses React, StyleX, SegmentedControlContext, useListFocus,
+ * useKeyboardHint, useTouchPresentation, useSegmentedSelectionMotion
* @output Exports SegmentedControl component and SegmentedControlProps type
* @position Container wrapper; provides context to SegmentedControlItem children
*
@@ -12,10 +13,11 @@
* - /packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
* - /packages/core/src/SegmentedControl/index.ts
* - /packages/core/src/SegmentedControl/SegmentedControl.test.tsx
+ * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
* - /packages/cli/assets/templates/blocks/components/SegmentedControl/ (showcase blocks)
*/
-import React, {useMemo, useCallback, type ReactNode} from 'react';
+import React, {useMemo, useCallback, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars, spacingVars, radiusVars} from '../theme/tokens.stylex';
import {SegmentedControlContext} from './SegmentedControlContext';
@@ -34,6 +36,9 @@ import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {useMergedRefs} from '../hooks/useMergedRefs';
+import {useTouchPresentation} from '../utils/touchPresentation';
+import {useSegmentedSelectionMotion} from './useSegmentedSelectionMotion';
+
export interface SegmentedControlProps extends Omit<
BaseProps<HTMLDivElement>,
'onChange'
@@ -94,6 +99,11 @@ export interface SegmentedControlProps extends Omit<
const styles = stylex.create({
container: {
+ // The lens's containing block and stacking context. The lens sits at
+ // z-index -1 inside it: above the track's own background, below every
+ // segment.
+ position: 'relative',
+ isolation: 'isolate',
display: 'inline-flex',
alignItems: 'center',
width: 'fit-content',
@@ -127,6 +137,140 @@ const styles = stylex.create({
disabled: {
opacity: 0.5,
},
+ // The lens uses the radiogroup's own pseudo-elements, so it adds no
+ // element. ::before carries the selected surface. Under Reduced Motion,
+ // ::after is the old surface that fades out in place. Both are hidden at
+ // rest. A negative z-index keeps them under every segment's content, inside
+ // the stacking context the container's isolation makes. Above the segments,
+ // a moving lens could paint over their titles. WebKit's overlap test can
+ // miss what a moving layer covers.
+ lens: {
+ '::before': {
+ content: '""',
+ position: 'absolute',
+ zIndex: -1,
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: laid out on a segment's box measured from client rects (useSegmentedSelectionMotion), in both directions.
+ left: 'var(--_segmented-lens-left, 0px)',
+ top: 'var(--_segmented-lens-top, 0px)',
+ width: 'var(--_segmented-lens-width, 0px)',
+ height: 'var(--_segmented-lens-height, 0px)',
+ boxSizing: 'border-box',
+ // Scales around its center: the lens's position and size are separate.
+ transformOrigin: '50% 50%',
+ pointerEvents: 'none',
+ visibility: 'var(--_segmented-lens-visibility, hidden)',
+ willChange: 'var(--astryx-motion-will-change-before, auto)',
+ // It carries a copy of an already resolved surface, forced colors
+ // included (Highlight), so the UA must not remap it again.
+ forcedColorAdjust: 'none',
+ backgroundColor: 'var(--_segmented-lens-background-color, transparent)',
+ backgroundImage: 'var(--_segmented-lens-background-image, none)',
+ backgroundPosition: 'var(--_segmented-lens-background-position, 0% 0%)',
+ backgroundSize: 'var(--_segmented-lens-background-size, auto)',
+ backgroundRepeat: 'var(--_segmented-lens-background-repeat, repeat)',
+ backgroundOrigin: 'var(--_segmented-lens-background-origin, padding-box)',
+ backgroundClip: 'var(--_segmented-lens-background-clip, border-box)',
+ boxShadow: 'var(--_segmented-lens-box-shadow, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderTopLeftRadius: 'var(--_segmented-lens-border-top-left-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderTopRightRadius:
+ 'var(--_segmented-lens-border-top-right-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderBottomRightRadius:
+ 'var(--_segmented-lens-border-bottom-right-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderBottomLeftRadius:
+ 'var(--_segmented-lens-border-bottom-left-radius, 0px)',
+ borderTopWidth: 'var(--_segmented-lens-border-top-width, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightWidth: 'var(--_segmented-lens-border-right-width, 0px)',
+ borderBottomWidth: 'var(--_segmented-lens-border-bottom-width, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftWidth: 'var(--_segmented-lens-border-left-width, 0px)',
+ borderTopStyle: 'var(--_segmented-lens-border-top-style, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightStyle: 'var(--_segmented-lens-border-right-style, none)',
+ borderBottomStyle: 'var(--_segmented-lens-border-bottom-style, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftStyle: 'var(--_segmented-lens-border-left-style, none)',
+ borderTopColor: 'var(--_segmented-lens-border-top-color, currentcolor)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightColor:
+ 'var(--_segmented-lens-border-right-color, currentcolor)',
+ borderBottomColor:
+ 'var(--_segmented-lens-border-bottom-color, currentcolor)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftColor: 'var(--_segmented-lens-border-left-color, currentcolor)',
+ backdropFilter: 'var(--_segmented-lens-backdrop-filter, none)',
+ WebkitBackdropFilter:
+ 'var(--_segmented-lens-webkit-backdrop-filter, none)',
+ },
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ zIndex: -1,
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: laid out on a segment's box measured from client rects (useSegmentedSelectionMotion), in both directions.
+ left: 'var(--_segmented-after-left, 0px)',
+ top: 'var(--_segmented-after-top, 0px)',
+ width: 'var(--_segmented-after-width, 0px)',
+ height: 'var(--_segmented-after-height, 0px)',
+ boxSizing: 'border-box',
+ // Scales around its center: the lens's position and size are separate.
+ transformOrigin: '50% 50%',
+ pointerEvents: 'none',
+ visibility: 'var(--_segmented-after-visibility, hidden)',
+ willChange: 'var(--astryx-motion-will-change-after, auto)',
+ // It carries a copy of an already resolved surface, forced colors
+ // included (Highlight), so the UA must not remap it again.
+ forcedColorAdjust: 'none',
+ backgroundColor: 'var(--_segmented-after-background-color, transparent)',
+ backgroundImage: 'var(--_segmented-after-background-image, none)',
+ backgroundPosition: 'var(--_segmented-after-background-position, 0% 0%)',
+ backgroundSize: 'var(--_segmented-after-background-size, auto)',
+ backgroundRepeat: 'var(--_segmented-after-background-repeat, repeat)',
+ backgroundOrigin:
+ 'var(--_segmented-after-background-origin, padding-box)',
+ backgroundClip: 'var(--_segmented-after-background-clip, border-box)',
+ boxShadow: 'var(--_segmented-after-box-shadow, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderTopLeftRadius:
+ 'var(--_segmented-after-border-top-left-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderTopRightRadius:
+ 'var(--_segmented-after-border-top-right-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderBottomRightRadius:
+ 'var(--_segmented-after-border-bottom-right-radius, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderBottomLeftRadius:
+ 'var(--_segmented-after-border-bottom-left-radius, 0px)',
+ borderTopWidth: 'var(--_segmented-after-border-top-width, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightWidth: 'var(--_segmented-after-border-right-width, 0px)',
+ borderBottomWidth: 'var(--_segmented-after-border-bottom-width, 0px)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftWidth: 'var(--_segmented-after-border-left-width, 0px)',
+ borderTopStyle: 'var(--_segmented-after-border-top-style, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightStyle: 'var(--_segmented-after-border-right-style, none)',
+ borderBottomStyle: 'var(--_segmented-after-border-bottom-style, none)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftStyle: 'var(--_segmented-after-border-left-style, none)',
+ borderTopColor: 'var(--_segmented-after-border-top-color, currentcolor)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderRightColor:
+ 'var(--_segmented-after-border-right-color, currentcolor)',
+ borderBottomColor:
+ 'var(--_segmented-after-border-bottom-color, currentcolor)',
+ // eslint-disable-next-line @astryx/no-physical-properties -- intentional: a copy of the segment's computed (physical) surface.
+ borderLeftColor:
+ 'var(--_segmented-after-border-left-color, currentcolor)',
+ backdropFilter: 'var(--_segmented-after-backdrop-filter, none)',
+ WebkitBackdropFilter:
+ 'var(--_segmented-after-webkit-backdrop-filter, none)',
+ },
+ },
});
const sizeStyles = stylex.create({
@@ -177,6 +321,20 @@ export function SegmentedControl({
...rest
}: SegmentedControlProps) {
const size = useSize(sizeProp, 'md');
+ // A touch device (a coarse primary pointer) gets UIKit's motion: the
+ // selection slides on a spring. Under a mouse it slides on the theme's
+ // duration and easing.
+ const isTouchPresentation = useTouchPresentation().isTouch;
+ const trackRef = useRef<HTMLDivElement | null>(null);
+ // Every pointer's press is tracked. A drag from the selected segment
+ // carries the lens, and the lift commits the segment nearest the pointer.
+ // A lift outside the control commits nothing.
+ const {selection, attachTrack} = useSegmentedSelectionMotion(
+ trackRef,
+ value,
+ isTouchPresentation,
+ !isDisabled,
+ );
// Disabled-reason tooltip. Applies to the whole-group disabled state. The
// tooltip listeners attach to the radiogroup container, which keeps pointer
@@ -215,6 +373,7 @@ export function SegmentedControl({
const handleContainerKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
+ selection.keyPressed();
onKeyDownProp?.(e);
if (e.defaultPrevented) {
return;
@@ -222,7 +381,7 @@ export function SegmentedControl({
hint.onKeyDown(e);
handleKeyDown(e);
},
- [onKeyDownProp, hint, handleKeyDown],
+ [selection, onKeyDownProp, hint, handleKeyDown],
);
// Selection-follows-focus (APG radiogroup): useListFocus only *moves* focus,
@@ -252,6 +411,12 @@ export function SegmentedControl({
if (!e.currentTarget.contains(e.relatedTarget)) {
return;
}
+ // A mouse or pen press moves focus at pointerdown. A finger moves it
+ // after the lift, before the tap's click. The press commits through
+ // that click, so this focus move selects nothing.
+ if (selection.isPressing()) {
+ return;
+ }
const focused = (e.target as HTMLElement | null)?.closest<HTMLElement>(
'[role="radio"][data-value]',
);
@@ -263,7 +428,7 @@ export function SegmentedControl({
onChange(nextValue);
}
},
- [onFocusProp, hint, handleFocus, isDisabled, onChange, value],
+ [onFocusProp, hint, handleFocus, isDisabled, onChange, selection, value],
);
const contextValue = useMemo(
@@ -276,6 +441,7 @@ export function SegmentedControl({
disabledReasonID: showsDisabledMessage
? disabledMessageTooltip.describedBy
: undefined,
+ isTouchPresentation,
}),
[
value,
@@ -285,13 +451,20 @@ export function SegmentedControl({
isDisabled,
showsDisabledMessage,
disabledMessageTooltip.describedBy,
+ isTouchPresentation,
],
);
return (
<SegmentedControlContext value={contextValue}>
<div
- ref={useMergedRefs(ref, listRef, disabledMessageTooltip.ref)}
+ ref={useMergedRefs(
+ ref,
+ listRef,
+ trackRef,
+ attachTrack,
+ disabledMessageTooltip.ref,
+ )}
{...rest}
role="radiogroup"
aria-label={label}
@@ -310,6 +483,7 @@ export function SegmentedControl({
styles.container,
sizeStyles[size],
layout === 'fill' && styles.fill,
+ (isTouchPresentation || !isDisabled) && styles.lens,
isDisabled && styles.disabled,
xstyle,
),
diff --git a/packages/core/src/SegmentedControl/SegmentedControlContext.ts b/packages/core/src/SegmentedControl/SegmentedControlContext.ts
index 6ec5126d89..a7f94d7bae 100644
--- a/packages/core/src/SegmentedControl/SegmentedControlContext.ts
+++ b/packages/core/src/SegmentedControl/SegmentedControlContext.ts
@@ -29,6 +29,12 @@ export interface SegmentedControlContextValue {
* described by the reason (spec:AST-085 FR5).
*/
disabledReasonID?: string;
+ /**
+ * True in the touch presentation (under a finger, `useTouchPresentation`):
+ * the control animates selection changes itself (the surface slides), so
+ * segments drop their CSS transitions.
+ */
+ isTouchPresentation?: boolean;
}
export const SegmentedControlContext =
diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
index 744909149a..43dad60424 100644
--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx
@@ -9,6 +9,7 @@
* @position Child item; renders as a radio button within the segmented control
*
* SYNC: When modified, update:
+ * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts (the title marker)
* - /packages/core/src/SegmentedControl/SegmentedControl.doc.mjs
* - /packages/core/src/SegmentedControl/index.ts
* - /packages/core/src/SegmentedControl/SegmentedControl.test.tsx
@@ -18,6 +19,7 @@
import React, {type ReactNode} from 'react';
import {joinAriaIDs} from '../utils/inputAria';
import {segmentDisabledProps} from '../privateAttributes/segmentDisabled.stylex';
+import {segmentTitleProps} from '../privateAttributes/segmentTitle.stylex';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -147,6 +149,12 @@ const styles = stylex.create({
textOverflow: 'ellipsis',
minWidth: 0,
},
+ // Under a finger, script animates the selection change, because the surface
+ // slides. A CSS transition would run a second, main-thread version of the
+ // same change.
+ touchPresentation: {
+ transitionProperty: 'none',
+ },
});
const CONCENTRIC_RADIUS =
@@ -263,12 +271,15 @@ export function SegmentedControlItem({
!isItemDisabled &&
interactionOverlayStyles.backgroundColor,
isItemDisabled && styles.disabled,
+ ctx.isTouchPresentation === true && styles.touchPresentation,
xstyle,
),
)}>
{iconElement}
{!isLabelHidden && (
- <span {...stylex.props(styles.labelText)}>{label}</span>
+ <span {...segmentTitleProps} {...stylex.props(styles.labelText)}>
+ {label}
+ </span>
)}
</button>
);
diff --git a/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
new file mode 100644
index 0000000000..3e508acca5
--- /dev/null
+++ b/packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
@@ -0,0 +1,2845 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SegmentedControl.interaction.browser.spec.ts
+ * @input The built SegmentedControl stories, real touch and mouse input, and
+ * the interaction harness
+ * @output Browser proofs for the touch layer: the slide on UIKit's spring,
+ * the hand-back, Reduce Motion, a blocked main thread, the press, the drag,
+ * the commit at the lift, scrolling, text selection and a mouse
+ * @position Browser layer of useSegmentedSelectionMotion.ts; the unit layers
+ * are useSegmentedSelectionMotion.test.ts and motion/uikit/segmented.test.ts
+ *
+ * The oracles come from the harness (`springStep`, `cubicBezier`). They share
+ * no code with the code under test.
+ */
+
+import {
+ expect,
+ test,
+ type Browser,
+ type BrowserContext,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+import {
+ animationStoryboard,
+ blockMainThread,
+ busyWindowProof,
+ castStoryboard,
+ compareCurve,
+ countBetween,
+ freezeTimers,
+ installLongTaskLog,
+ installTimerGate,
+ MARKER_RGB,
+ openStory,
+ readLongTasks,
+ releaseAnimations,
+ springStep,
+ startScreencast,
+ thawTimers,
+ timeline,
+ touchDriver,
+ traceRendering,
+ trackMarker,
+ tap as touchTap,
+ drag as touchDrag,
+ touchStoryboard,
+ toTouchEvents,
+ waitForAnimation,
+ webInputDriver,
+ withStorybook,
+ writeEvidence,
+ PEN_SKIP,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+/** 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. */
+const DRAG_OVERSHOOT = 11;
+/** design:reduced-motion DR2: a cross-fade, opacity only, 200 ms or less. */
+const RM_MAX_FADE_MS = 200;
+
+interface SegmentBox {
+ value: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+interface Control {
+ driver: TouchDriver;
+ /**
+ * The radiogroup. Its ::before is the lens; under Reduced Motion its
+ * ::after shows the surface that fades out.
+ */
+ group: Locator;
+ segment: (value: string) => Locator;
+ boxes: () => Promise<SegmentBox[]>;
+ tapSegment: (value: string) => Promise<void>;
+}
+
+async function openControl(
+ page: Page,
+ storyId = 'core-segmentedcontrol--default',
+ groupName = 'View mode',
+ {
+ direction,
+ }: {
+ direction?: 'rtl';
+ } = {},
+): Promise<Control> {
+ await installLongTaskLog(page);
+ if (direction == null) {
+ await openStory(page, storybook(), storyId);
+ } else {
+ // Storybook's highlight module reads every element's style on each DOM
+ // insertion. openStory turns it off, and this navigation does too. So
+ // frame and long-task proofs measure only the control.
+ await page.addInitScript(() => {
+ (
+ globalThis as unknown as {__STORYBOOK_HIGHLIGHT_INITIALIZED?: boolean}
+ ).__STORYBOOK_HIGHLIGHT_INITIALIZED = true;
+ });
+ // Storybook's direction toolbar (a global, not an arg).
+ await page.goto(
+ `${storybook()}/iframe.html?id=${storyId}&viewMode=story&globals=direction:${direction}`,
+ );
+ await page.locator('#storybook-root > *').first().waitFor();
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await new Promise(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ );
+ });
+ }
+ const driver = await touchDriver(page);
+ const group = page.getByRole('radiogroup', {name: groupName, exact: true});
+ await expect(group).toBeVisible();
+ const segment = (value: string) => group.locator(`[data-value="${value}"]`);
+ // Boxes in the track's padding-box coordinates, the lens's own space.
+ const boxes = async () =>
+ group.evaluate(track => {
+ const trackRect = track.getBoundingClientRect();
+ return [...track.querySelectorAll<HTMLElement>('[role="radio"]')].map(
+ element => {
+ const rect = element.getBoundingClientRect();
+ return {
+ value: element.dataset.value ?? '',
+ x: rect.left - trackRect.left - track.clientLeft,
+ y: rect.top - trackRect.top - track.clientTop,
+ width: rect.width,
+ height: rect.height,
+ };
+ },
+ );
+ });
+ const tapSegment = async (value: string) => {
+ const box = await segment(value).boundingBox();
+ if (box == null) {
+ throw new Error(`no segment ${value}`);
+ }
+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});
+ };
+ return {driver, group, segment, boxes, tapSegment};
+}
+
+/** One of the radiogroup's two layers: the lens or the ::after. */
+type Layer = '::before' | '::after';
+
+/**
+ * A layer's presented geometry, as computed now. The layer lays out on a box
+ * and scales around its center. So `center` is its layout center plus its
+ * translate, and `x` is its presented left edge.
+ */
+async function readLayer(
+ group: Locator,
+ layer: Layer = '::before',
+): Promise<{
+ visible: boolean;
+ opacity: number;
+ x: number;
+ center: number;
+ width: number;
+ height: number;
+ sx: number;
+ sy: number;
+}> {
+ return group.evaluate((element, pseudo) => {
+ const style = getComputedStyle(element, pseudo);
+ const [sx, sy = sx] =
+ style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
+ const translate =
+ style.translate === 'none' ? 0 : parseFloat(style.translate);
+ const width = parseFloat(style.width) * sx;
+ const center =
+ parseFloat(style.left) + parseFloat(style.width) / 2 + translate;
+ return {
+ visible: style.visibility === 'visible',
+ opacity: Number(style.opacity),
+ x: center - width / 2,
+ center,
+ width,
+ height: parseFloat(style.height) * sy,
+ sx,
+ sy,
+ };
+ }, layer);
+}
+
+/** Resolves once the lens is hidden again: the surface handed back. */
+async function expectLensHidden(
+ control: Control,
+ timeout = 3000,
+): Promise<void> {
+ await expect
+ .poll(async () => (await readLayer(control.group)).visible, {timeout})
+ .toBe(false);
+}
+
+/**
+ * The lens's running animations (the radiogroup's ::before), described as
+ * the harness's `waitForAnimation` describes an element's.
+ */
+async function waitForLens(
+ control: Control,
+ {
+ minProgressMs = 1,
+ timeout = 5000,
+ }: {minProgressMs?: number; timeout?: number} = {},
+): Promise<{from: number; to: number; durationMs: number; easing: string}[]> {
+ // Installs the harness's curve-end reader and waits for the control to move.
+ await waitForAnimation(control.group, {minProgressMs, timeout});
+ const deadline = Date.now() + timeout;
+ for (;;) {
+ const found = await control.group.evaluate((group, minProgress) => {
+ const curveEnd = (
+ window as unknown as {__harnessCurveEnd: (a: Animation) => number}
+ ).__harnessCurveEnd;
+ return group
+ .getAnimations({subtree: true})
+ .filter(a => {
+ const effect = a.effect as KeyframeEffect | null;
+ return (
+ effect?.target === group &&
+ effect.pseudoElement === '::before' &&
+ a.playState === 'running' &&
+ a.startTime != null &&
+ Number(a.currentTime ?? 0) >= minProgress
+ );
+ })
+ .map(a => {
+ const effect = a.effect as KeyframeEffect;
+ const timing = effect.getComputedTiming();
+ const startedAt = performance.timeOrigin + Number(a.startTime);
+ return {
+ from: startedAt + (timing.delay ?? 0),
+ to: startedAt + curveEnd(a),
+ durationMs: Number(timing.duration ?? 0),
+ easing: effect.getTiming().easing ?? 'linear',
+ };
+ });
+ }, minProgressMs);
+ if (found.length > 0) {
+ return found;
+ }
+ if (Date.now() > deadline) {
+ throw new Error('waitForLens: no lens animation started');
+ }
+ await new Promise(resolve => setTimeout(resolve, 4));
+ }
+}
+
+/**
+ * Pauses the running animations of both radiogroup pseudo-elements, the lens
+ * and its shadow, into the harness's held set. Then `releaseAnimations` moves
+ * exactly them. A pseudo-element has no inline style, so the animator holds
+ * each value with a finished, filling animation. Every running animation
+ * overrides those, so they are left alone.
+ */
+async function holdLens(
+ control: Control,
+): Promise<{easing: string; durationMs: number; pseudo: string}[]> {
+ return control.group.evaluate(group => {
+ const held = group.getAnimations({subtree: true}).filter(a => {
+ const effect = a.effect as KeyframeEffect | null;
+ return (
+ effect?.target === group &&
+ effect.pseudoElement != null &&
+ a.playState !== 'finished'
+ );
+ });
+ for (const animation of held) {
+ animation.pause();
+ }
+ (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld = held;
+ return held.map(a => ({
+ easing: String((a.effect as KeyframeEffect).getTiming().easing),
+ durationMs: Number(a.effect?.getComputedTiming().duration ?? 0),
+ pseudo: String((a.effect as KeyframeEffect).pseudoElement),
+ }));
+ });
+}
+
+/**
+ * The lens's presented geometry at each held time. `x` is its translate, the
+ * center's offset from its layout box's center. `center` is in the track's
+ * coordinates, beside its presented size.
+ */
+async function sampleLens(
+ group: Locator,
+ times: ReadonlyArray<number>,
+): Promise<
+ {
+ t: number;
+ x: number;
+ center: number;
+ width: number;
+ height: number;
+ visible: boolean;
+ }[]
+> {
+ return group.evaluate((element, ts) => {
+ const held =
+ (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ?? [];
+ const base = getComputedStyle(element, '::before');
+ const left = parseFloat(base.left);
+ const width = parseFloat(base.width);
+ const height = parseFloat(base.height);
+ return ts.map(t => {
+ for (const animation of held) {
+ const end = Number(animation.effect?.getComputedTiming().endTime ?? 0);
+ animation.currentTime = Math.min(t, end - 0.5);
+ }
+ const style = getComputedStyle(element, '::before');
+ const x = style.translate === 'none' ? 0 : parseFloat(style.translate);
+ const [sx, sy = sx] =
+ style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
+ return {
+ t,
+ x,
+ center: left + width / 2 + x,
+ width: width * sx,
+ height: height * sy,
+ visible: style.visibility === 'visible',
+ };
+ });
+ }, times);
+}
+
+const centerOf = (box: SegmentBox) => box.x + box.width / 2;
+
+/**
+ * Records each moment a control's lens hands its surface back and hides
+ * again, on the page's clock (epoch ms). The animator's keyframes hold the end
+ * state for a few seconds past the curve. So an animation's end time does not
+ * mark the end of the slide; the hand-back does.
+ */
+async function recordHandBacks(page: Page): Promise<() => Promise<number[]>> {
+ await page.evaluate(() => {
+ const times: number[] = [];
+ (window as unknown as {__handBacks: number[]}).__handBacks = times;
+ const shown = (group: HTMLElement) =>
+ group.style.getPropertyValue('--_segmented-lens-visibility') ===
+ 'visible';
+ for (const group of document.querySelectorAll<HTMLElement>(
+ '[role="radiogroup"]',
+ )) {
+ let visible = shown(group);
+ new MutationObserver(() => {
+ const now = shown(group);
+ if (visible && !now) {
+ times.push(performance.timeOrigin + performance.now());
+ }
+ visible = now;
+ }).observe(group, {attributes: true, attributeFilter: ['style']});
+ }
+ });
+ return async () =>
+ page.evaluate(
+ () => (window as unknown as {__handBacks: number[]}).__handBacks,
+ );
+}
+
+/**
+ * Paints the lens in the harness's marker color, then lets a frame show it.
+ * The lens has no element to carry the marker chip, so the frames find it by
+ * its color.
+ */
+async function paintLensMarker(control: Control): Promise<void> {
+ await control.group.evaluate((group, rgb) => {
+ group.style.setProperty(
+ '--_segmented-lens-background-color',
+ `rgb(${rgb.join(', ')})`,
+ );
+ group.style.setProperty('--_segmented-lens-background-image', 'none');
+ }, MARKER_RGB);
+ await control.group.evaluate(
+ async () =>
+ new Promise(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
+ ),
+ );
+}
+
+/** The box of one segment; a missing segment is a broken story, not a pass. */
+function boxOf(boxes: ReadonlyArray<SegmentBox>, value: string): SegmentBox {
+ const box = boxes.find(b => b.value === value);
+ if (box == null) {
+ throw new Error(`no segment "${value}" in ${JSON.stringify(boxes)}`);
+ }
+ return box;
+}
+
+test('a tap slides the selected surface to the new segment on UIKit’s spring, at its resting size', async ({
+ page,
+}, testInfo) => {
+ const control = await openControl(page);
+ // Under a finger the segments leave the change to this motion: no CSS
+ // transition runs a second, main-thread version of it.
+ for (const value of ['grid', 'list', 'table']) {
+ await expect(control.segment(value)).toHaveCSS(
+ 'transition-property',
+ 'none',
+ );
+ }
+ const from = boxOf(await control.boxes(), 'grid');
+ // Hold the clock still, and hold each lens animation at its birth. Then a
+ // slow engine cannot reach the hold after the slide moved on.
+ await installTimerGate(page);
+ await holdLensAnimationsAtBirth(page);
+ await control.tapSegment('table');
+ await freezeTimers(page);
+ const held = await page.evaluate(() => {
+ (window as unknown as {__restoreAnimate: () => void}).__restoreAnimate();
+ return (
+ window as unknown as {__harnessHeld: Animation[]}
+ ).__harnessHeld.map(
+ a => (a.effect as KeyframeEffect).getComputedTiming().easing,
+ );
+ });
+ // Baked curves: the lens's translate and scale; nothing on the ::after (no
+ // lift, so no shadow).
+ expect(held.length).toBeGreaterThanOrEqual(2);
+ expect(held.every(easing => easing === 'linear')).toBe(true);
+ const samples = await sampleLens(control.group, timeline(600));
+ await releaseAnimations(page);
+ await thawTimers(page);
+ // The value commits at the lift, as UISegmentedControl's valueChanged does.
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ // Where Table is once its title has its new weight: where the lens aims.
+ const to = boxOf(await control.boxes(), 'table');
+ expect(samples.every(s => s.visible)).toBe(true);
+ // The center travels on the slide spring...
+ const center = compareCurve(
+ samples.map(s => ({t: s.t, value: s.center})),
+ t =>
+ centerOf(from) + (centerOf(to) - centerOf(from)) * springStep(SLIDE, t),
+ 0.25,
+ );
+ // ...and the width follows Grid's to Table's on the same spring; nothing
+ // lifts it (a pressed thumb's lift is a theme's, none by default).
+ const width = compareCurve(
+ samples.map(s => ({t: s.t, value: s.width})),
+ t => from.width + (to.width - from.width) * springStep(SLIDE, t),
+ 0.25,
+ );
+ const height = compareCurve(
+ samples.map(s => ({t: s.t, value: s.height})),
+ () => to.height,
+ 0.25,
+ );
+ await writeEvidence(
+ 'curves/segmented-slide',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {from, to, held, samples, center, width, height},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ expect(center.maxError, JSON.stringify(center.worst)).toBeLessThanOrEqual(
+ 0.25,
+ );
+ expect(width.maxError, JSON.stringify(width.worst)).toBeLessThanOrEqual(0.25);
+ expect(height.maxError, JSON.stringify(height.worst)).toBeLessThanOrEqual(
+ 0.25,
+ );
+ // It lands and hands back.
+ await expectLensHidden(control);
+});
+
+test('the surface lands exactly where the segment paints it', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ // The surfaces are compared, not the titles. Text over a composited layer,
+ // such as the lens, loses subpixel antialiasing where the platform uses it.
+ // It gets it back at the hand-back. A desktop Linux runner does this;
+ // phones antialias text in grayscale either way.
+ await page.addStyleTag({
+ content: '[role="radiogroup"] * { color: transparent !important; }',
+ });
+ // Gate timers: the hand-back runs from the slide's completion timer, which
+ // must wait while the landed frame is photographed.
+ await installTimerGate(page);
+ await control.tapSegment('list');
+ await waitForLens(control);
+ await freezeTimers(page);
+ // The slide runs its course on the compositor. With the timers held, the
+ // hand-back waits. So this is the slide's last frame: the lens carries the
+ // surface, and the segment's own is hidden.
+ await page.waitForTimeout(1500);
+ const landed = await control.group.screenshot({animations: 'allow'});
+ expect(
+ await control.segment('list').evaluate(el => el.style.backgroundColor),
+ ).toBe('transparent');
+ await thawTimers(page);
+ await expectLensHidden(control);
+ expect(
+ await control.segment('list').evaluate(el => el.getAttribute('style')),
+ ).toBeFalsy();
+ const rest = await control.group.screenshot({animations: 'allow'});
+ const a = PNG.sync.read(landed);
+ const b = PNG.sync.read(rest);
+ expect([a.width, a.height]).toEqual([b.width, b.height]);
+ // The hand-back is invisible: the pixels match before and after it, except
+ // for the surface's outline. Each engine snaps that outline to device
+ // pixels its own way for a composited layer and a segment's background.
+ // They differ by at most two device pixels.
+ const edges = await control.group.evaluate(group => {
+ const ratio = window.devicePixelRatio || 1;
+ const host = group.getBoundingClientRect();
+ const segment = group.querySelector('[data-value="list"]');
+ if (segment == null) {
+ throw new Error('no List segment');
+ }
+ const box = segment.getBoundingClientRect();
+ const radius = parseFloat(getComputedStyle(segment).borderTopLeftRadius);
+ return {
+ left: (box.left - host.left) * ratio,
+ right: (box.right - host.left) * ratio,
+ top: (box.top - host.top) * ratio,
+ bottom: (box.bottom - host.top) * ratio,
+ radius: (Number.isFinite(radius) ? radius : 0) * ratio,
+ };
+ });
+ const nearEdge = (x: number, y: number) => {
+ const halfWidth = (edges.right - edges.left) / 2;
+ const halfHeight = (edges.bottom - edges.top) / 2;
+ const r = Math.min(edges.radius, halfWidth, halfHeight);
+ const qx = Math.abs(x - (edges.left + halfWidth)) - (halfWidth - r);
+ const qy = Math.abs(y - (edges.top + halfHeight)) - (halfHeight - r);
+ const distance =
+ Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) +
+ Math.min(Math.max(qx, qy), 0) -
+ r;
+ return Math.abs(distance) < 2;
+ };
+ let differing = 0;
+ for (let y = 0; y < a.height; y++) {
+ for (let x = 0; x < a.width; x++) {
+ const i = (y * a.width + x) * 4;
+ const delta = Math.max(
+ Math.abs(a.data[i] - b.data[i]),
+ Math.abs(a.data[i + 1] - b.data[i + 1]),
+ Math.abs(a.data[i + 2] - b.data[i + 2]),
+ );
+ if (delta > 10 && !nearEdge(x + 0.5, y + 0.5)) {
+ differing++;
+ }
+ }
+ }
+ expect(differing).toBe(0);
+});
+
+test('the titles switch at once with the selection: no second copy of a title is ever mounted', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const elements = await control.group.evaluate(
+ group => group.querySelectorAll('*').length,
+ );
+ await control.tapSegment('table');
+ await waitForLens(control);
+ // Mid-slide, as many elements as at rest, and nothing animates Table's
+ // title's weight or color: it already shows its selected rendering. (Its
+ // opacity comes back from the press's dim.)
+ expect(
+ await control.group.evaluate(group => group.querySelectorAll('*').length),
+ ).toBe(elements);
+ expect(
+ await control.segment('table').evaluate(element =>
+ element
+ .getAnimations({subtree: true})
+ .flatMap(a =>
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .flatMap(k => Object.keys(k)),
+ )
+ .filter(key => key === 'color' || key === 'fontWeight'),
+ ),
+ ).toEqual([]);
+});
+
+test('a second tap mid-flight retargets from what is on screen, keeping its velocity', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.tapSegment('table');
+ await waitForLens(control, {minProgressMs: 60});
+ const describe = async () =>
+ control.group.evaluate(async group => {
+ const animations = group.getAnimations({subtree: true}).filter(a => {
+ const effect = a.effect as KeyframeEffect;
+ return (
+ effect.target === group &&
+ effect.pseudoElement === '::before' &&
+ a.playState === 'running' &&
+ effect.getKeyframes().length > 2 &&
+ 'translate' in (effect.getKeyframes()[0] ?? {})
+ );
+ });
+ animations.reverse();
+ // A call starts when the browser commits it: wait for its start time.
+ await Promise.all(animations.map(async a => a.ready));
+ // The lens's layout box: its center is the reference `x` is measured
+ // from (it moves when the destination changes).
+ const style = getComputedStyle(group, '::before');
+ const origin = parseFloat(style.left) + parseFloat(style.width) / 2;
+ return animations.map(a => ({
+ startTime: a.startTime as number,
+ duration: Number(a.effect?.getComputedTiming().duration),
+ keyframes: (a.effect as KeyframeEffect).getKeyframes().map(k => ({
+ offset: k.computedOffset,
+ x: origin + parseFloat(String(k.translate)),
+ })),
+ }))[0];
+ });
+ const first = await describe();
+ await control.tapSegment('list');
+ await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true');
+ const second = await describe();
+ expect(second.startTime).toBeGreaterThan(first.startTime);
+ // The first curve, read where the second one starts.
+ const at = (
+ curve: typeof first,
+ time: number,
+ ): {value: number; slope: number} => {
+ const offset = (time - curve.startTime) / curve.duration;
+ const k = curve.keyframes;
+ for (let i = 0; i + 1 < k.length; i++) {
+ if (offset <= k[i + 1].offset) {
+ const span = k[i + 1].offset - k[i].offset;
+ const f = span === 0 ? 0 : (offset - k[i].offset) / span;
+ return {
+ value: k[i].x + (k[i + 1].x - k[i].x) * f,
+ slope:
+ span === 0 ? 0 : (k[i + 1].x - k[i].x) / (span * curve.duration),
+ };
+ }
+ }
+ return {value: k[k.length - 1].x, slope: 0};
+ };
+ const old = at(first, second.startTime);
+ const fresh = at(second, second.startTime + 0.001);
+ // No jump at the retarget: at most the travel of 2 ms. The animator's clock
+ // and the document timeline can disagree by a fraction of a frame.
+ expect(Math.abs(fresh.value - old.value)).toBeLessThan(
+ Math.max(0.5, Math.abs(old.slope) * 2),
+ );
+ // ...and the velocity carries over (px/ms, within 10 %). It is read on both
+ // curves at the instant the second one starts. The browser draws straight
+ // lines between keyframes. So a segment's slope is the curve's velocity at
+ // the segment's middle, not at its ends. Comparing two segments' slopes
+ // directly would compare velocities half a segment apart. Those differ by
+ // the spring's acceleration over that span.
+ const velocityAt = (curve: typeof first, time: number): number => {
+ const k = curve.keyframes;
+ const middles: {t: number; v: number}[] = [];
+ for (let i = 0; i + 1 < k.length; i++) {
+ const span = k[i + 1].offset - k[i].offset;
+ if (span > 0) {
+ middles.push({
+ t:
+ curve.startTime +
+ ((k[i].offset + k[i + 1].offset) / 2) * curve.duration,
+ v: (k[i + 1].x - k[i].x) / (span * curve.duration),
+ });
+ }
+ }
+ // Between the two middles around `time`; before the first one (the second
+ // curve at its own start), extrapolated from the first two.
+ const next = middles.findIndex(middle => middle.t >= time);
+ const j = next === -1 ? middles.length - 1 : Math.max(next, 1);
+ const a = middles[j - 1];
+ const b = middles[j];
+ return a.v + ((b.v - a.v) * (time - a.t)) / (b.t - a.t);
+ };
+ const before = velocityAt(first, second.startTime);
+ const after = velocityAt(second, second.startTime);
+ expect(
+ Math.abs(after - before),
+ JSON.stringify({before, after}),
+ ).toBeLessThan(Math.abs(before) * 0.1 + 0.02);
+ // It lands on the second segment's center.
+ const list = boxOf(await control.boxes(), 'list');
+ expect(second.keyframes.at(-1)?.x).toBeCloseTo(centerOf(list), 1);
+});
+
+test('a change mid-flight paints no press over the lens on the segment it leaves', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.tapSegment('table');
+ // The app changes the selection while the lens is still on its way and the
+ // tap on Table still fades. A second touch would end that fade itself.
+ const paint = await control.group.evaluate(async group => {
+ const segment = (value: string): HTMLElement => {
+ const element = group.querySelector<HTMLElement>(
+ `[data-value="${value}"]`,
+ );
+ if (element == null) {
+ throw new Error(`no segment ${value}`);
+ }
+ return element;
+ };
+ segment('list').click();
+ // The layout effect that retargets has run once the frame is drawn.
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ const table = segment('table');
+ const style = getComputedStyle(table);
+ return {
+ press: table.getAttribute('data-astryx-press'),
+ image: style.backgroundImage,
+ color: style.backgroundColor,
+ lensVisible: getComputedStyle(group, '::before').visibility === 'visible',
+ };
+ });
+ await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true');
+ expect(paint.press, 'the tap on Table is still fading').not.toBeNull();
+ expect(paint.lensVisible).toBe(true);
+ // Table paints nothing of its own until the lens lands: its press would
+ // cover the lens, which sits under the segments' backgrounds.
+ expect(paint.image).toBe('none');
+ expect(paint.color).toBe('rgba(0, 0, 0, 0)');
+ // 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),
+ )
+ .toBe('');
+});
+
+test('an arrow key and a programmatic change slide the selection too', async ({
+ page,
+}) => {
+ const control = await openControl(
+ page,
+ 'core-segmentedcontrol--selection-motion',
+ 'Period',
+ );
+ // An arrow key on the focused segment: selection follows focus.
+ await control.segment('day').focus();
+ await page.keyboard.press('ArrowRight');
+ await expect(control.segment('week')).toHaveAttribute('aria-checked', 'true');
+ const [keyed] = await waitForLens(control);
+ expect(keyed.easing).toBe('linear');
+ await releaseAnimations(page, {finish: true});
+ // A change made by the app (the button sets the value from outside).
+ const button = page.getByRole('button', {name: 'Next period'});
+ const box = await button.boundingBox();
+ if (box == null) {
+ throw new Error('no button');
+ }
+ await control.driver.tap({
+ x: box.x + box.width / 2,
+ y: box.y + box.height / 2,
+ });
+ await expect(control.segment('month')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ const animations = await waitForLens(control);
+ expect(animations.length).toBeGreaterThan(0);
+});
+
+test('Reduce Motion (design:reduced-motion): no travel or scale; the old surface fades out where it is as the new one fades in, opacity only, in 200 ms or less', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const control = await openControl(page);
+ // Grid as it rests before the tap, where the surface fades out. Table once
+ // its title has its new weight, where the lens fades in.
+ const grid = boxOf(await control.boxes(), 'grid');
+ const {samples, titleFades} = await sampleReducedMotionChange(page, control);
+ const boxes = await control.boxes();
+ const table = boxOf(boxes, 'table');
+ // Over in 200 ms or less (DR2); the titles switch at once.
+ const fadeEnd = fadeEndOf(samples);
+ expect(fadeEnd).toBeGreaterThan(0);
+ expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS);
+ expect(samples[samples.length - 1].entering?.opacity).toBe(1);
+ // No title cross-fades; the pressed title's dim fades on the same clock.
+ for (const duration of titleFades) {
+ expect(duration).toBeLessThanOrEqual(RM_MAX_FADE_MS);
+ }
+ for (const {t, entering, leaving} of samples) {
+ const label = JSON.stringify({t, entering, leaving});
+ expect(entering, label).not.toBeNull();
+ // The new surface: at Table from the first frame, full size; only its
+ // opacity changes (DR1).
+ expect(Math.abs((entering?.x ?? 0) - table.x), label).toBeLessThan(0.5);
+ expect(Math.abs((entering?.width ?? 0) - table.width), label).toBeLessThan(
+ 0.5,
+ );
+ expect(entering?.sx, label).toBe(1);
+ expect(entering?.sy, label).toBe(1);
+ // The old surface, while it shows: at Grid, full size.
+ if (leaving != null && leaving.opacity > 0.001) {
+ expect(Math.abs(leaving.x - grid.x), label).toBeLessThan(0.5);
+ expect(Math.abs(leaving.width - grid.width), label).toBeLessThan(0.5);
+ expect(leaving.sx, label).toBe(1);
+ // One surface's worth of paint between the two.
+ expect(
+ Math.abs((entering?.opacity ?? 0) + leaving.opacity - 1),
+ label,
+ ).toBeLessThan(0.02);
+ }
+ }
+ expect(samples[0].leaving?.opacity ?? 0).toBeGreaterThan(0.9);
+ expect(samples[0].entering?.opacity ?? 1).toBeLessThan(0.1);
+ // Then the segment paints its own surface again, and the leaving surface
+ // is gone.
+ await expectLensHidden(control);
+ expect((await readLayer(control.group, '::after')).visible).toBe(false);
+ await expect(control.segment('table')).not.toHaveCSS(
+ 'background-color',
+ 'rgba(0, 0, 0, 0)',
+ );
+});
+
+test('Reduce Motion: a theme’s durations cannot lengthen the fade or bring back travel (design:reduced-motion DR4)', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const control = await openControl(page);
+ // A theme's motion is its duration scale; a slow one changes nothing here.
+ await page.evaluate(() => {
+ const root = document.documentElement.style;
+ for (const name of ['fast', 'medium', 'slow']) {
+ for (const suffix of ['', '-min', '-max']) {
+ root.setProperty(`--duration-${name}${suffix}`, '1200ms');
+ }
+ }
+ });
+ const {samples, titleFades} = await sampleReducedMotionChange(page, control);
+ const fadeEnd = fadeEndOf(samples);
+ expect(fadeEnd).toBeGreaterThan(0);
+ expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS);
+ // No visible surface ever moves, scales or resizes.
+ const first = samples[0];
+ for (const {t, entering, leaving} of samples) {
+ const label = JSON.stringify({t, entering, leaving});
+ expect(entering?.x, label).toBe(first.entering?.x);
+ expect(entering?.width, label).toBe(first.entering?.width);
+ expect(entering?.sx, label).toBe(1);
+ if (leaving != null && leaving.opacity > 0.001) {
+ expect(leaving.x, label).toBe(first.leaving?.x);
+ expect(leaving.sx, label).toBe(1);
+ }
+ }
+ // No title cross-fades; the pressed title's dim fades on the same clock.
+ for (const duration of titleFades) {
+ expect(duration).toBeLessThanOrEqual(RM_MAX_FADE_MS);
+ }
+});
+
+interface SurfaceSample {
+ opacity: number;
+ sx: number;
+ sy: number;
+ x: number;
+ width: number;
+}
+
+/**
+ * Taps Table under Reduced Motion, with the lens's animations held from their
+ * birth. It reads both surfaces every 8 ms of their animations: the lens
+ * fading in and the ::after fading out. It also reads the title fades'
+ * durations.
+ */
+async function sampleReducedMotionChange(
+ page: Page,
+ control: Control,
+ act: () => Promise<unknown> = async () => control.tapSegment('table'),
+): Promise<{
+ samples: {
+ t: number;
+ entering: SurfaceSample | null;
+ leaving: SurfaceSample | null;
+ }[];
+ titleFades: number[];
+}> {
+ await installTimerGate(page);
+ await holdLensAnimationsAtBirth(page);
+ await act();
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () =>
+ (window as unknown as {__harnessHeld: Animation[]}).__harnessHeld
+ .length,
+ ),
+ )
+ .toBeGreaterThan(1);
+ await freezeTimers(page);
+ await page.evaluate(() => {
+ (window as unknown as {__restoreAnimate: () => void}).__restoreAnimate();
+ });
+ const samples = await control.group.evaluate(group => {
+ const held = (window as unknown as {__harnessHeld: Animation[]})
+ .__harnessHeld;
+ const read = (pseudo: '::before' | '::after') => {
+ const style = getComputedStyle(group, pseudo);
+ if (style.visibility !== 'visible') {
+ return null;
+ }
+ const [sx, sy = sx] =
+ style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
+ return {
+ opacity: Number(style.opacity),
+ sx,
+ sy,
+ x:
+ (parseFloat(style.left) || 0) +
+ (style.translate === 'none' ? 0 : parseFloat(style.translate)),
+ width: parseFloat(style.width),
+ };
+ };
+ const out = [];
+ for (let t = 0; t <= 1000; t += 8) {
+ for (const animation of held) {
+ const animationEnd = Number(
+ animation.effect?.getComputedTiming().endTime ?? 0,
+ );
+ animation.currentTime = Math.min(t, Math.max(0, animationEnd - 0.5));
+ }
+ out.push({
+ t,
+ entering: read('::before'),
+ leaving: read('::after'),
+ });
+ }
+ return out;
+ });
+ const titleFades = await control.group.evaluate(group =>
+ [...group.querySelectorAll('[data-astryx-segment-title]')].flatMap(
+ element =>
+ element
+ .getAnimations()
+ .map(a => Number(a.effect?.getComputedTiming().duration)),
+ ),
+ );
+ await releaseAnimations(page);
+ await thawTimers(page);
+ return {samples, titleFades};
+}
+
+/** The last sampled time either surface's opacity is still on its way. */
+function fadeEndOf(
+ samples: {
+ t: number;
+ entering: SurfaceSample | null;
+ leaving: SurfaceSample | null;
+ }[],
+): number {
+ const last = samples[samples.length - 1];
+ return Math.max(
+ 0,
+ ...samples
+ .filter(
+ ({entering, leaving}) =>
+ Math.abs((entering?.opacity ?? 0) - (last.entering?.opacity ?? 0)) >
+ 0.002 ||
+ Math.abs((leaving?.opacity ?? 0) - (last.leaving?.opacity ?? 0)) >
+ 0.002,
+ )
+ .map(({t}) => t),
+ );
+}
+
+/**
+ * Pauses every animation started on the lens (the radiogroup's pseudo-elements
+ * it) the moment it is created, into the harness's held set;
+ * `__restoreAnimate` puts `Element.animate` back.
+ */
+async function holdLensAnimationsAtBirth(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const original = Element.prototype.animate;
+ const held: Animation[] = [];
+ const w = window as unknown as {
+ __harnessHeld: Animation[];
+ __restoreAnimate: () => void;
+ };
+ w.__harnessHeld = held;
+ w.__restoreAnimate = () => {
+ Element.prototype.animate = original;
+ };
+ Element.prototype.animate = function (
+ this: Element,
+ ...args: Parameters<Element['animate']>
+ ): Animation {
+ const animation = original.apply(this, args);
+ const [, options] = args;
+ if (
+ this.getAttribute('role') === 'radiogroup' &&
+ typeof options === 'object' &&
+ options?.pseudoElement != null
+ ) {
+ animation.pause();
+ held.push(animation);
+ }
+ return animation;
+ };
+ });
+}
+
+test('with a mouse a click slides the selection from the old segment to the new one, on the theme’s duration, as every change does', async ({
+ browser,
+}) => {
+ const {context, group, lensShown} = await openWithMouse(browser);
+ try {
+ expect(await lensShown()).toBe(false);
+ await expect(group.locator('[data-value="list"]')).toHaveCSS(
+ 'transition-property',
+ 'color, background-color, box-shadow',
+ );
+ // From the click on, the page reads the lens's first running translate
+ // animation on each frame. It notes where the animation starts and ends,
+ // and how long it runs.
+ await group.evaluate(element => {
+ const w = window as unknown as {
+ __slide: {from: number; to: number; durationMs: number} | null;
+ };
+ w.__slide = null;
+ const read = () => {
+ for (const animation of element.getAnimations({subtree: true})) {
+ const effect = animation.effect as KeyframeEffect | null;
+ if (
+ effect?.target !== element ||
+ effect.pseudoElement !== '::before'
+ ) {
+ continue;
+ }
+ const frames = effect
+ .getKeyframes()
+ .filter(frame => typeof frame.translate === 'string');
+ if (frames.length < 2) {
+ continue;
+ }
+ // The animator holds the last value after the curve ends: the
+ // curve's own length runs to the first frame at the end value.
+ const values = frames.map(frame =>
+ parseFloat(String(frame.translate)),
+ );
+ const to = values[values.length - 1];
+ const firstAtEnd = frames.find(
+ (frame, i) => Math.abs(values[i] - to) < 0.01,
+ );
+ w.__slide = {
+ from: values[0],
+ to,
+ durationMs:
+ (firstAtEnd?.computedOffset ?? 1) *
+ Number(effect.getComputedTiming().duration ?? 0),
+ };
+ return;
+ }
+ requestAnimationFrame(read);
+ };
+ element.addEventListener('click', () => requestAnimationFrame(read), {
+ capture: true,
+ once: true,
+ });
+ });
+ const themeMs = await group
+ .locator('[data-value="table"]')
+ .evaluate(
+ segment =>
+ parseFloat(getComputedStyle(segment).transitionDuration) * 1000,
+ );
+ await group.locator('[data-value="table"]').click();
+ await expect(group.locator('[data-value="table"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ const slide = await group.page().waitForFunction(
+ () =>
+ (
+ window as unknown as {
+ __slide: {from: number; to: number; durationMs: number} | null;
+ }
+ ).__slide,
+ undefined,
+ {timeout: 3000},
+ );
+ const {from, to, durationMs} = (await slide.jsonValue()) as {
+ from: number;
+ to: number;
+ durationMs: number;
+ };
+ // Where the segments sit. A title's weight change moves them by a pixel
+ // or so, so the start is checked to within 3 px.
+ const centers = await group.evaluate(element => {
+ const of = (value: string) => {
+ const box = element
+ .querySelector(`[data-value="${value}"]`)!
+ .getBoundingClientRect();
+ return box.left + box.width / 2;
+ };
+ return {grid: of('grid'), table: of('table')};
+ });
+ // It starts on the old segment and ends on the new one.
+ expect(
+ Math.abs(from - (centers.grid - centers.table)),
+ JSON.stringify({from, centers}),
+ ).toBeLessThan(3);
+ expect(to).toBeCloseTo(0, 1);
+ // The theme's duration, as the segments' own transition reads it.
+ expect(themeMs).toBeGreaterThan(0);
+ expect(Math.abs(durationMs - themeMs), String(durationMs)).toBeLessThan(25);
+ // The lens hands the surface back once it settles.
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ } finally {
+ await context.close();
+ }
+});
+
+test('the slide plays UISegmentedControl’s measured spring, an internal motion role: no theme setting retunes it', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ // Neither the variable a theme role once had nor a slow duration scale
+ // changes the slide.
+ await page.evaluate(() => {
+ const root = document.documentElement.style;
+ root.setProperty('--motion-segmented-control-selection-spring', '0.25s 0');
+ for (const name of ['fast', 'medium', 'slow']) {
+ root.setProperty(`--duration-${name}`, '1200ms');
+ }
+ });
+ const from = boxOf(await control.boxes(), 'grid');
+ await control.tapSegment('table');
+ await waitForLens(control);
+ await holdLens(control);
+ const samples = await sampleLens(control.group, timeline(400));
+ await releaseAnimations(page);
+ // Where Table is once its title has its new weight: where the lens aims.
+ const to = boxOf(await control.boxes(), 'table');
+ const fit = compareCurve(
+ samples.map(sample => ({t: sample.t, value: sample.center})),
+ t =>
+ centerOf(from) + (centerOf(to) - centerOf(from)) * springStep(SLIDE, t),
+ 0.25,
+ );
+ expect(fit.maxError, JSON.stringify(fit.worst)).toBeLessThanOrEqual(0.25);
+ // ...not the spring the variable names.
+ const variable = {response: 0.25, dampingFraction: 1} as const;
+ const other = compareCurve(
+ samples.map(sample => ({t: sample.t, value: sample.center})),
+ t =>
+ centerOf(from) +
+ (centerOf(to) - centerOf(from)) * springStep(variable, t),
+ 0.25,
+ );
+ expect(other.maxError).toBeGreaterThan(5);
+});
+
+test('RTL: the surface slides toward the tapped segment', async ({page}) => {
+ const control = await openControl(
+ page,
+ 'core-segmentedcontrol--default',
+ 'View mode',
+ {direction: 'rtl'},
+ );
+ const grid = boxOf(await control.boxes(), 'grid');
+ await control.tapSegment('table');
+ await waitForLens(control);
+ await holdLens(control);
+ const [start, end] = await sampleLens(control.group, [0, 2000]);
+ // Where Table is once its title has its new weight.
+ const table = boxOf(await control.boxes(), 'table');
+ // The first segment is on the right in RTL.
+ expect(grid.x).toBeGreaterThan(table.x);
+ expect(start.center).toBeCloseTo(centerOf(grid), 1);
+ expect(end.center).toBeCloseTo(centerOf(table), 1);
+ // On screen, not only in the numbers: held at its last frame, the lens
+ // covers the tapped segment exactly (its box in viewport pixels).
+ const [lensBox, tableBox] = await Promise.all([
+ control.group.evaluate(group => {
+ const style = getComputedStyle(group, '::before');
+ const host = group.getBoundingClientRect();
+ const translate =
+ style.translate === 'none' ? 0 : parseFloat(style.translate);
+ const [sx, sy = sx] =
+ style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
+ const width = parseFloat(style.width);
+ const height = parseFloat(style.height);
+ const left = host.left + group.clientLeft + parseFloat(style.left);
+ const top = host.top + group.clientTop + parseFloat(style.top);
+ return {
+ x: left + width / 2 + translate - (width * sx) / 2,
+ y: top + height / 2 - (height * sy) / 2,
+ width: width * sx,
+ height: height * sy,
+ };
+ }),
+ control.segment('table').boundingBox(),
+ ]);
+ await releaseAnimations(page);
+ expect(tableBox).not.toBeNull();
+ for (const key of ['x', 'y', 'width', 'height'] as const) {
+ expect(
+ Math.abs(lensBox[key] - (tableBox?.[key] ?? NaN)),
+ `${key}: ${JSON.stringify({lensBox, tableBox})}`,
+ ).toBeLessThan(0.5);
+ }
+});
+
+test('Reduce Motion: the lens still follows the finger through a drag (direct movement), and only the lift cross-fades (design:reduced-motion)', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const control = await openControl(page);
+ const grid = boxOf(await control.boxes(), 'grid');
+ const tableAtRest = boxOf(await control.boxes(), 'table');
+ const tableCenter = tableAtRest.x + tableAtRest.width / 2;
+ const selections = await recordSelections(control.group);
+ const held: {visible: boolean; center: number}[] = [];
+ let liftAt = 0;
+ const {samples} = await sampleReducedMotionChange(page, control, async () => {
+ const played = await control.driver.play(
+ touchDrag(
+ await clientCenter(control, 'grid'),
+ await clientCenter(control, 'table'),
+ {durationMs: 400, restMs: 100},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ const now = await presentedNow(control);
+ held.push({visible: now.visible, center: now.center});
+ }
+ },
+ },
+ );
+ liftAt = played.find(event => event.type === 'touchEnd')?.dispatchedAt ?? 0;
+ });
+ // Once the pan claims the drag and binds the lens, the lens stays on screen
+ // and goes where the finger goes, at once. It ends on Table, where the
+ // finger rests.
+ const bound = held.findIndex(sample => sample.visible);
+ expect(bound, JSON.stringify(held)).toBeGreaterThanOrEqual(0);
+ const following = held.slice(bound);
+ expect(following.length).toBeGreaterThan(5);
+ expect(
+ following.every(sample => sample.visible),
+ JSON.stringify(held),
+ ).toBe(true);
+ for (let i = 1; i < following.length; i++) {
+ expect(following[i].center).toBeGreaterThanOrEqual(
+ following[i - 1].center - 0.5,
+ );
+ }
+ expect(
+ Math.abs(following[following.length - 1].center - tableCenter),
+ ).toBeLessThan(1);
+ // The segment under the finger at the lift, once.
+ const changes = await selections();
+ expect(changes.map(change => change.value)).toEqual(['table']);
+ expect(changes[0].at).toBeGreaterThanOrEqual(liftAt - 5);
+ // Then it cross-fades in 200 ms or less (DR1, DR2). The lens fades in on
+ // Table, full size and still, where Table sits with its new title weight.
+ // The ::after fades out where the lens was at the lift: on Table's center,
+ // at the width it carried from Grid.
+ const table = boxOf(await control.boxes(), 'table');
+ const fadeEnd = fadeEndOf(samples);
+ expect(fadeEnd).toBeGreaterThan(0);
+ expect(fadeEnd).toBeLessThanOrEqual(RM_MAX_FADE_MS);
+ for (const {t, entering, leaving} of samples) {
+ const label = JSON.stringify({t, entering, leaving});
+ expect(Math.abs((entering?.x ?? 0) - table.x), label).toBeLessThan(0.5);
+ expect(entering?.sx, label).toBe(1);
+ if (leaving != null && leaving.opacity > 0.001) {
+ expect(
+ Math.abs(leaving.x - (tableCenter - grid.width / 2)),
+ label,
+ ).toBeLessThan(1);
+ expect(leaving.sx, label).toBe(1);
+ }
+ }
+ await expectLensHidden(control);
+});
+
+test('the slide keeps advancing every frame while the main thread is blocked', async ({
+ page,
+ browserName,
+}, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit is recorded on the iOS simulator)',
+ );
+ const control = await openControl(page);
+ const cast = await startScreencast(page);
+ await control.tapSegment('table');
+ // Running and composited before the block.
+ const [slide] = await waitForLens(control, {minProgressMs: 16});
+ // The lens has no element to carry the harness's marker chip: paint the
+ // lens itself in the marker colour for the frames to find it.
+ await paintLensMarker(control);
+ const block = await blockMainThread(page, 500);
+ await page.waitForTimeout(250);
+ const castFrames = await cast.stop();
+ const tracked = await trackMarker(page, castFrames);
+ const proof = busyWindowProof(
+ tracked,
+ {from: block.from, to: Math.min(block.to, slide.to)},
+ {axis: 'x', settledWithin: 1},
+ );
+ await writeEvidence(
+ 'busy-main-thread/segmented-slide',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ block,
+ slide,
+ proof,
+ frames: tracked.map(f => ({
+ t: +(f.t - block.from).toFixed(1),
+ x: f.box?.x ?? null,
+ })),
+ },
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ const film = await castStoryboard(page, castFrames, {
+ name: 'segmented-slide-busy-main-thread',
+ zero: block.from,
+ from: block.from - 40,
+ to: Math.min(block.to, slide.to) + 40,
+ columns: 8,
+ cellScale: 0.35,
+ data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}),
+ });
+ await film.write(testInfo, {block, slide});
+ expect(proof.frames).toBeGreaterThanOrEqual(proof.expectedFrames - 2);
+ expect(proof.changed).toBeGreaterThanOrEqual(proof.frames - 3);
+});
+
+test('the slide does no Layout or Paint per frame', async ({
+ page,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ await openControl(page, 'core-segmentedcontrol--selection-motion', 'Period');
+ // A change the app makes, by a DOM click on the story's button. It slides
+ // the same way, with no press model, focus ring or keyboard hint.
+ const next = page.getByRole('button', {name: 'Next period'});
+ // The story's two controls share the value, so both slide; each lands (and
+ // hands its surface back) on its own clock.
+ const groups = page.getByRole('radiogroup');
+ await expect(groups).toHaveCount(2);
+ const handBacks = await recordHandBacks(page);
+ let start = 0;
+ const started = Date.now();
+ const trace = await traceRendering(page, async () => {
+ await next.evaluate(button => (button as HTMLButtonElement).click());
+ const slides = await Promise.all(
+ [0, 1].map(async i => (await waitForAnimation(groups.nth(i)))[0]),
+ );
+ start = Math.max(...slides.map(slide => slide.from));
+ // Wait in the test runner, not in the page. Polling the page forces its
+ // own style and layout work into the measured window.
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ });
+ const landed = await handBacks();
+ expect(landed).toHaveLength(2);
+ // The steady part of the slides: their first frame commits the selection
+ // and the first hand-back ends it.
+ const during = countBetween(trace, start + 50, Math.min(...landed) - 50);
+ expect(Math.min(...landed) - start).toBeGreaterThan(500);
+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);
+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);
+ // No long task once the slides run. The click's own task ends at their
+ // first frame: React renders the story, and the motion starts both slides.
+ // That task is the change's work, not the slides', and its length follows
+ // the machine's load.
+ const sinceSlides = (tasks: ReadonlyArray<{start: number}>) =>
+ tasks.filter(task => task.start >= start);
+ expect(sinceSlides(trace.longTasks)).toEqual([]);
+ expect(
+ sinceSlides(await readLongTasks(page, {from: started, to: Date.now()})),
+ ).toEqual([]);
+});
+
+test('assistive technology sees the same radios: the lens is decoration with no element', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.tapSegment('list');
+ await expect(control.group).toMatchAriaSnapshot(`
+ - radiogroup "View mode":
+ - radio "Grid"
+ - radio "List" [checked]
+ - radio "Table"
+ `);
+});
+
+test(
+ 'storyboard: tap to slide, and a second tap mid-flight',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const control = await openControl(page);
+ await installTimerGate(page);
+ const measure = async () => {
+ const [sample] = await control.group.evaluate(element => {
+ const style = getComputedStyle(element, '::before');
+ const x = style.translate === 'none' ? 0 : parseFloat(style.translate);
+ return [
+ {
+ x: parseFloat(style.left) + parseFloat(style.width) / 2 + x,
+ scaleX: style.scale === 'none' ? 1 : parseFloat(style.scale),
+ visible: style.visibility === 'visible',
+ },
+ ];
+ });
+ return sample;
+ };
+ await control.tapSegment('table');
+ await waitForLens(control);
+ await freezeTimers(page);
+ const {storyboard: slideBoard} = await animationStoryboard(page, {
+ name: 'segmented-tap-slide',
+ times: timeline(700),
+ clip: control.group,
+ scope: control.group,
+ measure,
+ columns: 8,
+ cellScale: 1,
+ });
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ await slideBoard.write(testInfo);
+ const xs = slideBoard.frames.map(f => f.data.x as number);
+ const boxes = await control.boxes();
+ const table = boxOf(boxes, 'table');
+ // The center rises to the destination's, overshoots a little, settles.
+ expect(xs.at(-1)).toBeCloseTo(centerOf(table), 0);
+ expect(Math.max(...xs)).toBeGreaterThan(centerOf(table));
+ expect(Math.max(...xs) - centerOf(table)).toBeLessThan(2);
+
+ // A second tap 80 ms into a slide back to the first segment.
+ await control.tapSegment('grid');
+ await waitForLens(control, {minProgressMs: 80});
+ await control.tapSegment('list');
+ await waitForLens(control);
+ await freezeTimers(page);
+ const {storyboard: retargetBoard} = await animationStoryboard(page, {
+ name: 'segmented-retarget',
+ times: timeline(700),
+ clip: control.group,
+ scope: control.group,
+ measure,
+ columns: 8,
+ cellScale: 1,
+ });
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ await retargetBoard.write(testInfo);
+ const retargetXs = retargetBoard.frames.map(f => f.data.x as number);
+ // Where List is now: the titles' weights changed with the selection.
+ const list = boxOf(await control.boxes(), 'list');
+ expect(retargetXs.at(-1)).toBeCloseTo(centerOf(list), 0);
+ // Continuous: no frame-to-frame jump larger than the fastest frame of a
+ // fresh slide would make.
+ for (let i = 1; i < retargetXs.length; i++) {
+ expect(Math.abs(retargetXs[i] - retargetXs[i - 1])).toBeLessThan(25);
+ }
+ },
+);
+
+/** Records each selection change (value, epoch ms on the page's clock). */
+async function recordSelections(
+ group: Locator,
+): Promise<() => Promise<{value: string; at: number}[]>> {
+ await group.evaluate(track => {
+ const changes: {value: string; at: number}[] = [];
+ (window as unknown as {__selections: typeof changes}).__selections =
+ changes;
+ new MutationObserver(records => {
+ for (const record of records) {
+ const element = record.target as HTMLElement;
+ if (element.getAttribute('aria-checked') === 'true') {
+ changes.push({
+ value: element.dataset.value ?? '',
+ at: performance.timeOrigin + performance.now(),
+ });
+ }
+ }
+ }).observe(track, {
+ subtree: true,
+ attributes: true,
+ attributeFilter: ['aria-checked'],
+ });
+ });
+ return async () =>
+ group.evaluate(
+ () =>
+ (window as unknown as {__selections: {value: string; at: number}[]})
+ .__selections,
+ );
+}
+
+/** The lens's presented center and size right now (no hold). */
+async function presentedNow(control: Control) {
+ return control.group.evaluate(element => {
+ const style = getComputedStyle(element, '::before');
+ const x = style.translate === 'none' ? 0 : parseFloat(style.translate);
+ const [sx, sy = sx] =
+ style.scale === 'none' ? [1, 1] : style.scale.split(' ').map(Number);
+ return {
+ center: parseFloat(style.left) + parseFloat(style.width) / 2 + x,
+ width: parseFloat(style.width) * sx,
+ height: parseFloat(style.height) * sy,
+ visible: style.visibility === 'visible',
+ };
+ });
+}
+
+/** A segment's center in client coordinates. */
+async function clientCenter(control: Control, value: string) {
+ const box = await control.segment(value).boundingBox();
+ if (box == null) {
+ throw new Error(`no segment ${value}`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+test('holding the selected segment lifts nothing by default (a theme’s pressed-thumb lift turns it on): no lens and no shadow; letting go changes nothing', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const selections = await recordSelections(control.group);
+ // Every time the radiogroup's style shows a pseudo-element layer.
+ await control.group.evaluate(group => {
+ const shown: string[] = [];
+ (window as unknown as {__layersShown: string[]}).__layersShown = shown;
+ new MutationObserver(() => {
+ const lens = group.style.getPropertyValue('--_segmented-lens-visibility');
+ const after = group.style.getPropertyValue(
+ '--_segmented-after-visibility',
+ );
+ if (lens !== '' || after !== '') {
+ shown.push(`lens=${lens} after=${after}`);
+ }
+ }).observe(group, {attributes: true, attributeFilter: ['style']});
+ });
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'grid'), {holdMs: 700}),
+ );
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {__layersShown: string[]}).__layersShown,
+ ),
+ ).toEqual([]);
+ // The selected segment kept painting its own surface throughout.
+ expect(
+ await control
+ .segment('grid')
+ .evaluate(element =>
+ (element as HTMLElement).style.getPropertyValue('background-color'),
+ ),
+ ).toBe('');
+ expect(await selections()).toEqual([]);
+});
+
+test('a drag from the selected segment carries the lens and commits once, at the lift', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const boxes = await control.boxes();
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'grid');
+ const to = await clientCenter(control, 'table');
+ const midDrag: {finger: number; lens: number; width: number; at: number}[] =
+ [];
+ const played = await control.driver.play(
+ touchDrag(from, to, {durationMs: 600, restMs: 200}),
+ {
+ onEvent: async (step, index) => {
+ if (step.type === 'touchMove' && index % 6 === 0) {
+ const now = await presentedNow(control);
+ midDrag.push({
+ finger: step.changed[0].x,
+ lens: now.center,
+ width: now.width,
+ at: Date.now(),
+ });
+ }
+ },
+ },
+ );
+ const lift = played.find(event => event.type === 'touchEnd');
+ const changes = await selections();
+ expect(changes.map(change => change.value)).toEqual(['table']);
+ // Not before the finger let go.
+ expect(changes[0].at).toBeGreaterThanOrEqual((lift?.dispatchedAt ?? 0) - 5);
+ // The lens followed the finger at its resting size (trailing it on the
+ // tracking spring, by less than the width of a segment).
+ const trackLeft = (await control.group.boundingBox())?.x ?? 0;
+ for (const sample of midDrag.slice(2)) {
+ // Nothing lifts it: its width stays a segment's.
+ expect(sample.width).toBeLessThan(boxOf(boxes, 'grid').width + 12);
+ const lag = sample.finger - trackLeft - sample.lens;
+ expect(lag).toBeGreaterThan(-2);
+ expect(lag).toBeLessThan(40);
+ }
+ await expectLensHidden(control);
+});
+
+test('letting go between segments commits the one nearest the finger', async ({
+ page,
+}) => {
+ for (const [progress, expected] of [
+ [0.4, 'grid'],
+ [0.6, 'list'],
+ ] as const) {
+ const control = await openControl(page);
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'grid');
+ const list = await clientCenter(control, 'list');
+ const to = {x: from.x + (list.x - from.x) * progress, y: from.y};
+ await control.driver.play(
+ touchDrag(from, to, {durationMs: 300, restMs: 200}),
+ );
+ await expectLensHidden(control);
+ await expect(control.segment(expected)).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect((await selections()).map(change => change.value)).toEqual(
+ expected === 'grid' ? [] : [expected],
+ );
+ }
+});
+
+test('past the end segment the lens stops 11 pt beyond its center, and letting go out there selects nothing (a press that slides off cancels: spec:AST-020 FR9, DEC-5)', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const table = boxOf(await control.boxes(), 'table');
+ const from = await clientCenter(control, 'grid');
+ const end = await control.segment('table').boundingBox();
+ if (end == null) {
+ throw new Error('no table segment');
+ }
+ const script = touchDrag(
+ from,
+ {x: end.x + end.width + 60, y: from.y},
+ {durationMs: 500, restMs: 700},
+ );
+ const lastMove = toTouchEvents(script).length - 2;
+ let resting: {center: number} | null = null;
+ await control.driver.play(script, {
+ onEvent: async (_step, index) => {
+ if (index === lastMove) {
+ // The finger rests 60 pt past the control; the chase settles.
+ await page.waitForTimeout(450);
+ resting = await presentedNow(control);
+ }
+ },
+ });
+ expect(resting).not.toBeNull();
+ const center = (resting as unknown as {center: number}).center;
+ expect(Math.abs(center - (centerOf(table) + DRAG_OVERSHOOT))).toBeLessThan(
+ 1.5,
+ );
+ // The finger let go 60 pt outside the control: nothing is selected, and
+ // the lens goes back to the selected segment.
+ await expectLensHidden(control);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'false',
+ );
+});
+
+test('a drag that leaves the control and lets go below it selects nothing: a press that slides off cancels (spec:AST-020 FR9, DEC-5)', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'grid');
+ const table = await clientCenter(control, 'table');
+ const group = await control.group.boundingBox();
+ if (group == null) {
+ throw new Error('no radiogroup');
+ }
+ // Sideways onto Table first (the drag claims the finger), then down and
+ // off the control, and let go 40 pt below it.
+ const below = {x: table.x, y: group.y + group.height + 40};
+ const sideways = touchDrag(from, table, {durationMs: 400}).slice(0, -1);
+ const lastT = sideways[sideways.length - 1].t;
+ const off = touchDrag(table, below, {durationMs: 300, restMs: 200})
+ .slice(1)
+ .map(frame => ({...frame, t: frame.t + lastT}));
+ await control.driver.play([...sideways, ...off]);
+ await expectLensHidden(control);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ expect(await selections()).toEqual([]);
+});
+
+test('a drag that starts on another segment leaves the lens alone and commits where it lets go', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'list');
+ const to = await clientCenter(control, 'table');
+ const visibleDuringDrag: boolean[] = [];
+ await control.driver.play(
+ touchDrag(from, to, {durationMs: 400, restMs: 100}),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ visibleDuringDrag.push((await presentedNow(control)).visible);
+ }
+ },
+ },
+ );
+ expect(visibleDuringDrag.length).toBeGreaterThan(5);
+ expect(visibleDuringDrag.every(visible => !visible)).toBe(true);
+ // Lift position wins, as in UIKit.
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+});
+
+/** The pressed segment's paint, read where its press marker changes. */
+interface PressRecord {
+ readonly press: string | null;
+ readonly image: string;
+ readonly opacity: string;
+ readonly title: string;
+}
+
+test('a finger on an unselected segment shows the shared pressed overlay and dims nothing; the lift commits it', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const list = control.segment('list');
+ // The press paint lasts only while the finger is down, so the page records
+ // it as it changes. A poll from the test can miss that window, because
+ // WebKit's input commands and the test's reads share one channel.
+ await list.evaluate(element => {
+ const records: PressRecord[] = [];
+ (window as unknown as {__pressRecords: PressRecord[]}).__pressRecords =
+ records;
+ new MutationObserver(() => {
+ records.push({
+ press: element.getAttribute('data-astryx-press'),
+ image: getComputedStyle(element).backgroundImage,
+ opacity: getComputedStyle(element).opacity,
+ title: getComputedStyle(
+ element.querySelector('[data-astryx-segment-title]') as Element,
+ ).opacity,
+ });
+ }).observe(element, {
+ attributes: true,
+ attributeFilter: ['data-astryx-press'],
+ });
+ });
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'list'), {holdMs: 400}),
+ );
+ const records = await page.evaluate(
+ () => (window as unknown as {__pressRecords: PressRecord[]}).__pressRecords,
+ );
+ // The shared press paint, as everywhere under a finger. The press
+ // controller marks the segment once it believes the press, and the shared
+ // overlay paints it.
+ const held = records.find(record => record.press === 'on');
+ expect(held, JSON.stringify(records)).toBeDefined();
+ // While the controller paints, the overlay is its image layer.
+ expect(held?.image).toContain('gradient');
+ // Nothing dims: not the segment, not its title.
+ expect({opacity: held?.opacity, title: held?.title}).toEqual({
+ opacity: '1',
+ title: '1',
+ });
+ await expect(list).toHaveAttribute('aria-checked', 'true');
+ await expect(list).toHaveCSS('opacity', '1');
+ await expect(list).not.toHaveAttribute('data-pressed');
+});
+
+test('during a drag the selected face follows the lens as a colour, with no weight swap mid-drag, and the commit keeps it as shown', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const read = async (value: string) =>
+ control
+ .segment(value)
+ .locator('[data-astryx-segment-title]')
+ .evaluate(element => {
+ const style = getComputedStyle(element);
+ return {weight: style.fontWeight, color: style.color};
+ });
+ const selected = await read('grid');
+ const unselected = await read('list');
+ expect(selected.color).not.toBe(unselected.color);
+ const boxes = await control.boxes();
+ const list = boxOf(boxes, 'list');
+ const table = boxOf(boxes, 'table');
+ const groupBox = await control.group.boundingBox();
+ const seen: {
+ finger: number;
+ grid: {weight: string; color: string};
+ list: {weight: string; color: string};
+ table: {weight: string; color: string};
+ }[] = [];
+ await control.driver.play(
+ touchDrag(
+ await clientCenter(control, 'grid'),
+ await clientCenter(control, 'table'),
+ {durationMs: 600, restMs: 300},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ seen.push({
+ finger: step.changed[0].x - (groupBox?.x ?? 0),
+ grid: await read('grid'),
+ list: await read('list'),
+ table: await read('table'),
+ });
+ }
+ },
+ },
+ );
+ expect(seen.length).toBeGreaterThan(5);
+ // No title changes weight mid-drag: the segments never reflow under it.
+ for (const s of seen) {
+ expect(s.grid.weight).toBe(selected.weight);
+ expect(s.list.weight).toBe(unselected.weight);
+ expect(s.table.weight).toBe(unselected.weight);
+ }
+ // The face trails the finger with the lens, never ahead of it.
+ const gapMiddle = (list.x + list.width + table.x) / 2;
+ for (const s of seen.filter(s => s.finger < gapMiddle - 1)) {
+ expect(s.table.color, `finger at ${s.finger}`).toBe(unselected.color);
+ }
+ expect(seen.at(-1)?.table.color).toBe(selected.color);
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ // The commit takes the face over: no borrowed style is left.
+ expect(
+ await control.group.evaluate(group =>
+ [...group.querySelectorAll<HTMLElement>('[data-astryx-segment-title]')]
+ .map(title => title.style.cssText)
+ .join(''),
+ ),
+ ).toBe('');
+ expect((await read('table')).weight).toBe(selected.weight);
+});
+
+test('a slow ±3 px dither across a boundary changes the selected face at most once', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const colorOf = async (value: string) =>
+ control
+ .segment(value)
+ .locator('[data-astryx-segment-title]')
+ .evaluate(element => getComputedStyle(element).color);
+ const selectedColor = await colorOf('grid');
+ const faced = async () => {
+ for (const value of ['list', 'grid', 'table']) {
+ if (value !== 'grid' && (await colorOf(value)) === selectedColor) {
+ return value;
+ }
+ }
+ return 'grid';
+ };
+ const boxes = await control.boxes();
+ const grid = boxOf(boxes, 'grid');
+ const list = boxOf(boxes, 'list');
+ const groupBox = await control.group.boundingBox();
+ const y = (groupBox?.y ?? 0) + (groupBox?.height ?? 0) / 2;
+ const boundary = (groupBox?.x ?? 0) + (grid.x + grid.width + list.x) / 2;
+ const start = await clientCenter(control, 'grid');
+ // Held on Grid, carried to the boundary, then dithered ±3 px, 70 ms a step.
+ const script = [
+ {t: 0, fingers: [{id: 0, x: start.x, y}]},
+ {t: 300, fingers: [{id: 0, x: boundary, y}]},
+ ...Array.from({length: 24}, (_, i) => ({
+ t: 700 + i * 70,
+ fingers: [{id: 0, x: boundary + (i % 2 === 0 ? 3 : -3), y}],
+ })),
+ {t: 700 + 24 * 70 + 50, fingers: []},
+ ];
+ const faces: string[] = [];
+ await control.driver.play(script, {
+ onEvent: async step => {
+ if (step.type === 'touchMove' && step.t >= 700) {
+ faces.push(await faced());
+ }
+ },
+ });
+ const changes = faces.filter((face, i) => i > 0 && face !== faces[i - 1]);
+ expect(changes.length, faces.join(' ')).toBeLessThanOrEqual(1);
+});
+
+test('a drag held just past a boundary: at the lift the selected colour snaps to the segment nearest the finger, which it commits', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const boxes = await control.boxes();
+ const grid = boxOf(boxes, 'grid');
+ const list = boxOf(boxes, 'list');
+ const groupBox = await control.group.boundingBox();
+ const y = (groupBox?.y ?? 0) + (groupBox?.height ?? 0) / 2;
+ const boundary = (groupBox?.x ?? 0) + (grid.x + grid.width + list.x) / 2;
+ const start = await clientCenter(control, 'grid');
+ const selections = await recordSelections(control.group);
+ // Held on Grid, carried 3 px past the boundary, rested, lifted.
+ await control.driver.play([
+ {t: 0, fingers: [{id: 0, x: start.x, y}]},
+ {t: 300, fingers: [{id: 0, x: boundary - 10, y}]},
+ {t: 400, fingers: [{id: 0, x: boundary + 3, y}]},
+ {t: 900, fingers: []},
+ ]);
+ // The hysteresis kept the colour on Grid while held; the lift commits List,
+ // the nearest, and the colour snaps there with the selection.
+ await expect(control.segment('list')).toHaveAttribute('aria-checked', 'true');
+ // The gesture ends when the lens hands its surface back.
+ await expectLensHidden(control);
+ expect((await selections()).map(change => change.value)).toEqual(['list']);
+});
+
+test('a tap’s commit is the browser’s own click (spec:AST-094 FR11)', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.segment('table').evaluate(element => {
+ const w = window as unknown as {__trusted: boolean[]};
+ w.__trusted = [];
+ element.addEventListener(
+ 'click',
+ event => w.__trusted.push(event.isTrusted),
+ {
+ capture: true,
+ },
+ );
+ });
+ // The engine's tap path. Playwright's WebKit makes the browser's click only
+ // from its tap gesture, not from a raw touch sequence. The harness README
+ // lists this limit. Chromium's touch input clicks either way.
+ await control.driver.tap(await clientCenter(control, 'table'));
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ // The lens hands back only after the commit's click, so no click comes
+ // after it.
+ await expectLensHidden(control);
+ expect(
+ await page.evaluate(
+ () => (window as unknown as {__trusted: boolean[]}).__trusted,
+ ),
+ ).toEqual([true]);
+});
+
+/**
+ * Counts the clicks that reach a segment. With `veto`, it prevents them as an
+ * item's consumer `onClick` would, with `event.preventDefault()`. The item's
+ * own handler honors that.
+ */
+async function watchClicks(
+ control: Control,
+ value: string,
+ {veto = false}: {veto?: boolean} = {},
+): Promise<() => Promise<number>> {
+ await control.segment(value).evaluate((element, shouldVeto) => {
+ const counter = {count: 0};
+ (element as unknown as {__clicks: typeof counter}).__clicks = counter;
+ element.addEventListener(
+ 'click',
+ event => {
+ counter.count++;
+ if (shouldVeto) {
+ event.preventDefault();
+ }
+ },
+ {capture: true},
+ );
+ }, veto);
+ return async () =>
+ control
+ .segment(value)
+ .evaluate(
+ element =>
+ (element as unknown as {__clicks: {count: number}}).__clicks.count,
+ );
+}
+
+test('a tap commits through the item’s click: its onClick runs once and can veto with preventDefault()', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const clicks = await watchClicks(control, 'table');
+ const selections = await recordSelections(control.group);
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'table'), {holdMs: 80}),
+ );
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ // Once: the browser's own click for the touch selects nothing again. The
+ // lens hands back only after the commit's click.
+ await expectLensHidden(control);
+ expect(await clicks()).toBe(1);
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+});
+
+test('a tap whose browser click comes late (a busy main thread) runs the item’s click once', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const clicks = await watchClicks(control, 'table');
+ const selections = await recordSelections(control.group);
+ // Counts the browser's own clicks where the window first sees them, before
+ // any listener of the control.
+ await page.evaluate(() => {
+ const w = window as unknown as {__browserClicks: number};
+ w.__browserClicks = 0;
+ window.addEventListener(
+ 'click',
+ event => {
+ if (event.isTrusted) {
+ w.__browserClicks++;
+ }
+ },
+ {capture: true},
+ );
+ });
+ // The lift arms a 300 ms wait for the browser's click. Block the main
+ // thread for 450 ms right after it. Then the browser's click for this tap
+ // comes only after the wait ran out.
+ await page.evaluate(() => {
+ const original = window.setTimeout;
+ const patched = (
+ handler: TimerHandler,
+ ms?: number,
+ ...rest: unknown[]
+ ): number => {
+ const id = original(handler, ms, ...rest);
+ if (ms === 300) {
+ window.setTimeout = original;
+ const end = performance.now() + 450;
+ while (performance.now() < end) {
+ // busy: the main thread is blocked
+ }
+ }
+ return id;
+ };
+ window.setTimeout = patched as typeof window.setTimeout;
+ });
+ await control.driver.tap(await clientCenter(control, 'table'));
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ // The browser's late click has come, and the control swallowed it.
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () => (window as unknown as {__browserClicks: number}).__browserClicks,
+ ),
+ )
+ .toBe(1);
+ expect(await clicks()).toBe(1);
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+});
+
+test('a vetoed tap selects nothing, and the lens goes back to the selection', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const vetoedClicks = await watchClicks(control, 'table', {veto: true});
+ const selections = await recordSelections(control.group);
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'table'), {holdMs: 80}),
+ );
+ // The vetoed click ends the gesture.
+ await expect.poll(vetoedClicks).toBe(1);
+ expect(await selections()).toEqual([]);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ // The lens settles back on Grid and hands its surface back.
+ await expectLensHidden(control);
+ expect(
+ await control.group.evaluate(group =>
+ [...group.querySelectorAll<HTMLElement>('[role="radio"]')]
+ .map(segment => segment.style.cssText)
+ .join(''),
+ ),
+ ).toBe('');
+});
+
+test('a parent that adopts the value 200 ms later gets no bounce: the lens keeps going and lands there', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ // The story's parent adopts a value at once, but this one waits 200 ms
+ // after the click. The commit's own click goes unheard, and nobody vetoes
+ // it. A later programmatic click delivers the value.
+ await control.segment('table').evaluate(segment => {
+ const lens: number[] = [];
+ (window as unknown as {__lens: number[]}).__lens = lens;
+ const group = segment.closest('[role="radiogroup"]') as HTMLElement;
+ const sample = () => {
+ const style = getComputedStyle(group, '::before');
+ if (style.visibility === 'visible') {
+ const translate =
+ style.translate === 'none' ? 0 : parseFloat(style.translate);
+ lens.push(
+ parseFloat(style.left) + parseFloat(style.width) / 2 + translate,
+ );
+ }
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ const hold = (event: Event) => {
+ if ((event as MouseEvent).detail === 0) {
+ return;
+ }
+ event.stopImmediatePropagation();
+ segment.removeEventListener('click', hold, true);
+ setTimeout(() => {
+ (segment as HTMLElement).click();
+ }, 200);
+ };
+ segment.addEventListener('click', hold, true);
+ });
+ await control.tapSegment('table');
+ await expect(control.segment('table')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await expectLensHidden(control);
+ const centers = await page.evaluate(
+ () => (window as unknown as {__lens: number[]}).__lens,
+ );
+ expect(centers.length).toBeGreaterThan(10);
+ // Every presented frame heads for Table: never back toward Grid (beyond
+ // the spring's own overshoot of about a pixel at the end).
+ let highest = -Infinity;
+ for (const center of centers) {
+ expect(center, JSON.stringify(centers)).toBeGreaterThan(highest - 2);
+ highest = Math.max(highest, center);
+ }
+});
+
+test('with focus already in the group, a vetoed finger tap still selects nothing: the focus move before its click selects nothing', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ // Focus is in the group already, as after a key press or an earlier tap.
+ await control.segment('grid').focus();
+ const vetoedClicks = await watchClicks(control, 'table', {veto: true});
+ const selections = await recordSelections(control.group);
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'table'), {holdMs: 80}),
+ );
+ // The vetoed click ends the gesture.
+ await expect.poll(vetoedClicks).toBe(1);
+ if (control.driver.engine === 'chromium') {
+ // Chromium moved focus to the tapped segment before its click: the case
+ // under test happened.
+ expect(
+ await control
+ .segment('table')
+ .evaluate(segment => segment === document.activeElement),
+ ).toBe(true);
+ }
+ expect(await selections()).toEqual([]);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ await expectLensHidden(control);
+});
+
+test('with focus already in the group, a vetoed tap whose click comes late still selects nothing', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.segment('grid').focus();
+ const vetoedClicks = await watchClicks(control, 'table', {veto: true});
+ const selections = await recordSelections(control.group);
+ await page.evaluate(() => {
+ const w = window as unknown as {__trusted: number};
+ w.__trusted = 0;
+ window.addEventListener(
+ 'click',
+ event => {
+ if (event.isTrusted) {
+ w.__trusted++;
+ }
+ },
+ {capture: true},
+ );
+ // The wait for the browser's click runs out before the browser's tap
+ // arrives, as under load. Chromium runs a queued tap before a due timer,
+ // so the page ends the 300 ms wait in a microtask instead.
+ const original = window.setTimeout;
+ const patched = (
+ handler: TimerHandler,
+ ms?: number,
+ ...rest: unknown[]
+ ): number => {
+ if (ms === 300 && typeof handler === 'function') {
+ window.setTimeout = original;
+ queueMicrotask(() => {
+ handler();
+ });
+ return 0;
+ }
+ return original(handler, ms, ...rest);
+ };
+ window.setTimeout = patched as typeof window.setTimeout;
+ });
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'table'), {holdMs: 80}),
+ );
+ await expect.poll(vetoedClicks).toBe(1);
+ if (control.driver.engine === 'chromium') {
+ // The late tap came: its focus move, then its click, which is swallowed.
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () => (window as unknown as {__trusted: number}).__trusted,
+ ),
+ )
+ .toBe(1);
+ expect(
+ await control
+ .segment('table')
+ .evaluate(segment => segment === document.activeElement),
+ ).toBe(true);
+ }
+ expect(await vetoedClicks()).toBe(1);
+ expect(await selections()).toEqual([]);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+});
+
+test('an arrow key pressed while a held press waits for its click still selects the segment it moves focus to', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await control.segment('grid').focus();
+ const selections = await recordSelections(control.group);
+ // A hold, which WebKit answers with no click: the wait for it runs on.
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'table'), {holdMs: 600}),
+ );
+ await page.keyboard.press('ArrowRight');
+ const focused = await page.evaluate(
+ () => (document.activeElement as HTMLElement | null)?.dataset.value,
+ );
+ // The arrow's own move selects: right away, whether the hold's commit came
+ // before it (Chromium's click) or comes after it (WebKit's direct click).
+ expect(focused).toBeDefined();
+ await expect
+ .poll(async () => (await selections()).map(change => change.value))
+ .toContain(focused);
+ await expectLensHidden(control);
+});
+
+test('with focus already in the group, a vetoed click from a mouse, a pen or the keyboard selects nothing', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf} = await openWithMouse(browser);
+ try {
+ const selections = await recordSelections(group);
+ const table = group.locator('[data-value="table"]');
+ await table.evaluate(segment => {
+ const w = window as unknown as {__vetoed: number};
+ w.__vetoed = 0;
+ segment.addEventListener(
+ 'click',
+ event => {
+ w.__vetoed++;
+ event.preventDefault();
+ },
+ {capture: true},
+ );
+ });
+ const vetoed = async () =>
+ page.evaluate(() => (window as unknown as {__vetoed: number}).__vetoed);
+ // A mouse: focus moves at the press, inside the group.
+ await group.locator('[data-value="grid"]').focus();
+ const at = await centerOf('table');
+ await page.mouse.click(at.x, at.y);
+ await expect.poll(vetoed).toBe(1);
+ // A pen, where the engine has one.
+ const driver = await webInputDriver(page);
+ if (driver.pens) {
+ await group.locator('[data-value="grid"]').focus();
+ await driver.pen([{x: at.x, y: at.y, t: 0}]);
+ await expect.poll(vetoed).toBe(2);
+ }
+ // The keyboard: Space on the focused segment, focused from outside.
+ await page.evaluate(() => (document.activeElement as HTMLElement)?.blur());
+ await table.focus();
+ await page.keyboard.press('Space');
+ await expect.poll(vetoed).toBe(driver.pens ? 3 : 2);
+ expect(await selections()).toEqual([]);
+ await expect(group.locator('[data-value="grid"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ } finally {
+ await context.close();
+ }
+});
+
+test('a drag commits through the destination item’s click too: its onClick runs once, and a veto keeps the selection', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const clicks = await watchClicks(control, 'table');
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'grid');
+ const to = await clientCenter(control, 'table');
+ await control.driver.play(
+ touchDrag(from, to, {durationMs: 400, restMs: 100}),
+ );
+ await expect.poll(clicks).toBe(1);
+ // The gesture ends when the lens hands its surface back.
+ await expectLensHidden(control);
+ expect(await clicks()).toBe(1);
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+ // Back to Grid, then a vetoed drag to List.
+ await control.driver.play(
+ touchTap(await clientCenter(control, 'grid'), {holdMs: 80}),
+ );
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ await expectLensHidden(control);
+ const vetoedClicks = await watchClicks(control, 'list', {veto: true});
+ const vetoed = await recordSelections(control.group);
+ await control.driver.play(
+ touchDrag(
+ await clientCenter(control, 'grid'),
+ await clientCenter(control, 'list'),
+ {durationMs: 300, restMs: 100},
+ ),
+ );
+ // The vetoed click ends the gesture.
+ await expect.poll(vetoedClicks).toBe(1);
+ expect(await vetoed()).toEqual([]);
+ await expect(control.segment('grid')).toHaveAttribute('aria-checked', 'true');
+ await expectLensHidden(control);
+});
+
+/** A desktop context: a mouse, no touch, a fine primary pointer. */
+async function openWithMouse(browser: Browser): Promise<{
+ context: BrowserContext;
+ page: Page;
+ group: Locator;
+ centerOf: (value: string) => Promise<{x: number; y: number}>;
+ lensShown: () => Promise<boolean>;
+}> {
+ const context = await browser.newContext({
+ hasTouch: false,
+ isMobile: false,
+ viewport: {width: 1024, height: 768},
+ });
+ const page = await context.newPage();
+ await openStory(page, storybook(), 'core-segmentedcontrol--default');
+ // This context's pointer is fine (a context without touch can still match
+ // a coarse one).
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const group = page.getByRole('radiogroup', {name: 'View mode', exact: true});
+ await expect(group).toBeVisible();
+ const centerOf = async (value: string) => {
+ const rect = await group.locator(`[data-value="${value}"]`).boundingBox();
+ if (rect == null) {
+ throw new Error(`no segment ${value}`);
+ }
+ return {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2};
+ };
+ // The motion shows the lens through the radiogroup's own custom property.
+ const lensShown = async () =>
+ group.evaluate(
+ element =>
+ element.style.getPropertyValue('--_segmented-lens-visibility') ===
+ 'visible',
+ );
+ return {context, page, group, centerOf, lensShown};
+}
+
+test('with a mouse a drag from the selected segment carries the selection and commits where it lifts, as every pointer does (spec:AST-094 FR43)', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf, lensShown} =
+ await openWithMouse(browser);
+ try {
+ const selections = await recordSelections(group);
+ const from = await centerOf('grid');
+ const to = await centerOf('table');
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(to.x, to.y, {steps: 12});
+ // Held: the lens is on the pointer, and nothing is committed before the
+ // lift.
+ expect(await lensShown()).toBe(true);
+ await expect(group.locator('[data-value="grid"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await page.mouse.up();
+ await expect(group.locator('[data-value="table"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+ // The lens hands back once it settles.
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ await expect(group.locator('[data-value="list"]')).toHaveCSS(
+ 'transition-property',
+ 'color, background-color, box-shadow',
+ );
+ // A click still selects.
+ await group.locator('[data-value="list"]').click();
+ await expect(group.locator('[data-value="list"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse a drag that starts on another segment carries no lens and commits only where it lifts, focus already in the group or not; the selection then slides there', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf, lensShown} =
+ await openWithMouse(browser);
+ try {
+ // A click on the selected segment first: focus is in the group, so the
+ // press below moves focus within it, which must select nothing.
+ await group.locator('[data-value="grid"]').click();
+ const selections = await recordSelections(group);
+ const from = await centerOf('list');
+ const to = await centerOf('table');
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(to.x, to.y, {steps: 12});
+ expect(await lensShown()).toBe(false);
+ // Nothing is committed before the lift.
+ await expect(group.locator('[data-value="grid"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await page.mouse.up();
+ await expect(group.locator('[data-value="table"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+ // The change slides as every change does, then hands the surface back.
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse a drag that leaves the control and lets go there selects nothing: a press that slides off cancels (spec:AST-020 FR9, DEC-5)', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf, lensShown} =
+ await openWithMouse(browser);
+ try {
+ const selections = await recordSelections(group);
+ const from = await centerOf('grid');
+ const to = await centerOf('table');
+ const box = await group.boundingBox();
+ if (box == null) {
+ throw new Error('no radiogroup');
+ }
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(to.x, to.y, {steps: 12});
+ // Down and off the control, then let go 40 px below it.
+ await page.mouse.move(to.x, box.y + box.height + 40, {steps: 6});
+ await page.mouse.up();
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ await expect(group.locator('[data-value="grid"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect(await selections()).toEqual([]);
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse or a pen under Reduce Motion, a drag’s release lands the selection at once, with no fade (design:reduced-motion DR3)', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf, lensShown} =
+ await openWithMouse(browser);
+ try {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ // Samples the lens (::before) and the leaving surface (::after) on every
+ // frame until stopped: a fade shows a part-way lens or a visible ::after.
+ const startSampling = async () =>
+ group.evaluate(element => {
+ const w = window as unknown as {
+ __fadeFrames: string[];
+ __stop: boolean;
+ };
+ w.__fadeFrames = [];
+ w.__stop = false;
+ const sample = () => {
+ const lens = getComputedStyle(element, '::before');
+ const after = getComputedStyle(element, '::after');
+ if (lens.visibility === 'visible' && Number(lens.opacity) < 0.999) {
+ w.__fadeFrames.push(`lens ${lens.opacity}`);
+ }
+ if (after.visibility === 'visible' && Number(after.opacity) > 0.001) {
+ w.__fadeFrames.push(`after ${after.opacity}`);
+ }
+ if (!w.__stop) {
+ requestAnimationFrame(sample);
+ }
+ };
+ requestAnimationFrame(sample);
+ });
+ const stopSampling = async () =>
+ page.evaluate(() => {
+ const w = window as unknown as {
+ __fadeFrames: string[];
+ __stop: boolean;
+ };
+ w.__stop = true;
+ return w.__fadeFrames;
+ });
+ // A mouse: from Grid to Table.
+ const grid = await centerOf('grid');
+ const table = await centerOf('table');
+ await page.mouse.move(grid.x, grid.y);
+ await page.mouse.down();
+ await page.mouse.move(table.x, table.y, {steps: 12});
+ expect(await lensShown()).toBe(true);
+ await startSampling();
+ await page.mouse.up();
+ await expect(group.locator('[data-value="table"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ expect(await stopSampling()).toEqual([]);
+ // A pen, where the engine has one: back from Table to Grid.
+ const driver = await webInputDriver(page);
+ if (driver.pens) {
+ await startSampling();
+ await driver.pen(
+ Array.from({length: 13}, (_, i) => ({
+ x: table.x + ((grid.x - table.x) * i) / 12,
+ y: table.y,
+ t: i * 25,
+ })),
+ );
+ await expect(group.locator('[data-value="grid"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ await expect.poll(lensShown, {timeout: 3000}).toBe(false);
+ expect(await stopSampling()).toEqual([]);
+ }
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a pen a drag from the selected segment carries the selection and commits where it lifts (spec:AST-094 FR43)', async ({
+ browser,
+}) => {
+ const {context, page, group, centerOf} = await openWithMouse(browser);
+ try {
+ const driver = await webInputDriver(page);
+ test.skip(!driver.pens, PEN_SKIP);
+ const selections = await recordSelections(group);
+ const from = await centerOf('grid');
+ const to = await centerOf('table');
+ const points = Array.from({length: 13}, (_, i) => ({
+ x: from.x + ((to.x - from.x) * i) / 12,
+ y: from.y,
+ t: i * 25,
+ }));
+ await driver.pen(points);
+ await expect(group.locator('[data-value="table"]')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+ expect((await selections()).map(change => change.value)).toEqual(['table']);
+ } finally {
+ await context.close();
+ }
+});
+
+test('the track keeps vertical scrolling and takes horizontal drags', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await expect(control.group).toHaveCSS('touch-action', 'pan-y pinch-zoom');
+});
+
+test('a held finger selects no text on the control; letting go gives selection back', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ const userSelect = async () =>
+ control.group.evaluate(element => {
+ const style = getComputedStyle(element) as CSSStyleDeclaration & {
+ webkitUserSelect?: string;
+ };
+ return style.userSelect || style.webkitUserSelect;
+ });
+ // Whether a selection that starts on the held segment is refused now.
+ // Outside iOS WebKit, the gesture host's lock cancels `selectstart` and
+ // writes no style. So nothing repaints at the touch-down or the lift
+ // (`spec:AST-094` FR41). iOS WebKit fires no `selectstart` for a long
+ // press. There the lock is `user-select` and the callout, which the
+ // simulator recordings cover.
+ const refusesSelection = async () =>
+ control.segment('list').evaluate(element => {
+ const event = new Event('selectstart', {bubbles: true, cancelable: true});
+ element.dispatchEvent(event);
+ return event.defaultPrevented;
+ });
+ // At rest the titles are as selectable as anywhere else on the page.
+ const atRest = await userSelect();
+ expect(atRest).not.toBe('none');
+ expect(await refusesSelection()).toBe(false);
+ const playing = control.driver.play(
+ touchTap(await clientCenter(control, 'list'), {holdMs: 600}),
+ );
+ await expect.poll(refusesSelection).toBe(true);
+ expect(await userSelect()).toBe(atRest);
+ await playing;
+ await expect.poll(refusesSelection).toBe(false);
+ expect(await userSelect()).toBe(atRest);
+});
+
+/** Makes the story page scroll: the control sits in a scroller. */
+async function makePageScroll(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const spacer = document.createElement('div');
+ spacer.style.height = '2000px';
+ document.body.append(spacer);
+ });
+}
+
+/** Records whether each `touchmove` was cancelled (read after every listener). */
+async function recordTouchMoves(page: Page): Promise<() => Promise<boolean[]>> {
+ await page.evaluate(() => {
+ const moves: boolean[] = [];
+ (window as unknown as {__moves: boolean[]}).__moves = moves;
+ window.addEventListener(
+ 'touchmove',
+ event => {
+ moves.push(event.defaultPrevented);
+ },
+ {passive: true},
+ );
+ });
+ return async () =>
+ page.evaluate(() => (window as unknown as {__moves: boolean[]}).__moves);
+}
+
+/** Records, on the page's clock, each time the lens is shown or hidden. */
+async function recordProxyVisibility(
+ control: Control,
+): Promise<() => Promise<{visible: boolean; at: number}[]>> {
+ await control.group.evaluate(element => {
+ const changes: {visible: boolean; at: number}[] = [];
+ (window as unknown as {__lens: typeof changes}).__lens = changes;
+ // The radiogroup's style also carries the gesture host's text-selection
+ // lock and the animator's promotion: only a change of the lens counts.
+ const shown = () =>
+ getComputedStyle(element, '::before').visibility === 'visible';
+ let visible = shown();
+ new MutationObserver(() => {
+ const now = shown();
+ if (now !== visible) {
+ visible = now;
+ changes.push({visible, at: performance.timeOrigin + performance.now()});
+ }
+ }).observe(element, {attributes: true, attributeFilter: ['style']});
+ });
+ return async () =>
+ control.group.evaluate(
+ () =>
+ (window as unknown as {__lens: {visible: boolean; at: number}[]})
+ .__lens,
+ );
+}
+
+test('a vertical drag that starts on the control scrolls the page and lifts nothing', async ({
+ page,
+}) => {
+ const control = await openControl(page);
+ await makePageScroll(page);
+ const selections = await recordSelections(control.group);
+ const moves = await recordTouchMoves(page);
+ const shown = await recordProxyVisibility(control);
+ const start = await clientCenter(control, 'grid');
+ await control.driver.play(
+ touchDrag(start, {x: start.x + 4, y: start.y - 140}, {durationMs: 300}),
+ );
+ // The page kept every move: nothing cancelled them...
+ const cancelled = await moves();
+ expect(cancelled.length).toBeGreaterThan(0);
+ expect(cancelled.some(Boolean)).toBe(false);
+ if (control.driver.engine === 'chromium') {
+ // ...and Chromium scrolled it natively.
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(60);
+ }
+ // A flick inside a scroller presses nothing: no lift, no change.
+ await page.waitForTimeout(300);
+ expect(await shown()).toEqual([]);
+ expect(await selections()).toEqual([]);
+});
+
+test('RTL: a drag carries the lens toward the finger and commits once, at the lift', async ({
+ page,
+}) => {
+ const control = await openControl(
+ page,
+ 'core-segmentedcontrol--default',
+ 'View mode',
+ {direction: 'rtl'},
+ );
+ const boxes = await control.boxes();
+ // The first segment is on the right in RTL.
+ expect(boxOf(boxes, 'grid').x).toBeGreaterThan(boxOf(boxes, 'table').x);
+ const selections = await recordSelections(control.group);
+ const from = await clientCenter(control, 'grid');
+ const to = await clientCenter(control, 'table');
+ const midDrag: {finger: number; lens: number; width: number; at: number}[] =
+ [];
+ const played = await control.driver.play(
+ touchDrag(from, to, {durationMs: 600, restMs: 200}),
+ {
+ onEvent: async (step, index) => {
+ if (step.type === 'touchMove' && index % 6 === 0) {
+ const now = await presentedNow(control);
+ midDrag.push({
+ finger: step.changed[0].x,
+ lens: now.center,
+ width: now.width,
+ at: Date.now(),
+ });
+ }
+ },
+ },
+ );
+ const lift = played.find(event => event.type === 'touchEnd');
+ const changes = await selections();
+ expect(changes.map(change => change.value)).toEqual(['table']);
+ expect(changes[0].at).toBeGreaterThanOrEqual((lift?.dispatchedAt ?? 0) - 5);
+ // Trailing the finger from the right as it moves left, at its resting
+ // size.
+ const trackLeft = (await control.group.boundingBox())?.x ?? 0;
+ expect(midDrag.length).toBeGreaterThan(3);
+ for (const sample of midDrag.slice(2)) {
+ // Nothing lifts it: its width stays a segment's.
+ expect(sample.width).toBeLessThan(boxOf(boxes, 'grid').width + 12);
+ const lag = sample.lens - (sample.finger - trackLeft);
+ expect(lag).toBeGreaterThan(-2);
+ expect(lag).toBeLessThan(40);
+ }
+ await expectLensHidden(control);
+});
+
+test(
+ 'storyboard: hold the selected segment, drag it, let go',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const control = await openControl(page);
+ const box = await control.group.boundingBox();
+ if (box == null) {
+ throw new Error('no control');
+ }
+ const from = await clientCenter(control, 'grid');
+ const to = await clientCenter(control, 'table');
+ const board = await touchStoryboard(
+ page,
+ control.driver,
+ touchDrag(from, to, {durationMs: 600, holdMs: 350, restMs: 250, hz: 20}),
+ {
+ name: 'segmented-hold-drag-release',
+ clip: {
+ x: box.x - 12,
+ y: box.y - 14,
+ width: box.width + 24,
+ height: box.height + 28,
+ },
+ measure: async () => presentedNow(control),
+ columns: 4,
+ cellScale: 1,
+ },
+ );
+ await board.write(testInfo);
+ // Nothing lifts while the finger holds the selected segment: the lens
+ // appears only once the drag moves it, at the resting size.
+ const rest = boxOf(await control.boxes(), 'grid').width;
+ const held = board.frames.filter(frame =>
+ frame.label.startsWith('touchStart'),
+ );
+ for (const frame of held) {
+ const data = frame.data as {width: number; visible: boolean};
+ expect(data.visible, frame.label).toBe(false);
+ }
+ // Carried the whole way: the selected face moving to the title under the
+ // finger reflows the titles, and the lens stays with the finger.
+ const dragged = board.frames.filter(
+ frame => frame.label.startsWith('touchMove') && frame.t >= 450,
+ );
+ expect(dragged.length).toBeGreaterThan(5);
+ for (const frame of dragged) {
+ const data = frame.data as {width: number; visible: boolean};
+ expect(data.visible, frame.label).toBe(true);
+ expect(data.width, frame.label).toBeLessThan(rest + 12);
+ }
+ },
+);
diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts
new file mode 100644
index 0000000000..204086bd2c
--- /dev/null
+++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.test.ts
@@ -0,0 +1,1370 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useSegmentedSelectionMotion.test.ts
+ * @input vitest, jsdom, SegmentedSelectionMotion with an animator on a
+ * scripted clock, stubbed segment geometry and a recording `animate`
+ * @output The touch layer's selection motion as a state machine: the slide,
+ * the hand-back, a change mid-flight, resize, Reduced Motion, the press, the
+ * chase, the commit at the lift and the face that follows a drag
+ * @position Unit tests for useSegmentedSelectionMotion.ts; the browser proofs
+ * are __tests__/SegmentedControl.interaction.browser.spec.ts
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {motionRoleOf} from '../motion/roles';
+import {createAnimator, type Animator} from '../motion/animator';
+import {solveSpring, toSpring} from '../motion/spring';
+import {cubicBezier} from '../motion/bezier';
+import {segmentedControl, springs} from '../motion/uikit';
+import {measureSegments, segmentTargetAt} from './useSegmentedTouchTracking';
+import {
+ SegmentedSelectionMotion,
+ layerVariable,
+ type Layer,
+} from './useSegmentedSelectionMotion';
+
+interface Geometry {
+ left: number;
+ width: number;
+}
+
+// The track sits at (10, 20) in the viewport; segments are 27 px tall, 2 px
+// below its padding edge. Unequal widths, like a hug layout.
+const TRACK = {left: 10, top: 20, width: 306, height: 31};
+const SEGMENTS: Record<string, Geometry> = {
+ grid: {left: 12, width: 96},
+ list: {left: 108, width: 100},
+ table: {left: 208, width: 106},
+};
+
+function rect(left: number, top: number, width: number, height: number) {
+ return {
+ left,
+ top,
+ width,
+ height,
+ right: left + width,
+ bottom: top + height,
+ x: left,
+ y: top,
+ toJSON: () => ({}),
+ } as DOMRect;
+}
+
+let clock = 0;
+let reduceMotion = false;
+
+/**
+ * The person's settings, through `matchMedia` as the animator reads them.
+ * No option overrides them. Reduce Motion follows `reduceMotion` at each
+ * read, and `coarse` says whether the primary pointer is coarse.
+ */
+function stubMedia(coarse: boolean): void {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: query.includes('prefers-reduced-motion')
+ ? reduceMotion
+ : query.includes('pointer: coarse')
+ ? coarse
+ : false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }));
+}
+
+function setup(selected: string, {coarse = true}: {coarse?: boolean} = {}) {
+ stubMedia(coarse);
+ const track = document.createElement('div');
+ track.getBoundingClientRect = () =>
+ rect(TRACK.left, TRACK.top, TRACK.width, TRACK.height);
+ Object.defineProperty(track, 'offsetWidth', {
+ value: TRACK.width,
+ configurable: true,
+ });
+ const segments: Record<string, HTMLElement> = {};
+ for (const [value, geometry] of Object.entries(SEGMENTS)) {
+ const segment = document.createElement('button');
+ segment.setAttribute('role', 'radio');
+ segment.dataset.value = value;
+ segment.getBoundingClientRect = () =>
+ rect(geometry.left, TRACK.top + 2, geometry.width, 27);
+ const title = document.createElement('span');
+ title.setAttribute('data-astryx-segment-title', '');
+ title.textContent = value;
+ segment.append(title);
+ track.append(segment);
+ segments[value] = segment;
+ }
+ const style = document.createElement('style');
+ style.textContent = STYLES;
+ document.head.append(style);
+ document.body.append(track);
+ // A finger by default: Reduced Motion fades (design:reduced-motion DR2).
+ const animator: Animator = createAnimator(null, {
+ now: () => clock,
+ pseudoElement: '::before',
+ });
+ // The ::after: the lifted lens's shadow, or the surface fading out.
+ const afterAnimator: Animator = createAnimator(null, {
+ now: () => clock,
+ pseudoElement: '::after',
+ initial: {opacity: 0},
+ });
+ const motion = new SegmentedSelectionMotion(animator, {
+ now: () => clock,
+ afterAnimator,
+ });
+ motion.attachTrack(track);
+ paint(segments, selected);
+ /** A custom property of one of the radiogroup's pseudo-element layers. */
+ const layer = (name: Layer, property: string) =>
+ track.style.getPropertyValue(layerVariable(name, property));
+ return {
+ track,
+ segments,
+ animator,
+ leavingAnimator: afterAnimator,
+ motion,
+ layer,
+ };
+}
+
+type Ctx = ReturnType<typeof setup>;
+
+/** The segment the touch tracking resolves for a finger at `clientX`. */
+function targetAt(ctx: Ctx, clientX: number): HTMLElement | null {
+ return segmentTargetAt(clientX, measureSegments(ctx.track));
+}
+
+/** A finger lands at `clientX` (the tracker's begin, then the motion's). */
+function begin(ctx: Ctx, clientX: number, isFinger = true): void {
+ ctx.motion.begin(ctx.track, targetAt(ctx, clientX), isFinger);
+}
+
+/** A finger lands at `clientX`. */
+function press(ctx: Ctx, clientX: number): void {
+ begin(ctx, clientX);
+}
+
+/** The finger moves to `clientX`: a lens it holds chases it. */
+function drag(ctx: Ctx, clientX: number): void {
+ ctx.motion.drag(clientX);
+}
+
+/** The finger lets go at `clientX`, on the segment the tracker resolves. */
+function release(ctx: Ctx, clientX: number): string | null {
+ return ctx.motion.release(targetAt(ctx, clientX));
+}
+
+/**
+ * The component's styles, as a stylesheet: the selected segment paints the
+ * raised surface, and each title's rendering follows its segment's state.
+ * (A stylesheet and not inline styles: the controller hides and restores the
+ * surface inline, exactly as it does over the real component's classes.)
+ */
+const STYLES = `
+ [role="radio"] { border-top-left-radius: 6px; }
+ [role="radio"][aria-checked="true"] {
+ background-color: rgb(255, 255, 255);
+ box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 2px;
+ }
+ [role="radio"][aria-checked="false"] [data-astryx-segment-title] {
+ color: rgb(110, 110, 110);
+ font-weight: 500;
+ }
+ [role="radio"][aria-checked="true"] [data-astryx-segment-title] {
+ color: rgb(10, 10, 10);
+ font-weight: 600;
+ }
+ [role="radio"][aria-disabled="true"] [data-astryx-segment-title] {
+ color: rgb(200, 200, 200);
+ }
+`;
+
+/** What a selection does to the DOM: the checked state moves. */
+function paint(segments: Record<string, HTMLElement>, selected: string) {
+ for (const [value, segment] of Object.entries(segments)) {
+ segment.setAttribute('aria-checked', String(value === selected));
+ }
+}
+
+function select(ctx: ReturnType<typeof setup>, from: string, to: string): void {
+ paint(ctx.segments, to);
+ ctx.motion.select(ctx.track, from, to);
+}
+
+/** A segment's center in the track's padding-box coordinates. */
+const centerOf = (value: string) =>
+ SEGMENTS[value].left - TRACK.left + SEGMENTS[value].width / 2;
+
+/** The lens carries this segment's surface: hidden on the segment, inline. */
+function expectHidden(segment: HTMLElement): void {
+ expect(segment.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+}
+
+/** The segment paints its own surface again: nothing inline, the stylesheet's paint. */
+/** No inline surface override is left on the segment. */
+function expectNoOverride(segment: HTMLElement): void {
+ expect(segment.style.getPropertyValue('background-color')).toBe('');
+ expect(segment.style.getPropertyValue('background-image')).toBe('');
+ expect(segment.style.getPropertyValue('box-shadow')).toBe('');
+}
+
+function expectOwnSurface(segment: HTMLElement): void {
+ expect(segment.style.getPropertyValue('background-color')).toBe('');
+ expect(segment.style.getPropertyValue('box-shadow')).toBe('');
+ expect(getComputedStyle(segment).backgroundColor).toBe('rgb(255, 255, 255)');
+}
+
+beforeEach(() => {
+ clock = 1000;
+ reduceMotion = false;
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ document.head.innerHTML = '';
+});
+
+async function advance(ms: number): Promise<void> {
+ clock += ms;
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
+describe('the motion roles (spec:AST-094 FR4)', () => {
+ it('plays the slide through its internal segmented role', () => {
+ setup('grid');
+ expect(motionRoleOf(segmentedControl.selectionSpring)?.id).toBe(
+ 'segmented.selectionSpring',
+ );
+ });
+});
+
+describe('the selection slide', () => {
+ it('paints the lens (the radiogroup’s ::before) with the selected surface and hides it on the segment: no element is added', () => {
+ const ctx = setup('grid');
+ const elements = ctx.track.querySelectorAll('*').length;
+ select(ctx, 'grid', 'table');
+ const {layer, segments} = ctx;
+ expect(ctx.track.querySelectorAll('*').length).toBe(elements);
+ expect(layer('lens', 'visibility')).toBe('visible');
+ expect(layer('lens', 'background-color')).toBe('rgb(255, 255, 255)');
+ expect(layer('lens', 'box-shadow')).toBe('rgba(0, 0, 0, 0.1) 0px 1px 2px');
+ expect(layer('lens', 'border-top-left-radius')).toBe('6px');
+ // Inline and with priority, so a theme's rule cannot paint a second one.
+ expect(segments.table.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+ expect(segments.table.style.getPropertyPriority('background-color')).toBe(
+ 'important',
+ );
+ expect(segments.table.style.getPropertyValue('box-shadow')).toBe('none');
+ // The lens is laid out on the destination's box.
+ expect(layer('lens', 'left')).toBe('198px');
+ expect(layer('lens', 'width')).toBe('106px');
+ expect(layer('lens', 'height')).toBe('27px');
+ expect(layer('lens', 'top')).toBe('2px');
+ });
+
+ it('hands the surface back to the segment when it lands', async () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ expect(ctx.motion.isSliding).toBe(true);
+ await advance(400);
+ expect(ctx.motion.isSliding).toBe(true);
+ await advance(2000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('the hand-back restores a segment’s own inline surface (its `style`)', async () => {
+ const ctx = setup('grid');
+ const {table, list} = ctx.segments;
+ table.style.setProperty('background-color', 'gold', 'important');
+ table.style.setProperty('border-top-color', 'red');
+ select(ctx, 'grid', 'table');
+ // Hidden while the lens carries the surface...
+ expect(table.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+ await advance(2400);
+ expect(ctx.motion.isSliding).toBe(false);
+ // ...then the segment's own declarations come back, priority included,
+ // and nothing it did not have is left behind.
+ expect(table.style.getPropertyValue('background-color')).toBe('gold');
+ expect(table.style.getPropertyPriority('background-color')).toBe(
+ 'important',
+ );
+ expect(table.style.getPropertyValue('border-top-color')).toBe('red');
+ expect(table.style.getPropertyPriority('border-top-color')).toBe('');
+ expect(table.style.getPropertyValue('background-image')).toBe('');
+ expect(table.style.getPropertyValue('box-shadow')).toBe('');
+ // A segment the slide never hid keeps its inline surface too.
+ list.style.setProperty('background-color', 'teal');
+ select(ctx, 'table', 'grid');
+ ctx.motion.settle();
+ expect(list.style.getPropertyValue('background-color')).toBe('teal');
+ });
+
+ it('a change mid-flight starts from what is on screen and keeps its velocity', async () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ await advance(80);
+ // The lens scales around its center: x is the center's offset from the
+ // destination's center.
+ const centerBefore = centerOf('table') + ctx.animator.get('x');
+ const vBefore = ctx.animator.getVelocity('x');
+ const widthBefore = ctx.animator.get('scaleX') * 106;
+ expect(vBefore).toBeGreaterThan(500);
+ select(ctx, 'table', 'list');
+ // No jump and no lost velocity at the retarget.
+ expect(centerOf('list') + ctx.animator.get('x')).toBeCloseTo(
+ centerBefore,
+ 6,
+ );
+ expect(ctx.animator.getVelocity('x')).toBeCloseTo(vBefore, 3);
+ expect(ctx.animator.get('scaleX') * 100).toBeCloseTo(widthBefore, 6);
+ // The lens now carries the new destination's surface and size. The
+ // abandoned destination paints nothing of its own until the lens lands:
+ // its tap may still be fading, and that paint would cover the lens.
+ expect(ctx.layer('lens', 'width')).toBe('100px');
+ expect(ctx.segments.table.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+ expect(ctx.segments.table.style.getPropertyValue('background-image')).toBe(
+ 'none',
+ );
+ expect(ctx.segments.list.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.list);
+ expectNoOverride(ctx.segments.table);
+ });
+
+ it('a change back to the abandoned segment takes it as the destination again', async () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ await advance(80);
+ select(ctx, 'table', 'list');
+ await advance(40);
+ select(ctx, 'list', 'table');
+ expect(ctx.segments.table.style.getPropertyValue('background-color')).toBe(
+ 'transparent',
+ );
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ expectNoOverride(ctx.segments.list);
+ });
+
+ it('settle() hands the surface back at once (resize, unmount, presentation change)', () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'list');
+ ctx.motion.settle();
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ expectOwnSurface(ctx.segments.list);
+ });
+
+ it('stop() ends a slide and leaves the controller usable (StrictMode remounts)', () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ ctx.motion.stop();
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ // The next change still slides, on the same lens.
+ select(ctx, 'table', 'list');
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.layer('lens', 'visibility')).toBe('visible');
+ expect(ctx.animator.get('x', clock)).toBeCloseTo(
+ centerOf('table') - centerOf('list'),
+ 6,
+ );
+ });
+
+ it('does not slide when nothing was selected, and settles when the selection clears', () => {
+ const ctx = setup('none');
+ select(ctx, 'none', 'list');
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ select(ctx, 'list', 'grid');
+ expect(ctx.motion.isSliding).toBe(true);
+ select(ctx, 'grid', 'none');
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.segments.grid.style.getPropertyValue('background-color')).toBe(
+ '',
+ );
+ });
+
+ it('does not slide a control that is not laid out', () => {
+ const ctx = setup('grid');
+ ctx.segments.table.getBoundingClientRect = () => rect(0, 0, 0, 0);
+ select(ctx, 'grid', 'table');
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('undoes an ancestor scale: boxes are measured in the track’s own pixels', () => {
+ const ctx = setup('grid');
+ // Rendered at 2x by a transformed ancestor: client rects double.
+ ctx.track.getBoundingClientRect = () =>
+ rect(TRACK.left, TRACK.top, TRACK.width * 2, TRACK.height * 2);
+ for (const [value, geometry] of Object.entries(SEGMENTS)) {
+ ctx.segments[value].getBoundingClientRect = () =>
+ rect(
+ TRACK.left + (geometry.left - TRACK.left) * 2,
+ TRACK.top + 4,
+ geometry.width * 2,
+ 54,
+ );
+ }
+ select(ctx, 'grid', 'table');
+ expect(ctx.layer('lens', 'width')).toBe('106px');
+ expect(ctx.animator.get('x', 5000)).toBeCloseTo(0, 6);
+ });
+
+ it('Reduced Motion (design:reduced-motion): no travel, no scale; the old surface fades out where it is as the new one fades in, in 200 ms or less', async () => {
+ reduceMotion = true;
+ const ctx = setup('grid');
+ const start = clock;
+ select(ctx, 'grid', 'table');
+ expect(ctx.layer('lens', 'width')).toBe('106px');
+ expectHidden(ctx.segments.table);
+ expectReducedMotionCrossFade(ctx, start, 'grid');
+ await advance(1000);
+ expect(isLeaving(ctx)).toBe(false);
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('Reduced Motion with any other pointer: a change completes at once, with no fade and no leaving surface (DR3)', () => {
+ reduceMotion = true;
+ const ctx = setup('grid', {coarse: false});
+ select(ctx, 'grid', 'table');
+ expect(isLeaving(ctx)).toBe(false);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.animator.get('opacity')).toBe(1);
+ expect(ctx.animator.get('scaleX')).toBe(1);
+ });
+
+ it('Reduced Motion off again: the next change slides at full size and opacity', async () => {
+ reduceMotion = true;
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ await advance(50);
+ // Turned off mid-fade: the next change travels, opaque and unscaled.
+ reduceMotion = false;
+ ctx.motion.settle();
+ select(ctx, 'table', 'list');
+ expect(ctx.animator.get('opacity')).toBe(1);
+ expect(ctx.animator.get('scaleY')).toBe(1);
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.motion.isSliding).toBe(false);
+ });
+});
+
+/**
+ * Under Reduced Motion the ::after shows the surface that fades out where it
+ * is: painted with a surface (the lifted lens's shadow has no fill).
+ */
+const isLeaving = (ctx: ReturnType<typeof setup>) =>
+ ctx.layer('after', 'visibility') === 'visible' &&
+ ctx.layer('after', 'background-color') !== '';
+
+/** When `get` stops changing: the end of the fade, in ms after `start`. */
+function endOf(get: (t: number) => number, start: number): number {
+ const last = get(start + 5000);
+ for (let t = 0; t <= 5000; t += 1) {
+ if (Math.abs(get(start + t) - last) < 1e-6) {
+ return t;
+ }
+ }
+ return Infinity;
+}
+
+/**
+ * The Reduce Motion cross-fade from `start` (design:reduced-motion DR1, DR2).
+ * The lens fades in on its new segment, full size, and never moves. A copy of
+ * the surface fades out where `leavingFrom` rests, on the same clock. It ends
+ * in 200 ms or less.
+ */
+function expectReducedMotionCrossFade(
+ ctx: ReturnType<typeof setup>,
+ start: number,
+ leavingFrom: string | {left: number; width: number},
+): void {
+ const leaving =
+ typeof leavingFrom === 'string'
+ ? {
+ left: SEGMENTS[leavingFrom].left - TRACK.left,
+ width: SEGMENTS[leavingFrom].width,
+ }
+ : leavingFrom;
+ const entering = (t: number) => ctx.animator.get('opacity', t);
+ const fadeIn = endOf(entering, start);
+ expect(fadeIn).toBeGreaterThan(0);
+ expect(fadeIn).toBeLessThanOrEqual(200);
+ expect(entering(start)).toBeCloseTo(0, 6);
+ expect(entering(start + fadeIn)).toBeCloseTo(1, 6);
+ for (let t = 0; t <= fadeIn; t += 10) {
+ expect(ctx.animator.get('x', start + t)).toBe(0);
+ expect(ctx.animator.get('scaleX', start + t)).toBe(1);
+ expect(ctx.animator.get('scaleY', start + t)).toBe(1);
+ }
+ // The ::after, painted with the selected surface where it rested; no
+ // element is added for it.
+ expect(isLeaving(ctx)).toBe(true);
+ expect(ctx.layer('after', 'background-color')).toBe('rgb(255, 255, 255)');
+ expect(ctx.layer('after', 'left')).toBe(`${leaving.left}px`);
+ expect(ctx.layer('after', 'width')).toBe(`${leaving.width}px`);
+ expect(ctx.track.querySelectorAll('*').length).toBe(6);
+ const leavingOpacity = (t: number) => ctx.leavingAnimator.get('opacity', t);
+ expect(leavingOpacity(start)).toBeCloseTo(1, 6);
+ expect(endOf(leavingOpacity, start)).toBe(fadeIn);
+ for (let t = 0; t < fadeIn; t += 10) {
+ expect(ctx.leavingAnimator.get('x', start + t)).toBe(0);
+ expect(entering(start + t) + leavingOpacity(start + t)).toBeCloseTo(1, 6);
+ }
+}
+
+/** Client x of a segment's center (the track starts at client x 10). */
+const clientCenterOf = (value: string) =>
+ SEGMENTS[value].left + SEGMENTS[value].width / 2;
+
+/** One step of the style traffic `recordStyleTraffic` records. */
+type StyleEvent =
+ | {kind: 'take'; style: CSSStyleDeclaration}
+ | {kind: 'read'; style: CSSStyleDeclaration}
+ | {kind: 'write'};
+
+describe('style reads at a change', () => {
+ /**
+ * Records, in order, each computed-style declaration taken, every value
+ * read from one, and every write to the track's inline style. A read from
+ * a declaration after a write to the track since it was taken makes the
+ * browser recompute style for it (a forced restyle).
+ */
+ function recordStyleTraffic(track: HTMLElement) {
+ const events: StyleEvent[] = [];
+ const realGetComputedStyle = window.getComputedStyle.bind(window);
+ vi.stubGlobal(
+ 'getComputedStyle',
+ (
+ element: Element,
+ pseudoElement?: string | null,
+ ): CSSStyleDeclaration => {
+ const style = realGetComputedStyle(element, pseudoElement);
+ events.push({kind: 'take', style});
+ const readValue = (name: string): string => {
+ events.push({kind: 'read', style});
+ return style.getPropertyValue(name);
+ };
+ return new Proxy(style, {
+ // `getPropertyValue` and a property (`style.opacity`) both read.
+ get(target, key): string | ((name: string) => string) | undefined {
+ if (key === 'getPropertyValue') {
+ return readValue;
+ }
+ if (typeof key !== 'string') {
+ return undefined;
+ }
+ events.push({kind: 'read', style: target});
+ const value = Reflect.get(target, key, target) as unknown;
+ return typeof value === 'string' ? value : undefined;
+ },
+ });
+ },
+ );
+ const setProperty = track.style.setProperty.bind(track.style);
+ track.style.setProperty = (
+ name: string,
+ value: string | null,
+ priority?: string,
+ ) => {
+ events.push({kind: 'write'});
+ setProperty(name, value, priority);
+ };
+ /** Reads that follow a track write made after their declaration was taken. */
+ return () => {
+ const takenAt = new Map<CSSStyleDeclaration, number>();
+ let reads = 0;
+ let forced = 0;
+ events.forEach((event, index) => {
+ if (event.kind === 'take') {
+ takenAt.set(event.style, index);
+ } else if (event.kind === 'read') {
+ reads += 1;
+ const from = takenAt.get(event.style) ?? 0;
+ if (events.slice(from, index).some(e => e.kind === 'write')) {
+ forced += 1;
+ }
+ }
+ });
+ return {reads, forced};
+ };
+ }
+
+ it('reads a segment’s whole surface before writing any of it to the track: no read follows a write, so a change restyles once, not once per property', () => {
+ reduceMotion = true;
+ const ctx = setup('grid');
+ const traffic = recordStyleTraffic(ctx.track);
+ // Under Reduce Motion a change paints both layers: the lens and the
+ // surface leaving.
+ select(ctx, 'grid', 'table');
+ const {reads, forced} = traffic();
+ expect(reads).toBeGreaterThan(0);
+ expect(forced).toBe(0);
+ expect(ctx.layer('lens', 'background-color')).toBe('rgb(255, 255, 255)');
+ expect(ctx.layer('after', 'background-color')).toBe('rgb(255, 255, 255)');
+ });
+
+ it('a finger’s drag and its lift read before they write: no read follows a write, with or without Reduce Motion', () => {
+ for (const reduced of [false, true]) {
+ reduceMotion = reduced;
+ const ctx = setup('grid');
+ const traffic = recordStyleTraffic(ctx.track);
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ drag(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ select(ctx, 'grid', 'table');
+ const {reads, forced} = traffic();
+ expect(reads).toBeGreaterThan(0);
+ expect({reduced, forced}).toEqual({reduced, forced: 0});
+ vi.unstubAllGlobals();
+ document.body.innerHTML = '';
+ document.head.innerHTML = '';
+ }
+ });
+});
+
+describe('under a finger', () => {
+ it('landing on the selected segment lifts nothing by default (the pressed-thumb lift is a theme’s): the lens and the ::after stay hidden', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ await advance(600);
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ expect(ctx.layer('after', 'visibility')).toBe('');
+ expectOwnSurface(ctx.segments.grid);
+ });
+
+ it('a drag holds the lens at its resting size until the finger lets go, then it settles back and hands back', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('grid') + 10);
+ await advance(2000);
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6);
+ expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6);
+ expect(release(ctx, clientCenterOf('grid'))).toBeNull();
+ await advance(2000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ });
+
+ it('landing on another segment leaves the lens alone', () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ drag(ctx, clientCenterOf('list'));
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ });
+
+ it('a commit that is not adopted (vetoed, or kept by the parent) sends the lens back, and the next change to that value still slides', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ // The commit's click ran (nobody vetoed it); the value has not come back.
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ await advance(60);
+ expect(ctx.motion.isSliding).toBe(true);
+ // Grid stays selected.
+ ctx.motion.decline(ctx.track, 'table');
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ // A later change to Table slides from Grid: the declined commit is gone.
+ select(ctx, 'grid', 'table');
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.layer('lens', 'visibility')).toBe('visible');
+ expect(ctx.animator.get('x', clock)).toBeCloseTo(
+ centerOf('grid') - centerOf('table'),
+ 6,
+ );
+ });
+
+ it('a click the item vetoes sends the lens back at once', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ await advance(60);
+ ctx.motion.clicked(ctx.track, 'table', true);
+ // Bound for Grid again, from where it is.
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ expectNoOverride(ctx.segments.table);
+ });
+
+ it('a parent that adopts the value 200 ms later: no bounce, the lens keeps going and lands there', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ // The click was not vetoed; the value has not come back yet (the lens
+ // sets off once the click's event is over).
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ // Every frame until the parent adopts it heads for Table, never back.
+ let center = centerOf('table') + ctx.animator.get('x');
+ for (let t = 0; t < 200; t += 16) {
+ await advance(16);
+ const next = centerOf('table') + ctx.animator.get('x');
+ expect(next).toBeGreaterThanOrEqual(center - 1e-6);
+ center = next;
+ }
+ select(ctx, 'grid', 'table');
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ expectNoOverride(ctx.segments.grid);
+ });
+
+ it('a value that never comes back: the lens goes back once its slide settles, the bound being the slide itself', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ release(ctx, clientCenterOf('table'));
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ // Mid-slide it still waits.
+ await advance(300);
+ expect(centerOf('table') + ctx.animator.get('x')).toBeGreaterThan(
+ centerOf('list'),
+ );
+ await advance(6000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ expectNoOverride(ctx.segments.table);
+ });
+
+ it('the commit re-aims the lens at the destination’s box as it is once the new value shows (the titles’ weights move the segments)', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ // The commit's titles take their new weights: Table grows 4 px.
+ ctx.segments.table.getBoundingClientRect = () =>
+ rect(206, TRACK.top + 2, 110, 27);
+ select(ctx, 'grid', 'table');
+ expect(ctx.layer('lens', 'width')).toBe('110px');
+ expect(ctx.layer('lens', 'left')).toBe('196px');
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.animator.get('scaleX')).toBe(1);
+ expect(ctx.motion.isSliding).toBe(false);
+ });
+
+ it('a resize while a finger holds the lens (the selected face reflows the titles) keeps it held', async () => {
+ const ctx = setup('grid');
+ let width = TRACK.width;
+ Object.defineProperty(ctx.track, 'offsetWidth', {get: () => width});
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ width += 3;
+ ctx.motion.resized(ctx.track);
+ expect(ctx.motion.isSliding).toBe(true);
+ await advance(1000);
+ expect(ctx.motion.isSliding).toBe(true);
+ });
+
+ it('a drag carries the lens on the shared finger-tracking role, no further than 11 pt past the end segments', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ const chase = solveSpring(toSpring(springs.fingerTracking), {
+ from: 0,
+ to: centerOf('list') - centerOf('grid'),
+ velocity: 0,
+ });
+ expect(ctx.animator.get('x', 1050)).toBeCloseTo(chase.value(0.05), 6);
+ await advance(1000);
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('list') - centerOf('grid'),
+ 6,
+ );
+ // Far past the last segment: clamped.
+ drag(ctx, 500);
+ await advance(1000);
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('table') + segmentedControl.dragOvershoot - centerOf('grid'),
+ 6,
+ );
+ // At its resting size throughout: nothing lifts it.
+ expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6);
+ expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6);
+ });
+
+ it('letting go commits the segment nearest the finger: 40 % of the way stays, 60 % moves', async () => {
+ const forty = setup('grid');
+ const at = (p: number) =>
+ clientCenterOf('grid') +
+ (clientCenterOf('list') - clientCenterOf('grid')) * p;
+ press(forty, clientCenterOf('grid'));
+ drag(forty, at(0.4));
+ await advance(500);
+ expect(release(forty, at(0.4))).toBeNull();
+ await advance(3000);
+ expect(forty.animator.get('x')).toBe(0);
+ expect(forty.motion.isSliding).toBe(false);
+ expectOwnSurface(forty.segments.grid);
+ document.body.innerHTML = '';
+ document.head.innerHTML = '';
+
+ const sixty = setup('grid');
+ press(sixty, clientCenterOf('grid'));
+ drag(sixty, at(0.6));
+ await advance(500);
+ const centerAtLift = centerOf('grid') + sixty.animator.get('x');
+ expect(release(sixty, at(0.6))).toBe('list');
+ // Until the new value comes back, the old selection's paint is carried.
+ expectHidden(sixty.segments.grid);
+ // The commit shows List synchronously, through the segment's click. The
+ // lens re-bases onto List without a jump. Then it springs there on the
+ // slide spring and comes down on the lift spring, painted by List.
+ select(sixty, 'grid', 'list');
+ expect(centerOf('list') + sixty.animator.get('x')).toBeCloseTo(
+ centerAtLift,
+ 6,
+ );
+ expect(sixty.layer('lens', 'width')).toBe('100px');
+ expectHidden(sixty.segments.list);
+ expect(sixty.segments.grid.style.getPropertyValue('background-color')).toBe(
+ '',
+ );
+ await advance(3000);
+ expect(sixty.animator.get('x')).toBe(0);
+ expect(sixty.animator.get('scaleX')).toBe(1);
+ expect(sixty.motion.isSliding).toBe(false);
+ expectOwnSurface(sixty.segments.list);
+ });
+
+ it('a tap on another segment slides there on the slide spring, at its resting size', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ select(ctx, 'grid', 'table');
+ const travel = solveSpring(toSpring(segmentedControl.selectionSpring), {
+ from: centerOf('grid') - centerOf('table'),
+ to: 0,
+ velocity: 0,
+ });
+ expect(ctx.animator.get('x', 1100)).toBeCloseTo(travel.value(0.1), 6);
+ // Nothing lifts it on the way: Grid's width grows to Table's on the
+ // same spring, and no further.
+ for (let t = 0; t <= 800; t += 20) {
+ expect(ctx.animator.get('scaleY', 1000 + t)).toBeCloseTo(1, 6);
+ expect(ctx.animator.get('scaleX', 1000 + t)).toBeLessThan(1.02);
+ }
+ await advance(2000);
+ expect(ctx.animator.get('scaleX')).toBe(1);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('a cancelled touch puts the lens back', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('table'));
+ await advance(200);
+ ctx.motion.cancel();
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBe(0);
+ expect(ctx.animator.get('scaleX')).toBe(1);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ });
+
+ it('the lens is bound only once a drag from the selected segment moves it', async () => {
+ const ctx = setup('grid');
+ begin(ctx, clientCenterOf('grid'));
+ expect(ctx.motion.isSliding).toBe(false);
+ drag(ctx, clientCenterOf('list'));
+ expect(ctx.motion.isSliding).toBe(true);
+ await advance(1000);
+ expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6);
+ expect(ctx.layer('after', 'visibility')).toBe('');
+ expect(release(ctx, clientCenterOf('list'))).toBe('list');
+ });
+
+ it('a press cancelled before it drags leaves everything as it was', () => {
+ const ctx = setup('grid');
+ begin(ctx, clientCenterOf('grid'));
+ ctx.motion.cancel();
+ expect(ctx.motion.isSliding).toBe(false);
+ drag(ctx, clientCenterOf('list'));
+ expect(ctx.motion.isSliding).toBe(false);
+ });
+
+ it('never commits a disabled segment', () => {
+ const ctx = setup('grid');
+ ctx.segments.table.setAttribute('aria-disabled', 'true');
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBeNull();
+ });
+
+ it('Reduced Motion: the lens still follows the finger, as direct movement, with no lift or chase; the lift commits and the selection cross-fades there, on any pointer (a touch release, DR2)', async () => {
+ reduceMotion = true;
+ // A fine primary pointer: the touch release still fades.
+ const ctx = setup('grid', {coarse: false});
+ press(ctx, clientCenterOf('grid'));
+ expect(ctx.motion.isSliding).toBe(false);
+ // The lens is where the finger is, at once: no spring chases it.
+ drag(ctx, clientCenterOf('list'));
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('list') - centerOf('grid'),
+ 6,
+ );
+ drag(ctx, clientCenterOf('table'));
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('table') - centerOf('grid'),
+ 6,
+ );
+ expect(ctx.animator.get('scaleX')).toBe(1);
+ expectHidden(ctx.segments.grid);
+ // The segment under the finger at the lift is committed...
+ const start = clock;
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ select(ctx, 'grid', 'table');
+ // ...and the selection cross-fades there, from where the lens was.
+ expect(ctx.layer('lens', 'width')).toBe('106px');
+ expectReducedMotionCrossFade(ctx, start, {
+ left: centerOf('table') - SEGMENTS.grid.width / 2,
+ width: SEGMENTS.grid.width,
+ });
+ expectHidden(ctx.segments.table);
+ await advance(1000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('Reduced Motion: a hold and a lift on the selected segment change nothing', () => {
+ reduceMotion = true;
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ expect(release(ctx, clientCenterOf('grid'))).toBeNull();
+ expect(ctx.motion.isSliding).toBe(false);
+ });
+});
+
+describe('under a mouse or a pen (spec:AST-094 FR43)', () => {
+ /**
+ * A fine primary pointer: the touch presentation is off (a change keeps the
+ * theme's transition), and press tracking is on, as for every pointer.
+ */
+ function setupFine(selected: string) {
+ const ctx = setup(selected, {coarse: false});
+ ctx.motion.present(false);
+ return ctx;
+ }
+
+ /** A theme's segment transition: 200 ms, linear. */
+ function themeTiming(ctx: ReturnType<typeof setup>): void {
+ for (const segment of Object.values(ctx.segments)) {
+ segment.style.setProperty('transition-duration', '200ms');
+ segment.style.setProperty('transition-timing-function', 'linear');
+ }
+ }
+
+ /**
+ * The lens slides from `from`'s box to `to`'s on the theme's 200 ms linear
+ * timing, with the segments' own transitions off, then hands back.
+ */
+ async function expectThemedSlide(
+ ctx: ReturnType<typeof setup>,
+ from: string,
+ to: string,
+ ): Promise<void> {
+ const start = centerOf(from) - centerOf(to);
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.animator.get('x')).toBeCloseTo(start, 6);
+ expectHidden(ctx.segments[to]);
+ for (const segment of Object.values(ctx.segments)) {
+ expect(segment.style.getPropertyValue('transition-property')).toBe(
+ 'none',
+ );
+ }
+ await advance(100);
+ const halfway = ctx.animator.get('x');
+ expect(Math.abs(halfway)).toBeGreaterThan(0);
+ expect(Math.abs(halfway)).toBeLessThan(Math.abs(start));
+ await advance(3000);
+ expect(ctx.animator.get('x')).toBeCloseTo(0, 6);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments[to]);
+ }
+
+ it('a change from a key or a new value slides the lens on the theme’s duration and easing, as every change does, then hands the surface back', async () => {
+ const ctx = setupFine('grid');
+ themeTiming(ctx);
+ select(ctx, 'grid', 'table');
+ await expectThemedSlide(ctx, 'grid', 'table');
+ });
+
+ it('a click on another segment slides the lens there from the selection, on the theme’s timing, once its click commits', async () => {
+ const ctx = setupFine('grid');
+ themeTiming(ctx);
+ press(ctx, clientCenterOf('table'));
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ select(ctx, 'grid', 'table');
+ await expectThemedSlide(ctx, 'grid', 'table');
+ });
+
+ it('a drag from the selected segment carries the lens on the pointer itself, written at each move, at its resting size and no further than 11 pt past the end segments', () => {
+ const ctx = setupFine('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ expect(ctx.motion.isSliding).toBe(true);
+ // Where the pointer is, at once: a pointer that holds the lens times it.
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('list') - centerOf('grid'),
+ 6,
+ );
+ expect(ctx.animator.get('scaleX')).toBeCloseTo(1, 6);
+ expect(ctx.animator.get('scaleY')).toBeCloseTo(1, 6);
+ drag(ctx, 500);
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('table') + segmentedControl.dragOvershoot - centerOf('grid'),
+ 6,
+ );
+ });
+
+ it('the lift commits the segment nearest the pointer; the lens settles there on the theme’s duration and easing, read from the segment’s own transition, and hands back', async () => {
+ const ctx = setupFine('grid');
+ for (const segment of Object.values(ctx.segments)) {
+ segment.style.setProperty('transition-duration', '175ms');
+ segment.style.setProperty(
+ 'transition-timing-function',
+ 'cubic-bezier(0.24, 1, 0.4, 1)',
+ );
+ }
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('table') - 5);
+ expect(release(ctx, clientCenterOf('table') - 5)).toBe('table');
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ select(ctx, 'grid', 'table');
+ const ease = cubicBezier([0.24, 1, 0.4, 1]);
+ expect(ctx.animator.get('x', 1100)).toBeCloseTo(
+ -5 + 5 * ease(100 / 175),
+ 4,
+ );
+ expect(ctx.animator.get('x', 1175)).toBeCloseTo(0, 6);
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('under a fine pointer the settle follows a theme’s own duration and easing', async () => {
+ const slow = setupFine('grid');
+ for (const segment of Object.values(slow.segments)) {
+ segment.style.setProperty('transition-duration', '0.4s, 0.4s');
+ segment.style.setProperty('transition-timing-function', 'linear, ease');
+ }
+ press(slow, clientCenterOf('grid'));
+ drag(slow, clientCenterOf('table') - 8);
+ expect(release(slow, clientCenterOf('table') - 8)).toBe('table');
+ slow.motion.clicked(slow.track, 'table', false);
+ await Promise.resolve();
+ select(slow, 'grid', 'table');
+ expect(slow.animator.get('x', 1200)).toBeCloseTo(-4, 4);
+ await advance(3000);
+ expect(slow.motion.isSliding).toBe(false);
+ });
+
+ it('under a fine pointer a theme with no segment transition lands the lens at once', async () => {
+ const none = setupFine('grid');
+ for (const segment of Object.values(none.segments)) {
+ segment.style.setProperty('transition-duration', '0s');
+ }
+ press(none, clientCenterOf('grid'));
+ drag(none, clientCenterOf('table') - 8);
+ expect(release(none, clientCenterOf('table') - 8)).toBe('table');
+ none.motion.clicked(none.track, 'table', false);
+ await Promise.resolve();
+ select(none, 'grid', 'table');
+ expect(none.animator.get('x', 1002)).toBeCloseTo(0, 6);
+ });
+
+ it('a drag that starts on another segment carries nothing; the lift commits there, and the selection slides there on the theme’s timing', async () => {
+ const ctx = setupFine('grid');
+ themeTiming(ctx);
+ press(ctx, clientCenterOf('list'));
+ drag(ctx, clientCenterOf('table'));
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ select(ctx, 'grid', 'table');
+ await expectThemedSlide(ctx, 'grid', 'table');
+ });
+
+ it('while the lens is carried the segments’ own transitions are off, so the surface it borrows neither fades out nor back in; they come back once it has handed back', async () => {
+ const ctx = setupFine('grid');
+ ctx.segments.list.style.setProperty('transition-property', 'color');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ for (const segment of Object.values(ctx.segments)) {
+ expect(segment.style.getPropertyValue('transition-property')).toBe(
+ 'none',
+ );
+ }
+ expect(release(ctx, clientCenterOf('grid'))).toBeNull();
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.grid);
+ // Each segment's own inline value is back.
+ expect(
+ ctx.segments.grid.style.getPropertyValue('transition-property'),
+ ).toBe('');
+ expect(
+ ctx.segments.list.style.getPropertyValue('transition-property'),
+ ).toBe('color');
+ });
+
+ it('Reduced Motion: a mouse drag still carries the lens on the pointer, and its release lands it at once, with no fade (DR3)', async () => {
+ reduceMotion = true;
+ const ctx = setupFine('grid');
+ begin(ctx, clientCenterOf('grid'), false);
+ drag(ctx, clientCenterOf('table'));
+ expect(ctx.motion.isSliding).toBe(true);
+ expect(ctx.animator.get('x')).toBeCloseTo(
+ centerOf('table') - centerOf('grid'),
+ 6,
+ );
+ const start = clock;
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ select(ctx, 'grid', 'table');
+ // No fade: no leaving surface, and the lens is at rest and opaque.
+ expect(isLeaving(ctx)).toBe(false);
+ expect(ctx.animator.get('opacity', start)).toBeCloseTo(1, 6);
+ expect(ctx.animator.get('x', start)).toBeCloseTo(0, 6);
+ await advance(3000);
+ expect(ctx.motion.isSliding).toBe(false);
+ expectOwnSurface(ctx.segments.table);
+ });
+
+ it('Reduced Motion: a click and a key change move no lens; the theme’s transition shows them', async () => {
+ reduceMotion = true;
+ const ctx = setupFine('grid');
+ themeTiming(ctx);
+ press(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ ctx.motion.clicked(ctx.track, 'table', false);
+ await Promise.resolve();
+ select(ctx, 'grid', 'table');
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ expectNoOverride(ctx.segments.table);
+ select(ctx, 'table', 'list');
+ expect(ctx.motion.isSliding).toBe(false);
+ expect(ctx.layer('lens', 'visibility')).toBe('');
+ });
+
+ it('back under a finger (a touchscreen laptop flips its primary pointer), changes slide again', () => {
+ const ctx = setupFine('grid');
+ ctx.motion.present(true);
+ select(ctx, 'grid', 'table');
+ expect(ctx.motion.isSliding).toBe(true);
+ });
+});
+
+describe('the titles under a finger', () => {
+ interface Recorded {
+ element: HTMLElement;
+ keyframes: Keyframe[];
+ options: KeyframeAnimationOptions;
+ cancel: ReturnType<typeof vi.fn>;
+ }
+ let recorded: Recorded[] = [];
+ const realAnimate = HTMLElement.prototype.animate;
+
+ beforeEach(() => {
+ recorded = [];
+ HTMLElement.prototype.animate = function (
+ this: HTMLElement,
+ keyframes: Keyframe[] | PropertyIndexedKeyframes | null,
+ options?: number | KeyframeAnimationOptions,
+ ) {
+ const finished = new Promise<void>(() => {});
+ const cancel = vi.fn();
+ if (this.getAttribute('role') !== 'radio') {
+ return {finished, cancel, startTime: null} as unknown as Animation;
+ }
+ recorded.push({
+ element: this,
+ keyframes: keyframes as Keyframe[],
+ options: options as KeyframeAnimationOptions,
+ cancel,
+ });
+ return {finished, cancel} as unknown as Animation;
+ };
+ });
+
+ afterEach(() => {
+ HTMLElement.prototype.animate = realAnimate;
+ });
+
+ const titleOf = (segment: HTMLElement): HTMLElement => {
+ const title = segment.querySelector<HTMLElement>(
+ '[data-astryx-segment-title]',
+ );
+ if (title == null) {
+ throw new Error('no title');
+ }
+ return title;
+ };
+ // Any fade the controller plays on a segment (none: a press shows the
+ // shared overlay, and nothing dims).
+ const fadesOf = (segment: HTMLElement) =>
+ recorded.filter(r => r.element === segment);
+ const faceOf = (segment: HTMLElement) => ({
+ weight: titleOf(segment).style.fontWeight,
+ color: titleOf(segment).style.color,
+ });
+ const NO_FACE = {weight: '', color: ''};
+
+ it('a finger on an unselected segment dims nothing: no pressed state and no fade on it; the lens stays', () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('list'));
+ drag(ctx, clientCenterOf('table'));
+ for (const segment of Object.values(ctx.segments)) {
+ expect(segment.hasAttribute('data-pressed')).toBe(false);
+ expect(fadesOf(segment)).toEqual([]);
+ }
+ expect(ctx.motion.isSliding).toBe(false);
+ });
+
+ it('a tap on the selected segment dims nothing', () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ expect(release(ctx, clientCenterOf('grid'))).toBeNull();
+ expect(recorded).toHaveLength(0);
+ });
+
+ it('during a lifted drag the selected face follows the lens, as a colour only (no weight swap mid-drag)', async () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('list'));
+ // The lens lags the finger: the face waits for it.
+ expect(faceOf(ctx.segments.list)).toEqual(NO_FACE);
+ await advance(400);
+ expect(faceOf(ctx.segments.list)).toEqual({
+ weight: '',
+ color: 'rgb(10, 10, 10)',
+ });
+ expect(faceOf(ctx.segments.grid)).toEqual({
+ weight: '',
+ color: 'rgb(110, 110, 110)',
+ });
+ expect(faceOf(ctx.segments.table)).toEqual(NO_FACE);
+ expect(recorded).toHaveLength(0);
+ drag(ctx, clientCenterOf('table'));
+ await advance(400);
+ expect(faceOf(ctx.segments.table).color).toBe('rgb(10, 10, 10)');
+ expect(faceOf(ctx.segments.list)).toEqual(NO_FACE);
+ // The lift commits; the selection's own styles take over in its commit.
+ expect(release(ctx, clientCenterOf('table'))).toBe('table');
+ select(ctx, 'grid', 'table');
+ for (const segment of Object.values(ctx.segments)) {
+ expect(faceOf(segment)).toEqual(NO_FACE);
+ }
+ expect(recorded).toHaveLength(0);
+ });
+
+ it('the segment a lifted drag leaves wears an enabled segment’s unselected face, never a disabled one’s', async () => {
+ const ctx = setup('list');
+ // The first segment in DOM order is disabled: its title has its own colour.
+ ctx.segments.grid.setAttribute('aria-disabled', 'true');
+ press(ctx, clientCenterOf('list'));
+ drag(ctx, clientCenterOf('table'));
+ await advance(400);
+ expect(faceOf(ctx.segments.table).color).toBe('rgb(10, 10, 10)');
+ expect(faceOf(ctx.segments.list)).toEqual({
+ weight: '',
+ color: 'rgb(110, 110, 110)',
+ });
+ });
+
+ it('the face crosses a boundary only once the lens is a quarter segment past it, so a ±3 px dither changes it at most once', async () => {
+ const ctx = setup('grid');
+ const faced = () =>
+ Object.entries(ctx.segments).find(
+ ([, segment]) => faceOf(segment).color === 'rgb(10, 10, 10)',
+ )?.[0] ?? 'grid';
+ press(ctx, clientCenterOf('grid'));
+ // Grid | List boundary at x 108; List is 100 px wide: 25 px of hysteresis.
+ drag(ctx, 108 + 20);
+ await advance(400);
+ expect(faced()).toBe('grid');
+ drag(ctx, 108 + 30);
+ await advance(400);
+ expect(faced()).toBe('list');
+ // A slow dither of ±3 px around the boundary, the lens following it.
+ const seen = [faced()];
+ for (let i = 0; i < 24; i++) {
+ drag(ctx, 108 + (i % 2 === 0 ? 3 : -3));
+ await advance(50);
+ if (faced() !== seen.at(-1)) {
+ seen.push(faced());
+ }
+ }
+ expect(seen.length - 1).toBeLessThanOrEqual(1);
+ });
+
+ it('a lifted drag back onto the selected segment, or a cancel, puts the faces back', () => {
+ const ctx = setup('grid');
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('table'));
+ drag(ctx, clientCenterOf('grid'));
+ expect(faceOf(ctx.segments.table)).toEqual(NO_FACE);
+ expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE);
+ drag(ctx, clientCenterOf('list'));
+ ctx.motion.cancel();
+ expect(faceOf(ctx.segments.list)).toEqual(NO_FACE);
+ expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE);
+ press(ctx, clientCenterOf('grid'));
+ drag(ctx, clientCenterOf('table'));
+ expect(release(ctx, clientCenterOf('grid'))).toBeNull();
+ expect(faceOf(ctx.segments.table)).toEqual(NO_FACE);
+ expect(faceOf(ctx.segments.grid)).toEqual(NO_FACE);
+ });
+
+ it('a programmatic or keyboard change animates no title: the titles switch at once', () => {
+ const ctx = setup('grid');
+ select(ctx, 'grid', 'table');
+ expect(recorded).toHaveLength(0);
+ });
+});
diff --git a/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
new file mode 100644
index 0000000000..0428ca171b
--- /dev/null
+++ b/packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
@@ -0,0 +1,1637 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useSegmentedSelectionMotion.ts
+ * @input The radiogroup, the selected value, the presentation and tracking
+ * flags; the animator, the UIKit table and the touch tracking
+ * @output Exports `useSegmentedSelectionMotion`, `SegmentedSelectionMotion`,
+ * the layer custom properties and the segment and title selectors
+ * @position SegmentedControl's touch layer
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/SegmentedControl/SegmentedControl.tsx (the pseudo-elements)
+ * - /packages/core/src/SegmentedControl/SegmentedControlItem.tsx (the title marker)
+ * - /packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type RefCallback,
+ type RefObject,
+} from 'react';
+import {
+ createAnimator,
+ type AnimateOptions,
+ type Animator,
+ type MotionCurve,
+ type MotionHandle,
+ type MotionValues,
+ type SpringTransition,
+} from '../motion/animator';
+import {
+ registerSegmentedTable,
+ segmentedControl,
+} from '../motion/uikit/segmented';
+import {registerSpringsTable, springs} from '../motion/uikit/springs';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {observeResize} from '../utils/sharedResizeObserver';
+import {titleOfSegment} from '../privateAttributes/segmentTitle.stylex';
+import {cubicBezier} from '../motion/bezier';
+import {parseCssEasing, parseMotionRoleValue} from '../motion/roles';
+import {useSegmentedTouchTracking} from './useSegmentedTouchTracking';
+
+/** The segments, in DOM order. */
+export const SEGMENT_SELECTOR = '[role="radio"][data-value]';
+/**
+ * The selected face moves to another segment only when the lens's center is
+ * this far past the boundary. The distance is a quarter of that segment's
+ * width, at least 8 px.
+ */
+const FACE_HYSTERESIS_RATIO = 0.25;
+const FACE_HYSTERESIS_MIN_PX = 8;
+
+/** The selected surface's paint, copied into a layer's custom properties. */
+export const SURFACE_PROPERTIES: ReadonlyArray<string> = [
+ 'background-color',
+ 'background-image',
+ 'background-position',
+ 'background-size',
+ 'background-repeat',
+ 'background-origin',
+ 'background-clip',
+ 'box-shadow',
+ 'border-top-left-radius',
+ 'border-top-right-radius',
+ 'border-bottom-right-radius',
+ 'border-bottom-left-radius',
+ 'border-top-width',
+ 'border-right-width',
+ 'border-bottom-width',
+ 'border-left-width',
+ 'border-top-style',
+ 'border-right-style',
+ 'border-bottom-style',
+ 'border-left-style',
+ 'border-top-color',
+ 'border-right-color',
+ 'border-bottom-color',
+ 'border-left-color',
+ 'backdrop-filter',
+ '-webkit-backdrop-filter',
+];
+
+/**
+ * The radiogroup's two pseudo-element layers: the lens (::before) and the
+ * ::after, which under Reduced Motion shows the surface that fades out where
+ * it is.
+ */
+export type Layer = 'lens' | 'after';
+
+/** Box and visibility of a layer, besides its paint. */
+export const LAYER_GEOMETRY: ReadonlyArray<string> = [
+ 'left',
+ 'top',
+ 'width',
+ 'height',
+ 'visibility',
+];
+
+/** The custom property on the radiogroup that sets `property` of `layer`. */
+export function layerVariable(layer: Layer, property: string): string {
+ return `--_segmented-${layer}-${property.replace(/^-+/, '')}`;
+}
+
+/**
+ * What the destination segment shows while the lens carries its surface.
+ * Written inline with priority so a theme's rule for the selected segment
+ * cannot paint a second surface; borders keep their width so nothing moves.
+ */
+const HIDDEN_SURFACE: ReadonlyArray<readonly [string, string]> = [
+ ['background-color', 'transparent'],
+ ['background-image', 'none'],
+ ['box-shadow', 'none'],
+ ['border-top-color', 'transparent'],
+ ['border-right-color', 'transparent'],
+ ['border-bottom-color', 'transparent'],
+ ['border-left-color', 'transparent'],
+ ['backdrop-filter', 'none'],
+ ['-webkit-backdrop-filter', 'none'],
+];
+
+/** A title's face: what a dragging finger moves between titles. */
+interface TitleFace {
+ readonly color: string;
+ readonly fontWeight: string;
+}
+
+/** A box in the track's padding-box coordinates, in CSS px. */
+interface Box {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+interface Carried {
+ /** The segment the lens is bound for: it lands there at rest. */
+ readonly segment: HTMLElement;
+ /**
+ * The lens's layout box: the segment's, so it lands at translate 0 from
+ * the segment and scale 1, the segment's own size.
+ */
+ readonly box: Box;
+ /**
+ * The segment whose surface the lens shows, hidden there meanwhile: the
+ * selected one. A touch moves the lens before the new value comes back,
+ * so until then this is still the old selection.
+ */
+ hidden: HTMLElement;
+ /** The track's layout size when the box was measured. */
+ readonly trackSize: {readonly width: number; readonly height: number};
+}
+
+/** A finger's touch, from landing to letting go. */
+interface Touch {
+ /** The track's geometry when the finger landed (read once). */
+ readonly toTrackX: (clientX: number) => number;
+ readonly boxes: ReadonlyMap<HTMLElement, Box>;
+ /** The segment the finger landed on, if any (the tracker's begin target). */
+ readonly origin: HTMLElement | null;
+ /** Whether it landed on the selected segment (a drag carries the lens). */
+ readonly carriesLens: boolean;
+ /** A finger pressed: under Reduced Motion its release cross-fades. */
+ readonly isFinger: boolean;
+ /** The selected title's face and an unselected one, read at landing. */
+ readonly faces: {
+ readonly selected: TitleFace;
+ readonly unselected: TitleFace;
+ } | null;
+}
+
+/**
+ * The motion a release starts after its commit's click runs. It aims at the
+ * destination's box when the new value shows, because the titles' new weights
+ * move the segments. Until the value comes back, it aims at the box measured
+ * at landing.
+ */
+interface Pending {
+ readonly destination: HTMLElement;
+ /** The destination's box when the finger landed. */
+ readonly box: Box;
+ /** The held lens settles there; otherwise it slides from `from`. */
+ readonly isHeld: boolean;
+ /** The selected segment's box: where a tap's slide starts. */
+ readonly from: Box | null;
+ /** A finger released it: under Reduced Motion it cross-fades. */
+ readonly touchRelease: boolean;
+}
+
+function faceOf(element: HTMLElement): TitleFace {
+ const style = getComputedStyle(element);
+ return {color: style.color, fontWeight: style.fontWeight};
+}
+
+/**
+ * A hidden segment's own inline declarations (its `style`) for the properties
+ * `hideSurface` overrides: value and priority, restored by `showSurface`.
+ */
+const ownSurface = new WeakMap<
+ HTMLElement,
+ ReadonlyArray<readonly [property: string, value: string, priority: string]>
+>();
+
+function hideSurface(segment: HTMLElement): void {
+ if (!ownSurface.has(segment)) {
+ ownSurface.set(
+ segment,
+ HIDDEN_SURFACE.map(([property]) => [
+ property,
+ segment.style.getPropertyValue(property),
+ segment.style.getPropertyPriority(property),
+ ]),
+ );
+ }
+ for (const [property, value] of HIDDEN_SURFACE) {
+ segment.style.setProperty(property, value, 'important');
+ }
+}
+
+/** Gives a hidden segment its surface back, its own inline values included. */
+function showSurface(segment: HTMLElement): void {
+ const own = ownSurface.get(segment);
+ if (own == null) {
+ return;
+ }
+ ownSurface.delete(segment);
+ for (const [property, value, priority] of own) {
+ if (value === '') {
+ segment.style.removeProperty(property);
+ } else {
+ segment.style.setProperty(property, value, priority);
+ }
+ }
+}
+
+/**
+ * Paints `layer` with `segment`'s computed surface. All values are read
+ * before any is written. A write to the track's style makes the next
+ * computed-style read recompute. Interleaved reads and writes restyle the
+ * control once per property.
+ */
+function paintLayer(
+ track: HTMLElement,
+ layer: Layer,
+ segment: HTMLElement,
+): void {
+ const style = getComputedStyle(segment);
+ const values = SURFACE_PROPERTIES.map(property =>
+ style.getPropertyValue(property),
+ );
+ SURFACE_PROPERTIES.forEach((property, index) => {
+ track.style.setProperty(layerVariable(layer, property), values[index]);
+ });
+}
+
+/** Copies the lens's paint onto the ::after. */
+function copyLensPaint(track: HTMLElement): void {
+ for (const property of SURFACE_PROPERTIES) {
+ track.style.setProperty(
+ layerVariable('after', property),
+ track.style.getPropertyValue(layerVariable('lens', property)),
+ );
+ }
+}
+
+/** Lays `layer` out on `box` and shows it. */
+function placeLayer(track: HTMLElement, layer: Layer, box: Box): void {
+ track.style.setProperty(layerVariable(layer, 'left'), `${box.x}px`);
+ track.style.setProperty(layerVariable(layer, 'top'), `${box.y}px`);
+ track.style.setProperty(layerVariable(layer, 'width'), `${box.width}px`);
+ track.style.setProperty(layerVariable(layer, 'height'), `${box.height}px`);
+ track.style.setProperty(layerVariable(layer, 'visibility'), 'visible');
+}
+
+/** Hides `layer` and drops its custom properties. */
+function clearLayer(track: HTMLElement, layer: Layer): void {
+ for (const property of [...LAYER_GEOMETRY, ...SURFACE_PROPERTIES]) {
+ track.style.removeProperty(layerVariable(layer, property));
+ }
+}
+
+/**
+ * The scale an ancestor transform applies to the track's client rects. The
+ * lens lays out untransformed. `offsetWidth` rounds to whole pixels, so a
+ * fractional track width reads as a scale slightly off 1. Only a real
+ * transform moves it further than that rounding.
+ */
+function scaleOf(track: HTMLElement, rect: DOMRect): number {
+ if (track.offsetWidth <= 0 || rect.width <= 0) {
+ return 1;
+ }
+ return Math.abs(rect.width - track.offsetWidth) <= 1
+ ? 1
+ : rect.width / track.offsetWidth;
+}
+
+/** Boxes relative to the track's padding box. */
+function boxesIn(track: HTMLElement): (element: HTMLElement) => Box {
+ const trackRect = track.getBoundingClientRect();
+ const scale = scaleOf(track, trackRect);
+ return element => {
+ const rect = element.getBoundingClientRect();
+ return {
+ x: (rect.left - trackRect.left) / scale - track.clientLeft,
+ y: (rect.top - trackRect.top) / scale - track.clientTop,
+ width: rect.width / scale,
+ height: rect.height / scale,
+ };
+ };
+}
+
+/** Maps a client x to the track's padding-box x, read once per touch. */
+function trackXIn(track: HTMLElement): (clientX: number) => number {
+ const rect = track.getBoundingClientRect();
+ const scale = scaleOf(track, rect);
+ return clientX => (clientX - rect.left) / scale - track.clientLeft;
+}
+
+function segmentsOf(track: HTMLElement): HTMLElement[] {
+ return Array.from(track.querySelectorAll<HTMLElement>(SEGMENT_SELECTOR));
+}
+
+function isLaidOut(box: Box): boolean {
+ return box.width > 0 && box.height > 0;
+}
+
+function center(box: Box): number {
+ return box.x + box.width / 2;
+}
+
+/** Whether two boxes are the same to a quarter of a pixel. */
+function isSameBox(a: Box, b: Box): boolean {
+ return (
+ Math.abs(a.x - b.x) < 0.25 &&
+ Math.abs(a.y - b.y) < 0.25 &&
+ Math.abs(a.width - b.width) < 0.25 &&
+ Math.abs(a.height - b.height) < 0.25
+ );
+}
+
+function isEnabledSegment(segment: HTMLElement): boolean {
+ return (
+ !segment.hasAttribute('disabled') &&
+ segment.getAttribute('aria-disabled') !== 'true'
+ );
+}
+
+const titleOf = titleOfSegment;
+
+/** The theme's timing: a duration in seconds and its easing. */
+interface ThemeTiming {
+ readonly seconds: number;
+ readonly ease: (progress: number) => number;
+}
+
+/**
+ * The timing of `segment`'s own transition, which reads the theme's duration
+ * and easing tokens. The values stay readable while a carry turns the
+ * transition's property off. Null when the theme gives no duration.
+ */
+function themeTimingOf(segment: HTMLElement): ThemeTiming | null {
+ const view = segment.ownerDocument.defaultView;
+ if (view == null) {
+ return null;
+ }
+ const style = view.getComputedStyle(segment);
+ const ms = parseMotionRoleValue(
+ 'duration',
+ style.transitionDuration.split(',')[0] ?? '',
+ );
+ const points = parseCssEasing(
+ style.transitionTimingFunction.split(/,(?![^(]*\))/)[0] ?? '',
+ );
+ if (ms == null || ms <= 0 || points == null) {
+ return null;
+ }
+ return {seconds: ms / 1000, ease: cubicBezier(points)};
+}
+
+/** A theme that gives the segments no transition: the lens lands at once. */
+const INSTANT: ThemeTiming = {seconds: 0.001, ease: progress => progress};
+
+/** A curve from `from` to `to` on `timing`. */
+function timedCurve(
+ from: number,
+ to: number,
+ timing: ThemeTiming,
+): MotionCurve {
+ const {seconds, ease} = timing;
+ const at = (t: number) =>
+ from + (to - from) * ease(Math.min(1, Math.max(0, t / seconds)));
+ const step = Math.min(seconds / 100, 0.001);
+ return {
+ duration: seconds,
+ at,
+ velocity: t => {
+ const before = Math.max(0, t - step);
+ const after = Math.min(seconds, t + step);
+ return (at(after) - at(before)) / (after - before);
+ },
+ };
+}
+
+/** What the control reads of its selection motion. */
+export interface SegmentedSelection {
+ /**
+ * A press is down on the control (any pointer's), or its tap's click has
+ * not run yet. The press commits through that click, so a focus move it
+ * causes selects nothing.
+ */
+ readonly isPressing: () => boolean;
+ /** A key went down: a focus move it causes is the keyboard's, and selects. */
+ readonly keyPressed: () => void;
+}
+
+export interface SegmentedSelectionMotionOptions {
+ /** The animator's clock (ms, document timeline); `performance.now()` by default. */
+ readonly now?: () => number;
+ /**
+ * The animator for the radiogroup's ::after (the surface that fades out
+ * under Reduced Motion); one of its own by default.
+ */
+ readonly afterAnimator?: Animator;
+}
+
+function defaultNow(): number {
+ return typeof performance === 'undefined' ? Date.now() : performance.now();
+}
+
+/**
+ * The selection motion of one SegmentedControl, as UIKit's segmented control
+ * moves it. It lives outside React's render cycle. Nothing here sets state,
+ * so a slide never re-renders anything.
+ *
+ * At rest, the selected segment paints its own surface, so themes style it
+ * as before. For a slide, the lens takes over. The lens is the radiogroup's
+ * ::before, painted from custom properties copied from the segment's
+ * computed surface. The segment hides its own surface inline, so a theme
+ * rule cannot keep it painted. The lens moves with `translate` and `scale`
+ * on the compositor animator. Nothing lays out or paints per frame, and the
+ * slide keeps moving while JavaScript is busy. The lens lays out on the
+ * destination's box. It lands at translate 0 and scale 1 and hands the
+ * surface back pixel for pixel. Its position and its size run on separate
+ * springs, as UIKit's do. A change mid-flight starts from the presented
+ * geometry and its velocities. The titles change with the selection, at
+ * once.
+ *
+ * Under a finger:
+ * - A theme role owns a pressed thumb's lift, so a press on the selected
+ * segment lifts nothing here.
+ * - A drag from the selected segment carries the lens at its resting size.
+ * Its center chases the finger, at most `dragOvershoot` past the end
+ * segments.
+ * - The selected title's color follows the lens's center. It moves to a
+ * neighbor only once the center is a quarter of that segment past the
+ * boundary. Every title keeps its weight until the lift.
+ * - The lift commits the segment nearest the finger, through that segment's
+ * click. A lift outside the control commits nothing, and the lens settles
+ * back.
+ * - A press on another segment leaves the lens in place until the lift.
+ * Meanwhile that segment shows the shared pressed overlay.
+ * - A click that the item cancels sends the lens back at once. Otherwise the
+ * lens waits for the new value, which a parent can adopt later. It goes
+ * back only if the slide settles without the new value.
+ * - A cancelled touch puts the lens back.
+ *
+ * Under a mouse or a pen, the same press commits the same segment, but the
+ * theme owns the timing. A click, a key or a new value slides the lens on the
+ * theme's duration and easing, as the segments' own transition does. A drag
+ * from the selected segment carries the lens on the pointer itself.
+ *
+ * Under Reduced Motion, a held lens still follows the pointer: that is direct
+ * movement, not a transition. Nothing else chases, travels or scales. The lens
+ * fades in at the new segment while ::after, painted with the old surface,
+ * fades out in place. With a fine pointer under Reduce Motion, a change shows
+ * through the theme's transition.
+ */
+export class SegmentedSelectionMotion {
+ private track: HTMLElement | null = null;
+ private carried: Carried | null = null;
+ /**
+ * Segments whose surface the lens carried until a change turned it
+ * elsewhere. They keep their surface hidden until the lens lands. A tap's
+ * press paint can still fade on such a segment. That paint would cover the
+ * lens, which sits under the segments' backgrounds, while the lens crosses
+ * it.
+ */
+ private readonly abandoned = new Set<HTMLElement>();
+ /** The segment showing the selected face under a dragging finger. */
+ private facedSegment: HTMLElement | null = null;
+ /** The frame request that keeps the face on the lens while it is carried. */
+ private lensFrame: number | null = null;
+ /** Titles wearing the other face's color during a drag. */
+ private readonly faceOverrides = new Set<HTMLElement>();
+ /** The motions the hand-back waits for. */
+ private readonly running = new Set<MotionHandle>();
+ /** A finger holds the lens: a drag from the selected segment carries it. */
+ private isHeld = false;
+ /**
+ * The touch presentation applies (a coarse primary pointer), so every
+ * change slides on UIKit's springs. When it is off, a change slides on the
+ * theme's duration and easing, as the segments' transition does. A drag from
+ * the selected segment carries the lens on the pointer itself.
+ */
+ private isPresenting = true;
+ /**
+ * Segments whose own transitions are off while a fine pointer's carry is
+ * on screen, with their own inline values to give back.
+ */
+ private readonly stilled = new Map<HTMLElement, readonly [string, string]>();
+ /** The frame request that gives the stilled segments their transitions back. */
+ private thawFrame: number | null = null;
+ private touch: Touch | null = null;
+ /**
+ * The value a touch already moved the lens to: the selection change that
+ * follows (the controlled value coming back) re-aims the lens.
+ */
+ private committed: string | null = null;
+ /**
+ * The commit's click ran without a veto: the lens waits for the value
+ * until the slide settles.
+ */
+ private isAwaitingValue = false;
+ /** The motion a release starts once its commit's click has run. */
+ private pending: Pending | null = null;
+ /** The last release was a finger's (decline and re-aim follow it). */
+ private releasedByFinger = true;
+ /** The ::after shows the leaving surface (Reduced Motion). */
+ private isLeavingShown = false;
+ /** Bumped by every leaving fade; a finished fade clears only its own. */
+ private leaving = 0;
+
+ private readonly now: () => number;
+ /** The ::after: the surface fading out under Reduced Motion. */
+ private readonly after: Animator;
+
+ constructor(
+ private readonly animator: Animator = createAnimator(null, {
+ pseudoElement: '::before',
+ }),
+ options: SegmentedSelectionMotionOptions = {},
+ ) {
+ // The chase plays the shared `springs.fingerTracking` role, and the slide
+ // plays the segmented role. Both register before the first animation,
+ // because nothing registers on import. A second call does nothing.
+ registerSpringsTable();
+ registerSegmentedTable();
+ this.now = options.now ?? defaultNow;
+ this.after =
+ options.afterAnimator ??
+ createAnimator(null, {pseudoElement: '::after', initial: {opacity: 0}});
+ }
+
+ /** Attaches the radiogroup whose pseudo-elements are the lens (null detaches). */
+ attachTrack(element: HTMLElement | null): void {
+ if (element !== this.track) {
+ this.settle();
+ }
+ this.track = element;
+ this.animator.attach(element);
+ this.after.attach(element);
+ }
+
+ /** True while the lens carries the selected surface. */
+ get isSliding(): boolean {
+ return this.carried != null;
+ }
+
+ /** A press (any pointer's) is down on the control, from landing to letting go. */
+ get isPressed(): boolean {
+ return this.touch != null;
+ }
+
+ /**
+ * Whether the touch presentation applies. Off, under a fine primary
+ * pointer, a change slides on the theme's timing, and a drag from the
+ * selected segment still carries the lens. A change of presentation hands
+ * anything in flight back.
+ */
+ present(isPresenting: boolean): void {
+ if (this.isPresenting === isPresenting) {
+ return;
+ }
+ this.isPresenting = isPresenting;
+ this.settle();
+ }
+
+ /** The segment that commits `value`, if the track has one. */
+ segmentFor(track: HTMLElement, value: string): HTMLElement | null {
+ return (
+ segmentsOf(track).find(segment => segment.dataset.value === value) ?? null
+ );
+ }
+
+ /** The selection moved from `from` to `to`; the DOM already shows `to`. */
+ select(track: HTMLElement, from: string, to: string): void {
+ if (this.track !== track) {
+ return;
+ }
+ const origin = this.segmentFor(track, from);
+ const destination = this.segmentFor(track, to);
+ const isTouchCommit = this.committed === to;
+ // The commit's own styles take over from a drag's borrowed faces.
+ this.clearFaces();
+ this.committed = null;
+ this.isAwaitingValue = false;
+ if (isTouchCommit) {
+ if (this.pending?.destination === destination && destination != null) {
+ // Adopted during the click: the lens moves now, on the box the
+ // destination has with the new value shown.
+ this.startPending(destination, boxesIn(track)(destination));
+ }
+ // The new selection now paints the surface the lens carries, and its
+ // titles' weights may have moved the segments since the lens set off.
+ const carried = this.carried;
+ if (carried != null && carried.segment === destination) {
+ if (carried.hidden !== destination) {
+ showSurface(carried.hidden);
+ paintLayer(track, 'lens', destination);
+ hideSurface(destination);
+ carried.hidden = destination;
+ }
+ this.reaim(track, destination);
+ }
+ return;
+ }
+ if (!this.slidesChanges()) {
+ // A fine pointer under Reduce Motion: the theme's transition shows the
+ // change.
+ this.settle();
+ return;
+ }
+ if (destination == null) {
+ // Nothing is selected any more: no surface to carry.
+ this.settle();
+ return;
+ }
+ if (this.carried == null && origin == null) {
+ // Nothing was selected: there is no surface to slide from.
+ return;
+ }
+ const boxOf = boxesIn(track);
+ const to_ = boxOf(destination);
+ if (!isLaidOut(to_)) {
+ this.settle();
+ return;
+ }
+ const from_ = this.carried == null ? boxOf(origin as HTMLElement) : null;
+ if (this.animator.reducedMotion() !== 'off') {
+ this.crossFadeTo(destination, to_, from_, destination, false);
+ return;
+ }
+ const at = this.carry(destination, to_, from_, destination);
+ // A programmatic or keyboard change: the whole box slides.
+ this.settleLens(destination, {at});
+ }
+
+ /**
+ * Whether a change of value slides the lens. A fine pointer under Reduce
+ * Motion leaves the change to the theme's transition.
+ */
+ private slidesChanges(): boolean {
+ return this.isPresenting || this.animator.reducedMotion() === 'off';
+ }
+
+ /**
+ * A press landed on `origin`, the segment the action-group tracker resolved
+ * for it (null: none). It reads the track's geometry and title faces once.
+ * Under Reduced Motion a finger's release cross-fades.
+ */
+ begin(track: HTMLElement, origin: HTMLElement | null, isFinger = true): void {
+ const segments = segmentsOf(track);
+ const boxOf = boxesIn(track);
+ const boxes = new Map(segments.map(segment => [segment, boxOf(segment)]));
+ const toTrackX = trackXIn(track);
+ const selected =
+ segments.find(
+ segment => segment.getAttribute('aria-checked') === 'true',
+ ) ?? null;
+ const carriesLens = origin != null && origin === selected;
+ const selectedTitle = selected != null ? titleOf(selected) : null;
+ // An enabled segment's unselected face: a disabled title has its own.
+ const other = segments.find(
+ segment => segment !== selected && isEnabledSegment(segment),
+ );
+ const otherTitle = other != null ? titleOf(other) : null;
+ const faces =
+ selectedTitle != null && otherTitle != null
+ ? {selected: faceOf(selectedTitle), unselected: faceOf(otherTitle)}
+ : null;
+ this.touch = {
+ toTrackX,
+ boxes,
+ origin,
+ carriesLens,
+ isFinger,
+ faces,
+ };
+ }
+
+ /**
+ * The finger moved to `clientX`. A drag from the selected segment carries
+ * the lens at its resting size. A touch elsewhere leaves the lens alone,
+ * and that segment shows the shared pressed overlay.
+ */
+ drag(clientX: number): void {
+ const touch = this.touch;
+ if (touch == null || !touch.carriesLens) {
+ return;
+ }
+ this.hold();
+ if (!this.isHeld) {
+ return;
+ }
+ this.chase(clientX);
+ this.followLens();
+ }
+
+ /**
+ * The first move of a drag from the selected segment binds the lens there,
+ * at its resting size. Under Reduced Motion too: the lens follows the hand,
+ * and only the release cross-fades.
+ */
+ private hold(): void {
+ const touch = this.touch;
+ if (touch == null || touch.origin == null || this.isHeld) {
+ return;
+ }
+ const box = touch.boxes.get(touch.origin) as Box;
+ if (!isLaidOut(box)) {
+ return;
+ }
+ this.carry(touch.origin, box, null, touch.origin);
+ this.isHeld = true;
+ }
+
+ /**
+ * The selected face follows the held lens: it goes to the segment under the
+ * lens's presented center. Hysteresis around each boundary keeps a finger
+ * that rests on a boundary from flipping it. This runs every frame while
+ * the lens is held, so the face keeps up as the lens settles under a still
+ * finger.
+ */
+ private followLens(): void {
+ const touch = this.touch;
+ const carried = this.carried;
+ if (
+ touch == null ||
+ !touch.carriesLens ||
+ !this.isHeld ||
+ carried == null ||
+ touch.origin == null
+ ) {
+ this.lensFrame = null;
+ return;
+ }
+ const lensCenter = this.presented(carried.box, this.now()).center;
+ const spans = [...touch.boxes.entries()]
+ .filter(([segment]) => isEnabledSegment(segment))
+ .sort((a, b) => a[1].x - b[1].x);
+ const current = this.facedSegment ?? touch.origin;
+ const at = spans.findIndex(([segment]) => segment === current);
+ if (at >= 0) {
+ const edge = (i: number) =>
+ (spans[i][1].x + spans[i][1].width + spans[i + 1][1].x) / 2;
+ let next = at;
+ while (next + 1 < spans.length && lensCenter > edge(next)) {
+ next += 1;
+ }
+ while (next > 0 && lensCenter < edge(next - 1)) {
+ next -= 1;
+ }
+ if (next !== at) {
+ const boundary = next > at ? edge(at) : edge(at - 1);
+ const hysteresis = Math.max(
+ FACE_HYSTERESIS_MIN_PX,
+ FACE_HYSTERESIS_RATIO * spans[next][1].width,
+ );
+ if (Math.abs(lensCenter - boundary) >= hysteresis) {
+ const segment = spans[next][0];
+ this.showFaceAt(segment === touch.origin ? null : segment);
+ }
+ }
+ }
+ const view = this.track?.ownerDocument.defaultView;
+ if (this.lensFrame == null && view != null) {
+ this.lensFrame = view.requestAnimationFrame(() => {
+ this.lensFrame = null;
+ this.followLens();
+ });
+ }
+ }
+
+ /** The held lens's center chases the finger at `clientX`. */
+ private chase(clientX: number): void {
+ const touch = this.touch;
+ const carried = this.carried;
+ if (touch == null || carried == null) {
+ return;
+ }
+ const centers = [...touch.boxes.values()].map(center);
+ const reach = segmentedControl.dragOvershoot;
+ const target = Math.min(
+ Math.max(touch.toTrackX(clientX), Math.min(...centers) - reach),
+ Math.max(...centers) + reach,
+ );
+ if (!this.isPresenting || this.animator.reducedMotion() !== 'off') {
+ // A mouse or a pen holds the lens directly, as a finger does under
+ // Reduce Motion. Each move writes the pointer's position.
+ this.animator.set({x: target - center(carried.box)});
+ return;
+ }
+ // Start each chase at the call. A chase from rest waits for the browser
+ // to start it. Android Chrome sends the next move first, so the lens
+ // would stick.
+ const at = this.now();
+ this.springLens(
+ {x: target - center(carried.box)},
+ this.springFrom({x: target - center(carried.box)}, 'tracking'),
+ {at},
+ );
+ }
+
+ /**
+ * The finger let go on `target`, the segment the tracker resolved for it
+ * (null: none, or a disabled one). Moves the lens there and returns its
+ * value when it is not the selected one (the tracker's lift commits it
+ * through its click), else null.
+ */
+ release(target: HTMLElement | null): string | null {
+ const touch = this.touch;
+ this.touch = null;
+ if (touch == null) {
+ return null;
+ }
+ const selected =
+ [...touch.boxes.keys()].find(
+ segment => segment.getAttribute('aria-checked') === 'true',
+ ) ?? null;
+ // A disabled segment never commits: the lens settles back on the
+ // selection.
+ const destination =
+ (target != null && isEnabledSegment(target) ? target : null) ?? selected;
+ if (destination == null) {
+ this.clearFaces();
+ if (this.isHeld) {
+ this.isHeld = false;
+ this.settle();
+ }
+ return null;
+ }
+ const box = touch.boxes.get(destination) as Box;
+ const value =
+ destination !== selected ? (destination.dataset.value ?? null) : null;
+ // A drag's borrowed face stays only if the lift commits (the commit
+ // takes it over).
+ if (value == null) {
+ this.clearFaces();
+ }
+ const isHeld = touch.carriesLens && this.isHeld;
+ this.committed = value;
+ this.isAwaitingValue = false;
+ this.releasedByFinger = touch.isFinger;
+ if (value == null) {
+ if (isHeld) {
+ // The held lens settles back on the selection.
+ this.moveLensTo(
+ destination,
+ box,
+ selected ?? destination,
+ touch.isFinger,
+ );
+ }
+ return null;
+ }
+ // The commit follows at once, through the segment's click; the lens
+ // moves once it has run, on the box the destination has then. A held
+ // lens settles there; a tap (or a drag that started elsewhere) slides
+ // there from the selected segment.
+ // A fine pointer under Reduce Motion moves only a held lens.
+ if (isHeld || (selected != null && this.slidesChanges())) {
+ this.pending = {
+ destination,
+ box,
+ isHeld,
+ from:
+ !isHeld && selected != null
+ ? (touch.boxes.get(selected) as Box)
+ : null,
+ touchRelease: touch.isFinger,
+ };
+ }
+ return value;
+ }
+
+ /**
+ * The commit's click for `value` has run. A click that the item's
+ * `onClick` cancels sends the lens back at once. Otherwise the lens waits
+ * for the value, which a parent can adopt later.
+ */
+ clicked(track: HTMLElement, value: string, isCancelled: boolean): void {
+ if (this.committed !== value) {
+ // Adopted during the click, or superseded.
+ return;
+ }
+ if (isCancelled) {
+ this.pending = null;
+ this.decline(track, value);
+ return;
+ }
+ this.isAwaitingValue = true;
+ // React can render the click's change only after the event that
+ // dispatched it ends: a click inside a touch handler is batched with it.
+ // Wait one turn. If the value is adopted by then, the lens already moves
+ // on the new box. Otherwise it aims at the box measured at landing and
+ // re-aims when the value comes back.
+ queueMicrotask(() => {
+ if (this.committed === value && this.pending != null) {
+ this.startPending(this.selectedIn(track));
+ }
+ });
+ }
+
+ /**
+ * The value the finger let go on was not adopted. The item's `onClick`
+ * cancelled it, or a controlled parent kept its value. The lens goes back
+ * to the selected segment. The next change to that value slides as any
+ * change does.
+ */
+ decline(track: HTMLElement, value: string): void {
+ if (this.committed !== value) {
+ return;
+ }
+ this.committed = null;
+ this.isAwaitingValue = false;
+ this.pending = null;
+ this.clearFaces();
+ const selected =
+ segmentsOf(track).find(
+ segment => segment.getAttribute('aria-checked') === 'true',
+ ) ?? null;
+ if (selected == null || this.carried == null) {
+ this.settle();
+ return;
+ }
+ const box = boxesIn(track)(selected);
+ if (!isLaidOut(box)) {
+ this.settle();
+ return;
+ }
+ this.moveLensTo(selected, box, selected, this.releasedByFinger);
+ }
+
+ /** The touch was taken away (the page scrolled): the lens goes back. */
+ cancel(): void {
+ const touch = this.touch;
+ this.touch = null;
+ this.clearFaces();
+ if (
+ touch == null ||
+ !touch.carriesLens ||
+ touch.origin == null ||
+ !this.isHeld
+ ) {
+ // Nothing was held: nothing to put back.
+ return;
+ }
+ const box = touch.boxes.get(touch.origin) as Box;
+ this.moveLensTo(touch.origin, box, touch.origin, touch.isFinger);
+ }
+
+ /** Hands the surface back to its segment now and hides the lens. */
+ settle(): void {
+ this.endLeaving();
+ this.isHeld = false;
+ this.pending = null;
+ const carried = this.carried;
+ if (carried != null) {
+ this.carried = null;
+ this.running.clear();
+ this.animator.stop();
+ this.after.stop();
+ showSurface(carried.hidden);
+ for (const segment of this.abandoned) {
+ showSurface(segment);
+ }
+ this.abandoned.clear();
+ if (this.track != null) {
+ clearLayer(this.track, 'lens');
+ clearLayer(this.track, 'after');
+ }
+ this.isLeavingShown = false;
+ }
+ // Once the surfaces are back on screen, so nothing fades in.
+ this.thawTransitions();
+ }
+
+ /**
+ * The control resized. The lens aims at boxes measured when its motion
+ * began, so it hands the surface back rather than land somewhere stale.
+ * Two cases keep the motion. In the first, the track keeps its measured
+ * size: a new title weight resized a content-sized control before the box
+ * was measured. In the second, a finger holds the lens.
+ */
+ resized(track: HTMLElement): void {
+ const carried = this.carried;
+ // A finger that holds the lens reflows the titles itself, because the
+ // selected face moves to the title under it. The lens follows the finger,
+ // and the commit measures the destination again.
+ if (carried == null || this.touch != null) {
+ return;
+ }
+ if (
+ Math.abs(track.offsetWidth - carried.trackSize.width) < 0.5 &&
+ Math.abs(track.offsetHeight - carried.trackSize.height) < 0.5
+ ) {
+ return;
+ }
+ this.settle();
+ }
+
+ /**
+ * Ends everything in flight (unmount). The controller stays usable, so an
+ * effect cleanup followed by a setup (StrictMode's extra mount) loses
+ * nothing.
+ */
+ stop(): void {
+ this.touch = null;
+ if (this.lensFrame != null) {
+ this.track?.ownerDocument.defaultView?.cancelAnimationFrame(
+ this.lensFrame,
+ );
+ this.lensFrame = null;
+ }
+ this.committed = null;
+ this.isAwaitingValue = false;
+ this.clearFaces();
+ this.settle();
+ this.cancelThaw();
+ this.restoreTransitions();
+ }
+
+ /**
+ * A fine pointer's carry. The segments' own transitions go off while the
+ * lens is on screen, so the borrowed surface does not fade out and back in.
+ * Under a finger, the touch presentation already turns them off.
+ */
+ private stillTransitions(): void {
+ const track = this.track;
+ if (track == null) {
+ return;
+ }
+ this.cancelThaw();
+ for (const segment of segmentsOf(track)) {
+ if (!this.stilled.has(segment)) {
+ this.stilled.set(segment, [
+ segment.style.getPropertyValue('transition-property'),
+ segment.style.getPropertyPriority('transition-property'),
+ ]);
+ }
+ segment.style.setProperty('transition-property', 'none', 'important');
+ }
+ }
+
+ /**
+ * Gives the stilled segments their transitions back two frames after the
+ * hand-back, once the surfaces it gave back have been on screen.
+ */
+ private thawTransitions(): void {
+ if (this.stilled.size === 0 || this.thawFrame != null) {
+ return;
+ }
+ const view = this.track?.ownerDocument.defaultView;
+ if (view == null) {
+ this.restoreTransitions();
+ return;
+ }
+ this.thawFrame = view.requestAnimationFrame(() => {
+ this.thawFrame = view.requestAnimationFrame(() => {
+ this.thawFrame = null;
+ this.restoreTransitions();
+ });
+ });
+ }
+
+ private cancelThaw(): void {
+ if (this.thawFrame != null) {
+ this.track?.ownerDocument.defaultView?.cancelAnimationFrame(
+ this.thawFrame,
+ );
+ this.thawFrame = null;
+ }
+ }
+
+ private restoreTransitions(): void {
+ for (const [segment, [value, priority]] of this.stilled) {
+ if (value === '') {
+ segment.style.removeProperty('transition-property');
+ } else {
+ segment.style.setProperty('transition-property', value, priority);
+ }
+ }
+ this.stilled.clear();
+ }
+
+ /** The selected segment, as the DOM shows it now. */
+ private selectedIn(track: HTMLElement): HTMLElement | null {
+ return (
+ segmentsOf(track).find(
+ segment => segment.getAttribute('aria-checked') === 'true',
+ ) ?? null
+ );
+ }
+
+ /**
+ * Starts the motion the release left pending: on `box` (the destination's
+ * box now) or the box measured at landing, showing `paint`'s surface (the
+ * selected segment's).
+ */
+ private startPending(paint: HTMLElement | null, box?: Box): void {
+ const pending = this.pending;
+ this.pending = null;
+ if (pending == null) {
+ return;
+ }
+ const to = box ?? pending.box;
+ const surface = this.carried?.hidden ?? paint ?? pending.destination;
+ if (pending.isHeld) {
+ this.moveLensTo(pending.destination, to, surface, pending.touchRelease);
+ } else if (pending.from != null) {
+ this.slideTo(
+ pending.destination,
+ to,
+ pending.from,
+ surface,
+ pending.touchRelease,
+ );
+ }
+ }
+
+ /**
+ * Aims the lens at `destination`'s box as it is now: a value adopted
+ * after its click (mid-flight) moves the segments with its titles' new
+ * weights.
+ */
+ private reaim(track: HTMLElement, destination: HTMLElement): void {
+ const carried = this.carried;
+ if (carried == null) {
+ return;
+ }
+ const box = boxesIn(track)(destination);
+ if (!isLaidOut(box) || isSameBox(box, carried.box)) {
+ return;
+ }
+ this.moveLensTo(destination, box, carried.hidden, this.releasedByFinger);
+ }
+
+ /**
+ * Binds the lens for `segment`, with `box` as its layout box and `paint`'s
+ * surface, the selected segment's. It keeps what is on screen. With nothing
+ * carried, it starts from `from`, a segment's resting box. Otherwise it
+ * starts from the presented geometry, re-based onto the new box with its
+ * velocities.
+ */
+ private carry(
+ segment: HTMLElement,
+ box: Box,
+ from: Box | null,
+ paint: HTMLElement,
+ ): number | undefined {
+ const track = this.track;
+ if (track == null) {
+ return undefined;
+ }
+ if (!this.isPresenting) {
+ // Before the surface is borrowed: it must not fade out.
+ this.stillTransitions();
+ }
+ const previous = this.carried;
+ let start: MotionValues;
+ // Motion already on screen continues from this instant; a start from
+ // rest waits for the browser to commit it (the animator's rule).
+ let at: number | undefined;
+ this.velocity = {};
+ if (previous != null) {
+ at = this.now();
+ const presented = this.presented(previous.box, at);
+ start = {
+ x: presented.center - center(box),
+ scaleX: presented.width / box.width,
+ scaleY: presented.height / box.height,
+ };
+ this.velocity = {
+ x: this.animator.getVelocity('x', at),
+ scaleX:
+ (this.animator.getVelocity('scaleX', at) * previous.box.width) /
+ box.width,
+ scaleY:
+ (this.animator.getVelocity('scaleY', at) * previous.box.height) /
+ box.height,
+ };
+ } else {
+ const origin = from ?? box;
+ start = {
+ x: center(origin) - center(box),
+ scaleX: origin.width / box.width,
+ scaleY: origin.height / box.height,
+ };
+ }
+ if (previous?.hidden !== paint) {
+ if (previous != null) {
+ this.abandoned.add(previous.hidden);
+ }
+ // A segment abandoned mid-flight still has its surface hidden: read
+ // its paint with it shown.
+ if (this.abandoned.has(paint)) {
+ showSurface(paint);
+ }
+ paintLayer(track, 'lens', paint);
+ hideSurface(paint);
+ this.abandoned.delete(paint);
+ }
+ placeLayer(track, 'lens', box);
+ this.carried = {
+ segment,
+ box,
+ hidden: paint,
+ trackSize: {width: track.offsetWidth, height: track.offsetHeight},
+ };
+ // Opaque, whatever a Reduce Motion fade left.
+ this.animator.set({...start, opacity: 1});
+ return at;
+ }
+
+ /** Velocities captured by the last `carry`, in the new box's units. */
+ private velocity: Partial<Record<'x' | 'scaleX' | 'scaleY', number>> = {};
+
+ /** A spring transition that keeps the captured velocities of `values`. */
+ private springFrom(
+ values: MotionValues,
+ kind: 'selection' | 'tracking',
+ ): SpringTransition {
+ const spring =
+ kind === 'selection'
+ ? segmentedControl.selectionSpring
+ : springs.fingerTracking;
+ const velocity: Record<string, number> = {};
+ for (const key of Object.keys(values) as (keyof typeof this.velocity)[]) {
+ const v = this.velocity[key];
+ if (v != null && v !== 0) {
+ velocity[key] = v;
+ }
+ }
+ // A captured velocity is spent by the first call that drives its channel.
+ this.velocity = Object.fromEntries(
+ Object.entries(this.velocity).filter(([key]) => !(key in values)),
+ );
+ return Object.keys(velocity).length > 0 ? {spring, velocity} : {spring};
+ }
+
+ /**
+ * The lens settles at its resting place on `segment`. Under a finger it
+ * springs on the slide spring. Under a fine pointer it takes the theme's
+ * duration and easing, as the segments' own transition does.
+ */
+ private settleLens(segment: HTMLElement, options: AnimateOptions): void {
+ const rest = {x: 0, scaleX: 1, scaleY: 1} as const;
+ if (this.isPresenting) {
+ this.springLens(rest, this.springFrom(rest, 'selection'), options);
+ return;
+ }
+ this.velocity = {};
+ const timing = themeTimingOf(segment) ?? INSTANT;
+ const at = options.at;
+ this.trackHandle(
+ this.animator.play(
+ {
+ x: timedCurve(this.animator.get('x', at), 0, timing),
+ scaleX: timedCurve(this.animator.get('scaleX', at), 1, timing),
+ scaleY: timedCurve(this.animator.get('scaleY', at), 1, timing),
+ },
+ options,
+ ),
+ );
+ }
+
+ /** Springs the lens toward `values`. */
+ private springLens(
+ values: MotionValues,
+ transition: SpringTransition,
+ options?: AnimateOptions,
+ ): void {
+ this.trackHandle(this.animator.animate(values, transition, options));
+ }
+
+ /** The lens's presented center and size, from the animator. */
+ private presented(
+ box: Box,
+ at: number,
+ ): {center: number; width: number; height: number} {
+ return {
+ center: center(box) + this.animator.get('x', at),
+ width: box.width * this.animator.get('scaleX', at),
+ height: box.height * this.animator.get('scaleY', at),
+ };
+ }
+
+ /**
+ * The lens settles on `segment`, at its resting size. Under Reduced Motion
+ * a finger's release (`touchRelease`) cross-fades on any primary pointer. A
+ * mouse's or a pen's lands at once under a fine one.
+ */
+ private moveLensTo(
+ segment: HTMLElement,
+ box: Box,
+ paint: HTMLElement,
+ touchRelease: boolean,
+ ): void {
+ this.isHeld = false;
+ if (!isLaidOut(box)) {
+ this.settle();
+ return;
+ }
+ if (this.animator.reducedMotion({touchRelease}) !== 'off') {
+ this.crossFadeTo(
+ segment,
+ box,
+ null,
+ this.carried?.hidden ?? paint,
+ touchRelease,
+ );
+ return;
+ }
+ const at = this.carry(segment, box, null, this.carried?.hidden ?? paint);
+ this.settleLens(segment, {at});
+ }
+
+ /**
+ * A tap's slide: from `from` to `segment` on the slide spring. Under Reduced
+ * Motion there is no travel, and a finger's tap (`touchRelease`) fades.
+ */
+ private slideTo(
+ segment: HTMLElement,
+ box: Box,
+ from: Box,
+ paint: HTMLElement,
+ touchRelease: boolean,
+ ): void {
+ if (!isLaidOut(box)) {
+ this.settle();
+ return;
+ }
+ if (this.animator.reducedMotion({touchRelease}) !== 'off') {
+ this.crossFadeTo(
+ segment,
+ box,
+ this.carried == null ? from : null,
+ this.carried?.hidden ?? paint,
+ touchRelease,
+ );
+ return;
+ }
+ const at = this.carry(
+ segment,
+ box,
+ this.carried == null ? from : null,
+ this.carried?.hidden ?? paint,
+ );
+ this.settleLens(segment, {at});
+ }
+
+ /**
+ * Under Reduced Motion, the lens lands on `segment` and fades in there, as
+ * an animator entrance. The surface on screen fades out in place on the
+ * same clock. That surface is the lens when it was carried, else `from`'s
+ * resting surface. The animator decides whether anything fades. On a fine
+ * pointer, both change at once unless a touch released the change
+ * (`touchRelease`).
+ */
+ private crossFadeTo(
+ segment: HTMLElement,
+ box: Box,
+ from: Box | null,
+ paint: HTMLElement,
+ touchRelease: boolean,
+ ): void {
+ const track = this.track;
+ if (track == null) {
+ return;
+ }
+ // What is on screen before the lens is rebound.
+ let leaving: Box | null = null;
+ let opacity = 1;
+ const previous = this.carried;
+ if (previous != null) {
+ const now = this.now();
+ const presented = this.presented(previous.box, now);
+ leaving = {
+ x: presented.center - presented.width / 2,
+ y: previous.box.y,
+ width: presented.width,
+ height: previous.box.height,
+ };
+ opacity = this.animator.get('opacity', now);
+ } else if (from != null) {
+ leaving = from;
+ }
+ this.isHeld = false;
+ this.endLeaving();
+ this.after.stop();
+ clearLayer(track, 'after');
+ this.isLeavingShown = false;
+ const fades =
+ leaving != null &&
+ opacity > 0 &&
+ this.animator.reducedMotion({touchRelease}) === 'crossfade';
+ if (fades) {
+ this.leave(track, previous != null, paint, leaving as Box, opacity, box);
+ }
+ const at = this.carry(segment, box, from, paint);
+ this.velocity = {};
+ this.trackHandle(
+ this.animator.animate(
+ {x: 0, scaleX: 1, scaleY: 1},
+ {spring: segmentedControl.selectionSpring},
+ {at, crossfadeAs: 'entrance', touchRelease},
+ ),
+ );
+ if (fades) {
+ this.fadeLeaving(box, leaving as Box, at, touchRelease);
+ }
+ }
+
+ /**
+ * Paints the ::after with the surface on screen (the lens's paint, or
+ * `paint`'s resting surface) where it is (`from`, at `opacity`).
+ */
+ private leave(
+ track: HTMLElement,
+ fromLens: boolean,
+ paint: HTMLElement,
+ from: Box,
+ opacity: number,
+ box: Box,
+ ): void {
+ if (fromLens) {
+ copyLensPaint(track);
+ } else {
+ paintLayer(track, 'after', paint);
+ }
+ placeLayer(track, 'after', {...from, y: box.y, height: box.height});
+ this.isLeavingShown = true;
+ this.after.set({x: 0, scaleX: 1, scaleY: 1, opacity});
+ }
+
+ /**
+ * The ::after fades out in place while the lens fades in on `box`. As a
+ * leaving travel, it fades on the animator's Reduce Motion clock. It lands
+ * only once it is invisible.
+ */
+ private fadeLeaving(
+ box: Box,
+ from: Box,
+ at: number | undefined,
+ touchRelease: boolean,
+ ): void {
+ const id = ++this.leaving;
+ const handle = this.after.animate(
+ {x: center(box) - center(from), opacity: 0},
+ {spring: segmentedControl.selectionSpring},
+ {at, touchRelease},
+ );
+ void handle.finished.then(() => {
+ if (this.leaving === id) {
+ this.endLeaving();
+ }
+ });
+ }
+
+ private endLeaving(): void {
+ if (!this.isLeavingShown) {
+ return;
+ }
+ this.isLeavingShown = false;
+ this.leaving++;
+ this.after.stop();
+ if (this.track != null) {
+ clearLayer(this.track, 'after');
+ }
+ }
+
+ /**
+ * Waits for `handle`; the surface goes back when nothing is left. A
+ * touch's value still waiting to come back when the motion settles goes
+ * back instead: the settled slide bounds the wait.
+ */
+ private trackHandle(handle: MotionHandle): void {
+ this.running.add(handle);
+ void handle.finished.then(() => {
+ this.running.delete(handle);
+ if (this.running.size > 0 || this.isHeld || this.touch != null) {
+ return;
+ }
+ const committed = this.committed;
+ if (this.isAwaitingValue && committed != null && this.track != null) {
+ this.decline(this.track, committed);
+ return;
+ }
+ if (this.committed == null) {
+ this.settle();
+ }
+ });
+ }
+
+ /**
+ * Gives `segment`'s title the selected face and the selected segment's
+ * title an unselected one (none for null or the selected segment), at once.
+ */
+ private showFaceAt(segment: HTMLElement | null): void {
+ const touch = this.touch;
+ const selected = touch?.origin ?? null;
+ if (segment === this.facedSegment) {
+ return;
+ }
+ this.clearFaces();
+ if (
+ touch?.faces == null ||
+ selected == null ||
+ segment == null ||
+ segment === selected
+ ) {
+ return;
+ }
+ const title = titleOf(segment);
+ const selectedTitle = titleOf(selected);
+ if (title == null || selectedTitle == null) {
+ return;
+ }
+ this.wearFace(title, touch.faces.selected);
+ this.wearFace(selectedTitle, touch.faces.unselected);
+ this.facedSegment = segment;
+ }
+
+ /**
+ * Mid-drag, the face is the color alone. A weight swap changes the titles'
+ * widths, which moves the segments under the finger and shakes the
+ * boundary. The commit's own styles give the new weight at the lift.
+ */
+ private wearFace(title: HTMLElement, face: TitleFace): void {
+ title.style.color = face.color;
+ this.faceOverrides.add(title);
+ }
+
+ /** Every title back to its own face. */
+ private clearFaces(): void {
+ for (const title of this.faceOverrides) {
+ title.style.removeProperty('color');
+ }
+ this.faceOverrides.clear();
+ this.facedSegment = null;
+ }
+}
+
+/**
+ * Wires `SegmentedSelectionMotion` to a SegmentedControl. While enabled,
+ * every change of `value` slides the selection in the commit that shows the
+ * new value, so no frame shows it unanimated. A press drives the lens while
+ * `isTracking`.
+ */
+export function useSegmentedSelectionMotion(
+ trackRef: RefObject<HTMLElement | null>,
+ value: string,
+ isPresenting: boolean,
+ isTracking: boolean,
+): {
+ readonly selection: SegmentedSelection;
+ /** The radiogroup's callback ref: it attaches the animators to the node. */
+ readonly attachTrack: RefCallback<HTMLElement>;
+} {
+ const [motion] = useState(() => new SegmentedSelectionMotion());
+ const previousValueRef = useRef(value);
+ // The lens is the radiogroup's own pseudo-elements. The animators attach to
+ // it while the touch presentation applies or while a press can drag it,
+ // which any pointer can.
+ const isEnabled = isPresenting || isTracking;
+
+ // Syncs the lens animators with the pointer presentation: a flip hands any
+ // motion in flight back.
+ useIsomorphicLayoutEffect(() => {
+ motion.present(isPresenting);
+ }, [isPresenting, motion]);
+
+ useIsomorphicLayoutEffect(() => {
+ const from = previousValueRef.current;
+ previousValueRef.current = value;
+ const track = trackRef.current;
+ if (!isEnabled || track == null || from === value) {
+ return;
+ }
+ motion.select(track, from, value);
+ }, [isEnabled, motion, trackRef, value]);
+
+ // Stops the animators that drive the radiogroup's pseudo-elements.
+ useEffect(() => () => motion.stop(), [motion]);
+
+ // Every pointer's press is tracked. The lift commits the segment nearest
+ // the pointer, through that segment's click.
+ const clickWait = useSegmentedTouchTracking(trackRef, motion, isTracking);
+
+ // The animators attach to the radiogroup while enabled. The lens aims at
+ // boxes measured when its motion began, so a resize hands the surface back.
+ const attachTrack = useCallback(
+ (track: HTMLElement | null) => {
+ if (track == null || !isEnabled) {
+ return undefined;
+ }
+ motion.attachTrack(track);
+ const unobserve = observeResize(track, () => motion.resized(track));
+ return () => {
+ unobserve();
+ motion.settle();
+ motion.attachTrack(null);
+ };
+ },
+ [isEnabled, motion],
+ );
+
+ const [selection] = useState<SegmentedSelection>(() => ({
+ isPressing: () => motion.isPressed || clickWait.isAwaiting(),
+ keyPressed: clickWait.end,
+ }));
+ return {selection, attachTrack};
+}
diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts
new file mode 100644
index 0000000000..b62b5b0fe8
--- /dev/null
+++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.test.ts
@@ -0,0 +1,103 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useSegmentedTouchTracking.test.ts
+ * @input useSegmentedTouchTracking.ts's segment resolution
+ * @output Proof of which segment a finger counts for, the rule the
+ * action-group tracker resolves the highlight and the commit with
+ * @position Testing for /packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ liftTargetAt,
+ segmentTargetAt,
+ type SegmentSpan,
+} from './useSegmentedTouchTracking';
+
+function spans(
+ layout: ReadonlyArray<[string, number, number]>,
+ disabled: ReadonlyArray<string> = [],
+): SegmentSpan[] {
+ return layout.map(([value, left, right]) => {
+ const element = document.createElement('button');
+ element.dataset.value = value;
+ if (disabled.includes(value)) {
+ element.setAttribute('aria-disabled', 'true');
+ }
+ return {element, left, right};
+ });
+}
+
+const valueAt = (x: number, segments: SegmentSpan[]) =>
+ segmentTargetAt(x, segments)?.dataset.value ?? null;
+
+describe('segmentTargetAt', () => {
+ // Gaps of 4 px, and a narrow segment beside a wide one.
+ const layout: ReadonlyArray<[string, number, number]> = [
+ ['grid', 12, 108],
+ ['list', 112, 152],
+ ['table', 156, 314],
+ ];
+
+ it('counts a finger over a segment for that segment, however near a narrower neighbour’s center', () => {
+ const segments = spans(layout);
+ // Inside Table, nearer List's center (132) than Table's own (235).
+ expect(valueAt(160, segments)).toBe('table');
+ expect(valueAt(60, segments)).toBe('grid');
+ });
+
+ it('splits a gap at its middle', () => {
+ const segments = spans(layout);
+ expect(valueAt(109, segments)).toBe('grid');
+ expect(valueAt(111, segments)).toBe('list');
+ expect(valueAt(153, segments)).toBe('list');
+ expect(valueAt(155, segments)).toBe('table');
+ });
+
+ it('counts a finger on the padding past either end for the end segment', () => {
+ const segments = spans(layout);
+ expect(valueAt(-40, segments)).toBe('grid');
+ expect(valueAt(400, segments)).toBe('table');
+ });
+
+ it('counts a finger over a disabled segment for nothing', () => {
+ const segments = spans(layout, ['list']);
+ expect(valueAt(130, segments)).toBeNull();
+ expect(valueAt(111, segments)).toBeNull();
+ expect(valueAt(109, segments)).toBe('grid');
+ });
+});
+
+describe('liftTargetAt', () => {
+ // The control's box: the segments plus 2 px of padding all round.
+ const bounds = {left: 10, top: 20, right: 316, bottom: 51};
+ const layout: ReadonlyArray<[string, number, number]> = [
+ ['grid', 12, 108],
+ ['list', 110, 208],
+ ['table', 210, 314],
+ ];
+ const liftAt = (x: number, y: number, segments: SegmentSpan[]) =>
+ 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);
+ expect(liftAt(250, 35, segments)).toBe('table');
+ expect(liftAt(109, 35, segments)).toBe('grid');
+ expect(liftAt(11, 21, segments)).toBe('grid');
+ expect(liftAt(315, 50, segments)).toBe('table');
+ });
+
+ it('commits nothing for a lift outside the control: a press that slides off cancels (spec:AST-020 FR9, DEC-5)', () => {
+ const segments = spans(layout);
+ // Past either end, above, below.
+ expect(liftAt(5, 35, segments)).toBeNull();
+ expect(liftAt(330, 35, segments)).toBeNull();
+ expect(liftAt(250, 10, segments)).toBeNull();
+ expect(liftAt(250, 90, segments)).toBeNull();
+ });
+
+ it('commits nothing over a disabled segment', () => {
+ expect(liftAt(150, 35, spans(layout, ['list']))).toBeNull();
+ });
+});
diff --git a/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
new file mode 100644
index 0000000000..41ccdc7b47
--- /dev/null
+++ b/packages/core/src/SegmentedControl/useSegmentedTouchTracking.ts
@@ -0,0 +1,308 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useSegmentedTouchTracking.ts
+ * @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
+ * @position Internal to SegmentedControl; drives useSegmentedSelectionMotion.ts
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
+ * - /packages/core/src/SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts
+ */
+
+import {useRef, useState, type RefObject} from 'react';
+import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';
+import {useGestureRecognizer} from '../gestures/useGestureRecognizer';
+import {usePressTracker} from '../gestures/usePressTracker';
+import {
+ createActionGroupTracker,
+ type ActionGroupTarget,
+ type ActionGroupTracker,
+} from '../hooks/actionGroupTracker';
+import {lockSelection} from '../gestures/selectionLock';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {awaitBrowserClick, clickForLift} from '../utils/browserClickWait';
+import {
+ SEGMENT_SELECTOR,
+ type SegmentedSelectionMotion,
+} from './useSegmentedSelectionMotion';
+
+/**
+ * A tap's click still to come. Until it runs, a focus move the tap causes
+ * selects nothing. A key press, the next press or a cancel ends the wait.
+ */
+export interface ClickWait {
+ readonly isAwaiting: () => boolean;
+ readonly end: () => void;
+}
+
+/** A ref to nothing: hooks given it attach nothing. */
+const DETACHED: RefObject<HTMLElement | null> = {current: null};
+
+/** The control's box as measured when the finger landed: viewport px. */
+export interface ControlBounds {
+ readonly left: number;
+ readonly top: number;
+ readonly right: number;
+ readonly bottom: number;
+}
+
+/** A segment as measured when the finger landed: its viewport span, px. */
+export interface SegmentSpan {
+ readonly element: HTMLElement;
+ readonly left: number;
+ readonly right: number;
+}
+
+/** Every segment of `track`, disabled ones included, measured once. */
+export function measureSegments(track: HTMLElement): SegmentSpan[] {
+ return Array.from(
+ track.querySelectorAll<HTMLElement>(SEGMENT_SELECTOR),
+ element => {
+ const rect = element.getBoundingClientRect();
+ return {element, left: rect.left, right: rect.right};
+ },
+ );
+}
+
+function isDisabled(element: HTMLElement): boolean {
+ return (
+ element.hasAttribute('disabled') ||
+ element.getAttribute('aria-disabled') === 'true'
+ );
+}
+
+/**
+ * The segment a finger at viewport `x` counts for: the one under it, else the
+ * nearest. A gap between two segments splits at its middle, as UIKit's
+ * segments share an edge. Past the ends, the end segment counts. The result is
+ * null when that segment is disabled.
+ */
+export function segmentTargetAt(
+ x: number,
+ segments: ReadonlyArray<SegmentSpan>,
+): HTMLElement | null {
+ let best: SegmentSpan | null = null;
+ let distance = Infinity;
+ for (const segment of segments) {
+ const d = Math.max(segment.left - x, 0, x - segment.right);
+ if (d < distance) {
+ distance = d;
+ best = segment;
+ }
+ }
+ return best != null && !isDisabled(best.element) ? best.element : null;
+}
+
+/**
+ * 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.
+ */
+export function liftTargetAt(
+ x: number,
+ y: number,
+ bounds: 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 NO_BOUNDS: ControlBounds = {left: 0, top: 0, right: -1, bottom: -1};
+
+/**
+ * Tracks a press on the control as UIKit's segmented control does. The press
+ * tracker reports the press from landing to lift. It never claims the
+ * pointer, so a vertical drag still scrolls the page. A horizontal pan
+ * carries the lens. It claims the pointer only past its slop, and the lift
+ * 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.
+ *
+ * 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
+ * `onClick` runs once and can cancel the selection. A mouse and a pen are
+ * tracked as a finger is. Keyboard and assistive technology keep the click.
+ */
+export function useSegmentedTouchTracking(
+ trackRef: RefObject<HTMLElement | null>,
+ motion: SegmentedSelectionMotion,
+ isEnabled: boolean,
+): ClickWait {
+ /** The horizontal pan began for this touch: it is a drag, not a tap. */
+ 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);
+ const trackerRef = useRef<ActionGroupTracker | null>(null);
+ const tracker = (trackerRef.current ??= createActionGroupTracker(() => ({
+ roots: () => [trackRef.current],
+ itemSelector: SEGMENT_SELECTOR,
+ highlightExpansion: 0,
+ // The press controller writes the shared press paint on the touched
+ // segment, as everywhere under a finger. The tracker paints nothing of its
+ // own. A held lens shows the selected face.
+ paintsHighlight: false,
+ resolveTarget: (
+ x: number,
+ y: number,
+ _targets: ReadonlyArray<ActionGroupTarget>,
+ ) => liftTargetAt(x, y, boundsRef.current, segmentsRef.current),
+ onActivated: (item, cancelled) => {
+ const track = trackRef.current;
+ const value = item.dataset.value;
+ if (track != null && value != null) {
+ motion.clicked(track, value, cancelled);
+ }
+ },
+ swallowsNativeClick: true,
+ })));
+ /** Click waits still running: an unmount ends them. */
+ const pendingClicksRef = useRef<Set<() => void>>(new Set());
+ /**
+ * A tap lifted and its click has not run. After a direct click, the
+ * browser's late copy can still move focus, so the wait then lasts until the
+ * next key or press.
+ */
+ const clickToComeRef = useRef(false);
+ const [clickWait] = useState<ClickWait>(() => ({
+ isAwaiting: () => clickToComeRef.current,
+ end: () => {
+ clickToComeRef.current = false;
+ },
+ }));
+ // Ends the tracker's window listeners and any click wait on unmount.
+ useIsomorphicLayoutEffect(() => {
+ const pendingClicks = pendingClicksRef.current;
+ return () => {
+ tracker.dispose();
+ clickWait.end();
+ for (const end of [...pendingClicks]) {
+ end();
+ }
+ };
+ }, [tracker, clickWait]);
+
+ // Every pointer type is tracked. A disabled control attaches nothing.
+ const attachRef = isEnabled ? trackRef : DETACHED;
+ usePressTracker(attachRef, {
+ isEnabled: () => isEnabled,
+ onControlEvent: (event, touch) => {
+ const track = trackRef.current;
+ if (track == null) {
+ return;
+ }
+ switch (event) {
+ case 'touchDown': {
+ 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,
+ };
+ tracker.begin(touch.x, touch.y);
+ motion.begin(track, tracker.beganOn, touch.pointerType === 'touch');
+ break;
+ }
+ case 'touchUpInside':
+ case 'touchUpOutside': {
+ // The lift decides, wherever the press began. A lift outside the
+ // control commits nothing.
+ tracker.move(touch.x, touch.y);
+ const lifted = tracker.highlighted;
+ const isTap =
+ event === 'touchUpInside' &&
+ !isDraggingRef.current &&
+ lifted != null &&
+ lifted === tracker.beganOn;
+ const value = motion.release(lifted);
+ if (value != null && isTap && lifted != null) {
+ // A tap: the browser's own click commits it.
+ tracker.cancel();
+ clickToComeRef.current = true;
+ const pending = pendingClicksRef.current;
+ const endWait = awaitBrowserClick(lifted, {
+ onClicked: isCancelled => {
+ pending.delete(endWait);
+ clickWait.end();
+ motion.clicked(track, value, isCancelled);
+ },
+ onNoClick: () => {
+ pending.delete(endWait);
+ motion.clicked(track, value, clickForLift(lifted));
+ },
+ });
+ pending.add(endWait);
+ } else if (value != null) {
+ // No click comes from the browser for a drag: the segment's own
+ // click, inside the lift's event; its onClick may veto it.
+ tracker.end();
+ } else {
+ tracker.cancel();
+ }
+ break;
+ }
+ case 'touchCancel':
+ clickWait.end();
+ tracker.cancel();
+ motion.cancel();
+ break;
+ case 'touchDragInside':
+ case 'touchDragOutside':
+ case 'touchDragEnter':
+ case 'touchDragExit':
+ // The horizontal pan carries the lens.
+ break;
+ }
+ },
+ });
+ useGestureRecognizer(
+ attachRef,
+ () =>
+ new PanGestureRecognizer({
+ name: 'segmented-control-drag',
+ direction: 'horizontal',
+ cancelsTouchesInView: false,
+ // No title is selectable under a held finger, as in UIKit. A hold on
+ // the track does something: a drag carries the lens and commits where
+ // it lifts. So this recognizer brings the lock, and the host turns off
+ // text selection and the callout on the track while a finger is down.
+ selectionLock: lockSelection,
+ }),
+ recognizer => {
+ if (recognizer.state === 'began') {
+ isDraggingRef.current = true;
+ }
+ if (recognizer.state === 'began' || recognizer.state === 'changed') {
+ const {x, y} = recognizer.location();
+ // The lens chases the finger, then the tracker moves the highlight.
+ motion.drag(x);
+ tracker.move(x, y);
+ }
+ },
+ {isEnabled},
+ );
+ return clickWait;
+}
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index 69d24d0dbe..2d0b2f0536 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -1398,11 +1398,15 @@ describe('touch listeners (spec:AST-094 FR24)', () => {
// React's root delegates touch events too: count against a plain element.
const listenersWhileRendering = (
isDisabled: boolean | 'none' | 'busy',
- ): {touch: number; pointer: number; contextMenu: number} => {
+ ): {touch: number; pointer: number; contextMenu: number; click: number} => {
vi.spyOn(window, 'matchMedia').mockImplementation(coarseMedia);
const types: string[] = [];
+ const clickTargets: unknown[] = [];
const record = function (this: unknown, type: string) {
types.push(type);
+ if (type === 'click') {
+ clickTargets.push(this);
+ }
};
const onDocument = vi
.spyOn(document, 'addEventListener')
@@ -1410,7 +1414,7 @@ describe('touch listeners (spec:AST-094 FR24)', () => {
const onElements = vi
.spyOn(HTMLElement.prototype, 'addEventListener')
.mockImplementation(record);
- const {unmount} = render(
+ const {container, unmount} = render(
isDisabled === 'none' ? (
<div />
) : (
@@ -1425,26 +1429,37 @@ describe('touch listeners (spec:AST-094 FR24)', () => {
);
onDocument.mockRestore();
onElements.mockRestore();
+ // On the switch's own elements, read while they are mounted: React's root
+ // and the page's shared listeners are not the switch's.
+ const ownClicks = clickTargets.filter(
+ target =>
+ target instanceof Node &&
+ target !== container &&
+ container.contains(target),
+ ).length;
unmount();
vi.restoreAllMocks();
return {
touch: types.filter(type => type.startsWith('touch')).length,
pointer: types.filter(type => type.startsWith('pointer')).length,
contextMenu: types.filter(type => type === 'contextmenu').length,
+ click: ownClicks,
};
};
- it('a switch under a coarse pointer attaches no touch listener, and a disabled one arms no press listener', () => {
+ it('a switch under a coarse pointer attaches no touch or click listener, and a disabled one arms no press listener', () => {
const baseline = listenersWhileRendering('none');
const enabled = listenersWhileRendering(false);
const disabled = listenersWhileRendering(true);
const busy = listenersWhileRendering('busy');
// No state adds a touch listener, so a scroll never waits on the switch.
// Nor a context-menu one: the gesture host keeps a held switch's menu
- // closed.
+ // closed. Nor a click one on its own elements: a lift's click wait
+ // listens only while it waits (utils/browserClickWait.ts).
for (const counts of [enabled, disabled, busy]) {
expect(counts.touch).toBe(baseline.touch);
expect(counts.contextMenu).toBe(baseline.contextMenu);
+ expect(counts.click).toBe(0);
}
// The gesture host arms a press listener for an enabled switch only.
expect(enabled.pointer).toBeGreaterThan(disabled.pointer);
diff --git a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
index da2dce3d7c..25331242d5 100644
--- a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
+++ b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
@@ -54,7 +54,7 @@ import {
type TouchDriver,
} from '@astryxdesign/interaction-harness';
import {press} from '../../motion/uikit/timing';
-import {BROWSER_CLICK_WAIT_MS} from '../switchTouch';
+import {BROWSER_CLICK_WAIT_MS} from '../../utils/browserClickWait';
import {CLICK_GUARD_WINDOW_MS} from '../../utils/clickGuard';
const storybook = withStorybook(test);
diff --git a/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts
index 4f1fd2df0b..403685fd52 100644
--- a/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts
+++ b/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts
@@ -21,7 +21,7 @@ import {
webInputDriver,
withStorybook,
} from '@astryxdesign/interaction-harness';
-import {BROWSER_CLICK_WAIT_MS} from '../switchTouch';
+import {BROWSER_CLICK_WAIT_MS} from '../../utils/browserClickWait';
const storybook = withStorybook(test);
diff --git a/packages/core/src/Switch/switchTouch.ts b/packages/core/src/Switch/switchTouch.ts
index 30e798c7ce..36e8867fa8 100644
--- a/packages/core/src/Switch/switchTouch.ts
+++ b/packages/core/src/Switch/switchTouch.ts
@@ -4,8 +4,8 @@
* @file switchTouch.ts
* @input The UIKit switch constants (motion/uikit/switch.ts) and a track size
* @output The pure model of Switch's touch presentation: thumb geometry, the
- * drag's target, the flip rule, the commit on release and its click wait,
- * and when the lifted thumb may settle
+ * drag's target, the flip rule, the commit on release, and when the lifted
+ * thumb may settle
* @position Pure half of Switch's touch presentation; driven by
* useSwitchTouch.ts, tested by switchTouch.test.ts without a browser
*
@@ -158,14 +158,6 @@ export function stepFlip(
return isPast === flip.isArmed ? flip : {...flip, isArmed: isPast};
}
-/**
- * Passive: how long a lift waits for the browser's own click before the
- * switch clicks its input itself, ms. The browser sends that click with the
- * lift's `touchend`. The surface's `touch-action` leaves no double-tap delay.
- * So this only runs out for a lift the browser does not count as a click.
- */
-export const BROWSER_CLICK_WAIT_MS = 300;
-
/**
* What a release commits: the side a drag flipped to; when nothing flipped,
* the other side of the value, wherever the finger lifts. A press slid off
diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.ts
index ed284e3f2c..0252a47587 100644
--- a/packages/core/src/Switch/useSwitchTouch.ts
+++ b/packages/core/src/Switch/useSwitchTouch.ts
@@ -31,9 +31,9 @@ import {solveSpring, toSpring, type SpringDescription} from '../motion/spring';
import {UIKIT_GESTURES} from '../motion/uikit/gestures';
import {registerSwitchTable, switchControl} from '../motion/uikit/switch';
import {useTouchPresentation} from '../utils/touchPresentation';
-import {armClickGuard, withoutClickGuard} from '../utils/clickGuard';
+import {awaitBrowserClick, clickForLift} from '../utils/browserClickWait';
+import {armClickGuard} from '../utils/clickGuard';
import {
- BROWSER_CLICK_WAIT_MS,
commitOnRelease,
dragTarget,
settleTime,
@@ -253,11 +253,8 @@ export class SwitchTouchController {
private isTracking = false;
/** Which presentation the switch has: the touch one, or its own. */
private presentation: SwitchPresentation = 'touch';
- /** The press-time listeners under a fine pointer, while armed. */
- private pressListeners: (() => void) | null = null;
- private pressListenersTimer: ReturnType<typeof setTimeout> | null = null;
- /** Passive: a lift is waiting for the browser's own click. */
- private browserClickTimer: ReturnType<typeof setTimeout> | null = null;
+ /** Passive: a lift is waiting for the browser's own click; this ends it. */
+ private endBrowserClickWait: (() => void) | null = null;
private reconcileTimer: ReturnType<typeof setTimeout> | null = null;
constructor(isOn: boolean, geometry: SwitchTouchGeometry) {
@@ -328,73 +325,7 @@ export class SwitchTouchController {
}
},
});
- // The lift's own click activates the input natively: the switch then
- // clicks nothing itself.
- const onClick = (event: MouseEvent) => {
- if (event.isTrusted && this.browserClickTimer != null) {
- clearTimeout(this.browserClickTimer);
- this.browserClickTimer = null;
- this.scheduleReconcile();
- }
- };
- const listen = (): (() => void) => {
- surface.addEventListener('click', onClick, true);
- return () => {
- surface.removeEventListener('click', onClick, true);
- };
- };
- if (this.presentation === 'pointer') {
- // Under a fine pointer only the press the host arms listens at rest.
- // The switch's click listener comes with a press and goes after its
- // click wait.
- this.listenForPress = listen;
- return [
- host.attachConsumer(surface, tracker),
- () => tracker.dispose(),
- () => this.stopPressListeners(),
- ];
- }
- return [
- host.attachConsumer(surface, tracker),
- () => tracker.dispose(),
- listen(),
- ];
- }
-
- /** Under a fine pointer: adds the switch's own listeners for a press. */
- private listenForPress: (() => () => void) | null = null;
-
- private startPressListeners(): void {
- if (this.pressListenersTimer != null) {
- clearTimeout(this.pressListenersTimer);
- this.pressListenersTimer = null;
- }
- if (this.pressListeners == null && this.listenForPress != null) {
- this.pressListeners = this.listenForPress();
- }
- }
-
- /** The press's click window is over: its listeners go. */
- private endPressListeners(afterMs: number): void {
- if (this.pressListeners == null) {
- return;
- }
- if (this.pressListenersTimer != null) {
- clearTimeout(this.pressListenersTimer);
- }
- this.pressListenersTimer = setTimeout(() => {
- this.pressListenersTimer = null;
- this.stopPressListeners();
- }, afterMs);
- }
-
- private stopPressListeners(): void {
- if (this.pressListenersTimer != null) {
- clearTimeout(this.pressListenersTimer);
- this.pressListenersTimer = null;
- }
- this.pressListeners?.();
- this.pressListeners = null;
+ return [host.attachConsumer(surface, tracker), () => tracker.dispose()];
}
/** Undo everything: listeners, timers, animations and inline styles. */
@@ -403,7 +334,6 @@ export class SwitchTouchController {
detach();
}
this.detachers = [];
- this.listenForPress = null;
this.clearTimers();
for (const animator of [this.thumb, this.fade, this.shadow]) {
const element = animator?.element;
@@ -576,7 +506,6 @@ export class SwitchTouchController {
switch (event) {
case 'touchDown':
this.isTracking = true;
- this.startPressListeners();
this.touchDown(time);
return;
case 'touchDragInside':
@@ -612,7 +541,6 @@ export class SwitchTouchController {
byBrowserClick: true,
clicksIfNoBrowserClick: touch.pointerType === 'touch',
});
- this.endPressListeners(BROWSER_CLICK_WAIT_MS);
return;
}
if (
@@ -625,7 +553,6 @@ export class SwitchTouchController {
// off toggles.
this.released = true;
this.abandon(time);
- this.endPressListeners(0);
return;
}
// A drag that flipped, or a press slid off and lifted outside, which
@@ -637,7 +564,6 @@ export class SwitchTouchController {
armClickGuard(this.elements.input.ownerDocument);
}
this.release(time);
- this.endPressListeners(0);
return;
case 'touchCancel':
// The browser took the touch for its scroll, or a recognizer above
@@ -647,7 +573,6 @@ export class SwitchTouchController {
this.released = true;
this.abandon(time);
}
- this.endPressListeners(0);
return;
case 'touchDragEnter':
case 'touchDragExit':
@@ -729,14 +654,23 @@ export class SwitchTouchController {
this.showSide(commit, time, undefined, true);
}
this.pressEnded(time, true);
- if (byBrowserClick) {
- this.browserClickTimer = setTimeout(() => {
- this.browserClickTimer = null;
- if (clicksIfNoBrowserClick && commit !== this.isOn) {
- this.clickInput();
- }
- this.scheduleReconcile();
- }, BROWSER_CLICK_WAIT_MS);
+ const surface = this.elements?.surface;
+ if (byBrowserClick && surface != null) {
+ // The lift's own click activates the input natively: the switch then
+ // clicks nothing itself.
+ this.endBrowserClickWait = awaitBrowserClick(surface, {
+ onClicked: () => {
+ this.endBrowserClickWait = null;
+ this.scheduleReconcile();
+ },
+ onNoClick: () => {
+ this.endBrowserClickWait = null;
+ if (clicksIfNoBrowserClick && commit !== this.isOn) {
+ this.clickInput();
+ }
+ this.scheduleReconcile();
+ },
+ });
return;
}
if (commit !== this.isOn) {
@@ -753,11 +687,9 @@ export class SwitchTouchController {
*/
private clickInput(): void {
const input = this.elements?.input;
- if (input == null) {
- return;
+ if (input != null) {
+ clickForLift(input);
}
- armClickGuard(input.ownerDocument);
- withoutClickGuard(() => input.click());
}
/** If the owner kept the old value, the visuals go back to it. */
@@ -1038,10 +970,8 @@ export class SwitchTouchController {
}
private clearTimers(): void {
- if (this.browserClickTimer != null) {
- clearTimeout(this.browserClickTimer);
- this.browserClickTimer = null;
- }
+ this.endBrowserClickWait?.();
+ this.endBrowserClickWait = null;
if (this.reconcileTimer != null) {
clearTimeout(this.reconcileTimer);
this.reconcileTimer = null;
diff --git a/packages/core/src/hooks/actionGroupTracker.test.ts b/packages/core/src/hooks/actionGroupTracker.test.ts
index 1719962cec..09a2f63958 100644
--- a/packages/core/src/hooks/actionGroupTracker.test.ts
+++ b/packages/core/src/hooks/actionGroupTracker.test.ts
@@ -13,11 +13,13 @@
* highlight callback (with the target it replaces) and the opt-out of the
* paint; an owner's own target resolution (a row of segments, past its
* ends), the finger's raw moves, the begin target, remeasure, a cancelled
- * click reported, and the browser's own click swallowed once
+ * click reported, and the browser's own click taken once by the shared
+ * click guard
* @position jsdom tests of packages/core/src/hooks/actionGroupTracker.ts
*/
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {__resetClickGuardForTest, isClickGuardArmed} from '../utils/clickGuard';
import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
import {PRESS_FADE_MS} from '../utils/pressGesture';
import {
@@ -67,6 +69,7 @@ beforeEach(() => {
afterEach(() => {
root.remove();
+ __resetClickGuardForTest();
vi.useRealTimers();
});
@@ -383,128 +386,49 @@ describe('createActionGroupTracker: options for other trackers', () => {
expect(onActivated).toHaveBeenCalledTimes(2);
});
- it('swallows the browser\u2019s own click after the lift once, listening only until then', () => {
- const add = vi.spyOn(window, 'addEventListener');
- const remove = vi.spyOn(window, 'removeEventListener');
- try {
- const group = tracker({swallowsNativeClick: true});
- group.begin(50, 10);
- add.mockClear();
- group.end();
- // The tracker's own click ran inside end, before the swallower.
- expect(left.onClick).toHaveBeenCalledTimes(1);
- // Listening now: what end added and did not take off again (the
- // capture that reads its own click comes and goes inside the call).
- const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
- const armed = add.mock.calls.filter(
- ([, listener, capture]) => capture === true && !gone.has(listener),
- );
- expect(armed.map(([type]) => type).sort()).toEqual([
- 'click',
- 'keydown',
- 'pointerdown',
- ]);
- remove.mockClear();
- // A script's click is not the browser's: it passes.
- const onDocumentClick = vi.fn();
- document.addEventListener('click', onDocumentClick);
- left.button.click();
- expect(onDocumentClick).toHaveBeenCalledTimes(1);
- // The browser's click for the touch is taken once, and the swallower goes.
- const swallow = armed.find(([type]) => type === 'click')?.[1] as (
- event: unknown,
- ) => void;
- const trusted = {
- isTrusted: true,
- preventDefault: vi.fn(),
- stopImmediatePropagation: vi.fn(),
- };
- swallow(trusted);
- expect(trusted.preventDefault).toHaveBeenCalled();
- expect(trusted.stopImmediatePropagation).toHaveBeenCalled();
- const removed = remove.mock.calls
- .filter(([, , capture]) => capture === true)
- .map(([type]) => type)
- .sort();
- expect(removed).toEqual(['click', 'keydown', 'pointerdown']);
- document.removeEventListener('click', onDocumentClick);
- } finally {
- add.mockRestore();
- remove.mockRestore();
- }
+ it('with swallowsNativeClick the lift clicks once, and the shared click guard takes the browser\u2019s own click', () => {
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ group.end();
+ // The tracker's own click ran inside end and passed the guard.
+ expect(left.onClick).toHaveBeenCalledTimes(1);
+ expect(isClickGuardArmed(document)).toBe(true);
+ // The browser's click for the touch (a pointer's, detail 1) is taken once.
+ left.button.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),
+ );
+ expect(left.onClick).toHaveBeenCalledTimes(1);
+ expect(isClickGuardArmed(document)).toBe(false);
});
- it('lets an activation with detail 0 (keyboard, assistive technology) through while it waits for the browser\u2019s click (spec:AST-094 FR21)', () => {
- const add = vi.spyOn(window, 'addEventListener');
- const remove = vi.spyOn(window, 'removeEventListener');
- try {
- const group = tracker({swallowsNativeClick: true});
- group.begin(50, 10);
- add.mockClear();
- group.end();
- const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
- const swallow = add.mock.calls.find(
- ([type, listener, capture]) =>
- type === 'click' && capture === true && !gone.has(listener),
- )?.[1] as (event: unknown) => void;
- remove.mockClear();
- // A screen reader's or a key's activation is not the touch's click: it
- // passes, and the swallower keeps waiting for the touch's own.
- const activation = {
- isTrusted: true,
- detail: 0,
- preventDefault: vi.fn(),
- stopImmediatePropagation: vi.fn(),
- };
- swallow(activation);
- expect(activation.preventDefault).not.toHaveBeenCalled();
- expect(activation.stopImmediatePropagation).not.toHaveBeenCalled();
- expect(remove).not.toHaveBeenCalled();
- // The touch's own click (detail 1) is still taken once.
- const touchClick = {
- isTrusted: true,
- detail: 1,
- preventDefault: vi.fn(),
- stopImmediatePropagation: vi.fn(),
- };
- swallow(touchClick);
- expect(touchClick.preventDefault).toHaveBeenCalled();
- expect(touchClick.stopImmediatePropagation).toHaveBeenCalled();
- } finally {
- add.mockRestore();
- remove.mockRestore();
- }
+ it('lets an activation with detail 0 (keyboard, assistive technology) through while the guard waits for the browser\u2019s click (spec:AST-094 FR21)', () => {
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ group.end();
+ left.button.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 0}),
+ );
+ expect(left.onClick).toHaveBeenCalledTimes(2);
+ expect(isClickGuardArmed(document)).toBe(true);
});
- it('a press or a key before the browser\u2019s click ends the swallowing; without the option nothing stays listening', () => {
- const add = vi.spyOn(window, 'addEventListener');
- const remove = vi.spyOn(window, 'removeEventListener');
- const listening = () => {
- const gone = new Set(remove.mock.calls.map(([, listener]) => listener));
- return add.mock.calls
- .filter(([, listener]) => !gone.has(listener))
- .map(([type]) => type)
- .sort();
- };
- try {
- const plain = tracker();
- plain.begin(50, 10);
- plain.end();
- expect(listening()).toEqual([]);
- const group = tracker({swallowsNativeClick: true});
- group.begin(50, 10);
- group.end();
- expect(listening()).toEqual(['click', 'keydown', 'pointerdown']);
- // The next press comes first (the browser gave no click): disarmed.
- window.dispatchEvent(new PointerEvent('pointerdown'));
- expect(listening()).toEqual([]);
- group.begin(50, 10);
- group.end();
- window.dispatchEvent(new KeyboardEvent('keydown', {key: 'Tab'}));
- expect(listening()).toEqual([]);
- } finally {
- add.mockRestore();
- remove.mockRestore();
- }
+ it('the next press ends the guard; without the option nothing is armed, and an owner\u2019s onActivate gets the guard too', () => {
+ const plain = tracker();
+ plain.begin(50, 10);
+ plain.end();
+ expect(isClickGuardArmed(document)).toBe(false);
+ const group = tracker({swallowsNativeClick: true});
+ group.begin(50, 10);
+ group.end();
+ expect(isClickGuardArmed(document)).toBe(true);
+ // The next press comes first (the browser gave no click): disarmed.
+ window.dispatchEvent(new PointerEvent('pointerdown'));
+ expect(isClickGuardArmed(document)).toBe(false);
+ const onActivate = vi.fn();
+ const owned = tracker({swallowsNativeClick: true, onActivate});
+ owned.begin(50, 10);
+ owned.end();
+ expect(onActivate).toHaveBeenCalledWith(left.button);
+ expect(isClickGuardArmed(document)).toBe(true);
});
});
diff --git a/packages/core/src/hooks/actionGroupTracker.ts b/packages/core/src/hooks/actionGroupTracker.ts
index 04ea432b64..4c86343941 100644
--- a/packages/core/src/hooks/actionGroupTracker.ts
+++ b/packages/core/src/hooks/actionGroupTracker.ts
@@ -12,6 +12,8 @@
* SYNC: When modified, update actionGroupTracker.test.ts
*/
+import {clickAndReport, clickForLift} from '../utils/browserClickWait';
+import {armClickGuard} from '../utils/clickGuard';
import {PRESSED_ATTRIBUTE} from '../utils/pressFeedback';
import {PRESS_FADE_MS} from '../utils/pressGesture';
@@ -70,9 +72,9 @@ export interface ActionGroupTrackerOptions {
*/
onActivated?: (item: HTMLElement, cancelled: boolean) => void;
/**
- * After the lift ran an action, take the browser's own click for that
- * touch (left to it by a recognizer that did not claim the touch), so the
- * action runs once. @default false
+ * After the lift ran an action, the shared click guard takes the browser's
+ * own click for that touch, so the action runs once. A recognizer that did
+ * not claim the touch leaves that click to the browser. @default false
*/
swallowsNativeClick?: boolean;
}
@@ -126,54 +128,6 @@ interface TrackedAction {
bottom: number;
}
-/**
- * Swallow the browser's own click for a touch that the lift already acted
- * on. The listeners exist only from that lift until the click, the next
- * press, or the next key. An activation with `detail === 0` (a key or
- * assistive technology) always passes, and the swallower keeps waiting
- * (`AST-094`).
- */
-function swallowNextClick(view: Window): void {
- const disarm = () => {
- view.removeEventListener('click', onClick, true);
- view.removeEventListener('pointerdown', disarm, true);
- view.removeEventListener('keydown', disarm, true);
- };
- const onClick = (event: MouseEvent) => {
- if (!event.isTrusted || event.detail === 0) {
- return;
- }
- disarm();
- event.preventDefault();
- event.stopImmediatePropagation();
- };
- view.addEventListener('click', onClick, true);
- view.addEventListener('pointerdown', disarm, true);
- view.addEventListener('keydown', disarm, true);
-}
-
-/**
- * Click `element` (its own `click()`, so its activation behavior and every
- * handler run as for any click) and report whether a handler cancelled it.
- * The event is read from a capture listener that exists only for the call.
- */
-function clickAndReport(element: HTMLElement): boolean {
- const view = element.ownerDocument.defaultView;
- let clicked: Event | null = null;
- const grab = (event: Event) => {
- if (clicked == null && event.target === element) {
- clicked = event;
- }
- };
- view?.addEventListener('click', grab, true);
- try {
- element.click();
- } finally {
- view?.removeEventListener('click', grab, true);
- }
- return (clicked as Event | null)?.defaultPrevented === true;
-}
-
/**
* Create a tracker. `getOptions` is read on every call, so a hook can pass
* the latest props without recreating it.
@@ -358,14 +312,16 @@ export function createActionGroupTracker(
const {onActivate, onActivated, swallowsNativeClick} = getOptions();
if (onActivate != null) {
onActivate(lifted);
+ if (swallowsNativeClick === true) {
+ armClickGuard(lifted.ownerDocument);
+ }
} else {
- const cancelled = clickAndReport(lifted);
+ const cancelled =
+ swallowsNativeClick === true
+ ? clickForLift(lifted)
+ : clickAndReport(lifted);
onActivated?.(lifted, cancelled);
}
- const view = lifted.ownerDocument.defaultView;
- if (swallowsNativeClick === true && view != null) {
- swallowNextClick(view);
- }
return lifted;
},
cancel() {
diff --git a/packages/core/src/hooks/useMediaQuery.doc.mjs b/packages/core/src/hooks/useMediaQuery.doc.mjs
index da3022b3a2..6f9cfcfdd4 100644
--- a/packages/core/src/hooks/useMediaQuery.doc.mjs
+++ b/packages/core/src/hooks/useMediaQuery.doc.mjs
@@ -21,7 +21,7 @@ export const docs = {
},
],
usage: {
- description: 'SSR-safe media query hook that subscribes to window.matchMedia changes. Returns whether the given media query matches. Always returns false on first render for SSR compatibility.',
+ description: 'SSR-safe media query hook that subscribes to window.matchMedia changes. Returns whether the given media query matches. Always returns false on first render for SSR compatibility. Where `window.matchMedia` is missing, it returns its server default and never throws.',
bestPractices: [
{ guidance: true, description: 'Use for responsive layout switching based on viewport width, color scheme, or motion preferences.' },
{ guidance: true, description: 'Prefer Astryx responsive tokens and component props over manual breakpoint logic when possible.' },
@@ -44,7 +44,7 @@ export const docsDense = {
matches: 'whether media query currently matches. Always false on first render (SSR-safe).',
},
usage: {
- description: 'SSR-safe media query hook subscribing to window.matchMedia changes. Returns whether given media query matches. Always returns false on first render for SSR compatibility.',
+ description: 'SSR-safe media query hook subscribing to window.matchMedia changes. Returns whether given media query matches. Always returns false on first render for SSR compatibility. Where `window.matchMedia` is missing, returns its server default and never throws.',
bestPractices: [
{ guidance: true, description: 'Use for responsive layout switching based on viewport width, color scheme, or motion preferences.' },
{ guidance: true, description: 'Prefer Astryx responsive tokens + component props over manual breakpoint logic when possible.' },
diff --git a/packages/core/src/hooks/useMediaQuery.test.ts b/packages/core/src/hooks/useMediaQuery.test.ts
index e4d7f79534..0d3979a0ec 100644
--- a/packages/core/src/hooks/useMediaQuery.test.ts
+++ b/packages/core/src/hooks/useMediaQuery.test.ts
@@ -162,4 +162,14 @@ describe('useMediaQuery', () => {
const html = renderToString(createElement(TestComponent));
expect(html).toContain('data-mobile="false"');
});
+
+ it('answers its server default where the window has no matchMedia, as a test DOM may', () => {
+ vi.stubGlobal('matchMedia', undefined);
+ const off = renderHook(() => useMediaQuery('(pointer: coarse)'));
+ expect(off.result.current).toBe(false);
+ const on = renderHook(() => useMediaQuery('(pointer: coarse)', true));
+ expect(on.result.current).toBe(true);
+ off.unmount();
+ on.unmount();
+ });
});
diff --git a/packages/core/src/hooks/useMediaQuery.ts b/packages/core/src/hooks/useMediaQuery.ts
index c7e7ee448f..1546d313b1 100644
--- a/packages/core/src/hooks/useMediaQuery.ts
+++ b/packages/core/src/hooks/useMediaQuery.ts
@@ -20,7 +20,8 @@ import {useCallback, useSyncExternalStore} from 'react';
/**
* SSR-safe media query hook.
- * Returns whether the given media query matches.
+ * Returns whether the given media query matches. Where the window has no
+ * `matchMedia`, as in a test DOM, it returns `serverDefault`.
*
* @param query - CSS media query string
* @param serverDefault - Value to return during SSR. Pass a server-side hint
@@ -35,6 +36,10 @@ import {useCallback, useSyncExternalStore} from 'react';
export function useMediaQuery(query: string, serverDefault = false): boolean {
const subscribe = useCallback(
(onStoreChange: () => void) => {
+ // A DOM without `matchMedia`, such as a test DOM, has nothing to watch.
+ if (typeof window.matchMedia !== 'function') {
+ return () => {};
+ }
const mql = window.matchMedia(query);
mql.addEventListener('change', onStoreChange);
return () => mql.removeEventListener('change', onStoreChange);
@@ -42,9 +47,13 @@ export function useMediaQuery(query: string, serverDefault = false): boolean {
[query],
);
- const getSnapshot = useCallback(() => {
- return window.matchMedia(query).matches;
- }, [query]);
+ const getSnapshot = useCallback(
+ () =>
+ typeof window.matchMedia === 'function'
+ ? window.matchMedia(query).matches
+ : serverDefault,
+ [query, serverDefault],
+ );
const getServerSnapshot = useCallback(() => serverDefault, [serverDefault]);
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index c9b0f16579..e5306b7539 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -219,6 +219,13 @@ Bookmarks sheet.
| M-SG18 | iPad S1 (touch; pointer if available) | tap, hold, drag; hover | differences from iPhone | B |
| M-SG19 | Safari showing the segmented stories vs S1 | the segmented storyboards side by side | synced recordings (parity proof) | B |
+Done (UIKit lab, iOS 26.2 simulator, Oct 23–24 2026; in the segmented control's
+own table, `uikit/segmented.ts`, tagged `measured:`): M-SG02 (the selection
+spring and the drag clamp; the tracking spring is the shared
+`springs.fingerTracking`; the lift was measured too and is not in the table,
+since a pressed thumb's lift is a theme's) and M-SG03 (the tap's frames,
+fitted per frame).
+
## Sheets (UISheetPresentationController)
Probe app "SheetProbe" on an iPhone 16 Pro (iPad Pro 11" for M-SH11 / M-SH20 /
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index 6ac6f5e5da..2f255c73a0 100644
--- a/packages/core/src/motion/README.md
+++ b/packages/core/src/motion/README.md
@@ -22,6 +22,7 @@ roles through `resolveMotion`.
| `uikit/navigation.ts` | UINavigationController: push velocity, parallax, dimming, transition clock, interactive pop finish rule. |
| `uikit/progressBar.ts` | UIProgressView's fill: the whole-track duration and curve, its minimum length and empty alpha; the reduced-motion pulse (three roles). |
| `uikit/gestures.ts` | Gesture recognizer thresholds, the velocity filter and haptic stand-ins, as `{value, unit}` entries (sources in JSDoc). |
+| `uikit/segmented.ts` | UISegmentedControl: the selection indicator's spring; under Reduce Motion the animator's cross-fade replaces it. |
| `uikit/switch.ts` | UISwitch on iOS 26.2: geometry, the lift, settle, travel and tracking springs, the flip distance, the track colour. |
| `roles.ts` | The internal motion roles: the springs, durations and curves `spec:AST-094` FR4 names, registered by the shared tables, and a role's CSS form read back. |
| `roleValue.ts` | A role's CSS form, written: a spring's duration and bounce, a duration in ms, a curve's `cubic-bezier()`. |
diff --git a/packages/core/src/motion/roles.test.ts b/packages/core/src/motion/roles.test.ts
index 4b072edb06..b38d97e4f1 100644
--- a/packages/core/src/motion/roles.test.ts
+++ b/packages/core/src/motion/roles.test.ts
@@ -23,6 +23,7 @@ import {
motionRoleIn,
motionRoleOf,
motionRoleVariable,
+ parseCssEasing,
parseMotionRoleValue,
registerMotionTable,
} from './roles';
@@ -219,6 +220,7 @@ describe('motion roles', () => {
expect(
Object.fromEntries(discoveredRoles().map(role => [role.id, role.kind])),
).toMatchObject({
+ 'segmented.selectionSpring': 'spring',
'springs.contextMenuDismiss': 'spring',
'springs.contextMenuLift': 'spring',
'springs.contextMenuMorph': 'spring',
@@ -295,3 +297,19 @@ describe('motion roles', () => {
expect(parseMotionRoleValue('curve', 'ease-in')).toBeNull();
});
});
+
+describe('parseCssEasing', () => {
+ it('reads a keyword as the control points CSS gives it, and a cubic-bezier() as a curve role does', () => {
+ expect(parseCssEasing('linear')).toEqual([0, 0, 1, 1]);
+ expect(parseCssEasing(' ease-out ')).toEqual([0, 0, 0.58, 1]);
+ expect(parseCssEasing('cubic-bezier(0.24, 1, 0.4, 1)')).toEqual([
+ 0.24, 1, 0.4, 1,
+ ]);
+ });
+
+ it('gives null for an easing it cannot read as one curve', () => {
+ expect(parseCssEasing('steps(4)')).toBeNull();
+ expect(parseCssEasing('')).toBeNull();
+ expect(parseCssEasing('cubic-bezier(2, 0, 0.5, 1)')).toBeNull();
+ });
+});
diff --git a/packages/core/src/motion/roles.ts b/packages/core/src/motion/roles.ts
index 15381b4a3d..f3a6d6d3cb 100644
--- a/packages/core/src/motion/roles.ts
+++ b/packages/core/src/motion/roles.ts
@@ -5,7 +5,8 @@
* @input The motion tables (motion/uikit and each component's own table)
* @output registerMotionTable, motionRoleOf, motionRoleIn, listMotionRoles,
* motionRoleVariable, and the CSS form of a role's value
- * (formatMotionRoleValue, parseMotionRoleValue)
+ * (formatMotionRoleValue, parseMotionRoleValue), and parseCssEasing for a
+ * CSS transition's easing
* @position Motion foundation, internal to core: read by the code that
* resolves a role when a motion starts. No public API writes a role: touch
* motion stays internal until the public motion-token set is decided.
@@ -260,3 +261,21 @@ export function parseMotionRoleValue(
? points
: null;
}
+
+/** The CSS easing keywords, as the control points CSS gives them. */
+const EASING_KEYWORDS: Readonly<Record<string, MotionCurvePoints>> = {
+ linear: [0, 0, 1, 1],
+ ease: [0.25, 0.1, 0.25, 1],
+ 'ease-in': [0.42, 0, 1, 1],
+ 'ease-out': [0, 0, 0.58, 1],
+ 'ease-in-out': [0.42, 0, 0.58, 1],
+};
+
+/**
+ * Reads a CSS easing, a keyword or a `cubic-bezier()`, as a curve role's value
+ * is read. Returns null for any other easing, such as `steps()`.
+ */
+export function parseCssEasing(text: string): MotionCurvePoints | null {
+ const value = text.trim();
+ return EASING_KEYWORDS[value] ?? parseMotionRoleValue('curve', value);
+}
diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts
index 8245cc908e..ab92f5038e 100644
--- a/packages/core/src/motion/uikit/index.ts
+++ b/packages/core/src/motion/uikit/index.ts
@@ -4,10 +4,10 @@
* @file index.ts
* @input The domain files of the UIKit constants table
* @output Re-exports `springs` and one constant per spring (`SHEET_PRESENT_SPRING`,
- * …), `scroll`, `timing`, `navigation`, `progressBar`, the `slider` and
- * switch (`switchControl`) domains, and the gesture thresholds (one
- * `UIKIT_*` group per recognizer, their union `UIKIT_GESTURES`, and the
- * haptic tables)
+ * …), `scroll`, `timing`, `navigation`, `progressBar`, `segmentedControl`,
+ * the `slider` and switch (`switchControl`) domains, and the gesture
+ * thresholds (one `UIKIT_*` group per recognizer, their union
+ * `UIKIT_GESTURES`, and the haptic tables)
* @position Entry of the UIKit constants table (motion/uikit). Internal to
* core: not exported from the package entry point
*
@@ -42,6 +42,7 @@ export {
export {navigation, registerNavigationTable} from './navigation';
export {progressBar, registerProgressBarTable} from './progressBar';
export {registerScrollTable, scroll} from './scroll';
+export {segmentedControl} from './segmented';
export {slider} from './slider';
export {
ACTION_SHEET_DISMISS_SPRING,
@@ -64,7 +65,6 @@ export {
NAVIGATION_POP_SPRING,
NAVIGATION_PUSH_SPRING,
QUICK_CHANGE_SPRING,
- SEGMENTED_THUMB_SPRING,
SETTLE_SPRING,
SHEET_DETENT_SPRING,
SHEET_DISMISS_SPRING,
diff --git a/packages/core/src/motion/uikit/segmented.test.ts b/packages/core/src/motion/uikit/segmented.test.ts
new file mode 100644
index 0000000000..9822e77093
--- /dev/null
+++ b/packages/core/src/motion/uikit/segmented.test.ts
@@ -0,0 +1,188 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file segmented.test.ts
+ * @input vitest, the segmented-control domain of the UIKit constants table,
+ * the spring solver, and samples of UIKit's own selection slide
+ * @output Holds `segmentedControl.selectionSpring` to UISegmentedControl's
+ * measured slide (position per frame, iOS 26.2 simulator), an internal
+ * constant no theme retunes
+ * @position Testing; parity of the segmented-control constants (law P4,
+ * unit layer). The browser layer is
+ * SegmentedControl/__tests__/SegmentedControl.interaction.browser.spec.ts.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {dampingRatioOf, responseOf, solveSpring, toSpring} from '../spring';
+import {motionRoleIn, motionRoleOf} from '../roles';
+import {resolveMotion} from '../resolveMotion';
+import {registerSegmentedTable, segmentedControl} from './segmented';
+import {registerSpringsTable, springs} from './springs';
+
+/**
+ * The selection lens's presented position per frame, in pt within the
+ * control. Time 0 is the frame where the slide's presentation value first
+ * appears. The data is UIKit lab capture `b5-segmented` on the iOS 26.2
+ * simulator: a 300 × 31 pt control of three equal segments.
+ */
+const MEASURED = {
+ tap: {
+ from: 50,
+ to: 250,
+ samples: [
+ [0.0, 50],
+ [69.1, 117.81],
+ [135.6, 191.14],
+ [206.4, 231.12],
+ [267.7, 246.72],
+ [333.3, 250.89],
+ [403.2, 251.17],
+ [470.0, 250.67],
+ [536.6, 250.27],
+ ],
+ },
+ animatedSet: {
+ from: 250,
+ to: 50,
+ samples: [
+ [0.0, 250],
+ [71.9, 184.42],
+ [139.9, 110.35],
+ [204.5, 69.55],
+ [272.0, 53.5],
+ [340.1, 49.15],
+ [406.5, 48.82],
+ [471.1, 49.32],
+ [538.5, 49.72],
+ ],
+ },
+} as const;
+
+/**
+ * The worst and rms distance between the table's spring and a measured
+ * slide. The capture logs a frame a few ms after the animation is created, so
+ * the start is searched within ±6 ms; nothing else is fitted.
+ */
+function residuals({
+ from,
+ to,
+ samples,
+}: (typeof MEASURED)[keyof typeof MEASURED]): {
+ worst: number;
+ rms: number;
+ offsetMs: number;
+} {
+ const curve = solveSpring(toSpring(segmentedControl.selectionSpring), {
+ from,
+ to,
+ velocity: 0,
+ });
+ let best = {worst: Infinity, rms: Infinity, offsetMs: 0};
+ for (let offset = -6; offset <= 6; offset += 0.25) {
+ let worst = 0;
+ let squares = 0;
+ for (const [t, x] of samples) {
+ const error = Math.abs(curve.value(Math.max(0, t + offset) / 1000) - x);
+ worst = Math.max(worst, error);
+ squares += error * error;
+ }
+ const rms = Math.sqrt(squares / samples.length);
+ if (rms < best.rms) {
+ best = {worst, rms, offsetMs: offset};
+ }
+ }
+ return best;
+}
+
+describe('segmentedControl.selectionSpring reproduces UIKit’s slide', () => {
+ it('is the response / damping ratio the capture fits', () => {
+ const spring = toSpring(segmentedControl.selectionSpring);
+ expect(responseOf(spring)).toBeCloseTo(0.4, 6);
+ expect(dampingRatioOf(spring)).toBeCloseTo(0.85, 6);
+ });
+
+ it.each(Object.entries(MEASURED))(
+ 'matches the measured %s slide within a point',
+ (_name, measured) => {
+ const {worst, rms} = residuals(measured);
+ expect(rms).toBeLessThan(0.75);
+ expect(worst).toBeLessThan(1.5);
+ },
+ );
+
+ it('overshoots like UIKit: about 1.25 pt past a 200 pt move, then settles back', () => {
+ const curve = solveSpring(toSpring(segmentedControl.selectionSpring), {
+ from: 50,
+ to: 250,
+ velocity: 0,
+ });
+ let peak = 0;
+ for (let t = 0; t <= 1; t += 0.001) {
+ peak = Math.max(peak, curve.value(t));
+ }
+ // Measured peak 251.25 at about 0.39 s (tap) and 251.23 (programmatic).
+ expect(peak - 250).toBeGreaterThan(0.9);
+ expect(peak - 250).toBeLessThan(1.6);
+ expect(Math.abs(curve.value(0.6) - 250)).toBeLessThan(0.5);
+ });
+});
+
+describe('the drag chase', () => {
+ it('is the shared role springs.fingerTracking (spec:AST-094 FR4), the values UIKit reports for this control: no copy in the table', () => {
+ registerSpringsTable();
+ expect('trackingSpring' in segmentedControl).toBe(false);
+ expect(springs.fingerTracking).toEqual({
+ response: 0.15,
+ dampingRatio: 0.86,
+ });
+ expect(motionRoleOf(springs.fingerTracking)).toMatchObject({
+ id: 'springs.fingerTracking',
+ kind: 'spring',
+ });
+ });
+});
+
+describe('motion roles and internal constants', () => {
+ it('its slide spring is an internal motion role once registered (spec:AST-094 FR4); the overshoot is not; the table holds no lift and no pressed dim, and the titles switch at once, with no clock', () => {
+ registerSegmentedTable();
+ expect(motionRoleOf(segmentedControl.selectionSpring)?.id).toBe(
+ 'segmented.selectionSpring',
+ );
+ expect(motionRoleIn(segmentedControl, 'dragOvershoot')).toBeUndefined();
+ // A pressed thumb's lift is a theme's (a shared role, none by default),
+ // and a pressed segment shows the shared overlay: nothing of either here.
+ expect(Object.keys(segmentedControl).sort()).toEqual([
+ 'dragOvershoot',
+ 'selectionSpring',
+ ]);
+ });
+
+ it('resolves to UIKit’s measured values whatever a theme sets: the old role variables do nothing', () => {
+ const element = document.createElement('div');
+ element.style.setProperty(
+ '--motion-segmented-control-selection-spring',
+ '0.25s 0',
+ );
+ document.body.append(element);
+ try {
+ expect(resolveMotion(element, segmentedControl.selectionSpring)).toEqual(
+ segmentedControl.selectionSpring,
+ );
+ } finally {
+ element.remove();
+ }
+ });
+});
+
+describe('one source for the slide', () => {
+ it('the segmented slide has one spring, the measured one: no guessed thumb spring is left', () => {
+ expect('segmentedThumb' in springs).toBe(false);
+ expect(motionRoleIn(springs, 'segmentedThumb')).toBeUndefined();
+ });
+});
+
+describe('Reduce Motion', () => {
+ it('holds no values: SegmentedControl follows design:reduced-motion through the animator’s cross-fade, not UIKit’s fade and scale-in', () => {
+ expect('reducedMotion' in segmentedControl).toBe(false);
+ });
+});
diff --git a/packages/core/src/motion/uikit/segmented.ts b/packages/core/src/motion/uikit/segmented.ts
new file mode 100644
index 0000000000..2ee0b0d187
--- /dev/null
+++ b/packages/core/src/motion/uikit/segmented.ts
@@ -0,0 +1,74 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file segmented.ts
+ * @input Nothing; data only
+ * @output Exports `segmentedControl`, UISegmentedControl's selection slide
+ * spring and its drag overshoot; and `registerSegmentedTable`, which
+ * registers the spring as an internal motion role
+ * @position The segmented-control domain of the UIKit constants table
+ * (motion/uikit); read by SegmentedControl's touch presentation
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/SegmentedControl/useSegmentedSelectionMotion.ts
+ * - /packages/core/src/motion/README.md (domain list)
+ */
+
+import {registerMotionTable} from '../roles';
+
+/**
+ * UIKit's own UISegmentedControl, measured with three text segments in a
+ * 300 × 31 pt control. A tap and a programmatic change follow the same
+ * spring. Every leaf carries a `@source`, and uikit.test.ts checks it.
+ *
+ * Some UIKit motion is left out on purpose. UIKit cross-fades the two titles
+ * that change, over 0.2 s. Astryx switches them at once, because a
+ * cross-fade needs a second copy of each title. Under Reduce Motion, UIKit's
+ * lens fades in at the new segment and scales from 0.88. Astryx allows no
+ * scaling there, so the animator's Reduce Motion cross-fade replaces it.
+ * UIKit's lens also lifts and stretches under a finger. A theme role owns
+ * the lift, and the stretch is not modeled. The lens chases a dragging
+ * finger on the shared `springs.fingerTracking` role, which matches the
+ * values UIKit reports for this control.
+ */
+export const segmentedControl = {
+ /**
+ * The selection indicator's slide from the old segment to the new one,
+ * after a tap or a programmatic change. Its response is 0.40 s and its
+ * damping ratio 0.85. That gives about 1.25 pt of overshoot on a 200 pt
+ * move, settled by about 0.6 s. The width follows the same spring when the
+ * segments differ in width.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, UIViewSpringAnimationBehavior read on the lens position
+ * for a tap and a programmatic set (dampingRatio 0.85, response 0.40,
+ * tracking off), Oct 23 2026
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, per-frame log of the lens's presentation position and
+ * velocity (method C) for a tap, a programmatic set and an animated set,
+ * least-squares spring fit (response 0.395 / 0.405 / 0.400 s, damping
+ * ratio 0.855 / 0.845 / 0.850, rms at most 0.65 pt over 200 pt),
+ * Oct 23 2026
+ */
+ selectionSpring: {response: 0.4, dampingRatio: 0.85},
+ /**
+ * How far past the first or last segment's center the lens follows a
+ * dragging finger, in pt. Beyond that, the lens stays put while the finger
+ * goes on.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, a drag 60 pt past the last segment: the lens stops about
+ * 11 pt past its center (312 vs 301), Oct 23 2026
+ */
+ dragOvershoot: 11,
+} as const;
+
+/**
+ * Registers this table with the motion registry (motion/roles.ts). The
+ * slide's spring becomes an internal motion role. The drag overshoot is not
+ * motion, so it stays an internal constant. Nothing registers on import, and
+ * a second call does nothing.
+ */
+export function registerSegmentedTable(): void {
+ registerMotionTable('segmented', segmentedControl, {
+ roles: ['selectionSpring'],
+ });
+}
diff --git a/packages/core/src/motion/uikit/springs.ts b/packages/core/src/motion/uikit/springs.ts
index 3a51fd9aa6..b6088f8d75 100644
--- a/packages/core/src/motion/uikit/springs.ts
+++ b/packages/core/src/motion/uikit/springs.ts
@@ -15,11 +15,11 @@
* that will confirm or replace them (MEASUREMENTS.md lists them all).
* uikit.test.ts enforces both.
*
- * Most springs are measured on iOS 26.2 or documented by Apple; two are still
- * GUESSES (`segmentedThumb`, `banner`). `switchThumbMove` is the switch's
- * measured travel, which uikit/switch.ts reads. A guess starts from the
- * nearest sourced spring and names it. A component built on the table gets
- * the measured value the moment it lands, without changing.
+ * Most springs are measured on iOS 26.2 or documented by Apple; one is still
+ * a GUESS (`banner`). `switchThumbMove` is the switch's measured travel,
+ * which uikit/switch.ts reads. A guess starts from the nearest sourced
+ * spring and names it. A component built on the table gets the measured
+ * value the moment it lands, without changing.
*
* Press highlight in/out are fades, not springs: see timing.ts.
*
@@ -400,21 +400,6 @@ export const SWITCH_THUMB_MOVE_SPRING = {
dampingRatio: 1,
} as const;
-/**
- * UISegmentedControl selection thumb sliding to a new segment.
- * @source GUESS — WebKit's UIKit-matched switch thumb spring
- * (RenderThemeCocoa.mm `thumbMoveSpring`: response 0.30 s, ratio 0.75),
- * kept only until UISegmentedControl's measured spring replaces it;
- * UISwitch's measured travel (`SWITCH_THUMB_MOVE_SPRING`)
- * belongs to another control
- * @measure M-SG02
- * @measure M-SG03
- */
-export const SEGMENTED_THUMB_SPRING = {
- response: 0.3,
- dampingRatio: 0.75,
-} as const;
-
// ---------------------------------------------------------------------
// System
// ---------------------------------------------------------------------
@@ -504,7 +489,6 @@ export const springs = {
contextMenuMorph: CONTEXT_MENU_MORPH_SPRING,
menuReducedMotion: MENU_REDUCED_MOTION_SPRING,
switchThumbMove: SWITCH_THUMB_MOVE_SPRING,
- segmentedThumb: SEGMENTED_THUMB_SPRING,
keyboard: KEYBOARD_SPRING,
banner: BANNER_SPRING,
sliderRelease: SLIDER_RELEASE_SPRING,
diff --git a/packages/core/src/privateAttributes/segmentTitle.stylex.ts b/packages/core/src/privateAttributes/segmentTitle.stylex.ts
new file mode 100644
index 0000000000..859cf1731f
--- /dev/null
+++ b/packages/core/src/privateAttributes/segmentTitle.stylex.ts
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file privateAttributes/segmentTitle.stylex.ts
+ * @input Nothing
+ * @output segmentTitleProps, which marks a SegmentedControl segment's title,
+ * and titleOfSegment, which finds that title in a segment
+ * @position Owner module of the private segment-title attribute: the only
+ * file that writes its name. No package entry exports it.
+ */
+
+const SEGMENT_TITLE = 'data-astryx-segment-title';
+
+/** Spread on a segment's title: marks it for the touch layer. */
+export const segmentTitleProps: Readonly<Record<string, string>> = {
+ [SEGMENT_TITLE]: '',
+};
+
+/** The title inside `segment`, or null when the label is hidden. */
+export function titleOfSegment(segment: Element): HTMLElement | null {
+ return segment.querySelector<HTMLElement>(`[${SEGMENT_TITLE}]`);
+}
diff --git a/packages/core/src/utils/browserClickWait.test.ts b/packages/core/src/utils/browserClickWait.test.ts
new file mode 100644
index 0000000000..35532ed56f
--- /dev/null
+++ b/packages/core/src/utils/browserClickWait.test.ts
@@ -0,0 +1,154 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file browserClickWait.test.ts
+ * @input browserClickWait.ts, with fake timers and the shared click guard
+ * @output Proof that the wait reports the browser's click after its handlers,
+ * runs `onNoClick` once the wait runs out, leaves nothing behind when ended,
+ * and that a lift's own click passes while the guard swallows the late one
+ * @position Testing for /packages/core/src/utils/browserClickWait.ts
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {
+ BROWSER_CLICK_WAIT_MS,
+ awaitBrowserClick,
+ clickForLift,
+} from './browserClickWait';
+import {__resetClickGuardForTest, isClickGuardArmed} from './clickGuard';
+
+/** Every wait a test starts: each ends after the test, so none listens on. */
+const waits: (() => void)[] = [];
+
+afterEach(() => {
+ for (const end of waits.splice(0)) {
+ end();
+ }
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ __resetClickGuardForTest();
+ document.body.replaceChildren();
+});
+
+/**
+ * Starts a wait on a new button, and hands back the window's click listener
+ * the wait added, to call with a browser-made (trusted) click.
+ */
+function startWait() {
+ vi.useFakeTimers();
+ const add = vi.spyOn(window, 'addEventListener');
+ const button = document.createElement('button');
+ const label = document.createElement('span');
+ button.append(label);
+ document.body.append(button);
+ const clicked: boolean[] = [];
+ const noClick = vi.fn();
+ const end = awaitBrowserClick(button, {
+ onClicked: isCancelled => clicked.push(isCancelled),
+ onNoClick: noClick,
+ });
+ waits.push(end);
+ const listener = add.mock.calls.find(([type]) => type === 'click')?.[1] as (
+ event: unknown,
+ ) => void;
+ const browserClick = (target: Node, defaultPrevented = false) => ({
+ isTrusted: true,
+ target,
+ defaultPrevented,
+ });
+ return {button, label, clicked, noClick, end, listener, browserClick};
+}
+
+describe('awaitBrowserClick', () => {
+ it('reports the browser’s click once its handlers have run, cancelled or not, and stops waiting', () => {
+ const {label, clicked, noClick, listener, browserClick} = startWait();
+ expect(listener).toBeDefined();
+ const event = browserClick(label);
+ listener(event);
+ // Not yet: the handlers run first.
+ expect(clicked).toEqual([]);
+ (event as {defaultPrevented: boolean}).defaultPrevented = true;
+ vi.advanceTimersByTime(0);
+ expect(clicked).toEqual([true]);
+ // The wait is over: no direct-click path, and a second click is not
+ // reported.
+ vi.advanceTimersByTime(BROWSER_CLICK_WAIT_MS * 2);
+ expect(noClick).not.toHaveBeenCalled();
+ listener(browserClick(label));
+ vi.advanceTimersByTime(0);
+ expect(clicked).toEqual([true]);
+ });
+
+ it('ignores a script’s click and a click elsewhere', () => {
+ const {clicked, listener, browserClick} = startWait();
+ listener({...browserClick(document.body)});
+ listener({isTrusted: false, target: document.body});
+ vi.advanceTimersByTime(0);
+ expect(clicked).toEqual([]);
+ });
+
+ it('runs onNoClick once the wait runs out with no browser click', () => {
+ const {clicked, noClick} = startWait();
+ vi.advanceTimersByTime(BROWSER_CLICK_WAIT_MS - 1);
+ expect(noClick).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(noClick).toHaveBeenCalledTimes(1);
+ expect(clicked).toEqual([]);
+ });
+
+ it('leaves no listener or timer behind once ended, as an unmount does, even with a report pending', () => {
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const {label, clicked, noClick, end, listener, browserClick} = startWait();
+ listener(browserClick(label));
+ end();
+ vi.advanceTimersByTime(BROWSER_CLICK_WAIT_MS * 2);
+ expect(clicked).toEqual([]);
+ expect(noClick).not.toHaveBeenCalled();
+ expect(remove.mock.calls.some(([type]) => type === 'click')).toBe(true);
+ // Ending twice is harmless.
+ end();
+ });
+});
+
+describe('awaitBrowserClick in a document with no window', () => {
+ it('runs onNoClick at once, unless the wait was ended first', async () => {
+ const doc = document.implementation.createHTMLDocument('');
+ const button = doc.createElement('button');
+ doc.body.append(button);
+ const noClick = vi.fn();
+ awaitBrowserClick(button, {onClicked: () => {}, onNoClick: noClick});
+ const ended = vi.fn();
+ const end = awaitBrowserClick(button, {
+ onClicked: () => {},
+ onNoClick: ended,
+ });
+ end();
+ await Promise.resolve();
+ expect(noClick).toHaveBeenCalledTimes(1);
+ expect(ended).not.toHaveBeenCalled();
+ });
+});
+
+describe('clickForLift', () => {
+ it('clicks the element, reports a veto, and the shared guard swallows the browser’s late click', () => {
+ const button = document.createElement('button');
+ document.body.append(button);
+ const onClick = vi.fn((event: Event) => event.preventDefault());
+ button.addEventListener('click', onClick);
+ expect(clickForLift(button)).toBe(true);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(isClickGuardArmed(document)).toBe(true);
+ // The browser's own click for the same lift (a pointer's, detail 1).
+ button.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 1}),
+ );
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(isClickGuardArmed(document)).toBe(false);
+ });
+
+ it('reports false for a click no handler cancels', () => {
+ const button = document.createElement('button');
+ document.body.append(button);
+ expect(clickForLift(button)).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/browserClickWait.ts b/packages/core/src/utils/browserClickWait.ts
new file mode 100644
index 0000000000..14cfa3e42e
--- /dev/null
+++ b/packages/core/src/utils/browserClickWait.ts
@@ -0,0 +1,133 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file browserClickWait.ts
+ * @input An element a tap's lift released on, and the control that acts on
+ * its click
+ * @output BROWSER_CLICK_WAIT_MS, awaitBrowserClick, clickForLift and
+ * clickAndReport
+ * @position The one wait for the browser's click after a tap, shared by
+ * Switch/useSwitchTouch.ts and SegmentedControl/useSegmentedTouchTracking.ts.
+ * It swallows nothing: utils/clickGuard.ts is the one guard for a late click.
+ *
+ * SYNC: When modified, update browserClickWait.test.ts.
+ */
+
+import {armClickGuard, withoutClickGuard} from './clickGuard';
+import {subscribeInput} from './inputStream';
+
+/**
+ * How long a tap's lift waits for the browser's own click, ms. The browser
+ * sends that click with the lift when the page has no double-tap delay. The
+ * wait runs out for a lift that the browser does not count as a click, such
+ * as a hold. It also runs out when a busy main thread holds the click back.
+ */
+export const BROWSER_CLICK_WAIT_MS = 300;
+
+/** What a control does when the browser's click comes, or does not. */
+export interface BrowserClickWaitHandlers {
+ /** The browser's click ran its handlers. `isCancelled`: one cancelled it. */
+ readonly onClicked: (isCancelled: boolean) => void;
+ /** No browser click came in time. */
+ readonly onNoClick: () => void;
+}
+
+/**
+ * Waits for the browser's own click inside `target` after a tap's lift. That
+ * click is the activation: `onClicked` runs once its handlers have run. With
+ * no click in time, `onNoClick` runs. The returned call ends the wait at once
+ * and leaves no listener or timer behind.
+ */
+export function awaitBrowserClick(
+ target: Element,
+ {onClicked, onNoClick}: BrowserClickWaitHandlers,
+): () => void {
+ const view = target.ownerDocument.defaultView;
+ if (view == null) {
+ // A document with no window gets no click: the wait runs out at once.
+ let isEnded = false;
+ queueMicrotask(() => {
+ if (!isEnded) {
+ onNoClick();
+ }
+ });
+ return () => {
+ isEnded = true;
+ };
+ }
+ let isDone = false;
+ let report: number | null = null;
+ let timer: number | null = null;
+ let stopListening: (() => void) | null = null;
+ const stop = () => {
+ isDone = true;
+ stopListening?.();
+ stopListening = null;
+ if (timer != null) {
+ view.clearTimeout(timer);
+ timer = null;
+ }
+ };
+ stopListening = subscribeInput(view, 'click', event => {
+ if (
+ isDone ||
+ !event.isTrusted ||
+ !target.contains(event.target as Node | null)
+ ) {
+ return;
+ }
+ stop();
+ // After every handler has run: was it cancelled?
+ report = view.setTimeout(() => {
+ report = null;
+ onClicked(event.defaultPrevented);
+ }, 0);
+ });
+ timer = view.setTimeout(() => {
+ if (isDone) {
+ return;
+ }
+ stop();
+ onNoClick();
+ }, BROWSER_CLICK_WAIT_MS);
+ return () => {
+ stop();
+ if (report != null) {
+ view.clearTimeout(report);
+ report = null;
+ }
+ };
+}
+
+/**
+ * Click `element` (its own `click()`, so its activation behavior and every
+ * handler run as for any click) and report whether a handler cancelled it.
+ * The event is read from a capture listener that exists only for the call.
+ */
+export function clickAndReport(element: HTMLElement): boolean {
+ const view = element.ownerDocument.defaultView;
+ let clicked: Event | null = null;
+ const grab = (event: Event) => {
+ if (clicked == null && event.target === element) {
+ clicked = event;
+ }
+ };
+ view?.addEventListener('click', grab, true);
+ try {
+ element.click();
+ } finally {
+ view?.removeEventListener('click', grab, true);
+ }
+ return (clicked as Event | null)?.defaultPrevented === true;
+}
+
+/**
+ * Clicks `element` for a lift the control decided itself, and reports
+ * whether a handler cancelled the click. The shared click guard swallows the
+ * browser's own click for the same lift, if it comes later, so the lift
+ * activates once.
+ */
+export function clickForLift(element: HTMLElement): boolean {
+ armClickGuard(element.ownerDocument);
+ return withoutClickGuard(() => clickAndReport(element));
+}
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
index 521f329535..58ca745edb 100644
--- a/scripts/touch-support-bundle.test.mjs
+++ b/scripts/touch-support-bundle.test.mjs
@@ -123,6 +123,10 @@ const GESTURE_USERS = new Set([
'Slider',
// Switch: its press tracking and its drag, for every pointer.
'Switch',
+ // SegmentedControl: its press tracking and its drag, for every pointer.
+ 'SegmentedControl',
+ // DateTimeInput: through the SegmentedControl its touch field renders.
+ 'DateTimeInput',
]);
/** Public imports that carry no gesture code, whatever the list above says. */