Skip to content

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

TypeScript

feat(Switch): the touch presentation, for every pointer (#9636)

Christopher Chedeau1f47db9c86cb
diff --git a/.changeset/switch-every-pointer.md b/.changeset/switch-every-pointer.md
new file mode 100644
index 0000000000..1246ec4101
--- /dev/null
+++ b/.changeset/switch-every-pointer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Switch's press and drag work with a mouse and a pen as well as a finger: a drag past the flip point toggles the switch at the release, wherever that happens, unless the pointer came back past where it pressed. A mouse or pen press slid off the switch still leaves it alone, as a checkbox does. With a mouse the switch keeps its desktop look, and the value moves the thumb. On a touchscreen laptop a finger flips it by the same rule, with the desktop look.
+
+@vjeux
diff --git a/.changeset/switch-touch-presentation.md b/.changeset/switch-touch-presentation.md
new file mode 100644
index 0000000000..109149d7a4
--- /dev/null
+++ b/.changeset/switch-touch-presentation.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Under a finger, on every touch screen, Switch moves like the iOS switch. A press lifts the thumb a little, with a soft shadow, and a horizontal drag moves it with the finger and flips the switch once the finger has travelled most of the track; lifting the finger commits. A tap toggles through the browser's own click, and a hold or a short drag toggles at the lift. The thumb stays inside the track however far the finger drags past either end, in either writing direction. A press slid off the switch and lifted outside still toggles it, as on iOS. A vertical drag scrolls the page and the switch lets go. The motion runs on the compositor, so it stays smooth while scripts run. The thumb keeps its circle and its size on every device, and under a coarse pointer the switch's invisible hit area grows toward 44 × 44 px with nothing visible added, stopping halfway to any neighbouring control so a tap goes to the nearer one. The track keeps its theme's fill, and the colour change crossfades over it. With reduced motion on, a change cross-fades instead of moving on a touch screen and is immediate with a mouse. A press shows the pressed overlay, through a drag too, and a still hold selects no text. Keyboard and assistive technology behave as before. In Chromium, a Switch retargeted right after a tap, such as one tapped again mid-travel, turns around from where it is, with no step back to the start of its travel. Switch joins Slider on the shared press tracking and touch negotiation.
+
+@vjeux
diff --git a/.changeset/uikit-switch-values.md b/.changeset/uikit-switch-values.md
new file mode 100644
index 0000000000..8c588dd1e4
--- /dev/null
+++ b/.changeset/uikit-switch-values.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: UISwitch's values measured on iOS 26.2 (its geometry, the springs of the thumb's lift, settle, travel and drag, the track colour, its minimum lift time and its flip distance) join the UIKit constants table as internal constants, with the rule a switch's drag follows as a pure function: the finger flips the switch once it has travelled the track width minus the thumb width from where it landed, coming back past that point flips it back, and lifting the finger commits the side shown, or toggles when nothing flipped. Not exported from the package entry point, and no theme sets them. Switch's touch presentation plays them.
+
+@vjeux
diff --git a/apps/storybook/stories/Switch.stories.tsx b/apps/storybook/stories/Switch.stories.tsx
index 8d3ea25adf..5f338b8c03 100644
--- a/apps/storybook/stories/Switch.stories.tsx
+++ b/apps/storybook/stories/Switch.stories.tsx
@@ -648,3 +648,61 @@ export const PressedState: Story = {
);
},
};
+
+export const BesideALink: Story = {
+ name: 'Beside a link',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'A small switch 8 px from a link. Under a coarse pointer the switch’s invisible hit area grows toward 44 × 44 px but stops halfway to the link, so a tap on the link opens it and a tap nearer the switch toggles it.',
+ },
+ },
+ },
+ render: () => {
+ const [value, setValue] = useState(false);
+ return (
+ <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
+ <Switch
+ label="Wi-Fi"
+ isLabelHidden
+ size="sm"
+ value={value}
+ onChange={setValue}
+ />
+ <a href="#wifi-details">Details</a>
+ </div>
+ );
+ },
+};
+
+export const InScrollingList: Story = {
+ name: 'In a scrolling list',
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Switches in rows of a list taller than the screen, as in a settings page. Under a finger, a vertical drag scrolls the page and changes nothing, even after the finger rests on a switch; a horizontal drag moves the thumb, and a tap toggles.',
+ },
+ },
+ },
+ render: () => {
+ const [values, setValues] = useState<boolean[]>(() =>
+ Array.from({length: 24}, (_, i) => i % 3 === 0),
+ );
+ return (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 20}}>
+ {values.map((value, i) => (
+ <Switch
+ key={i}
+ label={`Setting ${i + 1}`}
+ value={value}
+ onChange={next =>
+ setValues(current => current.map((v, j) => (j === i ? next : v)))
+ }
+ />
+ ))}
+ </div>
+ );
+ },
+};
diff --git a/docs/specs/AST-094-touch-presentations/motion-roles.md b/docs/specs/AST-094-touch-presentations/motion-roles.md
index 0854c35e6c..e234a8db04 100644
--- a/docs/specs/AST-094-touch-presentations/motion-roles.md
+++ b/docs/specs/AST-094-touch-presentations/motion-roles.md
@@ -4,31 +4,38 @@
Every motion role a registered table lists (`spec:AST-094` FR4, DEC-5): its kind, its default as the table measures it, and the record that names it. A role FR4 lists is named by FR4; any other role is one a component's own record measures, named by the current component records that carry its id.
-| Role | Kind | Default | Named by |
-| ------------------------------- | -------- | ----------------------------------- | ----------------------- |
-| `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` |
-| `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 |
-| `springs.directChange` | spring | response 0.5 s, damping ratio 0.825 | `spec:AST-094` FR4 |
-| `springs.emphasis` | spring | duration 0.5 s, bounce 0.3 | `spec:AST-094` FR4 |
-| `springs.fingerTracking` | spring | response 0.15 s, damping ratio 0.86 | `spec:AST-094` FR4 |
-| `springs.menuClose` | spring | response 0.35 s, damping ratio 0.85 | `spec:AST-094` FR4 |
-| `springs.menuOpen` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 |
-| `springs.quickChange` | spring | duration 0.5 s, bounce 0.15 | `spec:AST-094` FR4 |
-| `springs.settle` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |
-| `springs.sliderDrop` | spring | response 0.5 s, damping ratio 0.7 | `component:Slider` |
-| `springs.sliderLift` | spring | response 0.215 s, damping ratio 0.6 | `component:Slider` |
-| `springs.sliderRelease` | spring | response 0.4 s, damping ratio 1 | `component:Slider` |
-| `springs.stateChange` | spring | response 0.55 s, damping ratio 1 | `spec:AST-094` FR4 |
-| `springs.subMenuBack` | spring | response 0.4 s, damping ratio 1 | `spec:AST-094` FR4 |
-| `springs.subMenuOpen` | spring | response 0.4 s, damping ratio 0.85 | `spec:AST-094` FR4 |
-| `springs.timedChange` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |
-| `springs.viewChange` | spring | mass 3, stiffness 1000, damping 500 | `spec:AST-094` FR4 |
-| `timing.curves.entrance` | curve | cubic-bezier(0, 0, 0.58, 1) | `spec:AST-094` FR4 |
-| `timing.curves.exit` | curve | cubic-bezier(0.42, 0, 1, 1) | `spec:AST-094` FR4 |
-| `timing.curves.move` | curve | cubic-bezier(0.42, 0, 0.58, 1) | `spec:AST-094` FR4 |
-| `timing.curves.viewChange` | curve | cubic-bezier(0.25, 0.1, 0.25, 1) | `spec:AST-094` FR4 |
-| `timing.stateChangeMs` | duration | 250 ms | `spec:AST-094` FR4 |
+| Role | Kind | Default | Named by |
+| ------------------------------- | -------- | --------------------------------------------------------------- | ----------------------- |
+| `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` |
+| `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 |
+| `springs.directChange` | spring | response 0.5 s, damping ratio 0.825 | `spec:AST-094` FR4 |
+| `springs.emphasis` | spring | duration 0.5 s, bounce 0.3 | `spec:AST-094` FR4 |
+| `springs.fingerTracking` | spring | response 0.15 s, damping ratio 0.86 | `spec:AST-094` FR4 |
+| `springs.menuClose` | spring | response 0.35 s, damping ratio 0.85 | `spec:AST-094` FR4 |
+| `springs.menuOpen` | spring | response 0.32 s, damping ratio 0.8 | `spec:AST-094` FR4 |
+| `springs.quickChange` | spring | duration 0.5 s, bounce 0.15 | `spec:AST-094` FR4 |
+| `springs.settle` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |
+| `springs.sliderDrop` | spring | response 0.5 s, damping ratio 0.7 | `component:Slider` |
+| `springs.sliderLift` | spring | response 0.215 s, damping ratio 0.6 | `component:Slider` |
+| `springs.sliderRelease` | spring | response 0.4 s, damping ratio 1 | `component:Slider` |
+| `springs.stateChange` | spring | response 0.55 s, damping ratio 1 | `spec:AST-094` FR4 |
+| `springs.subMenuBack` | spring | response 0.4 s, damping ratio 1 | `spec:AST-094` FR4 |
+| `springs.subMenuOpen` | spring | response 0.4 s, damping ratio 0.85 | `spec:AST-094` FR4 |
+| `springs.timedChange` | spring | duration 0.5 s, bounce 0 | `spec:AST-094` FR4 |
+| `springs.viewChange` | spring | mass 3, stiffness 1000, damping 500 | `spec:AST-094` FR4 |
+| `switchControl.lift` | spring | response 0.23 s, damping ratio 0.55 | `component:Switch` |
+| `switchControl.minimumLiftMs` | duration | 235 ms | `component:Switch` |
+| `switchControl.settle` | spring | response 0.5 s, damping ratio 0.7 | `component:Switch` |
+| `switchControl.tracking` | spring | response 0.36 s, damping ratio 1 | `component:Switch` |
+| `switchControl.travel` | spring | response 0.3 s, damping ratio 1 | `component:Switch` |
+| `switchControl.wellOff` | spring | mass 1, stiffness 246.74011002723395, damping 31.41592653589793 | `component:Switch` |
+| `switchControl.wellOn` | spring | mass 1, stiffness 85.37720070146501, damping 18.47995678582231 | `component:Switch` |
+| `timing.curves.entrance` | curve | cubic-bezier(0, 0, 0.58, 1) | `spec:AST-094` FR4 |
+| `timing.curves.exit` | curve | cubic-bezier(0.42, 0, 1, 1) | `spec:AST-094` FR4 |
+| `timing.curves.move` | curve | cubic-bezier(0.42, 0, 0.58, 1) | `spec:AST-094` FR4 |
+| `timing.curves.viewChange` | curve | cubic-bezier(0.25, 0.1, 0.25, 1) | `spec:AST-094` FR4 |
+| `timing.stateChangeMs` | duration | 250 ms | `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 5684069e40..00e4957dd8 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -235,7 +235,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. 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). 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/Switch/Switch.spec.md b/docs/specs/components/Switch/Switch.spec.md
index 685d1ca151..1265c3bf95 100644
--- a/docs/specs/components/Switch/Switch.spec.md
+++ b/docs/specs/components/Switch/Switch.spec.md
@@ -27,6 +27,9 @@ verified_by:
[
packages/core/src/Switch/Switch.test.tsx,
packages/core/src/Switch/Switch.focusRing.source-build.test.mjs,
+ packages/core/src/Switch/switchTouch.test.ts,
+ packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts,
+ packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts,
packages/core/src/Switch/__tests__/Switch.a11y.test.tsx,
packages/core/src/Switch/__tests__/Switch.a11y.chromium.spec.ts,
packages/core/src/__tests__/PressedState.a11y.chromium.spec.ts,
@@ -43,22 +46,42 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: [spec:AST-021, spec:AST-085, spec:AST-086, spec:AST-094]
+system_specs:
+ [
+ spec:AST-020/DEC-5,
+ spec:AST-020/FR9,
+ spec:AST-021,
+ spec:AST-085,
+ spec:AST-086,
+ spec:AST-094,
+ spec:AST-094/FR4,
+ spec:AST-094/FR6,
+ spec:AST-094/FR18,
+ spec:AST-094/FR24,
+ ]
---
# Switch component contract
+<!-- path-applicability:v1 -->
+
+```json
+{
+ "paths": ["packages/core/src/motion/uikit/switch.ts"]
+}
+```
+
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | None changes. Switch takes `label`, `value`, `onChange`, `changeAction`, `isLoading`, `isDisabled`, `disabledMessage`, `isRequired`, `isOptional`, `status`, `size`, `labelPosition`, `labelSpacing`, field content, and base props. |
-| Behavior | A native checkbox with `role="switch"` drawn as a track and thumb. A change calls `onChange`, then an optional `changeAction` with the optimistic value; while busy the switch shows a Spinner in the thumb and refuses changes. |
-| End-user impact | People flip a setting that takes effect at once and hear when it is saving. Keyboard and screen-reader users can reach a disabled switch and its reason. |
-| Builder impact | None. |
-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. Caller handlers other than `onClick` run while disabled, the coarse-pointer hit area stops at 24 by 24, and caller ARIA lands on the field root; all three are listed under Current-state impact. |
-| Review checks | Reject a lost switch role or name, a change while disabled or busy, focus moving on change, a ring painted anywhere but the track, a thumb that travels the wrong way under RTL, or a disabled switch that submits. |
-| Governing rules | `spec:AST-021` switch pattern; `spec:AST-085` FR1–FR3, FR5, FR6; `spec:AST-086` FR8; `design:user-states` DR1, DR2 (pressed overlay); `design:reduced-motion` DR1; WCAG 2.5.2, 3.2.2, 1.4.11; `spec:AST-094` FR42. |
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Public contract | None changes. Switch takes `label`, `value`, `onChange`, `changeAction`, `isLoading`, `isDisabled`, `disabledMessage`, `isRequired`, `isOptional`, `status`, `size`, `labelPosition`, `labelSpacing`, field content, and base props. |
+| Behavior | A native checkbox with `role="switch"` drawn as a track and thumb. A change calls `onChange`, then an optional `changeAction` with the optimistic value; while busy the switch shows a Spinner in the thumb and refuses changes. Its press and drag work for every pointer, and under a finger it follows the finger as the iOS switch does (FR13–FR15). |
+| End-user impact | People flip a setting that takes effect at once and hear when it is saving. Keyboard and screen-reader users can reach a disabled switch and its reason. |
+| Builder impact | None. |
+| Compatibility/readiness | Under a finger a hold and a press slid off now toggle the switch, and under a mouse or a pen a drag past the flip distance now flips it (FR15); a coarse pointer's hit area grows toward 44 px (FR10); no API, default, or DOM change. Caller handlers other than `onClick` run while disabled, and caller ARIA lands on the field root; both are listed under Current-state impact. |
+| Review checks | Reject a lost switch role or name, a change while disabled or busy, focus moving on change, a ring painted anywhere but the track, a thumb that travels the wrong way under RTL, or a disabled switch that submits. |
+| Governing rules | `spec:AST-021` switch pattern; `spec:AST-085` FR1–FR3, FR5, FR6; `spec:AST-086` FR8; `design:user-states` DR1, DR2 (pressed overlay); `design:reduced-motion` DR1; WCAG 2.5.2, 3.2.2, 1.4.11; `spec:AST-094` FR4, FR11, FR13, FR24, FR42, FR43; `spec:AST-020` FR9 (DEC-5). |
This table is a review projection; the body below is authoritative.
@@ -67,14 +90,23 @@ This table is a review projection; the body below is authoritative.
Switch presents a labelled boolean setting whose change takes effect
immediately. It owns the switch control, its change and Action pipeline, busy
and disabled behavior, label placement, and the field's theming anatomy.
-Consumer usage lives in `Switch.doc.mjs`.
+Its press and drag work for a mouse, a pen and a finger (FR15). Under a touch
+presentation it follows a finger the way the iOS switch does (FR13–FR15);
+under a fine primary pointer it keeps its released look, and a keyboard or
+assistive technology keeps its released behavior. Consumer usage lives in `Switch.doc.mjs`.
## Compatibility and migration
-- Released default preserved: `yes`; `size="md"`, `labelPosition="end"`,
+- Released default preserved: `no` under a finger, where a hold and a press
+ slid off now toggle the switch (FR15), and under a mouse or a pen, where a
+ drag past the flip distance now flips it (FR15); `yes` for a keyboard and
+ assistive technology; `size="md"`, `labelPosition="end"`,
`labelSpacing="hug"`
-- Compatibility class: records shipped behavior; no public prop, default,
- export, or DOM change
+- Compatibility class: a touch presentation adds the finger behavior
+ (FR13–FR15), a mouse or a pen drags the switch by the same flip rule
+ (FR15), and a coarse pointer's hit area grows toward 44 × 44 px (FR10); the
+ look under a fine pointer and every public prop, default, export, and DOM
+ element stay as they were
- Controlled/uncontrolled behavior: controlled only; `value` is required, and
the switch shows an optimistic value only while a `changeAction` is pending
- Migration decision: none
@@ -114,20 +146,40 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1 | The current render places a thumb inside the switch track and arranges that control with its label: a visually hidden native `<input type="checkbox" role="switch">` sits over a decorative track, with the label after it by default or before it with `labelPosition="start"`. | `spec:AST-021`; current source, docs, and focused tests |
-| FR2 | The field, track, thumb, and label carry their existing local targets. The field reflects `data-label-position` and `data-label-spacing` only for non-default values; the track reflects `data-size`, `data-checked`, and `data-disabled`; the thumb reflects `data-size` and `data-checked`. | `architecture:component-theming-surface`; current source and tests |
-| FR3 | A busy switch renders Spinner inside the thumb; a status message renders through detached FieldStatus. | Current source, docs, and focused tests |
-| FR4 | The input is named by its label (or a caller `aria-labelledby`) and described by any caller description, then the description, status message, and disabled reason that exist; the description is not part of the name. A click on the label or description toggles the switch. | `spec:AST-021`; current tests |
-| FR5 | A change calls `onChange(checked, event)`; unless that call prevents default, `changeAction(checked, event)` runs in a transition and the switch shows the proposed state while the Action is pending, and `value` once it settles. | Current tests |
-| FR6 | While `isLoading`, or while the shown state differs from `value`, the input sets `aria-busy`, ignores pointer input, refuses changes, keeps focus, and the switch announces its busy start once per busy period through the shared channel. | `spec:AST-086` FR8; current tests |
-| FR7 | Disabled: `aria-disabled="true"` on a focusable input, no `name`, detached from its form (so it neither submits nor blocks submission when required), no change, no caller `onClick` on the field, no hover or press paint, and a half-opacity track. With `disabledMessage`, a reason tooltip opens on row hover and keyboard focus and describes the input. Implementation gap: caller DOM handlers other than `onClick`, such as `onKeyDown`, still run on the field root while disabled (`spec:AST-085` FR2). | `spec:AST-085` FR1–FR3, FR5; current tests |
-| FR8 | Enabled, the input submits `on` under `htmlName` when on and nothing when off; `isRequired` sets native `required`, while `aria-required` follows the effective required state; `aria-invalid` follows `status` (`false` on a required switch without an error), so the browser's own invalid state never shows before an error. | Current tests |
-| FR9 | Keyboard focus paints the shared focus outline on the track. Hovering the enabled row tints the track; pressing paints the pressed overlay on both, applying `design:user-states` DR1 and DR2; a touch press fades out from the row. Track color transitions are instant under reduced motion. | `architecture:interaction-modality` INV1; `design:user-states` DR1, DR2 for the pressed overlay; `design:reduced-motion`; current tests |
-| FR10 | The thumb travels toward the inline end when on, mirrored under RTL, and moves without a transition under reduced motion (`design:reduced-motion` DR1). On coarse pointers the input's hit area is at least 24 by 24 CSS pixels (WCAG 2.5.8) and follows the inline direction. Under `spec:AST-094` FR42 a coarse-pointer target MUST reach 44 CSS pixels through an invisible hit area where neighbors allow. Implementation gap: the input's hit area stops at 24 by 24. | WCAG 2.5.8; current tests; `design:reduced-motion` DR1; `spec:AST-094` FR42 |
-| FR11 | Under forced colors, on and off stay distinguishable (Highlight track when on), and the hover tint does not hide the thumb. | WCAG 1.4.11; current tests |
-| FR12 | `ref`, `onFocus`, and `onBlur` reach the input, and a caller `aria-labelledby` and `aria-describedby` name and describe it. Other base props (`id`, `data-*`, other ARIA, `onClick`, and other handlers), `className`, `style`, `xstyle`, and `width` reach the field root. Caller ARIA attributes name and describe the switch, so they MUST reach the input (`architecture:public-component-api` INV5). Implementation gap: ARIA other than `aria-labelledby` and `aria-describedby`, such as `aria-label`, lands on the field root. | Current tests; `architecture:public-component-api` INV5 |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1 | The current render places a thumb inside the switch track and arranges that control with its label: a visually hidden native `<input type="checkbox" role="switch">` sits over a decorative track, with the label after it by default or before it with `labelPosition="start"`. | `spec:AST-021`; current source, docs, and focused tests |
+| FR2 | The field, track, thumb, and label carry their existing local targets. The field reflects `data-label-position` and `data-label-spacing` only for non-default values; the track reflects `data-size`, `data-checked`, and `data-disabled`; the thumb reflects `data-size` and `data-checked`. | `architecture:component-theming-surface`; current source and tests |
+| FR3 | A busy switch renders Spinner inside the thumb; a status message renders through detached FieldStatus. | Current source, docs, and focused tests |
+| FR4 | The input is named by its label (or a caller `aria-labelledby`) and described by any caller description, then the description, status message, and disabled reason that exist; the description is not part of the name. A click on the label or description toggles the switch. | `spec:AST-021`; current tests |
+| FR5 | A change calls `onChange(checked, event)`; unless that call prevents default, `changeAction(checked, event)` runs in a transition and the switch shows the proposed state while the Action is pending, and `value` once it settles. | Current tests |
+| FR6 | While `isLoading`, or while the shown state differs from `value`, the input sets `aria-busy`, ignores pointer input, refuses changes, keeps focus, and the switch announces its busy start once per busy period through the shared channel. | `spec:AST-086` FR8; current tests |
+| FR7 | Disabled: `aria-disabled="true"` on a focusable input, no `name`, detached from its form (so it neither submits nor blocks submission when required), no change, no caller `onClick` on the field, no hover or press paint, and a half-opacity track. With `disabledMessage`, a reason tooltip opens on row hover and keyboard focus and describes the input. Implementation gap: caller DOM handlers other than `onClick`, such as `onKeyDown`, still run on the field root while disabled (`spec:AST-085` FR2). | `spec:AST-085` FR1–FR3, FR5; current tests |
+| FR8 | Enabled, the input submits `on` under `htmlName` when on and nothing when off; `isRequired` sets native `required`, while `aria-required` follows the effective required state; `aria-invalid` follows `status` (`false` on a required switch without an error), so the browser's own invalid state never shows before an error. | Current tests |
+| FR9 | Keyboard focus paints the shared focus outline on the track. Hovering the enabled row tints the track; pressing paints the pressed overlay on both, applying `design:user-states` DR1 and DR2; a touch press fades out from the row. Track color transitions are instant under reduced motion; under a finger the colour fades with the thumb's cross-fade (FR15). | `architecture:interaction-modality` INV1; `design:user-states` DR1, DR2 for the pressed overlay; `design:reduced-motion`; current tests |
+| FR10 | The thumb travels toward the inline end when on, mirrored under RTL, and moves without a transition under reduced motion (`design:reduced-motion` DR1); under a finger it cross-fades to its rest instead (FR15). Where the primary pointer is coarse, the switch's hit area grows around the track toward 44 by 44 CSS pixels, each side stopping at half the gap to a neighbouring target so a tap goes to the nearer one (`spec:AST-094` FR42, `utils/hitArea.ts`), with nothing visible added. | WCAG 2.5.8; current tests; `design:reduced-motion` DR1; `spec:AST-094` FR42 |
+| FR11 | Under forced colors, on and off stay distinguishable (Highlight track when on), and the hover tint does not hide the thumb. | WCAG 1.4.11; current tests |
+| FR12 | `ref`, `onFocus`, and `onBlur` reach the input, and a caller `aria-labelledby` and `aria-describedby` name and describe it. Other base props (`id`, `data-*`, other ARIA, `onClick`, and other handlers), `className`, `style`, `xstyle`, and `width` reach the field root. Caller ARIA attributes name and describe the switch, so they MUST reach the input (`architecture:public-component-api` INV5). Implementation gap: ARIA other than `aria-labelledby` and `aria-describedby`, such as `aria-label`, lands on the field root. | Current tests; `architecture:public-component-api` INV5 |
+| FR13 | The thumb is one circle under any pointer, at each state's size: a touch presentation moves and lifts it and never reshapes it, and its lift and rubber band derive from the box it renders. | Owner direction, 2026-10-26 |
+| FR14 | Under a finger the thumb, lifted or banded past either end, paints inside the track, in either writing direction. | Owner direction, 2026-10-25 |
+| FR15 | For every pointer (`spec:AST-094` FR43) a tap, a hold of any length or a short drag toggles the switch at the release (a tap through the browser's click; where the browser sends no click for a finger's release, as for a hold, the switch clicks its input itself), and a drag commits the side it flipped the switch to, which it reaches once the pointer is the track width less the thumb width from where it pressed, toward the other end, and leaves again once the pointer comes back past where it pressed, wherever the pointer is released (measured in `motion/uikit/switch.ts`: `travel`, `flipDistance`). Under a finger a press slid off and lifted outside without a flip toggles it too, as `spec:AST-094` FR11 allows for a toggle under `spec:AST-020` FR9's slide-off exception (DEC-5); a mouse or a pen slid off and released outside without a flip leaves it alone, as the native checkbox does. Under a finger the thumb follows the drag as UISwitch's does (iOS 26.2); under a fine primary pointer the switch keeps its own look, and the value moves its thumb (`spec:AST-094` FR13). The switch's own click, for a hold and for a flipping drag, is the exception `spec:AST-094` FR11 states for Switch. Under reduced motion nothing lifts or springs: a tap, a release or a change cross-fades the thumb to its rest and the track colour with it, while a dragging finger still moves the thumb. | `spec:AST-094` FR11, FR13, FR43; `spec:AST-020` FR9/DEC-5; `design:reduced-motion` |
+
+### Motion roles
+
+Under a finger the switch plays these motion roles, which this record names
+and the generated motion role table carries (`spec:AST-094` FR4, DEC-5). They
+are internal, so no theme overrides them yet (DEC-11); each value is
+measured on UISwitch, iOS 26.2 (`motion/uikit/switch.ts`).
+
+| Role | Default | Use |
+| ----------------------------- | --------------------------------------- | ------------------------------------------------------------ |
+| `switchControl.lift` | response 0.23 s, damping ratio 0.55 | The thumb lifting while a finger presses |
+| `switchControl.settle` | response 0.5 s, damping ratio 0.7 | The lifted thumb settling after the lift |
+| `switchControl.minimumLiftMs` | 235 ms | The shortest lift before the settle, so a quick tap shows it |
+| `switchControl.travel` | response 0.3 s, damping ratio 1 | The thumb travelling to the committed end |
+| `switchControl.tracking` | response 0.36 s, damping ratio 1 | The thumb chasing a dragging finger |
+| `switchControl.wellOn` | mass 1, stiffness 85.38, damping 18.48 | The track colour turning on |
+| `switchControl.wellOff` | mass 1, stiffness 246.74, damping 31.42 | The track colour turning off |
### Allowed variation
@@ -160,16 +212,28 @@ Consumer migration instructions belong in consumer docs and release notes.
disabled, and shares the press controller's window and document listeners
while any pressable is mounted, and, through the tooltip's layer, the shared
gesture counter's document listeners, installed once per page; it owns no
- observer, and the busy announcement fires once per busy period.
+ 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).
## Accessibility contract
+A touch presentation leaves Switch's accessible name, switch role, checked
+state, busy state, description and status association, and disabled behavior
+as they are under any other pointer.
+
Switch binds to the shared switch-pattern accessibility contract under
`spec:AST-021`. The binding owns the standards-derived outcomes — role,
accessible name, exposed on/off state, description, disabled exposure and
inoperability, pointer and keyboard activation, pointer cancellation, and focus
staying put on change — across the representative states listed in
-`__tests__/Switch.a11y.states.ts`. Callback payloads, form participation,
+`__tests__/Switch.a11y.states.ts`. The contract checks pointer cancellation
+with a mouse, where a press slid off leaves the switch alone; under a finger a
+press slid off toggles it, under `spec:AST-020` FR9's reversible-toggle
+exception (DEC-5, FR15). Callback payloads, form participation,
disabled-reason tooltip composition, and styling remain Switch-owned and stay in
`Switch.test.tsx`.
@@ -180,12 +244,12 @@ disabled-reason tooltip composition, and styling remain Switch-owned and stay in
## Design relationships
-| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
-| ---------------- | -------------------------------------------------------- | ------------------------------- | -------------- | ------------------ |
-| Field | Arranges the switch control with its label and feedback. | Current source and public docs | Supporting | FR1, FR2 |
-| Track and thumb | Present the current on/off control. | Current source and public docs | Prominent | FR1, FR2, FR9–FR11 |
-| Label | Identifies the controlled setting. | Current source and public docs | Prominent | FR1, FR2, FR4 |
-| Spinner/status | Present conditional progress and validation feedback. | Current shared-component source | Supporting | FR3, FR6 |
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | -------------------------------------------------------- | ------------------------------- | -------------- | ----------------------------- |
+| Field | Arranges the switch control with its label and feedback. | Current source and public docs | Supporting | FR1, FR2 |
+| Track and thumb | Present the current on/off control. | Current source and public docs | Prominent | FR1, FR2, FR9–FR11, FR13–FR15 |
+| Label | Identifies the controlled setting. | Current source and public docs | Prominent | FR1, FR2, FR4 |
+| Spinner/status | Present conditional progress and validation feedback. | Current shared-component source | Supporting | FR3, FR6 |
### Theming anatomy
@@ -225,6 +289,9 @@ making the absence intentional.
- `spec:AST-085` owns disabled focusability; Switch meets it.
- `spec:AST-086` FR8 owns the busy announcement.
- `design:user-states` owns the pressed treatment.
+- `spec:AST-094` owns touch presentations and FR43's gestures for every
+ pointer: Switch follows its FR11 press profiles, its FR42 hit area and FR43
+ (FR10, FR13–FR15).
- `architecture:component-theming-surface` owns anatomy qualification, factual
`none` dispositions, and composition-preserving target ownership.
- FieldStatus and Spinner retain their existing public target contracts when
@@ -232,20 +299,21 @@ making the absence intentional.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
-| FR1, FR4 | `Switch.test.tsx` structure, label, description, and interaction suites | On/off, size, label position, hidden label | Removing stable parts, or folding the description into the name, fails; the caller description first is asserted. Evidence gap: no test asserts the label order (the position cases count children only) or the disabled reason last. | `audit:Switch/anatomy` |
-| FR2 | `Switch.test.tsx` label-target, labelSpacing, and pressed-state cases; `themingTargets.test.ts` | Current local targets | A missing label, field, track, or thumb target, or a missing `data-label-spacing`, fails; a rendered class absent from the documented targets fails. Evidence gap: no test asserts `data-label-position`, or the track and thumb `data-size`, `data-checked`, and `data-disabled`. | `audit:Switch/theming` |
-| FR3, FR5, FR6 | `Switch.test.tsx` loading, announcement, and status suites | Busy, pending Action, StrictMode, re-busy, detached status | Removing composed feedback, or announcing more than once per busy period, fails. Evidence gap: no test asserts the Spinner inside the thumb, `changeAction` after `onChange` with `preventDefault`, the optimistic state, or that pointer input is ignored while busy. | `audit:Switch/anatomy` |
-| FR7, FR8 | `Switch.test.tsx` disabled, disabledMessage, and form cases; `PressedState.a11y.chromium.spec.ts` disabled press case | Disabled with and without reason; required; on and off | A change while disabled, a submitted disabled value, a blocked submit, or press paint on a disabled switch fails. Evidence gap: no test asserts the absent hover tint, the half-opacity track, or that caller `onKeyDown` still runs while disabled (the FR7 gap). No test asserts `aria-required` following a form-level required default. | `audit:Switch/behavior` |
-| FR9–FR11 | `Switch.test.tsx` pressed-state, RTL, coarse-pointer, and forced-colors cases; `Switch.focusRing.source-build.test.mjs` | Mouse and touch press; RTL; coarse pointer; forced colors | Missing press paint, unmirrored travel, or lost forced-colors state fails. Evidence gap: no test asserts the hover tint, the 24 by 24 coarse minimum (the coarse cases check only the centering class), instant transitions under reduced motion, or the track focus outline; the source-build check covers only how the outline finds the input. | `audit:Switch/visual` |
-| FR12 | `Switch.test.tsx` rest-forwarding and ref cases | Root attributes; caller labelledby and describedby | A dropped ref, or a caller `aria-labelledby` or `aria-describedby` on the root, fails; the rest-forwarding case asserts `aria-label` on the root, which is the FR12 gap, so fixing the gap changes that test. Evidence gap: no test distinguishes `onFocus` and `onBlur` on the input from the root, or asserts a caller `onClick`, other handlers, `className`, `style`, `xstyle`, or `width` on the root. | `audit:Switch/api` |
-| Switch pattern — semantics | `__tests__/Switch.a11y.test.tsx` (DOM layer, higher layers reported unrun) and `__tests__/Switch.a11y.chromium.spec.ts` (accessibility tree) | Off, on, on after a controlled update, described, hidden label, disabled, focusable-disabled, required, invalid, loading | Losing the switch role, the accessible name, the visible label's words within that name, the exposed on/off state, an attached description, or disabled, required, and invalid exposure fails the shared contract. | `audit:Switch/anatomy` |
-| Switch pattern — interaction | `__tests__/Switch.a11y.chromium.spec.ts` (real browser) | Every state, each checked for what applies to it: round trips, pointer cancellation, and focus-on-change cover the operable states (off, on, on after a controlled update, described, hidden label, required, invalid); Tab reach-and-escape covers every focusable state, adding focusable-disabled and loading; inoperability covers the states the user cannot change (disabled, focusable-disabled, loading). | Losing either direction of a pointer or Space round trip, letting a press slid off the control still change it (WCAG 2.5.2), moving focus when the state changes (WCAG 3.2.2), failing to reach or leave the control by Tab, or changing a state the user is not meant to be able to change fails the shared contract. | `audit:Switch/anatomy` |
-| Switch pattern — label stability | `__tests__/Switch.a11y.chromium.spec.ts`, reported not gated | Every operable state: off, on, on after a controlled update, described, hidden label, required, invalid | The APG requires the label not to change with the state. No current record adopts it, so the expectation is advisory: a name that flips across a round trip is reported, and does not fail the build. | `audit:Switch/anatomy` |
-| Switch pattern — state inventory | `__tests__/Switch.a11y.chromium.spec.ts` inventory assertion | Every bound state | The labels `__tests__/Switch.a11y.states.ts` claims each state renders are compared against the rendered page, so a stale inventory is reported as one rather than as a standards failure. | `audit:Switch/anatomy` |
-| ORD1, ORD2, PR1 | ORD1 is covered by the FR5 and FR7 rows, and the caller-description-first part of ORD2 by the FR1 row. Evidence gap: no test asserts the rest of the ORD2 order or listener bounds | — | — | `audit:Switch/behavior` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and all current targets | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails repository validation. | `audit:Switch/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
+| FR1, FR4 | `Switch.test.tsx` structure, label, description, and interaction suites | On/off, size, label position, hidden label | Removing stable parts, or folding the description into the name, fails; the caller description first is asserted. Evidence gap: no test asserts the label order (the position cases count children only) or the disabled reason last. | `audit:Switch/anatomy` |
+| FR2 | `Switch.test.tsx` label-target, labelSpacing, and pressed-state cases; `themingTargets.test.ts` | Current local targets | A missing label, field, track, or thumb target, or a missing `data-label-spacing`, fails; a rendered class absent from the documented targets fails. Evidence gap: no test asserts `data-label-position`, or the track and thumb `data-size`, `data-checked`, and `data-disabled`. | `audit:Switch/theming` |
+| FR3, FR5, FR6 | `Switch.test.tsx` loading, announcement, and status suites | Busy, pending Action, StrictMode, re-busy, detached status | Removing composed feedback, or announcing more than once per busy period, fails. Evidence gap: no test asserts the Spinner inside the thumb, `changeAction` after `onChange` with `preventDefault`, the optimistic state, or that pointer input is ignored while busy. | `audit:Switch/anatomy` |
+| FR7, FR8 | `Switch.test.tsx` disabled, disabledMessage, and form cases; `PressedState.a11y.chromium.spec.ts` disabled press case | Disabled with and without reason; required; on and off | A change while disabled, a submitted disabled value, a blocked submit, or press paint on a disabled switch fails. Evidence gap: no test asserts the absent hover tint, the half-opacity track, or that caller `onKeyDown` still runs while disabled (the FR7 gap). No test asserts `aria-required` following a form-level required default. | `audit:Switch/behavior` |
+| FR9–FR11 | `Switch.test.tsx` pressed-state, RTL, coarse-pointer, and forced-colors cases; `Switch.focusRing.source-build.test.mjs` | Mouse and touch press; RTL; coarse pointer; forced colors | Missing press paint, unmirrored travel, or lost forced-colors state fails. Evidence gap: no test asserts the hover tint, instant transitions under reduced motion with a mouse, or the track focus outline; the source-build check covers only how the outline finds the input. | `audit:Switch/visual` |
+| FR12 | `Switch.test.tsx` rest-forwarding and ref cases | Root attributes; caller labelledby and describedby | A dropped ref, or a caller `aria-labelledby` or `aria-describedby` on the root, fails; the rest-forwarding case asserts `aria-label` on the root, which is the FR12 gap, so fixing the gap changes that test. Evidence gap: no test distinguishes `onFocus` and `onBlur` on the input from the root, or asserts a caller `onClick`, other handlers, `className`, `style`, `xstyle`, or `width` on the root. | `audit:Switch/api` |
+| FR10 (coarse hit area), FR13–FR15 | `__tests__/Switch.interaction.browser.spec.ts` (Chromium and WebKit, real touch input), `__tests__/SwitchPointer.interaction.browser.spec.ts` (Chromium and WebKit, a real mouse; Chromium, a real pen), `Switch.test.tsx` hit-area cases and listener counts, and `switchTouch.test.ts` | The circle at each state's size; the 44 × 44 px hit area, and its stop halfway to a link beside it; a tap, a hold, a short drag, a flipping drag and a press slid off and lifted outside; right to left; Reduce Motion; a mouse or a pen drag past the flip, past it and back, and slid off; a click and a right click; a fine pointer's listeners at rest | A reshaped thumb, a hit area under 44 × 44 px with nothing near, a hit area past the midpoint to a neighbour, a thumb painted outside the track, a slid-off press that leaves the switch alone under a finger, a flip at any other distance, a mouse or pen drag that does not flip at the flip distance, a mouse or pen slid off that toggles, a lift or animation under a fine pointer, or more than one listener at rest under a fine pointer fails. | `audit:Switch/behavior` |
+| Switch pattern — semantics | `__tests__/Switch.a11y.test.tsx` (DOM layer, higher layers reported unrun) and `__tests__/Switch.a11y.chromium.spec.ts` (accessibility tree) | Off, on, on after a controlled update, described, hidden label, disabled, focusable-disabled, required, invalid, loading | Losing the switch role, the accessible name, the visible label's words within that name, the exposed on/off state, an attached description, or disabled, required, and invalid exposure fails the shared contract. | `audit:Switch/anatomy` |
+| Switch pattern — interaction | `__tests__/Switch.a11y.chromium.spec.ts` (real browser) | Every state, each checked for what applies to it: round trips, pointer cancellation, and focus-on-change cover the operable states (off, on, on after a controlled update, described, hidden label, required, invalid); Tab reach-and-escape covers every focusable state, adding focusable-disabled and loading; inoperability covers the states the user cannot change (disabled, focusable-disabled, loading). | Losing either direction of a pointer or Space round trip, letting a mouse press slid off the control still change it (WCAG 2.5.2; under a finger FR15's reversible-toggle exception applies), moving focus when the state changes (WCAG 3.2.2), failing to reach or leave the control by Tab, or changing a state the user is not meant to be able to change fails the shared contract. | `audit:Switch/anatomy` |
+| Switch pattern — label stability | `__tests__/Switch.a11y.chromium.spec.ts`, reported not gated | Every operable state: off, on, on after a controlled update, described, hidden label, required, invalid | The APG requires the label not to change with the state. No current record adopts it, so the expectation is advisory: a name that flips across a round trip is reported, and does not fail the build. | `audit:Switch/anatomy` |
+| Switch pattern — state inventory | `__tests__/Switch.a11y.chromium.spec.ts` inventory assertion | Every bound state | The labels `__tests__/Switch.a11y.states.ts` claims each state renders are compared against the rendered page, so a stale inventory is reported as one rather than as a standards failure. | `audit:Switch/anatomy` |
+| ORD1, ORD2, PR1 | ORD1 is covered by the FR5 and FR7 rows, and the caller-description-first part of ORD2 by the FR1 row. Evidence gap: no test asserts the rest of the ORD2 order or listener bounds | — | — | `audit:Switch/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and all current targets | Canonical-key drift, invalid dispositions or target spelling, or an unclaimed current local target fails repository validation. | `audit:Switch/theming` |
No repository check resolves `delegatesTo` owner and target pairs; the pairs
above match the current Spinner and FieldStatus targets.
@@ -255,9 +323,6 @@ above match the current Spinner and FieldStatus targets.
- **Caller handlers while disabled (FR7).** Caller DOM handlers other than
`onClick`, such as `onKeyDown`, still run while disabled, against
`spec:AST-085` FR2.
-- **Coarse target (FR10).** The coarse-pointer hit area stops at 24 by 24 CSS
- pixels, short of the 44 px target `spec:AST-094` FR42 sets where neighbors
- allow.
- **Caller ARIA on the root (FR12).** A caller's `aria-label` and other ARIA
attributes, except `aria-labelledby` and `aria-describedby`, land on the field
root instead of the switch input, against `architecture:public-component-api`
@@ -265,7 +330,14 @@ above match the current Spinner and FieldStatus targets.
## Decision log
-No component-local decision. Switch applies `spec:AST-021` and `spec:AST-085`.
+FR13 rests on owner direction of 2026-10-26: the thumb keeps its circle and its
+size on every device, and a coarse pointer gets a hit area that grows toward
+44 × 44 px and stops halfway to its neighbours, with nothing visible added
+(FR10). FR14 rests on owner direction of 2026-10-25. Under a mouse or a pen a
+press slid off keeps the native checkbox's cancel: `spec:AST-094` FR11 lets a
+toggle under `spec:AST-020` FR9's slide-off exception complete only on a lift
+after the finger slid off. Switch otherwise applies `spec:AST-021` and
+`spec:AST-085`.
## Open questions
diff --git a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
index 1aab6be4c1..399f2de0a6 100644
--- a/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
+++ b/internal/eslint-plugin-astryx/no-raw-private-attribute.baseline.json
@@ -87,8 +87,6 @@
"data-astryx-press"
],
"packages/core/src/Switch/Switch.tsx": [
- "data-astryx-press",
- "data-astryx-press",
"data-astryx-press",
"data-astryx-press"
],
diff --git a/packages/core/src/Switch/Switch.doc.mjs b/packages/core/src/Switch/Switch.doc.mjs
index 136244e4e2..e8d0c5bc36 100644
--- a/packages/core/src/Switch/Switch.doc.mjs
+++ b/packages/core/src/Switch/Switch.doc.mjs
@@ -223,7 +223,7 @@ export const docs = {
],
anatomy,
description:
- 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead.',
+ 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead. Under a finger it moves like the iOS switch on every touch screen: a press lifts the thumb, a drag across flips it, lifting the finger commits, and a tap toggles through the browser’s click. The thumb keeps its circle and size on every device, and under a coarse pointer the invisible hit area grows toward 44 × 44 px, stopping halfway to any neighbouring control so a tap goes to the nearer one. With reduced motion on, a change cross-fades on a touch screen and is immediate with a mouse.',
bestPractices: [
{
guidance: true,
@@ -395,7 +395,7 @@ export const docsZh = {
},
usage: {
description:
- 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead.',
+ 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead. Under a finger it moves like the iOS switch on every touch screen: a press lifts the thumb, a drag across flips it, lifting the finger commits, and a tap toggles through the browser’s click. The thumb keeps its circle and size on every device, and under a coarse pointer the invisible hit area grows toward 44 × 44 px, stopping halfway to any neighbouring control so a tap goes to the nearer one. With reduced motion on, a change cross-fades on a touch screen and is immediate with a mouse.',
bestPractices: [
{
guidance: true,
@@ -431,7 +431,7 @@ export const docsDense = {
description: 'Toggle switch for boolean values w/ integrated label support.',
usage: {
description:
- 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead.',
+ 'A toggle control for on/off states that take effect immediately. Supports labels, descriptions, loading states, and validation. Use it for settings or preferences that apply instantly. For changes requiring a form submission, use a checkbox instead. Under a finger it moves like the iOS switch on every touch screen: a press lifts the thumb, a drag across flips it, lifting the finger commits, and a tap toggles through the browser’s click. The thumb keeps its circle and size on every device, and under a coarse pointer the invisible hit area grows toward 44 × 44 px, stopping halfway to any neighbouring control so a tap goes to the nearer one. With reduced motion on, a change cross-fades on a touch screen and is immediate with a mouse.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/Switch/Switch.test.tsx b/packages/core/src/Switch/Switch.test.tsx
index fb95600716..69d24d0dbe 100644
--- a/packages/core/src/Switch/Switch.test.tsx
+++ b/packages/core/src/Switch/Switch.test.tsx
@@ -23,6 +23,7 @@
*/
import {StrictMode} from 'react';
+import * as stylex from '@stylexjs/stylex';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -33,11 +34,16 @@ import {
} from '../__tests__/forcedColors';
import {
hasPressedArm,
- hasReleaseFade,
readsPressStrength,
+ releasesOnLayer,
+ rulesDeclaredFor,
+ rulesWithSelector,
} from '../__tests__/pressState';
+import {press as uikitPress} from '../motion/uikit/timing';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
+import {installPressFeedback} from '../utils/pressFeedback';
+import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
afterEach(() => {
__resetLiveRegionsForTest();
@@ -312,6 +318,27 @@ describe('Switch', () => {
expect(children.length).toBe(2);
});
+ it('keeps its input when labelPosition changes, so what is attached to it stays attached', () => {
+ const view = render(
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ labelPosition="start"
+ />,
+ );
+ const input = screen.getByRole('switch');
+ view.rerender(
+ <Switch
+ label="Enable notifications"
+ value={false}
+ onChange={() => {}}
+ labelPosition="end"
+ />,
+ );
+ expect(screen.getByRole('switch')).toBe(input);
+ });
+
// Retained on purpose: the shared switch contract encodes no busy expectation
// — no current record adopts one — so this is the only thing gating it.
it('sets aria-busy on input when loading', () => {
@@ -1041,7 +1068,7 @@ describe('Switch', () => {
expect(hasPressedArm(thumb)).toBe(true);
});
- it('fades the touch press out from the row, with the track and thumb reading its strength', () => {
+ it("paints the touch press on the track's ::before and releases it on the compositor", () => {
const {container} = render(
<Switch label="Notifications" value={false} onChange={() => {}} />,
);
@@ -1051,15 +1078,273 @@ describe('Switch', () => {
if (track == null || thumb == null || row == null) {
throw new Error('the switch has no pressable row, track or thumb');
}
- // The controller writes the row; the row owns the strength and its
- // release, and the two parts paint the pressed token at that strength
- // on both touch arms, so they fade together.
- expect(hasReleaseFade(row)).toBe(true);
+ const coarse = {
+ insideMedia: /\(pointer: coarse\)/,
+ outsideMedia: /prefers-reduced-motion/,
+ };
+ const selector = (rule: string) => rule.slice(0, rule.indexOf('{'));
+ const body = (rule: string) => rule.slice(rule.indexOf('{'));
+ // The controller writes the row. Under a finger the press is a layer on
+ // the track, under the thumb. It exists only while the row is pressed
+ // or releasing, with no element and no box at rest. It paints the
+ // pressed token, shows at once, and releases on the compositor. Track
+ // and thumb both paint it.
for (const part of [track, thumb]) {
- expect(readsPressStrength(part, '[data-astryx-press="on"]')).toBe(true);
- expect(readsPressStrength(part)).toBe(true);
+ const layer = rulesDeclaredFor(part).filter(rule =>
+ selector(rule).includes('::before'),
+ );
+ const creates = layer.filter(rule =>
+ /(^|[{;\s])content:/.test(body(rule)),
+ );
+ expect(creates.length).toBeGreaterThan(0);
+ for (const rule of creates) {
+ expect(selector(rule)).toMatch(/data-astryx-press="(on|fading)"/);
+ }
+ expect(
+ layer.some(rule =>
+ /background-color:[^;}]*--color-overlay-pressed/.test(rule),
+ ),
+ ).toBe(true);
+ }
+ const on = rulesWithSelector(track, '[data-astryx-press="on"]', coarse);
+ expect(on.some(rule => /opacity:\s*1\b/.test(rule))).toBe(true);
+ expect(on.some(rule => /animation-name:\s*(?!none)/.test(rule))).toBe(
+ false,
+ );
+ for (const part of [track, thumb]) {
+ expect(
+ releasesOnLayer(part, '::before', uikitPress.highlightOutMs),
+ ).toBe(true);
+ }
+ // Nothing reads the strength under a finger, so its main-thread
+ // release stops there; any other pointer keeps it (the desktop rule).
+ expect(
+ rulesWithSelector(row, '[data-astryx-press="fading"]', coarse).some(
+ rule => /animation-name:\s*none/.test(rule),
+ ),
+ ).toBe(true);
+ const fine = {outsideMedia: /prefers-reduced-motion|\(pointer: coarse\)/};
+ expect(
+ rulesWithSelector(row, '[data-astryx-press="fading"]', fine).some(
+ rule => /animation-name:\s*(?!none)/.test(rule),
+ ),
+ ).toBe(true);
+ for (const part of [track, thumb]) {
+ expect(readsPressStrength(part, '[data-astryx-press="on"]')).toBe(
+ false,
+ );
+ expect(readsPressStrength(part)).toBe(false);
}
});
+
+ it('releases the touch press on the shared release’s clock and curve', () => {
+ render(
+ <>
+ <Switch label="Notifications" value={false} onChange={() => {}} />
+ <div
+ data-testid="shared-release"
+ {...stylex.props(interactionOverlayStyles.pressedAlpha)}
+ />
+ </>,
+ );
+ const track = document.querySelector('.astryx-switch');
+ if (track == null) {
+ throw new Error('the switch has no track');
+ }
+ const shared = screen.getByTestId('shared-release');
+ const fading = '[data-astryx-press="fading"]';
+ const reduced = /prefers-reduced-motion/;
+ const valuesOf = (rules: string[], property: string) => [
+ ...new Set(
+ rules.flatMap(rule => {
+ const match = rule.match(new RegExp(`${property}:\\s*([^;}]+)`));
+ // StyleX may write a time in s or ms: compare it in ms.
+ return match == null
+ ? []
+ : [
+ match[1]
+ .trim()
+ .replace(
+ /(\d*\.?\d+)(ms|s)\b/g,
+ (_, n: string, unit: string) =>
+ `${Number(n) * (unit === 's' ? 1000 : 1)}ms`,
+ ),
+ ];
+ }),
+ ),
+ ];
+ const layer = (filter: {insideMedia?: RegExp; outsideMedia?: RegExp}) =>
+ rulesWithSelector(track, fading, filter).filter(rule =>
+ rule.slice(0, rule.indexOf('{')).includes('::before'),
+ );
+ const touch = layer({
+ insideMedia: /\(pointer: coarse\)/,
+ outsideMedia: reduced,
+ });
+ const own = rulesWithSelector(shared, fading, {outsideMedia: reduced});
+ for (const property of [
+ 'animation-duration',
+ 'animation-timing-function',
+ ]) {
+ expect(valuesOf(own, property)).toHaveLength(1);
+ expect(valuesOf(touch, property)).toEqual(valuesOf(own, property));
+ }
+ // Reduce Motion's arm nests one `@media` rule in another, which the
+ // test DOM drops: the browser proofs check it.
+ });
+ });
+
+ describe('the row that holds the touch press', () => {
+ const FADING = '[data-astryx-press="fading"]';
+ /** Rules under a coarse primary pointer, Reduce Motion's arms left out. */
+ const UNDER_COARSE = {
+ insideMedia: /\(pointer: coarse\)/,
+ outsideMedia: /prefers-reduced-motion/,
+ };
+ /** Rules for any other pointer, Reduce Motion's arms left out. */
+ const UNDER_FINE = {
+ outsideMedia: /prefers-reduced-motion|\(pointer: coarse\)/,
+ };
+ const selectorOf = (rule: string) => rule.slice(0, rule.indexOf('{'));
+ const fadingOnHost = (rules: string[]) =>
+ rules.filter(
+ rule =>
+ selectorOf(rule).includes(FADING) && !selectorOf(rule).includes('::'),
+ );
+ const valuesOf = (rules: string[], property: string) =>
+ rules
+ .flatMap(rule => {
+ const match = rule.match(new RegExp(`${property}:\\s*([^;}]+)`));
+ return match == null ? [] : [match[1].trim()];
+ })
+ .sort();
+ /** The switch's row, and an element with the shared press styles alone. */
+ function renderOwners(): {alpha: HTMLElement; row: Element} {
+ render(
+ <>
+ <Switch label="Notifications" value={false} onChange={() => {}} />
+ <div
+ data-testid="alpha"
+ {...stylex.props(interactionOverlayStyles.pressedAlpha)}
+ />
+ </>,
+ );
+ const row = document
+ .querySelector('.astryx-switch')
+ ?.closest('[data-astryx-pressable]');
+ if (row == null) {
+ throw new Error('the switch has no pressable row');
+ }
+ return {alpha: screen.getByTestId('alpha'), row};
+ }
+
+ it('declares the shared strength and paint for the track’s and thumb’s layers', () => {
+ const {alpha, row} = renderOwners();
+ const strengthAndPaint = (el: Element) =>
+ rulesDeclaredFor(el)
+ .filter(rule => /--astryx-press-alpha|--_press-paint/.test(rule))
+ .sort();
+ expect(strengthAndPaint(alpha).length).toBeGreaterThan(0);
+ expect(strengthAndPaint(row)).toEqual(strengthAndPaint(alpha));
+ });
+
+ it('with any pointer but a coarse primary one, keeps the shared release on the row', () => {
+ const {alpha, row} = renderOwners();
+ const release = (el: Element) =>
+ fadingOnHost(rulesDeclaredFor(el, UNDER_FINE));
+ expect(valuesOf(release(alpha), 'animation-name')).not.toEqual([]);
+ for (const property of [
+ 'animation-name',
+ 'animation-duration',
+ 'animation-timing-function',
+ ]) {
+ expect(valuesOf(release(row), property)).toEqual(
+ valuesOf(release(alpha), property),
+ );
+ }
+ });
+
+ it('under a coarse primary pointer, drops the strength’s own release on the row', () => {
+ const {alpha, row} = renderOwners();
+ const names = (el: Element) =>
+ valuesOf(
+ fadingOnHost(rulesDeclaredFor(el, UNDER_COARSE)),
+ 'animation-name',
+ );
+ // The shared styles keep the strength's release there; the row holds
+ // the strength, so the layers' fade is the one fade.
+ expect(names(alpha)).not.toContain('none');
+ expect(names(row)).toEqual(['none']);
+ });
+ });
+
+ describe('mouse look', () => {
+ // jsdom applies no `@media (pointer: coarse)` rule, so these are the
+ // styles a mouse gets. The touch presentation must override none of
+ // them: a later style that names a property replaces all of it.
+ const look = (container: HTMLElement) => {
+ const track = container.querySelector<HTMLElement>('.astryx-switch');
+ const thumb = container.querySelector<HTMLElement>(
+ '.astryx-switch-thumb',
+ );
+ if (track == null || thumb == null) {
+ throw new Error('the switch has no track or thumb');
+ }
+ const t = getComputedStyle(track);
+ const h = getComputedStyle(thumb);
+ return {
+ fill: t.backgroundColor,
+ padding: t.paddingTop,
+ fade: [t.transitionProperty, t.transitionDuration],
+ size: [h.width, h.height],
+ slide: [h.transitionProperty.replace(/\s/g, ''), h.transitionDuration],
+ travel: h.transform,
+ };
+ };
+
+ it('keeps the track fill, padding and colour fade, and the thumb size and slide', () => {
+ // A fine pointer: the desktop switch.
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
+ const {container, rerender} = render(
+ <Switch label="Wi-Fi" value={false} onChange={() => {}} />,
+ );
+ const off = look(container);
+ expect(off.fill).toContain('--color-background-gray');
+ expect(off.padding).toBe('4px');
+ expect(off.fade[0]).toBe('background-color');
+ expect(off.fade[1]).not.toMatch(/^(0s)?$/);
+ expect(off.size).toEqual(['16px', '16px']);
+ expect(off.slide[0]).toBe('transform,width,height');
+ expect(off.slide[1]).not.toMatch(/^(0s)?$/);
+
+ rerender(<Switch label="Wi-Fi" value onChange={() => {}} />);
+ const on = look(container);
+ expect(on.fill).toContain('--color-accent');
+ expect(on.size).toEqual(['20px', '20px']);
+ expect(on.travel).toBe('translateX(14px)');
+ });
+
+ it('adds no element: the thumb is the track’s only child, under a finger too', () => {
+ const {container} = render(
+ <Switch label="Wi-Fi" value={false} onChange={() => {}} />,
+ );
+ const track = container.querySelector('.astryx-switch');
+ const thumb = container.querySelector('.astryx-switch-thumb');
+ // architecture:component-style-authoring INV7: the touch presentation
+ // styles the existing thumb (the fade layer is the track's ::before).
+ expect(track?.children.length).toBe(1);
+ expect(thumb?.parentElement).toBe(track);
+ });
+
+ it('keeps the small size’s padding and thumb', () => {
+ expect(window.matchMedia('(pointer: coarse)').matches).toBe(false);
+ const {container} = render(
+ <Switch label="Wi-Fi" size="sm" value={false} onChange={() => {}} />,
+ );
+ const off = look(container);
+ expect(off.padding).toBe('2px');
+ expect(off.size).toEqual(['14px', '14px']);
+ });
});
describe('coarse pointer and RTL hit-target positioning', () => {
@@ -1095,6 +1380,304 @@ describe('Switch', () => {
// jsdom cannot emulate forced-colors rendering, so these assert that the
// compiled output includes the forced-colors rules; visual behavior needs
// manual verification under Windows High Contrast.
+describe('touch listeners (spec:AST-094 FR24)', () => {
+ const coarseMedia = (query: string) =>
+ ({
+ matches:
+ query.includes('pointer: coarse') ||
+ query.includes('any-pointer: coarse'),
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }) as unknown as MediaQueryList;
+
+ // React's root delegates touch events too: count against a plain element.
+ const listenersWhileRendering = (
+ isDisabled: boolean | 'none' | 'busy',
+ ): {touch: number; pointer: number; contextMenu: number} => {
+ vi.spyOn(window, 'matchMedia').mockImplementation(coarseMedia);
+ const types: string[] = [];
+ const record = function (this: unknown, type: string) {
+ types.push(type);
+ };
+ const onDocument = vi
+ .spyOn(document, 'addEventListener')
+ .mockImplementation(record);
+ const onElements = vi
+ .spyOn(HTMLElement.prototype, 'addEventListener')
+ .mockImplementation(record);
+ const {unmount} = render(
+ isDisabled === 'none' ? (
+ <div />
+ ) : (
+ <Switch
+ label="Notifications"
+ value={false}
+ onChange={() => {}}
+ isDisabled={isDisabled === true}
+ isLoading={isDisabled === 'busy'}
+ />
+ ),
+ );
+ onDocument.mockRestore();
+ onElements.mockRestore();
+ 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,
+ };
+ };
+
+ it('a switch under a coarse pointer attaches no touch 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.
+ for (const counts of [enabled, disabled, busy]) {
+ expect(counts.touch).toBe(baseline.touch);
+ expect(counts.contextMenu).toBe(baseline.contextMenu);
+ }
+ // The gesture host arms a press listener for an enabled switch only.
+ expect(enabled.pointer).toBeGreaterThan(disabled.pointer);
+ // Busy stays attached, so the change that made it busy keeps its motion.
+ expect(busy.pointer).toBeGreaterThan(disabled.pointer);
+ });
+
+ it('under a fine pointer an enabled switch arms one passive pointerdown listener on its own element and adds no page listener until a press; a disabled one arms none (spec:AST-094 FR24, FR43)', () => {
+ const fineMedia = (query: string) =>
+ ({
+ matches:
+ query.includes('pointer: fine') || query.includes('hover: hover'),
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ }) as unknown as MediaQueryList;
+ const listenersWhileRendering = (isDisabled: boolean) => {
+ vi.spyOn(window, 'matchMedia').mockImplementation(fineMedia);
+ // The one shared press controller is the allowed idle page listener. It
+ // is installed before the render is measured, so a count is the
+ // switch's own.
+ const releasePressController = installPressFeedback();
+ const onElements: {
+ target: unknown;
+ type: string;
+ options: unknown;
+ }[] = [];
+ const onPage: string[] = [];
+ const elementSpy = vi
+ .spyOn(HTMLElement.prototype, 'addEventListener')
+ .mockImplementation(function (
+ this: unknown,
+ type: string,
+ _listener: unknown,
+ options?: unknown,
+ ) {
+ onElements.push({target: this, type, options});
+ });
+ const recordPage = function (this: unknown, type: string) {
+ onPage.push(type);
+ };
+ const documentSpy = vi
+ .spyOn(document, 'addEventListener')
+ .mockImplementation(recordPage);
+ const windowSpy = vi
+ .spyOn(window, 'addEventListener')
+ .mockImplementation(recordPage);
+ const {container, unmount} = render(
+ <Switch
+ label="Notifications"
+ value={false}
+ onChange={() => {}}
+ isDisabled={isDisabled}
+ />,
+ );
+ const surface = container.querySelector('[role="switch"]')?.parentElement;
+ elementSpy.mockRestore();
+ documentSpy.mockRestore();
+ windowSpy.mockRestore();
+ unmount();
+ releasePressController();
+ vi.restoreAllMocks();
+ const armed = onElements.filter(({target, type, options}) => {
+ const o = options as AddEventListenerOptions | undefined;
+ return (
+ target === surface &&
+ type === 'pointerdown' &&
+ o?.capture === true &&
+ o?.passive === true
+ );
+ }).length;
+ // The host's page listeners for a press: none at rest (FR24).
+ const pressListeners = onPage.filter(type =>
+ /^(pointermove|pointerup|pointercancel|touch)/.test(type),
+ ).length;
+ return {armed, pressListeners};
+ };
+ expect(listenersWhileRendering(false)).toEqual({
+ armed: 1,
+ pressListeners: 0,
+ });
+ expect(listenersWhileRendering(true)).toEqual({
+ armed: 0,
+ pressListeners: 0,
+ });
+ });
+
+ it('runs no hit-area observer or window listener under a fine pointer, or while disabled under a coarse one', () => {
+ const observersWhileRendering = (
+ isCoarse: boolean,
+ isDisabled: boolean,
+ ): {observers: number; resize: number} => {
+ vi.spyOn(window, 'matchMedia').mockImplementation(query => ({
+ ...coarseMedia(query),
+ matches: isCoarse && query.includes('pointer: coarse'),
+ }));
+ let observers = 0;
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor() {
+ observers += 1;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const onWindow = vi.spyOn(window, 'addEventListener');
+ const {unmount} = render(
+ <Switch
+ label="Notifications"
+ value={false}
+ onChange={() => {}}
+ isDisabled={isDisabled}
+ />,
+ );
+ const resize = onWindow.mock.calls.filter(
+ ([type]) => type === 'resize',
+ ).length;
+ unmount();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ return {observers, resize};
+ };
+ expect(observersWhileRendering(false, false)).toEqual({
+ observers: 0,
+ resize: 0,
+ });
+ expect(observersWhileRendering(true, true)).toEqual({
+ observers: 0,
+ resize: 0,
+ });
+ // Enabled under a coarse pointer it measures.
+ expect(observersWhileRendering(true, false).observers).toBe(1);
+ });
+});
+
+describe('hit area under a coarse pointer (Switch FR10)', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it('grows toward 44 × 44 px and stops halfway to a link beside it, so a tap nearer the link is the link’s', () => {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ }));
+ let reveal: ((entries: IntersectionObserverEntry[]) => void) | null = null;
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ constructor(callback: (entries: IntersectionObserverEntry[]) => void) {
+ reveal = callback;
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const frames: (() => void)[] = [];
+ vi.stubGlobal('requestAnimationFrame', (run: () => void) =>
+ frames.push(run),
+ );
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ const {container} = render(
+ <div>
+ <Switch
+ label="Wi-Fi"
+ isLabelHidden
+ size="sm"
+ value={false}
+ onChange={() => {}}
+ />
+ <a href="#details">Details</a>
+ </div>,
+ );
+ const input = screen.getByRole('switch');
+ const surface = input.parentElement as HTMLElement;
+ const link = container.querySelector('a') as HTMLElement;
+ const box = (left: number, top: number, width: number, height: number) =>
+ ({
+ left,
+ top,
+ right: left + width,
+ bottom: top + height,
+ width,
+ height,
+ x: left,
+ y: top,
+ toJSON: () => ({}),
+ }) as DOMRect;
+ // A 32 × 20 (small) switch with the link 8 px to its right.
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
+ function (this: HTMLElement) {
+ if (this === surface) {
+ return box(100, 100, 32, 20);
+ }
+ if (this === link) {
+ return box(140, 100, 60, 20);
+ }
+ return box(0, 0, 0, 0);
+ },
+ );
+ expect(surface.style.getPropertyValue('--astryx-hit-inset-right')).toBe('');
+ reveal!([
+ {
+ target: surface,
+ isIntersecting: true,
+ } as unknown as IntersectionObserverEntry,
+ ]);
+ frames.splice(0).forEach(run => run());
+ // Up and down 12 px (20 → 44); left 6 px (32 → 44); right stops at
+ // 4 px, half the 8 px gap.
+ expect(surface.style.getPropertyValue('--astryx-hit-inset-top')).toBe(
+ '12px',
+ );
+ expect(surface.style.getPropertyValue('--astryx-hit-inset-left')).toBe(
+ '6px',
+ );
+ expect(surface.style.getPropertyValue('--astryx-hit-inset-right')).toBe(
+ '4px',
+ );
+ });
+});
+
describe('forced colors (WCAG 1.4.11)', () => {
it('compiles forced-colors overrides so on/off state survives Windows High Contrast', () => {
render(<Switch label="Notifications" value={true} onChange={() => {}} />);
diff --git a/packages/core/src/Switch/Switch.tsx b/packages/core/src/Switch/Switch.tsx
index 98d7fd2034..35e99cf95b 100644
--- a/packages/core/src/Switch/Switch.tsx
+++ b/packages/core/src/Switch/Switch.tsx
@@ -17,7 +17,9 @@
*/
import {
+ Fragment,
useId,
+ useMemo,
useOptimistic,
useTransition,
useEffect,
@@ -36,6 +38,7 @@ import {
typographyVars,
typeScaleVars,
focusVars,
+ shadowVars,
} from '../theme/tokens.stylex';
import {FieldLabel} from '../Field/FieldLabel';
import {FieldStatus} from '../FieldStatus/FieldStatus';
@@ -45,7 +48,6 @@ import {Spinner} from '../Spinner';
import {useTooltip} from '../Tooltip';
import {mergeProps, mergeRefs, rtlStyles} from '../utils';
import {switchFocusInput, switchScope} from './switch.markers.stylex';
-import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import type {BaseProps} from '../BaseProps';
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
@@ -61,18 +63,53 @@ import {
import english from '../i18n/generated-english/Switch/Switch.generated';
registerEnglishFallback(english);
-const wrapperSizeStyles = stylex.create({
- sm: {
- width: 32,
- height: 20,
- },
- md: {
- width: 40,
- height: 24,
- },
-});
+import {
+ interactionOverlayStyles,
+ pressConsts,
+ pressVars,
+} from '../utils/interactionOverlay.stylex';
+import {pressHoldsDragProps} from '../privateAttributes/pressHoldsDrag.stylex';
+import {useSwitchTouch, type SwitchTouchParts} from './useSwitchTouch';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {watchHitArea, writeHitInsets} from '../utils/hitArea';
+
+/**
+ * The track box of each size, px (width × height), for the touch
+ * presentation's thumb geometry.
+ * SYNC: wrapperSizeStyles and trackSizeStyles below.
+ */
+const TRACK_SIZE = {sm: [32, 20], md: [40, 24]} as const;
-const inputSizeStyles = stylex.create({
+/**
+ * A finger: utils/touchPresentation.ts's TOUCH_QUERY. The touch presentation
+ * is one model on every touch device: the lift, tracking, flip rule and
+ * springs sit under it alone.
+ * SYNC: utils/touchPresentation.ts TOUCH_QUERY.
+ */
+const TOUCH = '@media (pointer: coarse)';
+
+/** The press controller's two states on the row it writes to. */
+const PRESS_ON = '[data-astryx-press="on"]';
+const PRESS_FADING = '[data-astryx-press="fading"]';
+
+/**
+ * The shared press release, for the press layers the switch fades on the
+ * compositor. The clock scales by the theme's tempo, and the curve is the
+ * controller's own. Switch.test.tsx compares the two.
+ * SYNC: utils/interactionOverlay.stylex.ts PRESS_RELEASE_DURATION,
+ * PRESS_RELEASE_DURATION_REDUCED and RELEASE_EASE.
+ */
+const PRESS_RELEASE_DURATION = `calc(${pressConsts.releaseMs}ms * min(var(--_astryx-motion-tempo, 1), 1.5))`;
+const PRESS_RELEASE_DURATION_REDUCED = `min(${pressConsts.releaseMs}ms, calc(${pressConsts.releaseMs}ms * var(--_astryx-motion-tempo, 1)))`;
+const PRESS_RELEASE_EASE = 'cubic-bezier(0, 0, 0.2, 1)';
+
+// The measured hit insets (utils/hitArea), 0 until measured.
+const HIT_TOP = 'var(--astryx-hit-inset-top, 0px)';
+const HIT_RIGHT = 'var(--astryx-hit-inset-right, 0px)';
+const HIT_BOTTOM = 'var(--astryx-hit-inset-bottom, 0px)';
+const HIT_LEFT = 'var(--astryx-hit-inset-left, 0px)';
+
+const wrapperSizeStyles = stylex.create({
sm: {
width: 32,
height: 20,
@@ -83,6 +120,9 @@ const inputSizeStyles = stylex.create({
},
});
+// Every touch value sits in the same property as the mouse value, as a
+// nested condition, never in a later style. A later style that names a
+// property replaces all of it, mouse value included.
const trackSizeStyles = stylex.create({
sm: {
width: 32,
@@ -96,16 +136,28 @@ const trackSizeStyles = stylex.create({
},
});
+// The thumb is one circle under any pointer, at each state's size. Under a
+// finger it rests by insets instead of a transform, centered in the track's
+// height at each end. So the compositor moves and lifts it with translate and
+// scale alone; useSwitchTouch measures the box it renders.
const thumbOffSizeStyles = stylex.create({
sm: {
width: 14,
height: 14,
- transform: 'translateX(0)',
+ insetInlineStart: {default: null, [TOUCH]: 3},
+ transform: {
+ default: 'translateX(0)',
+ [TOUCH]: 'none',
+ },
},
md: {
width: 16,
height: 16,
- transform: 'translateX(0)',
+ insetInlineStart: {default: null, [TOUCH]: 4},
+ transform: {
+ default: 'translateX(0)',
+ [TOUCH]: 'none',
+ },
},
});
@@ -113,6 +165,8 @@ const thumbOnSizeStyles = stylex.create({
sm: {
width: 16,
height: 16,
+ insetInlineStart: {default: null, [TOUCH]: 'auto'},
+ insetInlineEnd: {default: null, [TOUCH]: 2},
// The thumb rests at the inline-start edge (flex-start, which flexbox
// already mirrors under RTL). The on-state travel toward the inline-end
// edge is a physical translateX, so it must flip sign under RTL — right
@@ -120,15 +174,25 @@ const thumbOnSizeStyles = stylex.create({
// iOS): off-thumb on the reading-start side, on-thumb on the reading-end.
transform: {
default: 'translateX(12px)',
- ':is([dir="rtl"] *)': 'translateX(-12px)',
+ ':is([dir="rtl"] *)': {
+ default: 'translateX(-12px)',
+ [TOUCH]: 'none',
+ },
+ [TOUCH]: 'none',
},
},
md: {
width: 20,
height: 20,
+ insetInlineStart: {default: null, [TOUCH]: 'auto'},
+ insetInlineEnd: {default: null, [TOUCH]: 2},
transform: {
default: 'translateX(14px)',
- ':is([dir="rtl"] *)': 'translateX(-14px)',
+ ':is([dir="rtl"] *)': {
+ default: 'translateX(-14px)',
+ [TOUCH]: 'none',
+ },
+ [TOUCH]: 'none',
},
},
});
@@ -141,11 +205,43 @@ const thumbOnSizeStyles = stylex.create({
// hover tint already is: pressing the input, the track or the label all
// activate the row.
const pressedImage = `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`;
-// The touch press's paint, declared by the shared overlay styles on the
-// element the controller writes to (`pressedAlpha`) at the press's strength,
-// 1 while on and 1 → 0 over the release, and inherited resolved by the layer
-// that paints it. See interactionOverlay.stylex.ts.
-const pressedOverlayImage = 'var(--_press-paint-image)';
+
+/** The touch press's release on the press layer: opacity 1 → 0. */
+const pressLayerRelease = stylex.keyframes({
+ from: {opacity: 1},
+ to: {opacity: 0},
+});
+
+const PRESS_ALPHA = pressVars['--astryx-press-alpha'];
+
+/**
+ * The shared strength's release, restated so a fine pointer keeps it: the
+ * same keyframes, so the same animation.
+ */
+const pressStrengthRelease = stylex.keyframes({
+ from: {[PRESS_ALPHA]: 1},
+ to: {[PRESS_ALPHA]: 0},
+});
+
+const pressOwnerStyles = stylex.create({
+ /**
+ * Composed after `interactionOverlayStyles.pressedAlpha` on the row. Under
+ * a coarse primary pointer the track's and thumb's layers fade the press.
+ * So the strength holds through the release, not animated on the main
+ * thread. With any other pointer the row keeps `pressedAlpha`'s release.
+ */
+ pressedAlphaLayered: {
+ animationName: {
+ default: null,
+ [PRESS_FADING]: {
+ default: pressStrengthRelease,
+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))':
+ 'none',
+ '@media (pointer: coarse)': 'none',
+ },
+ },
+ },
+});
const labelWrapperSizeStyles = stylex.create({
sm: {
@@ -182,6 +278,13 @@ const styles = stylex.create({
flexShrink: 0,
isolation: 'isolate',
},
+ // Horizontal touch moves are the switch's drag and vertical ones the page's
+ // scroll, under any primary pointer. A touchscreen laptop's finger counts
+ // too. It is set in CSS so it holds before hydration. A disabled or loading
+ // switch takes no drag, so it leaves every move to the page.
+ switchWrapperInteractive: {
+ touchAction: 'pan-y pinch-zoom',
+ },
input: {
position: 'absolute',
top: '50%',
@@ -194,10 +297,24 @@ const styles = stylex.create({
},
zIndex: 1,
},
+ // The invisible input covers the track. Under a coarse pointer it is the
+ // hit area a finger needs. It grows toward 44 × 44 px by the insets
+ // utils/hitArea measures, each side stopping at half the gap to a
+ // neighbouring target. Its center moves with any uneven side, and nothing
+ // visible grows. The insets are 0 until measured. Physical left and
+ // translate, as centerInline: the insets are physical sides.
inputCoarse: {
- '@media (pointer: coarse)': {
- minInlineSize: 24,
- minBlockSize: 24,
+ width: {
+ default: '100%',
+ '@media (pointer: coarse)': `calc(100% + ${HIT_LEFT} + ${HIT_RIGHT})`,
+ },
+ height: {
+ default: '100%',
+ '@media (pointer: coarse)': `calc(100% + ${HIT_TOP} + ${HIT_BOTTOM})`,
+ },
+ transform: {
+ default: 'translate(-50%, -50%)',
+ '@media (pointer: coarse)': `translate(calc(-50% + (${HIT_RIGHT} - ${HIT_LEFT}) / 2), calc(-50% + (${HIT_BOTTOM} - ${HIT_TOP}) / 2))`,
},
},
inputDisabled: {
@@ -209,11 +326,22 @@ const styles = stylex.create({
track: {
display: 'flex',
alignItems: 'center',
+ // Under a finger the press layer (::before), the colour fade (::after)
+ // and the thumb sit in the track, in a stacking context of its own.
+ position: {default: null, [TOUCH]: 'relative'},
+ isolation: {default: null, [TOUCH]: 'isolate'},
borderRadius: radiusVars['--radius-full'],
transitionProperty: 'background-color',
+ // Under a finger the track's fill changes at once and the fade layer
+ // crossfades it on the compositor. Reduced motion comes last so it holds
+ // everywhere: under a finger the fade layer
+ // carries the colour, and with a mouse the change is immediate.
transitionDuration: {
default: durationVars['--duration-fast'],
- '@media (prefers-reduced-motion: reduce)': '0s',
+ [TOUCH]: '0s',
+ '@media (prefers-reduced-motion: reduce) and (pointer: coarse)': '0s',
+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))':
+ '0s',
},
transitionTimingFunction: easeVars['--ease-standard'],
boxSizing: 'border-box',
@@ -240,28 +368,102 @@ const styles = stylex.create({
default: null,
'@media (forced-colors: none)': {
default: pressedImage,
- // Under a coarse pointer the touch press model writes `data-astryx-press`
- // on the row instead; see interactionOverlay.stylex.ts.
+ // Under a coarse pointer the touch press controller writes
+ // `data-astryx-press` on the row instead, and the press layer
+ // (::before) paints it.
'@media (pointer: coarse)': 'none',
},
},
- // Nested in the same media as the arm above so it outranks the drop: an
- // ancestor-scoped attribute selector gets no priority of its own.
- [stylex.when.ancestor('[data-astryx-press="on"]', switchScope)]: {
+ },
+ // The press, under a finger: a layer over the track's fill and colour
+ // fade and under the thumb. It exists only while the row is pressed or
+ // releasing. Its opacity is the press: on at once, then the shared
+ // release's clock and curve. The release runs on the compositor, so the
+ // press never sticks while the main thread is busy.
+ '::before': {
+ content: {
default: null,
- '@media (forced-colors: none)': {
+ [stylex.when.ancestor(PRESS_ON, switchScope)]: {
default: null,
- '@media (pointer: coarse)': pressedOverlayImage,
+ [TOUCH]: '""',
+ },
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: '""',
},
},
- [stylex.when.ancestor('[data-astryx-press="fading"]', switchScope)]: {
+ position: 'absolute',
+ inset: 0,
+ zIndex: 1,
+ borderRadius: 'inherit',
+ pointerEvents: 'none',
+ backgroundColor: {
default: null,
- '@media (forced-colors: none)': {
+ '@media (forced-colors: none)': colorVars['--color-overlay-pressed'],
+ },
+ opacity: {
+ default: null,
+ [stylex.when.ancestor(PRESS_ON, switchScope)]: {
+ default: null,
+ [TOUCH]: 1,
+ },
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: 0,
+ },
+ },
+ animationName: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
default: null,
- '@media (pointer: coarse)': pressedOverlayImage,
+ [TOUCH]: pressLayerRelease,
+ },
+ },
+ animationDuration: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: {
+ default: PRESS_RELEASE_DURATION,
+ '@media (prefers-reduced-motion: reduce) and (pointer: coarse)':
+ PRESS_RELEASE_DURATION_REDUCED,
+ },
+ },
+ },
+ animationTimingFunction: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: PRESS_RELEASE_EASE,
+ },
+ },
+ animationFillMode: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: 'both',
},
},
},
+ // The colour fade, under a finger: a layer over the track's own fill. It
+ // shows the fill the track is leaving, or mid-drag the one it heads to,
+ // and fades it on the compositor. Its colour is the theme's, read from
+ // the track (switchFill.ts). The animator owns its opacity, and at rest it
+ // is clear.
+ '::after': {
+ content: '""',
+ display: {default: 'none', [TOUCH]: 'block'},
+ position: 'absolute',
+ inset: 0,
+ zIndex: 0,
+ borderRadius: 'inherit',
+ pointerEvents: 'none',
+ opacity: 0,
+ backgroundColor: 'var(--_switch-fade-fill, transparent)',
+ // Its own compositing layer from the start, so its fade runs off the
+ // main thread (iOS Safari otherwise animates it on the main thread).
+ willChange: {default: null, [TOUCH]: 'opacity'},
+ },
},
// The one ring in the system not drawn by focusOutlineStyles. The focusable
// input is the track's preceding sibling, so the condition reads that input
@@ -329,38 +531,117 @@ const styles = stylex.create({
alignItems: 'center',
justifyContent: 'center',
borderRadius: radiusVars['--radius-full'],
- transitionProperty: 'transform, width, height',
+ // Under a finger it sits in the track, centered in its height, above the
+ // colour fade (::after) and the press layer (::before). useSwitchTouch
+ // moves and lifts it on the compositor: nothing of its own transitions.
+ position: {default: null, [TOUCH]: 'absolute'},
+ insetBlock: {default: null, [TOUCH]: 0},
+ marginBlock: {default: null, [TOUCH]: 'auto'},
+ zIndex: {default: null, [TOUCH]: 2},
+ pointerEvents: {default: null, [TOUCH]: 'none'},
+ transitionProperty: {
+ default: 'transform, width, height',
+ [TOUCH]: 'none',
+ },
+ // Under reduced motion nothing slides: under a finger the thumb
+ // cross-fades through the animator, and with a mouse it moves at once.
transitionDuration: {
default: durationVars['--duration-fast'],
- '@media (prefers-reduced-motion: reduce)': '0s',
+ '@media (prefers-reduced-motion: reduce) and (pointer: coarse)': '0s',
+ '@media (prefers-reduced-motion: reduce) and (not (pointer: coarse))':
+ '0s',
},
transitionTimingFunction: easeVars['--ease-standard'],
- // Pressed: the same overlay as the track, so the whole control darkens
- // under the finger rather than the thumb standing out against a darker
- // track.
- backgroundImage: {
- default: null,
- [stylex.when.ancestor(':active', switchScope)]: {
+ // The lifted shadow, under a finger: the theme's elevation on a layer the
+ // thumb's size. It fades in with the lift on the compositor, and at rest
+ // it is clear. The press on the thumb too, under a finger: the same layer
+ // as the track's, over the thumb's fill.
+ '::before': {
+ content: {
default: null,
- '@media (forced-colors: none)': {
- default: pressedImage,
- '@media (pointer: coarse)': 'none',
+ [stylex.when.ancestor(PRESS_ON, switchScope)]: {
+ default: null,
+ [TOUCH]: '""',
+ },
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: '""',
},
},
- // Nested in the same media as the arm above so it outranks the drop: an
- // ancestor-scoped attribute selector gets no priority of its own.
- [stylex.when.ancestor('[data-astryx-press="on"]', switchScope)]: {
+ position: 'absolute',
+ inset: 0,
+ borderRadius: 'inherit',
+ pointerEvents: 'none',
+ backgroundColor: {
default: null,
- '@media (forced-colors: none)': {
+ '@media (forced-colors: none)': colorVars['--color-overlay-pressed'],
+ },
+ opacity: {
+ default: null,
+ [stylex.when.ancestor(PRESS_ON, switchScope)]: {
+ default: null,
+ [TOUCH]: 1,
+ },
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
default: null,
- '@media (pointer: coarse)': pressedOverlayImage,
+ [TOUCH]: 0,
},
},
- [stylex.when.ancestor('[data-astryx-press="fading"]', switchScope)]: {
+ animationName: {
default: null,
- '@media (forced-colors: none)': {
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
default: null,
- '@media (pointer: coarse)': pressedOverlayImage,
+ [TOUCH]: pressLayerRelease,
+ },
+ },
+ animationDuration: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: {
+ default: PRESS_RELEASE_DURATION,
+ '@media (prefers-reduced-motion: reduce) and (pointer: coarse)':
+ PRESS_RELEASE_DURATION_REDUCED,
+ },
+ },
+ },
+ animationTimingFunction: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: PRESS_RELEASE_EASE,
+ },
+ },
+ animationFillMode: {
+ default: null,
+ [stylex.when.ancestor(PRESS_FADING, switchScope)]: {
+ default: null,
+ [TOUCH]: 'both',
+ },
+ },
+ },
+ '::after': {
+ content: '""',
+ display: {default: 'none', [TOUCH]: 'block'},
+ position: 'absolute',
+ inset: 0,
+ borderRadius: 'inherit',
+ pointerEvents: 'none',
+ opacity: 0,
+ boxShadow: shadowVars['--shadow-low'],
+ willChange: {default: null, [TOUCH]: 'opacity'},
+ },
+ // Pressed with a mouse: the same overlay as the track, so the whole
+ // control darkens rather than the thumb standing out against a darker
+ // track. Under a finger the track's press layer paints under the thumb,
+ // which lifts.
+ backgroundImage: {
+ default: null,
+ [stylex.when.ancestor(':active', switchScope)]: {
+ default: null,
+ '@media (forced-colors: none)': {
+ default: pressedImage,
+ '@media (pointer: coarse)': 'none',
},
},
},
@@ -519,7 +800,7 @@ export interface SwitchProps extends Omit<BaseProps, 'onChange'> {
status?: InputStatus;
/**
* Size variant controlling track and thumb dimensions.
- * - 'sm': 34x20px (matches sm checkbox/radio vertical rhythm)
+ * - 'sm': 32x20px (matches sm checkbox/radio vertical rhythm)
* - 'md': 40x24px (default, matches md checkbox/radio vertical rhythm)
* @default 'md'
*/
@@ -649,10 +930,68 @@ export function Switch({
const ariaDescribedBy =
describedByParts.length > 0 ? describedByParts.join(' ') : undefined;
+ // The touch presentation (coarse pointer): its parts are always rendered;
+ // CSS shows them under a finger and the hook animates and listens there.
+ const surfaceRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const thumbRef = useRef<HTMLDivElement>(null);
+ const trackRef = useRef<HTMLDivElement>(null);
+ const touchParts = useMemo<SwitchTouchParts>(
+ () => ({
+ surface: surfaceRef,
+ input: inputRef,
+ thumb: thumbRef,
+ track: trackRef,
+ }),
+ [],
+ );
+ // The track in a state: its theme target and fill. The other state's, for
+ // the fade layer's colour (switchFill.ts).
+ const trackPropsFor = (on: boolean) =>
+ mergeProps(
+ themeProps('switch', {
+ checked: on ? 'checked' : null,
+ disabled: isDisabled ? 'disabled' : null,
+ size,
+ }),
+ stylex.props(
+ styles.track,
+ trackSizeStyles[size],
+ on ? styles.trackOn : styles.trackOff,
+ styles.trackFocus,
+ isDisabled && styles.trackDisabled,
+ isDisabled && !on && styles.trackDisabledOff,
+ ),
+ );
+ // Syncs the hit area's insets with the layout around the switch, through
+ // utils/hitArea's observers. Under a coarse pointer they grow toward 44 px,
+ // stopping at half the gap to each neighbouring target. A disabled switch
+ // watches nothing.
+ useIsomorphicLayoutEffect(() => {
+ const surface = surfaceRef.current;
+ if (surface == null || isDisabled) {
+ return;
+ }
+ return watchHitArea(surface, insets => writeHitInsets(surface, insets));
+ }, [isDisabled]);
+ useSwitchTouch(touchParts, {
+ isOn,
+ isInteractive: !isDisabled && !isBusy,
+ isDisabled,
+ trackSize: TRACK_SIZE[size],
+ otherTrackProps: trackPropsFor(!isOn),
+ });
+
const switchElement = (
- <div {...stylex.props(styles.switchWrapper, wrapperSizeStyles[size])}>
+ <div
+ ref={surfaceRef}
+ {...stylex.props(
+ styles.switchWrapper,
+ wrapperSizeStyles[size],
+ !isDisabled && !isBusy && styles.switchWrapperInteractive,
+ )}>
<input
- ref={useMergedRefs(ref, disabledMessageTooltip.positionRef)}
+ ref={useMergedRefs(ref, disabledMessageTooltip.positionRef, inputRef)}
id={id}
type="checkbox"
role="switch"
@@ -695,30 +1034,14 @@ export function Switch({
styles.input,
rtlStyles.centerInline('-50%'),
styles.inputCoarse,
- inputSizeStyles[size],
isDisabled && styles.inputDisabled,
isBusy && styles.inputBusy,
switchFocusInput,
)}
/>
- <div
- aria-hidden="true"
- {...mergeProps(
- themeProps('switch', {
- checked: isOn ? 'checked' : null,
- disabled: isDisabled ? 'disabled' : null,
- size,
- }),
- stylex.props(
- styles.track,
- trackSizeStyles[size],
- isOn ? styles.trackOn : styles.trackOff,
- styles.trackFocus,
- isDisabled && styles.trackDisabled,
- isDisabled && !isOn && styles.trackDisabledOff,
- ),
- )}>
+ <div ref={trackRef} aria-hidden="true" {...trackPropsFor(isOn)}>
<div
+ ref={thumbRef}
{...mergeProps(
themeProps('switch-thumb', {
checked: isOn ? 'checked' : null,
@@ -785,6 +1108,7 @@ export function Switch({
disabledMessageTooltip.interactionRef(el);
}}
{...(isDisabled ? undefined : pressable)}
+ {...pressHoldsDragProps(!isDisabled)}
{...stylex.props(
styles.container,
isLabelHidden && styles.containerLabelHidden,
@@ -793,19 +1117,21 @@ export function Switch({
// The touch press's strength and release live on the row the
// controller writes to; the track and thumb inherit and paint it.
!isDisabled && interactionOverlayStyles.pressedAlpha,
+ !isDisabled && pressOwnerStyles.pressedAlphaLayered,
)}>
{' '}
- {labelPosition === 'start' ? (
- <>
- {labelElement}
- {switchElement}
- </>
- ) : (
- <>
- {switchElement}
- {labelElement}
- </>
- )}
+ {/* Keyed, so a labelPosition change moves the nodes instead of
+ rebuilding them: the touch controller stays on the input, track
+ and thumb it attached to. */}
+ {labelPosition === 'start'
+ ? [
+ <Fragment key="label">{labelElement}</Fragment>,
+ <Fragment key="switch">{switchElement}</Fragment>,
+ ]
+ : [
+ <Fragment key="switch">{switchElement}</Fragment>,
+ <Fragment key="label">{labelElement}</Fragment>,
+ ]}
</div>
{status?.message && (
<FieldStatus
diff --git a/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
new file mode 100644
index 0000000000..da2dce3d7c
--- /dev/null
+++ b/packages/core/src/Switch/__tests__/Switch.interaction.browser.spec.ts
@@ -0,0 +1,2680 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Switch.interaction.browser.spec.ts
+ * @input The built Switch stories, real touch input (Chromium CDP / WebKit's
+ * input command) and @astryxdesign/interaction-harness
+ * @output Interaction and animation proofs of Switch's touch presentation
+ * against UISwitch on iOS 26.2, one named case per path (P1–P14), and
+ * storyboards of a tap and of a drag
+ * @position The browser layer of Switch's touch tests; the pure model is
+ * switchTouch.test.ts. Runs on the phone profile (coarse pointer); a mouse
+ * context keeps the desktop switch.
+ *
+ * SYNC: useSwitchTouch.ts, switchTouch.ts, motion/uikit/switch.ts.
+ */
+
+import {
+ expect,
+ test,
+ type Browser,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+import {
+ castStoryboard,
+ animationStoryboard,
+ blockMainThread,
+ busyWindowProof,
+ compareCurve,
+ cubicBezier,
+ countBetween,
+ drag,
+ freezeTimers,
+ holdAnimations,
+ installTimerGate,
+ markElement,
+ openStory,
+ releaseAnimations,
+ seekAnimations,
+ springStep,
+ startScreencast,
+ tap,
+ thawTimers,
+ timeline,
+ touchDriver,
+ touchStoryboard,
+ traceRendering,
+ trackMarker,
+ waitForAnimation,
+ waitForRest,
+ withStorybook,
+ writeEvidence,
+ type CastFrame,
+ type TouchDriver,
+} from '@astryxdesign/interaction-harness';
+import {press} from '../../motion/uikit/timing';
+import {BROWSER_CLICK_WAIT_MS} from '../switchTouch';
+import {CLICK_GUARD_WINDOW_MS} from '../../utils/clickGuard';
+
+const storybook = withStorybook(test);
+
+// UISwitch on iOS 26.2 (motion/uikit/switch.ts), restated here as the oracle.
+const TRAVEL = {response: 0.3, dampingFraction: 1};
+const WELL_ON = {response: 0.68, dampingFraction: 1};
+/** The md track is 40 × 24. */
+const TRACK = {width: 40, height: 24};
+/** The md thumb, a circle at the size a mouse sees: 16 off, 20 on (Switch FR13). */
+const THUMB_OFF = 16;
+const THUMB_ON = 20;
+/** The off thumb's inset in the track, on every side. */
+const INSET = (TRACK.height - THUMB_OFF) / 2;
+/** How far the thumb's center travels: each circle centered in the track's height at its end. */
+const TRAVEL_PX = TRACK.width - TRACK.height;
+/** The flip rule: the track minus the thumb past where the finger landed. */
+const FLIP_DISTANCE = TRACK.width - THUMB_OFF;
+const FLIP_FROM_ON = TRACK.width - THUMB_ON;
+/** The lift grows the thumb into half the gap on each side (switchTouch.ts). */
+const LIFT_SCALE = 1 + INSET / THUMB_OFF;
+/**
+ * design:reduced-motion DR2: under reduced motion a touch change is an
+ * opacity-only cross-fade of this many ms or less.
+ */
+const REDUCED_FADE_MAX_MS = 200;
+/** The shared press release (motion/uikit/timing.ts `press`), ms. */
+const PRESS_RELEASE_MS = press.highlightOutMs;
+const pressReleaseEase = cubicBezier(...press.highlightOutCurve);
+/** The press layer's opacity t ms into the release, 1 → 0. */
+const pressReleaseAt = (t: number) =>
+ 1 - pressReleaseEase(Math.min(1, Math.max(0, t / PRESS_RELEASE_MS)));
+
+interface ChangeSample {
+ t: number;
+ /** The thumb's scale as presented. */
+ scale: number;
+ /**
+ * The thumb's center from the track's left edge (each state has its own
+ * circle size, so the center is where it is).
+ */
+ left: number;
+ /** How opaque the thumb shows. */
+ opacity: number;
+ /** How far the colour shows on (see presented()). */
+ on: number;
+ /** The track's own fill. */
+ fill: string;
+}
+
+/**
+ * Samples the first switch every frame for `ms` while `act` runs.
+ */
+async function sampleChange(
+ page: Page,
+ act: () => Promise<void>,
+ ms = 700,
+): Promise<ChangeSample[]> {
+ await page.evaluate(duration => {
+ const w = window as unknown as {__change: unknown[]};
+ const track = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const thumb = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const input = document.querySelector<HTMLInputElement>(
+ '#storybook-root [role="switch"]',
+ )!;
+ const scaleOf = (element: Element) => {
+ const scale = getComputedStyle(element).scale;
+ return scale === 'none' ? 1 : Number(scale.split(' ')[0]);
+ };
+ w.__change = [];
+ const start = performance.now();
+ const tick = () => {
+ const t = performance.now() - start;
+ const faded = Number(getComputedStyle(track, '::after').opacity);
+ w.__change.push({
+ t,
+ scale: scaleOf(thumb),
+ left:
+ (thumb.getBoundingClientRect().left +
+ thumb.getBoundingClientRect().right) /
+ 2 -
+ track.getBoundingClientRect().left,
+ opacity: Number(getComputedStyle(thumb).opacity),
+ on: input.checked ? 1 - faded : faded,
+ fill: getComputedStyle(track).backgroundColor,
+ });
+ if (t < duration) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ }, ms);
+ await act();
+ await page.waitForTimeout(ms + 100);
+ return page.evaluate(
+ () => (window as unknown as {__change: ChangeSample[]}).__change,
+ );
+}
+
+/**
+ * Holds the press's release from the task that starts it: a microtask after
+ * the row's attribute turns `fading`, before any timer or frame runs. The
+ * page's gated timers freeze, so nothing removes the attribute. The release's
+ * CSS animations are created there and held at their start, so a loaded
+ * machine cannot play them out before the test reads them.
+ */
+async function holdReleaseWhenFading(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ const row = document.querySelector(
+ '#storybook-root [data-astryx-pressable]',
+ )!;
+ const gate = (window as unknown as {__harnessTimerGate: {frozen: boolean}})
+ .__harnessTimerGate;
+ const observer = new MutationObserver(() => {
+ if (row.getAttribute('data-astryx-press') !== 'fading') {
+ return;
+ }
+ gate.frozen = true;
+ observer.disconnect();
+ for (const animation of row.getAnimations({subtree: true})) {
+ if (animation instanceof CSSAnimation) {
+ animation.playbackRate = 0;
+ }
+ }
+ });
+ observer.observe(row, {attributeFilter: ['data-astryx-press']});
+ });
+}
+
+/**
+ * Gives the held release animations their rate back before the release.
+ * The hold set it to 0, and an animation at rate 0 cannot finish. They stay
+ * paused, so nothing moves.
+ */
+async function restoreHeldRates(page: Page): Promise<void> {
+ await page.evaluate(() => {
+ for (const animation of document.getAnimations()) {
+ if (animation.playbackRate === 0) {
+ animation.playbackRate = 1;
+ }
+ }
+ });
+}
+
+/**
+ * Resolves after a timer of `ms` queued now on the page. The switch queued
+ * its own timer at the release, before this one. With the same delay, this
+ * one runs after it, however late the page runs.
+ */
+async function afterPageTimer(page: Page, ms: number): Promise<void> {
+ await page.evaluate(async delay => {
+ await new Promise<void>(resolve => {
+ setTimeout(resolve, delay);
+ });
+ }, ms);
+}
+
+/**
+ * design:reduced-motion DR1 and DR2: the change scales nothing, never shows
+ * the thumb between its two places, fades (opacity), and is done within the
+ * cross-fade's bound.
+ */
+function expectCrossFade(samples: ChangeSample[]): void {
+ const first = samples[0];
+ const last = samples.at(-1)!;
+ expect(Math.abs(last.left - first.left)).toBeGreaterThan(4);
+ for (const sample of samples) {
+ expect(Math.abs(sample.scale - 1), JSON.stringify(sample)).toBeLessThan(
+ 0.01,
+ );
+ if (sample.opacity > 0.1) {
+ const atAnEnd = Math.min(
+ Math.abs(sample.left - first.left),
+ Math.abs(sample.left - last.left),
+ );
+ expect(atAnEnd, JSON.stringify(sample)).toBeLessThan(0.75);
+ }
+ }
+ // A fade, not a jump: some frame shows the thumb or the colour part-way.
+ expect(
+ samples.some(
+ s => (s.opacity > 0.1 && s.opacity < 0.9) || (s.on > 0.1 && s.on < 0.9),
+ ),
+ ).toBe(true);
+ // Each fade, the thumb's and the colour's, lasts the bound or less. The
+ // colour starts at the release and the thumb at the commit. A busy page can
+ // start them frames apart, so each is measured on its own. Both samples of
+ // a span lie inside its fade, so a frame read late cannot lengthen it.
+ const spanOf = (fading: (s: ChangeSample) => boolean) => {
+ const inside = samples.filter(fading);
+ return inside.length === 0 ? 0 : inside.at(-1)!.t - inside[0].t;
+ };
+ const thumbFading = (s: ChangeSample) => s.opacity < 0.98;
+ const colourFading = (s: ChangeSample) =>
+ Math.abs(s.on - first.on) > 0.02 && Math.abs(s.on - last.on) > 0.02;
+ // Present first: the change shows on screen.
+ expect(samples.some(s => thumbFading(s) || colourFading(s))).toBe(true);
+ expect(spanOf(thumbFading)).toBeLessThanOrEqual(REDUCED_FADE_MAX_MS);
+ expect(spanOf(colourFading)).toBeLessThanOrEqual(REDUCED_FADE_MAX_MS);
+}
+
+interface OpenSwitch {
+ driver: TouchDriver;
+ input: Locator;
+ thumb: Locator;
+ onLayer: Locator;
+ /** The thumb's center at rest, client px. */
+ center: {x: number; y: number};
+}
+
+/** Waits for the switch's measured hit insets (utils/hitArea, a frame after mount). */
+async function waitForHitArea(page: Page): Promise<void> {
+ await page.waitForFunction(() => {
+ const surface = document.querySelector<HTMLElement>(
+ '#storybook-root [role="switch"]',
+ )?.parentElement;
+ return (
+ surface?.style.getPropertyValue('--astryx-hit-inset-top') !== '' &&
+ surface?.style.getPropertyValue('--astryx-hit-inset-top') != null
+ );
+ });
+}
+
+async function openSwitch(
+ page: Page,
+ storyId = 'core-switch--default',
+ {
+ direction = 'ltr',
+ globals = [],
+ }: {
+ direction?: 'ltr' | 'rtl';
+ /** More Storybook globals, e.g. `theme:probe`. */
+ globals?: string[];
+ } = {},
+): Promise<OpenSwitch> {
+ const allGlobals = [
+ ...(direction === 'rtl' ? ['direction:rtl'] : []),
+ ...globals,
+ ];
+ if (allGlobals.length === 0) {
+ await openStory(page, storybook(), storyId);
+ } else {
+ // Storybook's globals apply from the story's first render (the direction
+ // global wraps it in `dir="rtl"`, so the switch mounts right to left).
+ await page.goto(
+ `${storybook()}/iframe.html?id=${storyId}&viewMode=story&globals=${allGlobals.join(';')}`,
+ );
+ await page
+ .locator('#storybook-root > *')
+ .first()
+ .waitFor({state: 'attached'});
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ await new Promise<void>(resolve =>
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
+ );
+ });
+ }
+ const driver = await touchDriver(page);
+ const root = page.locator('#storybook-root');
+ const input = root.getByRole('switch').first();
+ const thumb = root.locator('.astryx-switch-thumb').first();
+ // The track: its ::after is the colour fade, its ::before the press.
+ const onLayer = root.locator('.astryx-switch').first();
+ // Under a finger the thumb itself moves and lifts.
+ const box = await thumb.boundingBox();
+ if (box == null) {
+ throw new Error('no thumb');
+ }
+ return {
+ driver,
+ input,
+ thumb,
+ onLayer,
+ center: {x: box.x + box.width / 2, y: box.y + box.height / 2},
+ };
+}
+
+interface Presented {
+ scaleX: number;
+ scaleY: number;
+ on: number;
+ fill: number;
+}
+
+/**
+ * A tap the browser turns into its own click. Chromium synthesises the click
+ * from the scripted touch. WebKit synthesises one only from its tap path,
+ * which has no hold.
+ */
+async function tapForClick(
+ driver: TouchDriver,
+ at: {x: number; y: number},
+ holdMs = 50,
+): Promise<void> {
+ if (driver.engine === 'webkit') {
+ await driver.tap(at);
+ } else {
+ await driver.play(tap(at, {holdMs}));
+ }
+}
+
+/**
+ * The opacity of the first track's press layer (its ::before), or null when
+ * the track has none (at rest).
+ */
+async function pressLayer(
+ page: Page,
+ part: 'track' | 'thumb' = 'track',
+): Promise<number | null> {
+ return page.evaluate(which => {
+ const track = document.querySelector<HTMLElement>(
+ which === 'track'
+ ? '#storybook-root .astryx-switch'
+ : '#storybook-root .astryx-switch-thumb',
+ )!;
+ const layer = getComputedStyle(track, '::before');
+ return layer.content === 'none' || layer.content === 'normal'
+ ? null
+ : Number(layer.opacity);
+ }, part);
+}
+
+/** The press state the row's press feedback shows (`data-astryx-press`). */
+async function pressState(page: Page, index = 0): Promise<string | null> {
+ return page.evaluate(i => {
+ const inputs = document.querySelectorAll('#storybook-root [role="switch"]');
+ const row = inputs[i]?.closest('[data-astryx-pressable]');
+ return row?.getAttribute('data-astryx-press') ?? null;
+ }, index);
+}
+
+/**
+ * The switch at rest: the thumb still, and the track's colour fade (its
+ * ::after, which waitForRest does not read) finished too.
+ */
+async function waitForSwitchRest(page: Page, thumb: Locator): Promise<void> {
+ await waitForRest(thumb);
+ await page.waitForFunction(() =>
+ document
+ .querySelector('#storybook-root .astryx-switch')!
+ .getAnimations({subtree: true})
+ .every(animation => animation.playState !== 'running'),
+ );
+}
+
+/** The thumb's scale and the track's color, as presented. */
+async function presented(page: Page): Promise<Presented> {
+ return page.evaluate(() => {
+ const thumb = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ // The fade layer over the track shows the other side's fill. How far the
+ // colour shows on is its opacity while off, and its complement while on.
+ const fade = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const input = document.querySelector<HTMLInputElement>(
+ '#storybook-root [role="switch"]',
+ )!;
+ const faded = Number(getComputedStyle(fade, '::after').opacity);
+ const scale = getComputedStyle(thumb).scale;
+ const [sx, sy = sx] = (scale === 'none' ? '1' : scale)
+ .split(' ')
+ .map(Number);
+ return {
+ scaleX: sx,
+ scaleY: sy,
+ on: input.checked ? 1 - faded : faded,
+ fill: Number(getComputedStyle(thumb).opacity),
+ };
+ });
+}
+
+/**
+ * The thumb's offset from the track's start edge, exact: its center (a scale
+ * about the center does not move it) less half its unscaled width.
+ */
+async function thumbOffset(page: Page): Promise<number> {
+ // The thumb's center from the inline-start rest's: 0 off, TRAVEL_PX on (in
+ // LTR). The center, since each state has its own circle size.
+ return page.evaluate(height => {
+ const box = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const rect = box.getBoundingClientRect();
+ const track = box.parentElement!.getBoundingClientRect();
+ return rect.left + rect.width / 2 - track.left - height / 2;
+ }, TRACK.height);
+}
+
+/**
+ * The thumb's travel: the newest animation of its `translate`, from its start
+ * to the end of its motion, epoch ms.
+ */
+async function travelAnimation(
+ page: Page,
+): Promise<{from: number; to: number}> {
+ for (let attempt = 0; attempt < 500; attempt++) {
+ const found = await page.evaluate(() => {
+ const box = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const travel = box
+ .getAnimations()
+ .filter(
+ a =>
+ a.playState === 'running' &&
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => 'translate' in k),
+ )
+ .at(-1);
+ if (travel == null || travel.startTime == null) {
+ return null;
+ }
+ const from = performance.timeOrigin + Number(travel.startTime);
+ // The animator's keyframes end with a hold of the end state: the
+ // motion ends at the last keyframe before it.
+ const effect = travel.effect as KeyframeEffect;
+ const offsets = effect
+ .getKeyframes()
+ .map(k => k.computedOffset)
+ .filter(o => o < 1);
+ return {
+ from,
+ to:
+ from +
+ Number(effect.getComputedTiming().activeDuration) *
+ Math.max(...offsets),
+ };
+ });
+ if (found != null) {
+ return found;
+ }
+ await page.waitForTimeout(4);
+ }
+ throw new Error('the thumb never travelled');
+}
+
+/** The probe theme paints every state of the `switch` target its own fill. */
+const PROBE_THEME = 'astryxTheme:probe';
+
+/**
+ * The track's fill off and on as a theme paints it under a mouse: what a
+ * finger has to show too.
+ */
+async function mouseFills(
+ browser: Browser,
+ globals: string[],
+): Promise<{off: string; on: string}> {
+ const context = await browser.newContext({
+ hasTouch: false,
+ isMobile: false,
+ deviceScaleFactor: 1,
+ viewport: {width: 480, height: 320},
+ });
+ try {
+ const page = await context.newPage();
+ await page.goto(
+ `${storybook()}/iframe.html?id=core-switch--default&viewMode=story&globals=${globals.join(';')}`,
+ );
+ const input = page.locator('#storybook-root').getByRole('switch').first();
+ await input.waitFor({state: 'attached'});
+ const fill = async () => {
+ // Off the switch (no hover tint), after the track's own transition.
+ await page.mouse.move(1, 1);
+ await page.waitForTimeout(400);
+ return page.evaluate(
+ () =>
+ getComputedStyle(
+ document.querySelector('#storybook-root .astryx-switch')!,
+ ).backgroundColor,
+ );
+ };
+ const off = await fill();
+ await input.click({force: true});
+ await expect(input).toBeChecked();
+ return {off, on: await fill()};
+ } finally {
+ await context.close();
+ }
+}
+
+/**
+ * The colour a finger sees on the track: the fade layer's while it is
+ * opaque, the track's own fill while it is clear.
+ */
+async function visibleFill(page: Page): Promise<string> {
+ return page.evaluate(() => {
+ const track = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const fade = getComputedStyle(track, '::after');
+ return Number(fade.opacity) > 0.5
+ ? fade.backgroundColor
+ : getComputedStyle(track).backgroundColor;
+ });
+}
+
+test.describe('Switch touch presentation (UISwitch, iOS 26.2), under a finger', () => {
+ test('a theme’s `switch` fill shows under a finger, off and on: the track keeps the theme’s fill and the fade layer only crossfades', async ({
+ page,
+ browser,
+ }) => {
+ const expected = await mouseFills(browser, [PROBE_THEME]);
+ expect(expected.on).not.toBe(expected.off);
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ 'core-switch--default',
+ {globals: [PROBE_THEME]},
+ );
+ expect(await visibleFill(page)).toBe(expected.off);
+ await driver.play(tap(center));
+ await expect(input).toBeChecked();
+ await waitForSwitchRest(page, thumb);
+ // The well spring (0.68 s on) has settled.
+ await page.waitForTimeout(900);
+ expect(await visibleFill(page)).toBe(expected.on);
+ });
+
+ test('P1 · a tap toggles at the release: the thumb travels and the track turns on, and the lift settles back', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(page);
+ await expect(input).not.toBeChecked();
+ expect(await thumbOffset(page)).toBeCloseTo(0, 0);
+ await driver.play(tap(center, {holdMs: 50}));
+ await expect(input).toBeChecked();
+ await waitForSwitchRest(page, thumb);
+ const rest = await presented(page);
+ expect(rest.scaleX).toBeCloseTo(1, 2);
+ expect(rest.on).toBeCloseTo(1, 2);
+ expect(rest.fill).toBeCloseTo(1, 2);
+ expect(await thumbOffset(page)).toBeCloseTo(TRAVEL_PX, 0);
+ });
+
+ test('P2 · a hold lifts the thumb inside the track and shows the pressed overlay, and the release toggles', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ const script = tap(center, {holdMs: 700});
+ let held: Presented | null = null;
+ let press: string | null = null;
+ let layer: number | null = null;
+ let thumbLayer: number | null = null;
+ await driver.play(script, {
+ onEvent: async step => {
+ if (step.type === 'touchStart') {
+ await page.waitForTimeout(500);
+ held = await presented(page);
+ press = await pressState(page);
+ layer = await pressLayer(page);
+ thumbLayer = await pressLayer(page, 'thumb');
+ }
+ },
+ });
+ expect(held).not.toBeNull();
+ // The thumb grows into half the gap around it and keeps its fill. The row
+ // is pressed, and the track's press layer (its ::before, under the thumb)
+ // shows the pressed overlay in full.
+ expect(held!.scaleX).toBeCloseTo(LIFT_SCALE, 2);
+ expect(held!.scaleY).toBeCloseTo(LIFT_SCALE, 2);
+ expect(held!.fill).toBeCloseTo(1, 2);
+ expect(press).toBe('on');
+ expect(layer).toBeCloseTo(1, 2);
+ // The thumb paints it too (design:user-states DR1: track and thumb).
+ expect(thumbLayer).toBeCloseTo(1, 2);
+ await expect(input).toBeChecked();
+ // Released: the layer is gone once its fade ends.
+ await expect.poll(async () => pressLayer(page, 'thumb')).toBeNull();
+ });
+
+ for (const direction of ['ltr', 'rtl'] as const) {
+ test(`a lifted thumb dragged far past either end stays inside the track (${direction})`, async ({
+ page,
+ }) => {
+ const {driver, center} = await openSwitch(page, 'core-switch--default', {
+ direction,
+ });
+ const toEnd = direction === 'ltr' ? 1 : -1;
+ const boxes: {thumbs: number; thumb: DOMRect; track: DOMRect}[] = [];
+ const read = async () =>
+ page.evaluate(() => {
+ const thumbs = document.querySelectorAll<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ );
+ const thumb = thumbs[0];
+ const toJSON = (r: DOMRect) => r.toJSON() as DOMRect;
+ return {
+ thumbs: thumbs.length,
+ thumb: toJSON(thumb.getBoundingClientRect()),
+ track: toJSON(thumb.parentElement!.getBoundingClientRect()),
+ };
+ });
+ // Held, then 160 px past the inline end, then 160 px past the inline
+ // start, the finger resting at each so the thumb settles there.
+ const far = 160;
+ const out = {x: center.x + toEnd * far, y: center.y};
+ const back = {x: center.x - toEnd * far, y: center.y};
+ const script = [
+ ...drag(center, out, {durationMs: 400, holdMs: 300}).slice(0, -1),
+ ...drag(out, back, {durationMs: 600, restMs: 300})
+ .slice(1)
+ .map(frame => ({...frame, t: frame.t + 1200})),
+ ];
+ await driver.play(script, {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ boxes.push(await read());
+ }
+ },
+ });
+ expect(boxes.length).toBeGreaterThan(10);
+ // Present and painted first: one thumb in every read, with a box, on a
+ // track at its own size. So the bounds below hold for a real thumb.
+ for (const {thumbs, thumb, track} of boxes) {
+ expect(thumbs).toBe(1);
+ expect(thumb.width).toBeGreaterThan(0);
+ expect(thumb.height).toBeGreaterThan(0);
+ expect(track.width).toBeCloseTo(TRACK.width, 1);
+ expect(track.height).toBeCloseTo(TRACK.height, 1);
+ }
+ for (const {thumb, track} of boxes) {
+ expect(thumb.left).toBeGreaterThanOrEqual(track.left - 0.01);
+ expect(thumb.right).toBeLessThanOrEqual(track.right + 0.01);
+ expect(thumb.top).toBeGreaterThanOrEqual(track.top - 0.01);
+ expect(thumb.bottom).toBeLessThanOrEqual(track.bottom + 0.01);
+ }
+ // It did reach both ends.
+ const centers = boxes.map(
+ b => (b.thumb.left + b.thumb.right) / 2 - b.track.left,
+ );
+ expect(Math.min(...centers)).toBeLessThan(TRACK.height / 2 + 0.5);
+ expect(Math.max(...centers)).toBeGreaterThan(
+ TRACK.width - TRACK.height / 2 - 0.5,
+ );
+ });
+ }
+
+ test('a tap activates the switch through the browser’s own click (spec:AST-094 FR11)', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ await page.evaluate(() => {
+ const w = window as unknown as {__clicks: boolean[]};
+ w.__clicks = [];
+ document
+ .querySelector('#storybook-root [role="switch"]')!
+ .addEventListener('click', event => w.__clicks.push(event.isTrusted));
+ });
+ await tapForClick(driver, center);
+ await expect(input).toBeChecked();
+ const clicks = await page.evaluate(
+ () => (window as unknown as {__clicks: boolean[]}).__clicks,
+ );
+ expect(clicks).toEqual([true]);
+ });
+
+ test('under a finger the thumb is the circle a mouse sees, at each state’s size (Switch FR13)', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(page);
+ const read = async () =>
+ page.evaluate(() => {
+ const t = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const style = getComputedStyle(t);
+ return {
+ width: parseFloat(style.width),
+ height: parseFloat(style.height),
+ radius: style.borderTopLeftRadius,
+ };
+ });
+ // Off: the md thumb is 16 × 16, as with a mouse.
+ expect(await read()).toEqual({
+ width: THUMB_OFF,
+ height: THUMB_OFF,
+ radius: expect.stringMatching(/px$/),
+ });
+ await driver.play(tap(center, {holdMs: 50}));
+ await expect(input).toBeChecked();
+ await waitForSwitchRest(page, thumb);
+ // On: 20 × 20, as with a mouse; the touch layer moves it, never reshapes it.
+ const on = await read();
+ expect(on.width).toBe(THUMB_ON);
+ expect(on.height).toBe(THUMB_ON);
+ });
+
+ test('under a coarse pointer the switch’s hit area grows to 44 × 44 px, centered on the track, with nothing visible added', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ await waitForHitArea(page);
+ const boxes = await page.evaluate(() => {
+ const i = document.querySelector<HTMLElement>(
+ '#storybook-root [role="switch"]',
+ )!;
+ const k = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const r = i.getBoundingClientRect();
+ const t = k.getBoundingClientRect();
+ return {
+ hit: {
+ width: r.width,
+ height: r.height,
+ cx: r.left + r.width / 2,
+ cy: r.top + r.height / 2,
+ },
+ track: {
+ width: t.width,
+ height: t.height,
+ cx: t.left + t.width / 2,
+ cy: t.top + t.height / 2,
+ },
+ opacity: getComputedStyle(i).opacity,
+ };
+ });
+ expect(boxes.hit.width).toBeGreaterThanOrEqual(44);
+ expect(boxes.hit.height).toBeGreaterThanOrEqual(44);
+ expect(Math.abs(boxes.hit.cx - boxes.track.cx)).toBeLessThan(0.5);
+ expect(Math.abs(boxes.hit.cy - boxes.track.cy)).toBeLessThan(0.5);
+ // Nothing visible changes: the track keeps its size and the input stays
+ // invisible.
+ expect(boxes.track).toMatchObject({
+ width: TRACK.width,
+ height: TRACK.height,
+ });
+ expect(boxes.opacity).toBe('0');
+ // A tap 18 px above the thumb's center, outside the 24 px track but
+ // inside the hit area, toggles the switch.
+ await tapForClick(driver, {x: center.x, y: center.y - 18});
+ await expect(input).toBeChecked();
+ });
+
+ test('under a coarse pointer the hit area stops halfway to a link beside it: a tap on the link is the link’s, a tap nearer the switch toggles it', async ({
+ page,
+ }) => {
+ const {driver, input} = await openSwitch(
+ page,
+ 'core-switch--beside-a-link',
+ );
+ await waitForHitArea(page);
+ const boxes = await page.evaluate(() => {
+ const i = document.querySelector<HTMLElement>(
+ '#storybook-root [role="switch"]',
+ )!;
+ const surface = i.parentElement!;
+ const link = document.querySelector<HTMLElement>('#storybook-root a')!;
+ const box = (e: HTMLElement) => {
+ const r = e.getBoundingClientRect();
+ return {left: r.left, right: r.right, top: r.top, bottom: r.bottom};
+ };
+ return {
+ switches: document.querySelectorAll('#storybook-root [role="switch"]')
+ .length,
+ links: document.querySelectorAll('#storybook-root a').length,
+ hit: box(i),
+ switch: box(surface),
+ link: box(link),
+ };
+ });
+ // Present and painted first: one switch and one link, each with a box.
+ expect(boxes.switches).toBe(1);
+ expect(boxes.links).toBe(1);
+ for (const b of [boxes.switch, boxes.link]) {
+ expect(b.right - b.left).toBeGreaterThan(0);
+ expect(b.bottom - b.top).toBeGreaterThan(0);
+ }
+ const gap = boxes.link.left - boxes.switch.right;
+ expect(gap).toBeGreaterThan(0);
+ // The right side stops at half the gap; the other sides grow to 44 px.
+ expect(boxes.hit.right).toBeCloseTo(boxes.switch.right + gap / 2, 0);
+ expect(boxes.hit.bottom - boxes.hit.top).toBeCloseTo(44, 0);
+ const y = (boxes.switch.top + boxes.switch.bottom) / 2;
+ // 2 px inside the link: the link's. A tap in the gap is the engine's to
+ // adjust: WebKit moves it to the nearest target that takes taps.
+ await tapForClick(driver, {x: boxes.link.left + 2, y});
+ await expect(input).not.toBeChecked();
+ await expect(page).toHaveURL(/#wifi-details$/);
+ // 1.5 px from the switch: the switch's.
+ await tapForClick(driver, {x: boxes.switch.right + 1.5, y});
+ await expect(input).toBeChecked();
+ });
+
+ test('the touch press is a layer on the track, absent at rest, released on the shared release’s clock and curve on the compositor', async ({
+ page,
+ }, testInfo) => {
+ const {driver, center} = await openSwitch(page);
+ // At rest the track has no press layer: it exists only while the row is
+ // pressed or releasing.
+ expect(await pressLayer(page)).toBeNull();
+ // Gate the page's timers before the press, so the release timer (which
+ // removes the attribute when the clock runs out) holds while seeking.
+ await installTimerGate(page);
+ await holdReleaseWhenFading(page);
+ // Hold each CSS animation of the row from its start, in the page. A
+ // loaded machine can reach the hold below after the release has ended.
+ // Its keyframes and timing are untouched; the curve is read by seeking.
+ await page.evaluate(() => {
+ const row = document.querySelector(
+ '#storybook-root [data-astryx-pressable]',
+ )!;
+ row.addEventListener(
+ 'animationstart',
+ event => {
+ for (const animation of (event.target as Element).getAnimations({
+ subtree: false,
+ })) {
+ if (
+ animation instanceof CSSAnimation &&
+ animation.animationName ===
+ (event as AnimationEvent).animationName
+ ) {
+ animation.playbackRate = 0;
+ }
+ }
+ },
+ {capture: true},
+ );
+ });
+ await driver.play(tap(center, {holdMs: 400}));
+ expect(await pressState(page)).toBe('fading');
+ await freezeTimers(page);
+ const row = page.locator('#storybook-root [data-astryx-pressable]').first();
+ const held = await holdAnimations(page, row);
+ // One CSS animation per press layer runs the release, the track's and
+ // the thumb's (design:user-states DR1), each its opacity on the shared
+ // release's clock. The row's strength has no release of its own under a finger (no
+ // main-thread fade), and the lift and travel are the animator's.
+ const css = held.filter(a => a.kind === 'CSSAnimation');
+ expect(
+ css.map(a => (a.target ?? '').split('.')[1]).sort(),
+ JSON.stringify(held),
+ ).toEqual(['astryx-switch', 'astryx-switch-thumb']);
+ for (const animation of css) {
+ expect(animation.durationMs).toBe(PRESS_RELEASE_MS);
+ }
+ // The lift's settle started at the lift's touch event, a frame or two
+ // before the attribute's change started the release. So seek on the
+ // release's own clock.
+ const samples: {t: number; value: number}[] = [];
+ for (const t of timeline(PRESS_RELEASE_MS)) {
+ await seekAnimations(page, t + css[0].offsetMs);
+ samples.push({t, value: (await pressLayer(page)) ?? 0});
+ }
+ await restoreHeldRates(page);
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ const comparison = compareCurve(samples, pressReleaseAt, 0.005);
+ await writeEvidence(
+ 'curves/switch-press-release',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ releaseMs: PRESS_RELEASE_MS,
+ curve: press.highlightOutCurve,
+ held,
+ samples,
+ comparison,
+ },
+ null,
+ 2,
+ ),
+ },
+ testInfo,
+ );
+ expect(samples[0].value).toBeCloseTo(1, 2);
+ expect(
+ comparison.maxError,
+ JSON.stringify(comparison.worst),
+ ).toBeLessThanOrEqual(0.005);
+ await expect.poll(async () => pressState(page)).toBeNull();
+ expect(await pressLayer(page)).toBeNull();
+ });
+
+ test('the press layers’ release follows the theme’s tempo, and Reduce Motion never lengthens it', async ({
+ page,
+ }) => {
+ // The shared release scales its clock by the theme's tempo, up to 1.5;
+ // under Reduce Motion a tempo may shorten it, never lengthen it.
+ const releaseMsUnder = async (
+ reducedMotion: 'reduce' | 'no-preference',
+ ): Promise<number[]> => {
+ await page.emulateMedia({reducedMotion});
+ const {driver, center} = await openSwitch(page);
+ await page.evaluate(() =>
+ document.documentElement.style.setProperty(
+ '--_astryx-motion-tempo',
+ '1.5',
+ ),
+ );
+ // Hold the release timer and each release animation from its start, so
+ // a loaded machine still reads them before the clock runs out.
+ await installTimerGate(page);
+ await holdReleaseWhenFading(page);
+ await page.evaluate(() => {
+ document
+ .querySelector('#storybook-root [data-astryx-pressable]')!
+ .addEventListener(
+ 'animationstart',
+ event => {
+ for (const animation of (event.target as Element).getAnimations({
+ subtree: false,
+ })) {
+ if (animation instanceof CSSAnimation) {
+ animation.playbackRate = 0;
+ }
+ }
+ },
+ {capture: true},
+ );
+ });
+ await driver.play(tap(center, {holdMs: 400}));
+ expect(await pressState(page)).toBe('fading');
+ await freezeTimers(page);
+ const row = page
+ .locator('#storybook-root [data-astryx-pressable]')
+ .first();
+ const css = (await holdAnimations(page, row)).filter(
+ a => a.kind === 'CSSAnimation',
+ );
+ // Present first: the track's layer and the thumb's.
+ expect(css.map(a => (a.target ?? '').split('.')[1]).sort()).toEqual([
+ 'astryx-switch',
+ 'astryx-switch-thumb',
+ ]);
+ await restoreHeldRates(page);
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ return css.map(a => a.durationMs);
+ };
+ for (const [reducedMotion, releaseMs] of [
+ ['no-preference', PRESS_RELEASE_MS * 1.5],
+ ['reduce', PRESS_RELEASE_MS],
+ ] as const) {
+ const durations = await releaseMsUnder(reducedMotion);
+ for (const durationMs of durations) {
+ expect(
+ durationMs,
+ `${reducedMotion}: ${durations.join(', ')}`,
+ ).toBeCloseTo(releaseMs, 6);
+ }
+ }
+ });
+
+ /**
+ * The element under a held finger, read 300 ms into a 600 ms hold and
+ * again after the lift. It records its role, how it selects text, and
+ * whether an inline lock is on it.
+ */
+ interface HeldHit {
+ role: string | null;
+ userSelect: string;
+ locked: boolean;
+ }
+ async function hitDuringHold(
+ page: Page,
+ driver: TouchDriver,
+ at: {x: number; y: number},
+ ): Promise<{during: HeldHit | null; after: HeldHit | null}> {
+ const read = async () =>
+ page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y) as HTMLElement | null;
+ if (el == null) {
+ return null;
+ }
+ const style = getComputedStyle(el);
+ return {
+ role: el.getAttribute('role'),
+ userSelect:
+ style.getPropertyValue('-webkit-user-select') || style.userSelect,
+ locked:
+ el.style.getPropertyValue('user-select') === 'none' ||
+ el.style.getPropertyValue('-webkit-user-select') === 'none',
+ };
+ }, at);
+ let during: HeldHit | null = null;
+ await driver.play(tap(at, {holdMs: 600}), {
+ onEvent: async step => {
+ if (step.type === 'touchStart') {
+ await page.waitForTimeout(300);
+ during = await read();
+ }
+ },
+ });
+ // The lock lets go when the contact ends; read it after the release's
+ // click wait, on the page's own timers.
+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS);
+ return {during, after: await read()};
+ }
+
+ test('P2 · a long press on the label selects natively, a tap selects nothing, and no press leaves selection suppressed (spec:AST-094 FR41)', async ({
+ page,
+ }) => {
+ // The Switch defines no hold action. So, like a checkbox row's label, its
+ // label keeps the browser's long-press selection. A tap activates and
+ // never selects, and any suppression lasts only for its press.
+ const {driver, input, center} = await openSwitch(page);
+ const label = page
+ .locator('#storybook-root')
+ .getByText('Enable notifications', {exact: true});
+ const box = await label.boundingBox();
+ if (box == null) {
+ throw new Error('no label');
+ }
+ const onLabel = {x: box.x + box.width / 2, y: box.y + box.height / 2};
+ const onText = await hitDuringHold(page, driver, onLabel);
+ expect(onText.during).not.toBeNull();
+ expect(onText.during?.userSelect).not.toBe('none');
+ expect(onText.during?.locked).toBe(false);
+ expect(onText.after?.locked).toBe(false);
+ // A hold on the switch suppresses nothing past its press.
+ const onSwitch = await hitDuringHold(page, driver, center);
+ expect(onSwitch.after?.locked).toBe(false);
+ // A tap activates and selects nothing.
+ await page.evaluate(() => window.getSelection()?.removeAllRanges());
+ const wasOn = await input.isChecked();
+ await driver.play(tap(center));
+ await expect(input).toBeChecked({checked: !wasOn});
+ expect(
+ await page.evaluate(() => window.getSelection()?.toString() ?? ''),
+ ).toBe('');
+ });
+
+ test('P3 · a drag flips once the finger is the track minus the thumb past where it landed, and the release commits it', async ({
+ page,
+ }) => {
+ const {driver, input, onLayer, center} = await openSwitch(page);
+ const script = drag(
+ center,
+ {x: center.x + FLIP_DISTANCE + 6, y: center.y},
+ {durationMs: 600, holdMs: 300, restMs: 200},
+ );
+ const onAt: {dx: number; on: number; press: string | null}[] = [];
+ await driver.play(script, {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ onAt.push({
+ dx: step.fingers[0].x - center.x,
+ on: Number(
+ await onLayer.evaluate(
+ el => getComputedStyle(el, '::after').opacity,
+ ),
+ ),
+ press: await pressState(page),
+ });
+ }
+ },
+ });
+ // The pressed overlay stays on through the whole drag (design:user-states
+ // DR1: during a hold or drag).
+ expect(onAt.length).toBeGreaterThan(3);
+ expect(onAt.every(s => s.press === 'on')).toBe(true);
+ // The track turned on during the drag, only after the flip distance.
+ const before = onAt.filter(s => s.dx < FLIP_DISTANCE - 0.5);
+ expect(before.every(s => s.on < 0.01)).toBe(true);
+ expect(onAt.at(-1)!.on).toBeGreaterThan(0.1);
+ await expect(input).toBeChecked();
+ });
+
+ for (const direction of ['ltr', 'rtl'] as const) {
+ test(`a press slid off and lifted outside toggles, as UISwitch's does (AST-020 FR9/DEC-5, ${direction})`, async ({
+ page,
+ }) => {
+ // Held, slid 160 px toward the off end (no flip), lifted outside: it
+ // toggles.
+ {
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ undefined,
+ {
+ direction,
+ },
+ );
+ const sign = direction === 'rtl' ? 1 : -1;
+ await driver.play(
+ drag(
+ center,
+ {x: center.x + sign * 160, y: center.y},
+ {durationMs: 300, holdMs: 300, restMs: 100},
+ ),
+ );
+ await waitForSwitchRest(page, thumb);
+ await expect(input).toBeChecked();
+ }
+ // Held, flipped by a drag 160 px toward the on end, lifted outside: it
+ // commits the side it shows.
+ {
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ undefined,
+ {
+ direction,
+ },
+ );
+ const sign = direction === 'rtl' ? -1 : 1;
+ await driver.play(
+ drag(
+ center,
+ {x: center.x + sign * 160, y: center.y},
+ {durationMs: 300, holdMs: 300, restMs: 100},
+ ),
+ );
+ await waitForSwitchRest(page, thumb);
+ await expect(input).toBeChecked();
+ }
+ });
+ }
+
+ test('P4 · a drag past the flip and back to where it landed commits nothing', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(page);
+ const out = {x: center.x + FLIP_DISTANCE + 6, y: center.y};
+ const script = [
+ ...drag(center, out, {durationMs: 400, holdMs: 300}).slice(0, -1),
+ ...drag(
+ out,
+ {x: center.x - 4, y: center.y},
+ {durationMs: 400, restMs: 200},
+ )
+ .slice(1)
+ .map(frame => ({...frame, t: frame.t + 700})),
+ ];
+ await driver.play(script);
+ await waitForSwitchRest(page, thumb);
+ await expect(input).not.toBeChecked();
+ expect(await thumbOffset(page)).toBeCloseTo(0, 0);
+ });
+
+ test('P5 · a drag shorter than the flip distance toggles at the release, like a tap', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ await driver.play(
+ drag(
+ center,
+ {x: center.x + FLIP_DISTANCE - 4, y: center.y},
+ {durationMs: 300, holdMs: 200, restMs: 150},
+ ),
+ );
+ await expect(input).toBeChecked();
+ });
+
+ test('P6 · a quick swipe toward the side it is already on toggles it', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ await driver.play(
+ drag(center, {x: center.x - 30, y: center.y}, {durationMs: 80}),
+ );
+ await expect(input).toBeChecked();
+ });
+
+ test('P7 · a vertical pan that starts on the switch scrolls the page, shows no press, and changes nothing', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ 'core-switch--in-scrolling-list',
+ );
+ test.skip(
+ !driver.drivesNativeGestures,
+ 'injected touches do not scroll natively in this engine (checked on the iOS simulator instead)',
+ );
+ // The page scrolls the document: it is the scroll view, so the press
+ // waits UIScrollView's content delay and the scroll takes the touch
+ // first. UIKit shows no press for a scroll (iOS 26.2, in a table).
+ const presses: (string | null)[] = [];
+ await driver.play(
+ drag(center, {x: center.x, y: center.y - 300}, {durationMs: 300}),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove' || step.type === 'touchEnd') {
+ presses.push(await pressState(page));
+ }
+ },
+ },
+ );
+ expect(presses.length).toBeGreaterThan(3);
+ expect(presses).not.toContain('on');
+ await waitForSwitchRest(page, thumb);
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(100);
+ // The first row starts on and stays on.
+ await expect(input).toBeChecked();
+ const rest = await presented(page);
+ expect(rest.scaleX).toBeCloseTo(1, 2);
+ expect(rest.on).toBeCloseTo(1, 2);
+ });
+
+ test('P7 · on a page that scrolls, a press waits UIScrollView’s content delay before it shows', async ({
+ page,
+ }) => {
+ // The document is the page's scroll view, as a table is UIKit's. The
+ // press waits the content delay, so a scroll takes the touch first. In a
+ // table UIKit's press shows ~200 ms after touch-down.
+ const {driver, center} = await openSwitch(
+ page,
+ 'core-switch--in-scrolling-list',
+ );
+ const presses: {at: number; press: string | null}[] = [];
+ await driver.play(tap(center, {holdMs: 450}), {
+ onEvent: async step => {
+ if (step.type === 'touchStart') {
+ await page.waitForTimeout(60);
+ presses.push({at: 60, press: await pressState(page)});
+ await page.waitForTimeout(300);
+ presses.push({at: 360, press: await pressState(page)});
+ }
+ },
+ });
+ expect(presses).toHaveLength(2);
+ expect(presses[0].press).not.toBe('on');
+ expect(presses[1].press).toBe('on');
+ });
+
+ test('two switches tapped 0.2 s apart leave the page selectable: no page-wide selection lock', async ({
+ page,
+ }) => {
+ const {driver} = await openSwitch(page, 'core-switch--in-scrolling-list');
+ const centers = await page.evaluate(() =>
+ Array.from(
+ document.querySelectorAll<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ ),
+ )
+ .slice(0, 2)
+ .map(thumb => {
+ const rect = thumb.getBoundingClientRect();
+ return {
+ x: rect.x + rect.width / 2,
+ y: rect.y + rect.height / 2,
+ };
+ }),
+ );
+ await driver.play(tap(centers[0]));
+ await page.waitForTimeout(200);
+ await driver.play(tap(centers[1]));
+ // Past the last lift's click wait and the shared click guard's window.
+ await afterPageTimer(page, BROWSER_CLICK_WAIT_MS + CLICK_GUARD_WINDOW_MS);
+ const root = await page.evaluate(() => {
+ const html = document.documentElement;
+ return {
+ inline:
+ html.style.getPropertyValue('user-select') +
+ html.style.getPropertyValue('-webkit-user-select'),
+ computed:
+ getComputedStyle(html).getPropertyValue('-webkit-user-select') ||
+ getComputedStyle(html).userSelect,
+ };
+ });
+ expect(root.inline).toBe('');
+ expect(root.computed).not.toBe('none');
+ });
+
+ test('P8 · a held switch in a scrolling list yields a vertical drag to the page: it scrolls and the switch changes nothing (spec:AST-094 FR20)', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ 'core-switch--in-scrolling-list',
+ );
+ test.skip(
+ !driver.drivesNativeGestures,
+ 'injected touches do not scroll natively in this engine (checked on the iOS simulator instead)',
+ );
+ // Held 300 ms, then dragged up 200 px: the page scrolls and the switch
+ // yields. UISwitch in a table cell would keep the touch.
+ await driver.play(
+ drag(
+ center,
+ {x: center.x, y: center.y - 200},
+ {durationMs: 300, holdMs: 300},
+ ),
+ );
+ await waitForSwitchRest(page, thumb);
+ const scrollY = await page.evaluate(() => window.scrollY);
+ expect(scrollY).toBeGreaterThan(100);
+ await expect(input).toBeChecked();
+ const rest = await presented(page);
+ expect(rest.scaleX).toBeCloseTo(1, 2);
+ expect(rest.on).toBeCloseTo(1, 2);
+ });
+
+ test('P9 · a horizontal drag in a scrolling list flips the switch and never scrolls the page', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(
+ page,
+ 'core-switch--in-scrolling-list',
+ );
+ // The first row starts on: dragging left past the flip distance turns
+ // it off, whichever way a held touch is handled.
+ await driver.play(
+ drag(
+ center,
+ {x: center.x - FLIP_FROM_ON - 6, y: center.y},
+ {durationMs: 400, holdMs: 200, restMs: 150},
+ ),
+ );
+ await expect(input).not.toBeChecked();
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ });
+
+ test('P11 · a mouse click on a touch device toggles once, through the native checkbox', async ({
+ page,
+ }) => {
+ const {input} = await openSwitch(page);
+ // A touch device (a coarse primary pointer), clicked with a mouse.
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(true);
+ await input.click({force: true});
+ await expect(input).toBeChecked();
+ });
+
+ test('P11 · under a mouse with Reduce Motion a click changes at once (design:reduced-motion DR3)', async ({
+ browser,
+ }) => {
+ const context = await browser.newContext({
+ viewport: {width: 480, height: 320},
+ screen: {width: 480, height: 320},
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+ reducedMotion: 'reduce',
+ });
+ try {
+ const page = await context.newPage();
+ await openStory(page, storybook(), 'core-switch--default');
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const input = page.locator('#storybook-root').getByRole('switch').first();
+ const samples = await sampleChange(page, async () => {
+ await input.click();
+ // Off the switch: no hover tint on the fill.
+ await page.mouse.move(1, 1);
+ });
+ await expect(input).toBeChecked();
+ const last = samples.at(-1)!;
+ const changed = samples.findIndex(
+ s => Math.abs(s.left - samples[0].left) > 0.5,
+ );
+ expect(changed).toBeGreaterThan(0);
+ for (const sample of samples.slice(changed)) {
+ expect(
+ Math.abs(sample.left - last.left),
+ JSON.stringify(sample),
+ ).toBeLessThan(0.5);
+ expect(sample.opacity).toBeCloseTo(1, 2);
+ expect(sample.scale).toBeCloseTo(1, 2);
+ }
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('P11 · under a mouse the switch keeps its desktop look: the track’s fill and padding, the thumb’s size and slide', async ({
+ browser,
+ }) => {
+ // A context with no touch screen: the primary pointer is not coarse. A
+ // headless box reports no pointer at all. So no touch presentation rule
+ // applies, and the switch must look as it always has. Contexts made here
+ // inherit the project's phone options unless they are named.
+ const context = await browser.newContext({
+ viewport: {width: 480, height: 320},
+ screen: {width: 480, height: 320},
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch: false,
+ });
+ try {
+ const page = await context.newPage();
+ await openStory(page, storybook(), 'core-switch--default');
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const read = async () =>
+ page.evaluate(() => {
+ const track = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ );
+ const thumb = track?.querySelector<HTMLElement>(
+ '.astryx-switch-thumb',
+ );
+ if (track == null || thumb == null) {
+ throw new Error('the switch has no track or thumb');
+ }
+ const t = getComputedStyle(track);
+ const box = thumb.getBoundingClientRect();
+ return {
+ fill: t.backgroundColor,
+ padding: t.paddingTop,
+ fade: t.transitionDuration,
+ size: [box.width, box.height],
+ slide: getComputedStyle(thumb).transitionProperty,
+ // The fade layer (the track's ::after) exists only under a
+ // finger, and the thumb sits directly in the track (no wrapper).
+ layer: getComputedStyle(track, '::after').display,
+ direct: thumb.parentElement === track,
+ children: track.children.length,
+ };
+ });
+ const off = await read();
+ expect(off.fill).not.toBe('rgba(0, 0, 0, 0)');
+ expect(off.padding).toBe('4px');
+ expect(off.fade).not.toBe('0s');
+ expect(off.size).toEqual([16, 16]);
+ expect(off.slide).toBe('transform, width, height');
+ expect(off.layer).toBe('none');
+ expect(off.direct).toBe(true);
+ expect(off.children).toBe(1);
+
+ const input = page.locator('#storybook-root').getByRole('switch');
+ await input.click({force: true});
+ await expect(input).toBeChecked();
+ // The thumb slides and grows over the theme's fast duration.
+ await page.waitForTimeout(500);
+ const on = await read();
+ expect(on.fill).not.toBe('rgba(0, 0, 0, 0)');
+ expect(on.fill).not.toBe(off.fill);
+ expect(on.size).toEqual([20, 20]);
+ } finally {
+ await context.close();
+ }
+ });
+
+ test('a held switch opens no context menu, as UISwitch shows none: the gesture host cancels it while the press is held', async ({
+ page,
+ }) => {
+ const {driver, input, center} = await openSwitch(page);
+ const opensMenu = async () =>
+ page.evaluate(({x, y}) => {
+ const event = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ clientX: x,
+ clientY: y,
+ });
+ document.elementFromPoint(x, y)!.dispatchEvent(event);
+ return !event.defaultPrevented;
+ }, center);
+ expect(await opensMenu()).toBe(true);
+ let whileHeld: boolean | null = null;
+ await driver.play(tap(center, {holdMs: 600}), {
+ onEvent: async step => {
+ if (step.type === 'touchStart') {
+ await expect.poll(async () => pressState(page)).toBe('on');
+ whileHeld = await opensMenu();
+ }
+ },
+ });
+ expect(whileHeld).toBe(false);
+ // The hold still toggles the switch at the release.
+ await expect(input).toBeChecked();
+ });
+
+ test('P12 · with Reduce Motion a tap cross-fades the change: no lift, no travel, opacity only, within 200 ms (design:reduced-motion DR1, DR2)', async ({
+ page,
+ }) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver, input, center} = await openSwitch(page);
+ const samples = await sampleChange(page, async () => {
+ await tapForClick(driver, center);
+ });
+ await expect(input).toBeChecked();
+ expectCrossFade(samples);
+ // It lands at the on end, not a travel past it (iOS 26.2 simulator).
+ expect(await thumbOffset(page)).toBeCloseTo(TRAVEL_PX, 0);
+ });
+
+ test('P12 · with Reduce Motion a programmatic change cross-fades too (design:reduced-motion DR2)', async ({
+ page,
+ }) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ await openSwitch(page, 'core-switch--controlled-update');
+ const samples = await sampleChange(page, async () => {
+ await page.getByRole('button', {name: 'Turn on remotely'}).click();
+ });
+ expectCrossFade(samples);
+ expect(await thumbOffset(page)).toBeCloseTo(TRAVEL_PX, 0);
+ });
+
+ test('P12 · with Reduce Motion a drag still moves the thumb under the finger, unlifted (direct manipulation)', async ({
+ page,
+ }) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const {driver, input, center} = await openSwitch(page);
+ const samples = await sampleChange(page, async () => {
+ await driver.play(
+ drag(
+ center,
+ {x: center.x + FLIP_DISTANCE + 6, y: center.y},
+ {durationMs: 400, holdMs: 200, restMs: 100},
+ ),
+ );
+ });
+ await expect(input).toBeChecked();
+ for (const sample of samples) {
+ expect(Math.abs(sample.scale - 1), JSON.stringify(sample)).toBeLessThan(
+ 0.01,
+ );
+ }
+ // It followed the finger part of the way before the release.
+ const start = samples[0].left;
+ expect(
+ samples.some(s => s.opacity > 0.9 && s.left > start + 6 && s.on < 0.9),
+ ).toBe(true);
+ });
+
+ test('P13 · RTL: the off thumb rests at the right, and a tap carries it to the left end and turns the track on', async ({
+ page,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(
+ page,
+ 'core-switch--default',
+ {direction: 'rtl'},
+ );
+ expect(await input.evaluate(el => getComputedStyle(el).direction)).toBe(
+ 'rtl',
+ );
+ expect(await thumbOffset(page)).toBeCloseTo(TRAVEL_PX, 0);
+ await driver.play(tap(center, {holdMs: 50}));
+ await expect(input).toBeChecked();
+ await waitForSwitchRest(page, thumb);
+ expect(await thumbOffset(page)).toBeCloseTo(0, 0);
+ expect((await presented(page)).on).toBeCloseTo(1, 2);
+ });
+
+ test('P13 · RTL: a drag toward the left flips the switch during the drag; a drag toward the right never flips and toggles at the release', async ({
+ page,
+ }) => {
+ // Toward the left: the track turns on once the finger has travelled the
+ // flip distance, before the lift.
+ {
+ const {driver, input, onLayer, center} = await openSwitch(
+ page,
+ 'core-switch--default',
+ {direction: 'rtl'},
+ );
+ const onAt: {dx: number; on: number}[] = [];
+ await driver.play(
+ drag(
+ center,
+ {x: center.x - FLIP_DISTANCE - 6, y: center.y},
+ {durationMs: 600, holdMs: 300, restMs: 200},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ onAt.push({
+ dx: center.x - step.fingers[0].x,
+ on: Number(
+ await onLayer.evaluate(
+ el => getComputedStyle(el, '::after').opacity,
+ ),
+ ),
+ });
+ }
+ },
+ },
+ );
+ const before = onAt.filter(s => s.dx < FLIP_DISTANCE - 0.5);
+ expect(before.every(s => s.on < 0.01)).toBe(true);
+ expect(onAt.at(-1)!.on).toBeGreaterThan(0.1);
+ await expect(input).toBeChecked();
+ }
+ // Toward the right, the side an off switch already is on: no flip
+ // during the drag, and the lift toggles like a tap.
+ {
+ const {driver, input, onLayer, center} = await openSwitch(
+ page,
+ 'core-switch--default',
+ {direction: 'rtl'},
+ );
+ const ons: number[] = [];
+ await driver.play(
+ drag(
+ center,
+ {x: center.x + 30, y: center.y},
+ {durationMs: 600, holdMs: 300, restMs: 200},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ ons.push(
+ Number(
+ await onLayer.evaluate(
+ el => getComputedStyle(el, '::after').opacity,
+ ),
+ ),
+ );
+ }
+ },
+ },
+ );
+ expect(ons.every(on => on < 0.01)).toBe(true);
+ await expect(input).toBeChecked();
+ }
+ });
+
+ /**
+ * Records the thumb's on-screen center on animation frames, from the next
+ * frame on, with the frame's timestamp: `[ms, px]`. `everyNthFrame` reads
+ * only one frame in that many, as a loaded machine reads frames late or
+ * misses them while the compositor keeps the thumb moving.
+ */
+ async function recordThumbCenters(
+ page: Page,
+ {everyNthFrame = 1}: {everyNthFrame?: number} = {},
+ ): Promise<void> {
+ await page.evaluate(nth => {
+ const box = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const record = window as unknown as {__thumbXs: [number, number][]};
+ record.__thumbXs = [];
+ let frame = 0;
+ const loop = (time: number) => {
+ if (frame++ % nth === 0) {
+ const rect = box.getBoundingClientRect();
+ record.__thumbXs.push([time, rect.left + rect.width / 2]);
+ }
+ if (record.__thumbXs.length < 240) {
+ requestAnimationFrame(loop);
+ }
+ };
+ requestAnimationFrame(loop);
+ }, everyNthFrame);
+ }
+
+ /**
+ * Resolves once the thumb's travel is on screen: its newest `translate`
+ * animation running, started, and one frame into its curve. A page-side
+ * wait, so a loaded machine starts what follows at the same point of the
+ * travel, not at a fixed time after the tap.
+ */
+ async function travelOnScreen(page: Page, rest?: number): Promise<void> {
+ await page.waitForFunction(
+ rest => {
+ const thumb = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ // The travel shows on screen: the thumb is 1 px or more off its rest.
+ if (rest != null) {
+ const box = thumb.getBoundingClientRect();
+ if (Math.abs(box.left + box.width / 2 - rest) < 1) {
+ return false;
+ }
+ }
+ return document
+ .querySelector<HTMLElement>('#storybook-root .astryx-switch-thumb')!
+ .getAnimations()
+ .some(
+ a =>
+ a.playState === 'running' &&
+ !a.pending &&
+ Number(a.currentTime ?? 0) >= 16 &&
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => 'translate' in k),
+ );
+ },
+ rest ?? null,
+ {polling: 'raf'},
+ );
+ }
+
+ /** P14's two taps: the second lands once the first one's travel is on screen. */
+ async function secondTapMidTravel(
+ page: Page,
+ driver: TouchDriver,
+ center: {x: number; y: number},
+ ): Promise<void> {
+ const finger = {id: 0, ...center};
+ const rest = await page.evaluate(() => {
+ const box = document
+ .querySelector<HTMLElement>('#storybook-root .astryx-switch-thumb')!
+ .getBoundingClientRect();
+ return box.left + box.width / 2;
+ });
+ // Each tap is the browser's click (WebKit's comes only from its own tap
+ // path).
+ if (driver.engine === 'webkit') {
+ await driver.tap(center);
+ await travelOnScreen(page, rest);
+ await driver.tap(center);
+ } else {
+ await driver.play([
+ {t: 0, fingers: [finger]},
+ {t: 40, fingers: []},
+ ]);
+ await travelOnScreen(page, rest);
+ await driver.play([
+ {t: 0, fingers: [finger]},
+ {t: 30, fingers: []},
+ ]);
+ }
+ }
+
+ /**
+ * Records the thumb's center through a catch, `[ms, px]`. Chromium's
+ * samples are the frames the compositor presents (a screencast and a
+ * marker on the thumb). A starved main thread runs its frame callbacks
+ * late, with the frame's old time. A read there can stamp a later picture
+ * with an earlier time. WebKit's are its animation frames.
+ */
+ async function recordCatch(
+ page: Page,
+ thumb: Locator,
+ browserName: string,
+ ): Promise<{stop: () => Promise<[number, number][]>}> {
+ if (browserName !== 'chromium') {
+ await recordThumbCenters(page);
+ return {
+ stop: async () =>
+ page.evaluate(
+ () =>
+ (window as unknown as {__thumbXs: [number, number][]}).__thumbXs,
+ ),
+ };
+ }
+ await markElement(thumb, {size: 6, inset: 2});
+ const cast = await startScreencast(page);
+ return {
+ stop: async () => {
+ const tracked = await trackMarker(page, await cast.stop());
+ const shown = tracked.filter(
+ (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
+ f.box != null && f.box.width > 0 && f.box.height > 0,
+ );
+ // Present and painted first: the marked thumb in the frames, with a
+ // box.
+ expect(shown.length).toBeGreaterThan(10);
+ return shown.map(f => [f.t, f.box.x + f.box.width / 2]);
+ },
+ };
+ }
+
+ function expectCaughtWithoutAJump(samples: [number, number][]): void {
+ const xs = samples.map(([, x]) => x);
+ const farthest = Math.max(...xs) - xs[0];
+ // It turned around mid-travel, short of the on end...
+ expect(farthest).toBeGreaterThan(1);
+ expect(farthest).toBeLessThan(TRAVEL_PX - 1);
+ // ...from where it was: no frame moves it more than a few px. Each step is
+ // measured against the time its frames span. So a frame read late, two
+ // vsyncs of motion in one sample, is not a jump.
+ const FRAME_MS = 1000 / 60;
+ const perFrame = samples
+ .slice(1)
+ .map(
+ ([time, x], i) =>
+ (Math.abs(x - samples[i][1]) * FRAME_MS) /
+ Math.max(time - samples[i][0], FRAME_MS),
+ );
+ expect(Math.max(...perFrame), JSON.stringify(samples)).toBeLessThan(4);
+ }
+
+ test('P14 · a second tap mid-travel catches the thumb where it is and sends it back, without a jump', async ({
+ page,
+ browserName,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(page);
+ const record = await recordCatch(page, thumb, browserName);
+ await secondTapMidTravel(page, driver, center);
+ await waitForSwitchRest(page, thumb);
+ const samples = await record.stop();
+ await expect(input).not.toBeChecked();
+ expect(await thumbOffset(page)).toBeCloseTo(0, 0);
+ expectCaughtWithoutAJump(samples);
+ });
+
+ test('P14 · with frames read late (one frame in three) the catch still shows no jump', async ({
+ page,
+ browserName,
+ }) => {
+ const {driver, input, thumb, center} = await openSwitch(page);
+ const record = await recordCatch(page, thumb, browserName);
+ await secondTapMidTravel(page, driver, center);
+ await waitForSwitchRest(page, thumb);
+ const samples = await record.stop();
+ await expect(input).not.toBeChecked();
+ expect(await thumbOffset(page)).toBeCloseTo(0, 0);
+ expectCaughtWithoutAJump(samples.filter((_, index) => index % 3 === 0));
+ });
+
+ test('P14 · a second tap whose lift the page handles late (its main thread busy for 100 ms) catches the thumb where the screen shows it, without a jump (spec:AST-094 FR6)', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',
+ );
+ const {driver, input, thumb, center} = await openSwitch(page);
+ await markElement(thumb, {size: 6, inset: 2});
+ // The page blocks at the second touch's start, so that touch's lift waits
+ // for the block. The switch handles the lift about 70 ms after it
+ // happened, while the compositor keeps the first travel moving.
+ await page.evaluate(() => {
+ const w = window as unknown as {__block?: {from: number; to: number}};
+ let starts = 0;
+ addEventListener(
+ 'touchstart',
+ () => {
+ starts += 1;
+ if (starts !== 2) {
+ return;
+ }
+ // In the touch's own dispatch, after the switch's listeners (they
+ // were added first): a task queued here can run after the lift.
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 100;
+ while (performance.now() < end) {
+ // the page's main thread is busy
+ }
+ w.__block = {from, to: performance.timeOrigin + performance.now()};
+ },
+ {capture: true, passive: true},
+ );
+ });
+ const cast = await startScreencast(page);
+ await secondTapMidTravel(page, driver, center);
+ await waitForSwitchRest(page, thumb);
+ const castFrames = await cast.stop();
+ await expect(input).not.toBeChecked();
+ const block = await page.evaluate(
+ () =>
+ (window as unknown as {__block?: {from: number; to: number}}).__block,
+ );
+ expect(block, 'the page was busy when the lift came').toBeDefined();
+ const tracked = await trackMarker(page, castFrames);
+ // Present and painted first: the marked thumb in the frames, with a box.
+ const shown = tracked.filter(
+ (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
+ f.box != null && f.box.width > 0 && f.box.height > 0,
+ );
+ expect(shown.length).toBeGreaterThan(10);
+ const samples = shown.map(
+ f => [f.t, f.box.x + f.box.width / 2] as [number, number],
+ );
+ const xs = samples.map(([, x]) => x);
+ const farthest = Math.max(...xs) - xs[0];
+ // It turned around mid-travel, short of the on end...
+ expect(farthest).toBeGreaterThan(1);
+ expect(farthest).toBeLessThan(TRAVEL_PX - 1);
+ // ...from the place the screen showed when the late lift was handled. No
+ // presented frame moves it more than a few px from the one before,
+ // measured against the time the two frames span.
+ const FRAME_MS = 1000 / 60;
+ const perFrame = samples
+ .slice(1)
+ .map(
+ ([time, x], i) =>
+ (Math.abs(x - samples[i][1]) * FRAME_MS) /
+ Math.max(time - samples[i][0], FRAME_MS),
+ );
+ expect(Math.max(...perFrame), JSON.stringify(samples)).toBeLessThan(4);
+ });
+
+ test('a tap whose first frame the page commits late (its main thread busy for 100 ms after the lift) starts the travel from rest on that frame, not partway into its curve', async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',
+ );
+ const {driver, input, thumb, center} = await openSwitch(page);
+ await markElement(thumb, {size: 6, inset: 2});
+ // The page blocks in the lift's own dispatch, after the switch's
+ // listeners have started the travel. The frame that first shows the
+ // travel comes about 100 ms after the switch asked for it. As Core
+ // Animation starts an animation at its commit, a block before that frame
+ // delays the motion instead of skipping into it.
+ await page.evaluate(() => {
+ const w = window as unknown as {__block?: {from: number; to: number}};
+ addEventListener(
+ 'touchend',
+ () => {
+ if (w.__block != null) {
+ return;
+ }
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 100;
+ while (performance.now() < end) {
+ // the page's main thread is busy
+ }
+ w.__block = {from, to: performance.timeOrigin + performance.now()};
+ },
+ {capture: true, passive: true},
+ );
+ });
+ // The marker sits at the thumb's inline start. At rest it moves with the
+ // thumb's left edge, since each state has its own thumb size.
+ const restLeft = async () =>
+ thumb.evaluate(element => element.getBoundingClientRect().left);
+ const offLeft = await restLeft();
+ const cast = await startScreencast(page);
+ await driver.play(tap(center, {holdMs: 40}));
+ await expect(input).toBeChecked();
+ await waitForSwitchRest(page, thumb);
+ const castFrames = await cast.stop();
+ const onLeft = await restLeft();
+ const block = await page.evaluate(
+ () =>
+ (window as unknown as {__block?: {from: number; to: number}}).__block,
+ );
+ expect(block, 'the page was busy after the lift').toBeDefined();
+ const tracked = await trackMarker(page, castFrames);
+ // Present and painted first: the marked thumb in the frames, with a box.
+ const shown = tracked.filter(
+ (f): f is typeof f & {box: NonNullable<typeof f.box>} =>
+ f.box != null && f.box.width > 0 && f.box.height > 0,
+ );
+ expect(shown.length).toBeGreaterThan(10);
+ const samples = shown.map(
+ f => [f.t, f.box.x + f.box.width / 2] as [number, number],
+ );
+ const xs = samples.map(([, x]) => x);
+ // It travelled from the off rest to the on rest (the frames place the
+ // marker to the whole px)...
+ expect(Math.abs(xs.at(-1)! - xs[0] - (onLeft - offLeft))).toBeLessThan(1.5);
+ // ...from rest: no presented frame moves it more than a few px from the
+ // one before, measured against the time the two frames span.
+ const FRAME_MS = 1000 / 60;
+ const perFrame = samples
+ .slice(1)
+ .map(
+ ([time, x], i) =>
+ (Math.abs(x - samples[i][1]) * FRAME_MS) /
+ Math.max(time - samples[i][0], FRAME_MS),
+ );
+ expect(Math.max(...perFrame), JSON.stringify(samples)).toBeLessThan(4);
+ });
+
+ test('a disabled or busy switch stays inert under a finger', async ({
+ page,
+ }) => {
+ for (const storyId of ['core-switch--disabled', 'core-switch--loading']) {
+ const {driver, input, center} = await openSwitch(page, storyId);
+ const wasOn = await input.isChecked();
+ let held: Presented | null = null;
+ await driver.play(tap(center, {holdMs: 400}), {
+ onEvent: async step => {
+ if (step.type === 'touchStart') {
+ await page.waitForTimeout(250);
+ held = await presented(page);
+ }
+ },
+ });
+ expect(held!.scaleX, storyId).toBe(1);
+ expect(await input.isChecked(), storyId).toBe(wasOn);
+ }
+ });
+
+ test('the travel and the track colour follow the UIKit springs, sampled frame by frame', async ({
+ page,
+ }, testInfo) => {
+ const {thumb} = await openSwitch(page);
+ // The travel and the track color, from a programmatic change: the thumb
+ // starts at rest, as UISwitch's `setOn(_:animated:)` does.
+ await openStory(page, storybook(), 'core-switch--controlled-update');
+ await page.getByRole('button', {name: 'Turn on remotely'}).click();
+ await waitForAnimation(thumb);
+ await holdAnimations(page, page.locator('#storybook-root .astryx-switch'));
+ const travelSamples = await sampleThumb(page, timeline(500));
+ await releaseAnimations(page);
+ const travelResult = compareCurve(
+ travelSamples.map(s => ({t: s.t, value: s.x})),
+ t => -TRAVEL_PX * (1 - springStep(TRAVEL, t)),
+ 0.15,
+ );
+ const wellResult = compareCurve(
+ travelSamples.map(s => ({t: s.t, value: s.on})),
+ t => springStep(WELL_ON, t),
+ 0.01,
+ );
+ await writeEvidence(
+ 'curves/switch',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {travelSamples, travelResult, wellResult},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ expect(
+ travelResult.maxError,
+ JSON.stringify(travelResult.worst),
+ ).toBeLessThanOrEqual(0.15);
+ expect(
+ wellResult.maxError,
+ JSON.stringify(wellResult.worst),
+ ).toBeLessThanOrEqual(0.01);
+ });
+
+ test('P10 · the toggle 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: checked on the iOS simulator instead)',
+ );
+ const {driver, input, thumb, center} = await openSwitch(page);
+ await markElement(thumb, {size: 6, inset: 2});
+ // The block starts in the page once the travel is one frame into its
+ // curve, from a task queued in that frame. So it holds the same part of
+ // the travel whatever the page's own timing. The lift starts at
+ // touch-down, and a round trip from here would start the block late.
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ __block?: {from: number; to: number; spins: number};
+ __travel?: {from: number; to: number};
+ };
+ const input = document.querySelector('#storybook-root [role="switch"]')!;
+ const thumb = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ const onScreen = () =>
+ thumb
+ .getAnimations()
+ .filter(
+ a =>
+ a.playState === 'running' &&
+ !a.pending &&
+ Number(a.currentTime ?? 0) >= 16 &&
+ (a.effect as KeyframeEffect)
+ .getKeyframes()
+ .some(k => 'translate' in k),
+ )
+ .at(-1);
+ const whenOnScreen = (run: () => void) => {
+ const tick = () => {
+ if (onScreen() == null) {
+ requestAnimationFrame(tick);
+ } else {
+ setTimeout(run, 0);
+ }
+ };
+ requestAnimationFrame(tick);
+ };
+ input.addEventListener(
+ 'change',
+ () =>
+ whenOnScreen(() => {
+ const travel = onScreen();
+ if (travel?.startTime != null) {
+ const effect = travel.effect as KeyframeEffect;
+ const from = performance.timeOrigin + Number(travel.startTime);
+ const ends = effect
+ .getKeyframes()
+ .map(k => k.computedOffset)
+ .filter(o => o < 1);
+ w.__travel = {
+ from,
+ to:
+ from +
+ Number(effect.getComputedTiming().activeDuration) *
+ Math.max(...ends),
+ };
+ }
+ const from = performance.timeOrigin + performance.now();
+ const end = performance.now() + 700;
+ let spins = 0;
+ while (performance.now() < end) {
+ spins++;
+ }
+ w.__block = {
+ from,
+ to: performance.timeOrigin + performance.now(),
+ spins,
+ };
+ }),
+ {once: true},
+ );
+ });
+ const cast = await startScreencast(page);
+ await driver.play(tap(center, {holdMs: 50}));
+ await expect(input).toBeChecked();
+ await page.waitForFunction(
+ () => (window as unknown as {__block?: unknown}).__block != null,
+ );
+ const {block, travel} = await page.evaluate(() => {
+ const w = window as unknown as {
+ __block: {from: number; to: number; spins: number};
+ __travel: {from: number; to: number};
+ };
+ return {block: w.__block, travel: w.__travel};
+ });
+ expect(travel, 'the travel was running when the block began').toBeDefined();
+ await page.waitForTimeout(150);
+ const castFrames = await cast.stop();
+ const tracked = await trackMarker(page, castFrames);
+ const proof = busyWindowProof(
+ tracked,
+ {from: block.from, to: Math.min(block.to, travel.to)},
+ // The screencast places the marker to the whole px. On UISwitch's 0.3 s
+ // spring, the 13 px travel moves under 1 px per frame once 4.3 px remain
+ // (110 ms). From there a frame can show no change while the thumb moves,
+ // so it is judged until then.
+ {axis: 'x', settledWithin: 4.5},
+ );
+ await writeEvidence(
+ 'busy-main-thread/switch-toggle',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ block,
+ travel,
+ proof,
+ frames: tracked.map(f => ({
+ t: +(f.t - block.from).toFixed(1),
+ x: f.box?.x ?? null,
+ w: f.box?.width ?? null,
+ })),
+ },
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ expect(proof.monotonic).toBe(true);
+ // The travel is 13 px: past its first half it moves less than a
+ // screencast pixel per frame, so not every frame changes...
+ expect(proof.changed).toBeGreaterThanOrEqual(Math.floor(proof.frames / 2));
+ // ...but most of it happened while the main thread was held.
+ const held = tracked.filter(
+ f => f.t >= block.from && f.t <= block.to && f.box != null,
+ );
+ expect(held.at(-1)!.box!.x - held[0].box!.x).toBeGreaterThanOrEqual(8);
+ });
+
+ test('P10 · the touch press keeps fading out on 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: checked on the iOS simulator instead)',
+ );
+ const {driver, input, onLayer, center} = await openSwitch(page);
+ // Only the press layer may change the probe. The thumb is hidden, though
+ // its animations still run, and the colour fade is off. The value stays
+ // off: every click is stopped before it reaches the input.
+ await page.addStyleTag({
+ content:
+ '#storybook-root .astryx-switch-thumb { visibility: hidden } #storybook-root .astryx-switch::after { display: none !important }',
+ });
+ await page.evaluate(() => {
+ window.addEventListener(
+ 'click',
+ event => {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ },
+ true,
+ );
+ });
+ const box = await onLayer.boundingBox();
+ if (box == null) {
+ throw new Error('no track');
+ }
+ const probe = {
+ x: box.x + box.width / 2 - 2,
+ y: box.y + box.height / 2 - 2,
+ width: 4,
+ height: 4,
+ };
+ const cast = await startScreencast(page);
+ await driver.play(tap(center, {holdMs: 400}));
+ expect(await pressState(page)).toBe('fading');
+ // The release is the press layer's CSS animation (the track's ::before);
+ // the lift and the travel are the animator's. Block once it has run a
+ // frame.
+ const release = await page.evaluate(
+ async () =>
+ new Promise<{from: number; to: number}>(resolve => {
+ const track = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const poll = () => {
+ const layer = track
+ .getAnimations({subtree: true})
+ .find(
+ animation =>
+ animation instanceof CSSAnimation &&
+ (animation.effect as KeyframeEffect | null)?.pseudoElement ===
+ '::before',
+ );
+ const at = Number(layer?.currentTime ?? 0);
+ if (layer?.startTime != null && at >= 16) {
+ const from = performance.timeOrigin + Number(layer.startTime);
+ const timing = layer.effect!.getComputedTiming();
+ resolve({from, to: from + Number(timing.activeDuration)});
+ return;
+ }
+ requestAnimationFrame(poll);
+ };
+ poll();
+ }),
+ );
+ const block = await blockMainThread(page, 700);
+ await page.waitForTimeout(150);
+ const frames = await cast.stop();
+ await expect(input).not.toBeChecked();
+ const lumas = await sampleLuma(page, frames, probe);
+ const rest = lumas[0].luma;
+ const pressed = Math.min(
+ ...lumas.filter(p => p.t < release.from).map(p => p.luma),
+ );
+ const strength = (v: number) => (rest - v) / (rest - pressed);
+ const end = Math.min(block.to, release.to) - 10;
+ const during = lumas.filter(p => p.t > block.from && p.t <= end);
+ const strengths = during.map(p => ({
+ t: +(p.t - block.from).toFixed(1),
+ strength: +strength(p.luma).toFixed(3),
+ }));
+ const intervals = during
+ .map((p, i) => (i === 0 ? p.t - block.from : p.t - during[i - 1].t))
+ .filter(dt => dt > 0);
+ const longestGap = Math.max(
+ end - (during.at(-1)?.t ?? block.from),
+ ...intervals,
+ );
+ // The screencast's own delivered cadence: stalls are judged against it,
+ // never against a frame rate.
+ const sorted = [...intervals].sort((a, b) => a - b);
+ const cadence = sorted[Math.floor(sorted.length / 2)] ?? Infinity;
+ await writeEvidence(
+ 'busy-main-thread/switch-press-release',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {block, release, rest, pressed, strengths},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ const film = await castStoryboard(page, frames, {
+ name: 'switch-press-release-busy-main-thread',
+ zero: block.from,
+ from: release.from - 40,
+ to: release.to + 40,
+ columns: 6,
+ cellScale: 0.45,
+ data: t => {
+ const p = lumas.find(f => f.t === t);
+ return {strength: p == null ? -1 : +strength(p.luma).toFixed(3)};
+ },
+ });
+ await film.write(testInfo, {block, release});
+ // The press showed, and its release kept stepping on every frame of the
+ // block, never backing up, to well below where it started.
+ expect(rest - pressed).toBeGreaterThan(5);
+ // Enough delivered frames to judge, and no stall longer than three of
+ // them.
+ expect(during.length, JSON.stringify(strengths)).toBeGreaterThanOrEqual(5);
+ expect(longestGap).toBeLessThanOrEqual(3 * cadence);
+ for (let i = 1; i < strengths.length; i++) {
+ expect(strengths[i].strength).toBeLessThanOrEqual(
+ strengths[i - 1].strength + 0.02,
+ );
+ }
+ const last = strengths.at(-1);
+ expect(last).toBeDefined();
+ expect(strengths[0].strength).toBeGreaterThan((last?.strength ?? 1) + 0.2);
+ });
+
+ test('P10 · the track colour keeps fading in while the main thread is blocked', async ({
+ page,
+ browserName,
+ }, testInfo) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'screencast frame evidence is Chromium-only in Playwright (WebKit: checked on the iOS simulator instead)',
+ );
+ const {driver, input, onLayer, center} = await openSwitch(page);
+ // Hide the thumb (its animations still run) so the whole track shows
+ // its colour.
+ await page.addStyleTag({
+ content: '#storybook-root .astryx-switch-thumb { visibility: hidden }',
+ });
+ const box = await page
+ .locator('#storybook-root .astryx-switch')
+ .first()
+ .boundingBox();
+ if (box == null) {
+ throw new Error('no track');
+ }
+ const cast = await startScreencast(page);
+ await driver.play(tap(center, {holdMs: 50}));
+ await expect(input).toBeChecked();
+ await waitForAnimation(onLayer, {minProgressMs: 16});
+ const block = await blockMainThread(page, 700);
+ await page.waitForTimeout(150);
+ const castFrames = await cast.stop();
+ const luma = await sampleLuma(page, castFrames, {
+ x: box.x + 4,
+ y: box.y + 4,
+ width: box.width - 8,
+ height: box.height - 8,
+ });
+ await writeEvidence(
+ 'busy-main-thread/switch-track-colour',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {
+ block,
+ frames: luma.map(f => ({
+ t: +(f.t - block.from).toFixed(1),
+ luma: +f.luma.toFixed(1),
+ })),
+ },
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ const off = luma[0].luma;
+ const on = luma.at(-1)!.luma;
+ const held = luma.filter(
+ f => f.t >= block.from + 20 && f.t <= block.to - 20,
+ );
+ expect(held.length).toBeGreaterThan(20);
+ // Most of the fade happened while the main thread was held.
+ expect(held[0].luma - held.at(-1)!.luma).toBeGreaterThan(0.5 * (off - on));
+ });
+
+ test('P10 · a change does no Layout or Paint per frame', async ({
+ page,
+ browserName,
+ }, testInfo) => {
+ test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
+ // A programmatic change, so the trace holds the switch's own motion: a
+ // press also paints the shared press overlay, the press feedback's.
+ const {input, thumb} = await openSwitch(
+ page,
+ 'core-switch--controlled-update',
+ );
+ let travel = {from: 0, to: 0};
+ const trace = await traceRendering(page, async () => {
+ await page.evaluate(() => {
+ // The change's own task: the click, React's commit and the switch's
+ // setValue all run in it. A message posted at its start is handled
+ // by the first task after it.
+ const record = window as unknown as {__changeTaskMs?: number};
+ const start = performance.now();
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => {
+ record.__changeTaskMs = performance.now() - start;
+ channel.port1.close();
+ };
+ channel.port2.postMessage(null);
+ Array.from(document.querySelectorAll('button'))
+ .find(button => button.textContent?.includes('Turn on remotely'))!
+ .click();
+ });
+ await expect(input).toBeChecked();
+ travel = await travelAnimation(page);
+ await waitForSwitchRest(page, thumb);
+ });
+ // The steady part of the travel, while the thumb settles and the track
+ // color rises too: the value's commit comes before it.
+ const steady = {from: travel.from + 50, to: travel.to - 50};
+ const during = countBetween(trace, steady.from, steady.to);
+ expect(during.Layout ?? 0, JSON.stringify(during)).toBe(0);
+ expect(during.Paint ?? 0, JSON.stringify(during)).toBe(0);
+ // No long task while it runs either. The change's own task comes before
+ // it, and is measured below.
+ expect(
+ trace.longTasks.filter(
+ task =>
+ task.start < steady.to && task.start + task.durationMs > steady.from,
+ ),
+ JSON.stringify(trace.longTasks),
+ ).toEqual([]);
+ await test.step('measured, not asserted: the first change’s own task after load', async () => {
+ // The first change runs the switch's and the animator's code for the
+ // first time: tens of ms on a slow CPU. The pull request states the
+ // numbers. Reported with the run, never judged against a bound.
+ const changeTaskMs = await page.evaluate(
+ () => (window as unknown as {__changeTaskMs?: number}).__changeTaskMs,
+ );
+ // Present first: the change's task was measured.
+ expect(changeTaskMs).toBeGreaterThan(0);
+ const before = trace.longTasks.filter(task => task.start < steady.from);
+ testInfo.annotations.push({
+ type: 'first change task (ms)',
+ description: `${changeTaskMs!.toFixed(1)}; long tasks before the travel: ${JSON.stringify(before.map(task => Math.round(task.durationMs)))}`,
+ });
+ await writeEvidence(
+ 'perf/switch-first-change-task',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {changeTaskMs, longTasksBeforeTravel: before, travel},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ });
+ });
+
+ test(
+ 'storyboard: tap — travel',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const {driver, thumb, center} = await openSwitch(page);
+ await installTimerGate(page);
+ const clip = page.locator('#storybook-root .astryx-switch');
+ await driver.play(tap(center, {holdMs: 50}));
+ await waitForAnimation(thumb);
+ await freezeTimers(page);
+ const {storyboard} = await animationStoryboard(page, {
+ name: 'switch-tap',
+ // The motion: the track colour settles last, about 1.2 s after the
+ // release.
+ times: timeline(1250),
+ clip: {...(await clipAround(clip))},
+ measure: async () => ({
+ ...(await presented(page)),
+ offset: await thumbOffset(page),
+ }),
+ columns: 8,
+ cellScale: 2,
+ });
+ await releaseAnimations(page, {finish: true});
+ await thawTimers(page);
+ await storyboard.write(testInfo);
+ const offsets = storyboard.frames.map(f => f.data.offset as number);
+ expect(offsets.at(-1)).toBeCloseTo(TRAVEL_PX, 0);
+ // Critically damped travel: never past the on end.
+ expect(Math.max(...offsets)).toBeLessThanOrEqual(TRAVEL_PX + 0.1);
+ },
+ );
+
+ test(
+ 'storyboard: hold, drag across, release',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const {driver, center} = await openSwitch(page);
+ const clip = page.locator('#storybook-root .astryx-switch');
+ const board = await touchStoryboard(
+ page,
+ driver,
+ drag(
+ center,
+ {x: center.x + FLIP_DISTANCE + 8, y: center.y},
+ {durationMs: 400, hz: 20, holdMs: 300, restMs: 100},
+ ),
+ {
+ name: 'switch-hold-drag',
+ clip: {...(await clipAround(clip))},
+ measure: async () => ({
+ ...(await presented(page)),
+ offset: await thumbOffset(page),
+ }),
+ columns: 6,
+ cellScale: 2,
+ },
+ );
+ await board.write(testInfo);
+ const ons = board.frames.map(f => f.data.on as number);
+ // Off until the flip, then the track color rises. It is waited for in
+ // the page: a loaded machine can take the last frame before it shows.
+ expect(ons[0]).toBeCloseTo(0, 2);
+ await expect
+ .poll(async () => (await presented(page)).on)
+ .toBeGreaterThan(0.05);
+ },
+ );
+});
+
+/**
+ * The mean luma of a box (CSS px) in each screencast frame, decoded in a
+ * scratch page like the harness's marker tracking.
+ */
+async function sampleLuma(
+ page: Page,
+ frames: ReadonlyArray<CastFrame>,
+ region: {x: number; y: number; width: number; height: number},
+): Promise<{t: number; luma: number}[]> {
+ const scratch = await page.context().newPage();
+ try {
+ const out: {t: number; luma: number}[] = [];
+ for (let i = 0; i < frames.length; i += 12) {
+ const batch = frames.slice(i, i + 12);
+ const values = await scratch.evaluate(
+ async ({items, box}) => {
+ const result: number[] = [];
+ for (const item of items) {
+ const blob = await (
+ await fetch(`data:image/${item.format};base64,${item.data}`)
+ ).blob();
+ const bitmap = await createImageBitmap(blob);
+ const scale = bitmap.width / item.viewportWidth;
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
+ const context = canvas.getContext('2d');
+ if (context == null) {
+ throw new Error('no 2d context');
+ }
+ context.drawImage(bitmap, 0, 0);
+ const {data} = context.getImageData(
+ Math.round(box.x * scale),
+ Math.round(box.y * scale),
+ Math.max(1, Math.round(box.width * scale)),
+ Math.max(1, Math.round(box.height * scale)),
+ );
+ let sum = 0;
+ for (let o = 0; o < data.length; o += 4) {
+ sum +=
+ 0.2126 * data[o] + 0.7152 * data[o + 1] + 0.0722 * data[o + 2];
+ }
+ result.push(sum / (data.length / 4));
+ }
+ return result;
+ },
+ {
+ items: batch.map(f => ({
+ data: f.data,
+ format: f.format,
+ viewportWidth: f.viewportWidth,
+ })),
+ box: region,
+ },
+ );
+ values.forEach((luma, k) => out.push({t: batch[k].t, luma}));
+ }
+ return out;
+ } finally {
+ await scratch.close();
+ }
+}
+
+/** The track with room for the lifted thumb around it. */
+async function clipAround(track: Locator) {
+ const box = await track.boundingBox();
+ if (box == null) {
+ throw new Error('no track');
+ }
+ return {
+ x: box.x - 12,
+ y: box.y - 10,
+ width: box.width + 24,
+ height: box.height + 20,
+ };
+}
+
+/** Seek the held animations and read the thumb's x delta, scale and the track color. */
+async function sampleThumb(
+ page: Page,
+ times: ReadonlyArray<number>,
+): Promise<
+ {
+ t: number;
+ x: number;
+ scaleX: number;
+ fill: number;
+ on: number;
+ boxOpacity: number;
+ }[]
+> {
+ return page.evaluate(
+ ts => {
+ const held =
+ (window as unknown as {__harnessHeld?: Animation[]}).__harnessHeld ??
+ [];
+ const thumb = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ // The thumb itself moves and lifts.
+ const box = thumb;
+ // The fade layer shows the other side's fill (see presented()).
+ const fade = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch',
+ )!;
+ const input = document.querySelector<HTMLInputElement>(
+ '#storybook-root [role="switch"]',
+ )!;
+ const start = Math.min(...held.map(a => Number(a.startTime ?? 0)));
+ return ts.map(t => {
+ for (const animation of held) {
+ const end = Number(
+ animation.effect?.getComputedTiming().endTime ?? Infinity,
+ );
+ const offset = Number(animation.startTime ?? start) - start;
+ animation.currentTime = Math.max(0, Math.min(t - offset, end - 0.5));
+ }
+ const style = getComputedStyle(box);
+ const translate = style.translate === 'none' ? '0px' : style.translate;
+ const scale = style.scale === 'none' ? '1' : style.scale;
+ return {
+ t,
+ x: parseFloat(translate),
+ scaleX: Number(scale.split(' ')[0]),
+ fill: Number(getComputedStyle(thumb).opacity),
+ on: input.checked
+ ? 1 - Number(getComputedStyle(fade, '::after').opacity)
+ : Number(getComputedStyle(fade, '::after').opacity),
+ boxOpacity: Number(style.opacity),
+ };
+ });
+ },
+ [...times],
+ );
+}
diff --git a/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts b/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts
new file mode 100644
index 0000000000..b865277a5c
--- /dev/null
+++ b/packages/core/src/Switch/__tests__/SwitchPointer.interaction.browser.spec.ts
@@ -0,0 +1,403 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SwitchPointer.interaction.browser.spec.ts
+ * @input The Switch stories in a context with no touch screen (a fine
+ * primary pointer), driven by a real mouse.
+ * @output Browser proofs that Switch's gestures work for a mouse and a pen
+ * (`spec:AST-094` FR43): a drag flips it by the flip rule (Switch FR15), a
+ * press slid off and released outside leaves it alone (the
+ * reversible-toggle exception is a finger's), a click toggles once, a right
+ * click does nothing, and the switch keeps its desktop presentation (FR13).
+ * The pen is the harness's real engine pen (Chromium only).
+ * @position Beside Switch.interaction.browser.spec.ts, which proves the
+ * touch presentation under a finger.
+ */
+
+import {expect, test, type Browser, type Page} from '@playwright/test';
+import {
+ openStory,
+ PEN_SKIP,
+ webInputDriver,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+import {BROWSER_CLICK_WAIT_MS} from '../switchTouch';
+
+const storybook = withStorybook(test);
+
+/** The md track is 40 × 24 and its off thumb 16 × 16: the flip distance. */
+const FLIP_DISTANCE = 40 - 16;
+
+interface MouseSwitch {
+ page: Page;
+ close: () => Promise<void>;
+ /** The thumb's center, client px. */
+ center: {x: number; y: number};
+ isChecked: () => Promise<boolean>;
+ /** How many `change` events the input has sent since opening. */
+ changes: () => Promise<number>;
+ /** Each click the input has heard since opening: whether it was trusted. */
+ clicks: () => Promise<boolean[]>;
+}
+
+/**
+ * The Default story in a context with no touch screen, so the primary
+ * pointer is not coarse. With `hasTouch`, a touch screen sits beside the
+ * mouse. Contexts made here inherit the project's phone options unless they
+ * are named.
+ */
+async function openMouseSwitch(
+ browser: Browser,
+ storyId = 'core-switch--default',
+ {hasTouch = false}: {hasTouch?: boolean} = {},
+): Promise<MouseSwitch> {
+ const context = await browser.newContext({
+ viewport: {width: 480, height: 320},
+ screen: {width: 480, height: 320},
+ deviceScaleFactor: 1,
+ isMobile: false,
+ hasTouch,
+ });
+ const page = await context.newPage();
+ await openStory(page, storybook(), storyId);
+ if (!hasTouch) {
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ }
+ await page.evaluate(() => {
+ const w = window as unknown as {__changes: number; __clicks: boolean[]};
+ w.__changes = 0;
+ w.__clicks = [];
+ const input = document.querySelector('#storybook-root [role="switch"]')!;
+ input.addEventListener('change', () => {
+ w.__changes++;
+ });
+ input.addEventListener('click', event => {
+ w.__clicks.push(event.isTrusted);
+ });
+ });
+ const thumb = await page
+ .locator('#storybook-root .astryx-switch-thumb')
+ .first()
+ .boundingBox();
+ if (thumb == null) {
+ throw new Error('the switch has no thumb');
+ }
+ const input = page.locator('#storybook-root').getByRole('switch').first();
+ return {
+ page,
+ close: async () => context.close(),
+ center: {x: thumb.x + thumb.width / 2, y: thumb.y + thumb.height / 2},
+ isChecked: async () => input.isChecked(),
+ changes: async () =>
+ page.evaluate(() => (window as unknown as {__changes: number}).__changes),
+ clicks: async () =>
+ page.evaluate(
+ () => (window as unknown as {__clicks: boolean[]}).__clicks,
+ ),
+ };
+}
+
+/**
+ * Resolves once the switch's click wait after a release has run out, on the
+ * page's own timers. The release queued that wait first, so a timer queued
+ * now with the same delay runs after it, however late the page runs.
+ */
+async function afterClickWait(page: Page): Promise<void> {
+ await page.evaluate(async ms => {
+ await new Promise<void>(resolve => {
+ setTimeout(resolve, ms);
+ });
+ }, BROWSER_CLICK_WAIT_MS);
+}
+
+/** Resolves after the page renders two more frames. */
+async function afterTwoFrames(page: Page): Promise<void> {
+ await page.evaluate(async () => {
+ for (let frame = 0; frame < 2; frame++) {
+ await new Promise(requestAnimationFrame);
+ }
+ });
+}
+
+/** A mouse drag through `points`, pressed at the first and released at the last. */
+async function mouseDrag(
+ page: Page,
+ points: ReadonlyArray<{x: number; y: number}>,
+): Promise<void> {
+ const [first, ...rest] = points;
+ await page.mouse.move(first.x, first.y);
+ await page.mouse.down();
+ for (const point of rest) {
+ await page.mouse.move(point.x, point.y, {steps: 8});
+ }
+ await page.mouse.up();
+ await afterClickWait(page);
+}
+
+test.describe('Switch under a mouse (spec:AST-094 FR43)', () => {
+ test('a drag past the flip distance flips the switch, and the release commits it off the switch too (Switch FR15)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ // Past the flip, then on past the switch onto its label: the browser
+ // sends the input no click for a release that far.
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x: x + FLIP_DISTANCE + 6, y},
+ {x: x + 90, y},
+ ]);
+ expect(await sw.isChecked()).toBe(true);
+ expect(await sw.changes()).toBe(1);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a drag past the flip distance and back to where it pressed commits nothing: the browser’s click on the input is swallowed', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x: x + FLIP_DISTANCE + 6, y},
+ {x: x - 4, y},
+ ]);
+ expect(await sw.isChecked()).toBe(false);
+ expect(await sw.changes()).toBe(0);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a press slid off and released outside without a flip leaves the switch alone: the reversible-toggle exception is a finger’s (Switch FR15)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x, y: y + 40},
+ {x, y: y + 120},
+ ]);
+ expect(await sw.isChecked()).toBe(false);
+ expect(await sw.changes()).toBe(0);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a press released just off the switch, still inside UIControl’s touch slop, with no flip, leaves the switch alone: no browser click comes, and the switch adds none', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x, y: y + 20},
+ {x, y: y + 40},
+ ]);
+ expect(await sw.isChecked()).toBe(false);
+ expect(await sw.changes()).toBe(0);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('after a mouse flip, a finger’s tap on a touch screen still gets the browser’s own click: the next press disarms the shared click guard', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser, 'core-switch--default', {
+ hasTouch: true,
+ });
+ try {
+ const {x, y} = sw.center;
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x: x + FLIP_DISTANCE + 6, y},
+ {x: x + 90, y},
+ ]);
+ expect(await sw.isChecked()).toBe(true);
+ const thumb = await sw.page
+ .locator('#storybook-root .astryx-switch-thumb')
+ .first()
+ .boundingBox();
+ if (thumb == null) {
+ throw new Error('the switch has no thumb');
+ }
+ await sw.page.touchscreen.tap(
+ thumb.x + thumb.width / 2,
+ thumb.y + thumb.height / 2,
+ );
+ await afterClickWait(sw.page);
+ expect(await sw.isChecked()).toBe(false);
+ // The tap's click is the browser's (trusted), not the switch's
+ // fallback click.
+ expect((await sw.clicks()).at(-1)).toBe(true);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a drag past the flip distance released on the switch toggles it once: the browser’s click on the input is swallowed (Switch FR15)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ // Pressed and released on the input, so the browser sends it a click
+ // after the switch has committed the flip itself.
+ await mouseDrag(sw.page, [
+ {x, y},
+ {x: x + FLIP_DISTANCE + 2, y},
+ ]);
+ expect(await sw.isChecked()).toBe(true);
+ expect(await sw.changes()).toBe(1);
+ // Only the switch's own click reached the input.
+ expect(await sw.clicks()).toEqual([false]);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a click toggles once and a right click does nothing', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ await sw.page.mouse.click(x, y);
+ await afterClickWait(sw.page);
+ expect(await sw.isChecked()).toBe(true);
+ expect(await sw.changes()).toBe(1);
+ await sw.page.mouse.click(x, y, {button: 'right'});
+ await sw.page.keyboard.press('Escape');
+ await afterClickWait(sw.page);
+ expect(await sw.isChecked()).toBe(true);
+ expect(await sw.changes()).toBe(1);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('the switch keeps horizontal touch moves for its drag under any primary pointer, so a touchscreen laptop’s finger flips it by the same rule (spec:AST-094 FR18, FR43)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const touchAction = await sw.page.evaluate(
+ () =>
+ getComputedStyle(
+ document.querySelector('#storybook-root [role="switch"]')!
+ .parentElement!,
+ ).touchAction,
+ );
+ expect(touchAction).toBe('pan-y pinch-zoom');
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a disabled or a loading switch takes no drag, so it leaves horizontal touch moves to the page', async ({
+ browser,
+ }) => {
+ for (const storyId of ['core-switch--disabled', 'core-switch--loading']) {
+ const sw = await openMouseSwitch(browser, storyId);
+ try {
+ const touchAction = await sw.page.evaluate(
+ () =>
+ getComputedStyle(
+ document.querySelector('#storybook-root [role="switch"]')!
+ .parentElement!,
+ ).touchAction,
+ );
+ expect(touchAction, storyId).toBe('auto');
+ } finally {
+ await sw.close();
+ }
+ }
+ });
+
+ test('a pen drag past the flip distance flips the switch, and the release commits it off the switch too (Switch FR15)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const driver = await webInputDriver(sw.page);
+ test.skip(!driver.pens, PEN_SKIP);
+ const {x, y} = sw.center;
+ await driver.pen([
+ {x, y, t: 0},
+ {x: x + 10, y, t: 60},
+ {x: x + 20, y, t: 120},
+ {x: x + FLIP_DISTANCE + 6, y, t: 180},
+ {x: x + 60, y, t: 240},
+ {x: x + 90, y, t: 300},
+ ]);
+ await afterClickWait(sw.page);
+ expect(await sw.isChecked()).toBe(true);
+ expect(await sw.changes()).toBe(1);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('a pen slid off and released outside without a flip leaves the switch alone, as a mouse does (Switch FR15)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const driver = await webInputDriver(sw.page);
+ test.skip(!driver.pens, PEN_SKIP);
+ const {x, y} = sw.center;
+ await driver.pen([
+ {x, y, t: 0},
+ {x, y: y + 20, t: 60},
+ {x, y: y + 60, t: 120},
+ {x, y: y + 120, t: 180},
+ ]);
+ await afterClickWait(sw.page);
+ expect(await sw.isChecked()).toBe(false);
+ expect(await sw.changes()).toBe(0);
+ } finally {
+ await sw.close();
+ }
+ });
+
+ test('through a drag the switch keeps its desktop presentation: no lift and no motion of its own on the thumb (FR13)', async ({
+ browser,
+ }) => {
+ const sw = await openMouseSwitch(browser);
+ try {
+ const {x, y} = sw.center;
+ await sw.page.mouse.move(x, y);
+ await sw.page.mouse.down();
+ await sw.page.mouse.move(x + 12, y, {steps: 4});
+ // Any motion the moves started is on the thumb two frames later.
+ await afterTwoFrames(sw.page);
+ const thumb = await sw.page.evaluate(() => {
+ const t = document.querySelector<HTMLElement>(
+ '#storybook-root .astryx-switch-thumb',
+ )!;
+ return {
+ inline: [t.style.translate, t.style.scale, t.style.opacity],
+ scale: getComputedStyle(t).scale,
+ animations: t.getAnimations().length,
+ };
+ });
+ await sw.page.mouse.up();
+ expect(thumb.inline).toEqual(['', '', '']);
+ expect(thumb.scale).toBe('none');
+ expect(thumb.animations).toBe(0);
+ } finally {
+ await sw.close();
+ }
+ });
+});
diff --git a/packages/core/src/Switch/switchFill.ts b/packages/core/src/Switch/switchFill.ts
new file mode 100644
index 0000000000..2f2ef91b69
--- /dev/null
+++ b/packages/core/src/Switch/switchFill.ts
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file switchFill.ts
+ * @input Switch's track element and the props its other state renders with
+ * @output Exports TrackState, sameTrackState, trackStateOf, readInState and
+ * readFillOf: an element read in its other state, in place
+ * @position Shared by Switch.tsx and useSwitchTouch.ts for the colour fade
+ * under a finger
+ *
+ * The colour fade needs the track's fill in its other state, as the theme
+ * paints it. readFillOf swaps the track's class and attributes, reads the
+ * colour and swaps back in the same task, so nothing paints in between.
+ *
+ * SYNC: When modified, update Switch.tsx and useSwitchTouch.ts.
+ */
+
+/** A track state: its class name and its data attributes. */
+export interface TrackState {
+ readonly className: string;
+ readonly attributes: Readonly<Record<string, string>>;
+}
+
+/** Whether two track states render alike: the same class and attributes. */
+export function sameTrackState(
+ a: TrackState | null,
+ b: TrackState | null,
+): boolean {
+ if (a === b) {
+ return true;
+ }
+ if (a == null || b == null || a.className !== b.className) {
+ return false;
+ }
+ const names = Object.keys(a.attributes);
+ return (
+ names.length === Object.keys(b.attributes).length &&
+ names.every(name => a.attributes[name] === b.attributes[name])
+ );
+}
+
+/** The track state of rendered props (`className` and `data-*` props). */
+export function trackStateOf(props: object): TrackState {
+ const attributes: Record<string, string> = {};
+ let className = '';
+ for (const [name, value] of Object.entries(props)) {
+ if (name === 'className' && typeof value === 'string') {
+ className = value;
+ } else if (name.startsWith('data-') && value != null) {
+ // As React writes a data attribute: every value but null or undefined.
+ attributes[name] = String(value);
+ }
+ }
+ return {className, attributes};
+}
+
+/**
+ * Reads `element` as it renders in `state` (its class and data attributes),
+ * swapping them in and back in the same task, so nothing paints between.
+ */
+export function readInState<T>(
+ element: HTMLElement,
+ state: TrackState,
+ read: (element: HTMLElement) => T,
+): T {
+ const names = new Set(Object.keys(state.attributes));
+ for (const attribute of Array.from(element.attributes)) {
+ if (attribute.name.startsWith('data-')) {
+ names.add(attribute.name);
+ }
+ }
+ const savedClass = element.className;
+ const saved = new Map<string, string | null>();
+ for (const name of names) {
+ saved.set(name, element.getAttribute(name));
+ }
+ const apply = (
+ className: string,
+ valueOf: (name: string) => string | null,
+ ) => {
+ element.className = className;
+ for (const name of names) {
+ const value = valueOf(name);
+ if (value == null) {
+ element.removeAttribute(name);
+ } else {
+ element.setAttribute(name, value);
+ }
+ }
+ };
+ apply(state.className, name => state.attributes[name] ?? null);
+ try {
+ return read(element);
+ } finally {
+ apply(savedClass, name => saved.get(name) ?? null);
+ }
+}
+
+/** The track's computed fill in `state`, read without a paint. */
+export function readFillOf(track: HTMLElement, state: TrackState): string {
+ return readInState(
+ track,
+ state,
+ element => getComputedStyle(element).backgroundColor,
+ );
+}
diff --git a/packages/core/src/Switch/switchTouch.test.ts b/packages/core/src/Switch/switchTouch.test.ts
new file mode 100644
index 0000000000..44f0a80e4f
--- /dev/null
+++ b/packages/core/src/Switch/switchTouch.test.ts
@@ -0,0 +1,345 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file switchTouch.test.ts
+ * @input vitest, switchTouch.ts, the UIKit switch constants and the spring math
+ * @output Unit tests for Switch's touch model: geometry, the drag's thumb
+ * target, the flip rule, the release commit and the settle time, held to
+ * UISwitch on iOS 26.2; and the switch springs held to UIKit's own frames
+ * @position Testing; the pure half of Switch's touch presentation
+ *
+ * The UIKit points below were read from a UISwitch on the iOS 26.2
+ * simulator, in switch-local pt. The switch springs were fitted to them, so
+ * a change that leaves UIKit's curve fails here.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {listMotionRoles, motionRoleOf} from '../motion/roles';
+import {solveSpring, toSpring} from '../motion/spring';
+import {registerSwitchTable, switchControl} from '../motion/uikit/switch';
+import {
+ commitOnRelease,
+ dragTarget,
+ settleTime,
+ startFlip,
+ stepFlip,
+ switchTouchGeometry,
+ type SwitchFlip,
+} from './switchTouch';
+
+const UIKIT = switchTouchGeometry(63, 28);
+
+/** Feed a drag's events (finger travel since it landed) through the rule. */
+function drag(
+ isOn: boolean,
+ travels: number[],
+ geometry = UIKIT,
+): SwitchFlip[] {
+ const states: SwitchFlip[] = [];
+ let flip = startFlip(isOn);
+ for (const travel of travels) {
+ flip = stepFlip(flip, travel, geometry);
+ states.push(flip);
+ }
+ return states;
+}
+
+describe('switchTouchGeometry', () => {
+ it('is UIKit itself at UIKit size', () => {
+ expect(UIKIT.thumbWidth).toBeCloseTo(37, 9);
+ expect(UIKIT.thumbHeight).toBeCloseTo(24, 9);
+ expect(UIKIT.inset).toBeCloseTo(2, 9);
+ expect(UIKIT.travel).toBeCloseTo(22, 9);
+ expect(UIKIT.flipDistance).toBeCloseTo(26, 9);
+ // The lift fills half the 2 pt gap on each side, and the band the other
+ // half. UIKit's own lens grows to 58 × 38.3, past the track.
+ expect(UIKIT.liftScaleX).toBeCloseTo(1 + 2 / 37, 9);
+ expect(UIKIT.liftScaleY).toBeCloseTo(UIKIT.liftScaleX, 9);
+ expect(UIKIT.rubberBandDimension).toBeCloseTo(1, 9);
+ });
+
+ it('keeps UIKit proportions in a smaller track (md 40 × 24, sm 32 × 20)', () => {
+ for (const [width, height] of [
+ [40, 24],
+ [32, 20],
+ ] as const) {
+ const geometry = switchTouchGeometry(width, height);
+ expect(geometry.thumbWidth / width).toBeCloseTo(37 / 63, 9);
+ expect(geometry.thumbHeight / height).toBeCloseTo(24 / 28, 9);
+ // Inset equally on three sides; the thumb reaches the far inset.
+ expect(geometry.inset * 2 + geometry.thumbHeight).toBeCloseTo(height, 9);
+ expect(
+ geometry.inset * 2 + geometry.thumbWidth + geometry.travel,
+ ).toBeCloseTo(width, 9);
+ // The finger flips the switch after the track minus the thumb.
+ expect(geometry.flipDistance).toBeCloseTo(width - geometry.thumbWidth, 9);
+ }
+ });
+});
+
+describe('dragTarget', () => {
+ it('moves 1:1 with the finger between the ends', () => {
+ expect(dragTarget(0, 5, UIKIT)).toBeCloseTo(5, 9);
+ expect(dragTarget(22, -7, UIKIT)).toBeCloseTo(15, 9);
+ });
+
+ it("rubber-bands past either end with UIScrollView's curve (c 0.55), reaching no further than the lift leaves", () => {
+ const past = 46;
+ const d = UIKIT.rubberBandDimension;
+ const expected = (1 - 1 / ((past * 0.55) / d + 1)) * d;
+ expect(dragTarget(0, 22 + past, UIKIT)).toBeCloseTo(22 + expected, 9);
+ expect(dragTarget(22, -22 - past, UIKIT)).toBeCloseTo(-expected, 9);
+ });
+
+ it('keeps a lifted thumb inside the track at any overdrag, at every size and thumb shape', () => {
+ for (const [width, height, thumb] of [
+ [63, 28, undefined],
+ [40, 24, undefined],
+ [32, 20, undefined],
+ // A theme's circle (aspect ratio 1) in the md and sm tracks.
+ [40, 24, {width: (24 * 24) / 28, height: (24 * 24) / 28}],
+ [32, 20, {width: (20 * 24) / 28, height: (20 * 24) / 28}],
+ ] as const) {
+ const geometry = switchTouchGeometry(width, height, thumb);
+ const grownX = (geometry.thumbWidth * (geometry.liftScaleX - 1)) / 2;
+ const grownY = (geometry.thumbHeight * (geometry.liftScaleY - 1)) / 2;
+ expect(geometry.inset - grownY).toBeGreaterThanOrEqual(0);
+ for (const finger of [1e3, 1e6]) {
+ const end = dragTarget(0, finger, geometry);
+ const start = dragTarget(geometry.travel, -finger, geometry);
+ // Lifted edges from the track's start: inset + offset ∓ growth.
+ expect(
+ geometry.inset + end + geometry.thumbWidth + grownX,
+ ).toBeLessThanOrEqual(width + 1e-9);
+ expect(geometry.inset + start - grownX).toBeGreaterThanOrEqual(-1e-9);
+ }
+ }
+ });
+
+ it('measures the thumb a theme shapes: a circle travels further and flips at the track minus its width', () => {
+ const circle = switchTouchGeometry(40, 24, {width: 20, height: 20});
+ expect(circle.inset).toBeCloseTo(2, 9);
+ expect(circle.travel).toBeCloseTo(16, 9);
+ expect(circle.flipDistance).toBeCloseTo(20, 9);
+ });
+
+ it('starts from a banded thumb without a jump (grab mid-flight)', () => {
+ const banded = dragTarget(0, 40, UIKIT);
+ // A new finger lands on the thumb where it is: no movement, no jump.
+ expect(dragTarget(banded, 0, UIKIT)).toBeCloseTo(banded, 9);
+ });
+});
+
+describe('stepFlip (UIKit, 1 pt steps)', () => {
+ it('flips on the event after the finger reaches 26 pt toward on, from any press point', () => {
+ // UIKit: armed at +26, flipped at +27, for presses at x 8, 20.5 and 45.
+ const states = drag(false, [24, 25, 26, 27, 28]);
+ expect(states.map(s => s.isVisuallyOn)).toEqual([
+ false,
+ false,
+ false,
+ true,
+ true,
+ ]);
+ expect(states[2].isArmed).toBe(true);
+ expect(states[3].didFlip).toBe(true);
+ });
+
+ it('flips back when the finger returns past where it landed, not before', () => {
+ // UIKit: still on at +0.67, back off at −0.33.
+ const states = drag(false, [26, 27, 40, 10, 0.67, -0.33]);
+ expect(states.map(s => s.isVisuallyOn)).toEqual([
+ false,
+ true,
+ true,
+ true,
+ true,
+ false,
+ ]);
+ expect(states[5].didFlip).toBe(true);
+ });
+
+ it('mirrors on an on switch: off 27 pt to the left, back on past the press', () => {
+ const states = drag(true, [-26, -27, -0.33, 0.67]);
+ expect(states.map(s => s.isVisuallyOn)).toEqual([true, false, false, true]);
+ });
+
+ it('never flips toward the side the switch is already on', () => {
+ // UIKit: a quick 40 pt swipe left on an off switch flips nothing (the
+ // lift then toggles it, like a tap).
+ expect(drag(false, [-10, -30, -40]).some(s => s.didFlip)).toBe(false);
+ });
+
+ it('arms on the last move of a fast swipe and flips on the lift', () => {
+ // UIKit: +4, +20, +32 then the lift at +40: the flip came with the lift.
+ const states = drag(false, [4, 20, 32]);
+ expect(states[2]).toMatchObject({isVisuallyOn: false, isArmed: true});
+ expect(stepFlip(states[2], 40, UIKIT).isVisuallyOn).toBe(true);
+ });
+
+ it('disarms when the finger falls back short of the line before the next event', () => {
+ const states = drag(false, [26, 20, 27]);
+ expect(states.map(s => s.isVisuallyOn)).toEqual([false, false, false]);
+ expect(states[2].isArmed).toBe(true);
+ });
+
+ it('uses the track minus the thumb as the distance in a smaller track', () => {
+ const md = switchTouchGeometry(40, 24);
+ const states = drag(
+ false,
+ [md.flipDistance - 0.01, md.flipDistance, md.flipDistance + 1],
+ md,
+ );
+ expect(states.map(s => s.isVisuallyOn)).toEqual([false, false, true]);
+ });
+});
+
+describe('commitOnRelease (UIKit)', () => {
+ it('toggles when nothing flipped, wherever the finger lifts: a tap, a hold, a 15 pt drag, a slide off (UISwitch)', () => {
+ expect(commitOnRelease(null, false)).toBe(true);
+ expect(commitOnRelease(null, true)).toBe(false);
+ expect(commitOnRelease(drag(false, [15]).at(-1)!, false)).toBe(true);
+ // Slid 160 pt toward the off end, which never flips an off switch.
+ expect(commitOnRelease(drag(false, [-40, -160]).at(-1)!, false)).toBe(true);
+ });
+
+ it('commits the side a flipped drag shows, wherever the finger lifts (UISwitch)', () => {
+ // Flipped on, then slid back past where it landed and off the far end. It
+ // shows the side it started on, so it commits that side.
+ expect(
+ commitOnRelease(drag(false, [26, 27, 30, 0, -160]).at(-1)!, false),
+ ).toBe(false);
+ });
+
+ it('commits the side a drag shows once it flipped: a 30 pt drag stays on', () => {
+ expect(commitOnRelease(drag(false, [26, 27, 30]).at(-1)!, false)).toBe(
+ true,
+ );
+ });
+
+ it('commits nothing new for a drag on and back off', () => {
+ expect(commitOnRelease(drag(false, [26, 27, -1]).at(-1)!, false)).toBe(
+ false,
+ );
+ });
+});
+
+describe('settleTime', () => {
+ it('settles at the release, but no sooner than the minimum lift', () => {
+ expect(settleTime(1000, 0)).toBe(1000);
+ expect(settleTime(50, 30)).toBe(30 + switchControl.minimumLiftMs);
+ // A caller's minimum, when it passes one, replaces it.
+ expect(settleTime(50, 30, 400)).toBe(430);
+ });
+});
+
+describe('the switch springs against UIKit frames (iOS 26.2)', () => {
+ // [ms after the spring's start, value] read per frame from UIKit.
+ const cases = [
+ {
+ name: 'lift: lens width 37 → 58 during a hold',
+ spring: switchControl.lift,
+ from: 37,
+ to: 58,
+ // Started 30.5 ms after the finger landed.
+ frames: [
+ [49.8, 48.5],
+ [82.5, 56.34],
+ [116.9, 59.92],
+ [151.5, 60.58],
+ [186.8, 59.88],
+ [282.8, 58.0],
+ ],
+ // The fit's rms is 0.29 pt; UIKit writes the lens once per frame.
+ tolerance: 0.7,
+ },
+ {
+ name: 'settle: lens width 58 → 37 after a hold',
+ spring: switchControl.settle,
+ from: 58,
+ to: 37,
+ // Started 23 ms after the finger lifted.
+ frames: [
+ [42.7, 55.6],
+ [76.0, 51.72],
+ [109.4, 47.64],
+ [176.4, 41.03],
+ [277.9, 36.55],
+ [410.6, 36.23],
+ ],
+ // UIKit's own settings (0.5 s, 0.7) against frames whose start time is
+ // read to a frame. The best one-spring fit is 0.49 s (rms 0.065 pt).
+ tolerance: 0.45,
+ },
+ {
+ name: 'travel: lens center 20.33 → 42.5 after a hold',
+ spring: switchControl.travel,
+ from: 20.333,
+ to: 42.5,
+ // Started 34.5 ms after the finger lifted.
+ frames: [
+ [31.2, 23.17],
+ [64.5, 28.73],
+ [97.9, 33.55],
+ [133.4, 36.94],
+ [198.7, 40.42],
+ [300.8, 42.1],
+ ],
+ // UIKit's own settings (0.3 s, 1); the best one-spring fit is 0.31 s.
+ tolerance: 0.45,
+ },
+ ] as const;
+
+ for (const {name, spring, from, to, frames, tolerance} of cases) {
+ it(name, () => {
+ const curve = solveSpring(toSpring(spring), {from, to});
+ for (const [ms, value] of frames) {
+ expect(Math.abs(curve.value(ms / 1000) - value)).toBeLessThan(
+ tolerance,
+ );
+ }
+ });
+ }
+
+ it('the track color springs are the CASpringAnimations UIKit attached', () => {
+ // Read exactly: response 0.68 s and 0.40 s, critically damped.
+ for (const [spring, response] of [
+ [switchControl.wellOn, 0.68],
+ [switchControl.wellOff, 0.4],
+ ] as const) {
+ const physics = toSpring(spring);
+ expect(
+ (2 * Math.PI) / Math.sqrt(physics.stiffness / physics.mass),
+ ).toBeCloseTo(response, 6);
+ expect(
+ physics.damping / (2 * Math.sqrt(physics.stiffness * physics.mass)),
+ ).toBeCloseTo(1, 6);
+ }
+ });
+});
+
+describe('switch values', () => {
+ it("are the motion roles Switch's record names, registered internally", () => {
+ // spec:AST-094 FR4, DEC-5: the springs and the minimum lift time are
+ // roles; DEC-11: internal, so nothing public writes them.
+ registerSwitchTable();
+ expect(
+ listMotionRoles()
+ .filter(role => role.id.startsWith('switchControl.'))
+ .map(role => [role.id, role.kind]),
+ ).toEqual([
+ ['switchControl.lift', 'spring'],
+ ['switchControl.minimumLiftMs', 'duration'],
+ ['switchControl.settle', 'spring'],
+ ['switchControl.tracking', 'spring'],
+ ['switchControl.travel', 'spring'],
+ ['switchControl.wellOff', 'spring'],
+ ['switchControl.wellOn', 'spring'],
+ ]);
+ expect(motionRoleOf(switchControl.lift)?.id).toBe('switchControl.lift');
+ expect(motionRoleOf(switchControl.travel)?.id).toBe('switchControl.travel');
+ // The geometry and the rubber band are not motion.
+ expect(motionRoleOf(switchControl.rubberBand)).toBeUndefined();
+ expect(settleTime(0, 0)).toBe(switchControl.minimumLiftMs);
+ });
+});
diff --git a/packages/core/src/Switch/switchTouch.ts b/packages/core/src/Switch/switchTouch.ts
new file mode 100644
index 0000000000..30e798c7ce
--- /dev/null
+++ b/packages/core/src/Switch/switchTouch.ts
@@ -0,0 +1,194 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @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
+ * @position Pure half of Switch's touch presentation; driven by
+ * useSwitchTouch.ts, tested by switchTouch.test.ts without a browser
+ *
+ * Positions are thumb offsets from the off end, 0 … `travel`, in the writing
+ * direction; the caller mirrors them for right-to-left.
+ * SYNC: When modified, update useSwitchTouch.ts and switchTouch.test.ts.
+ */
+
+import {rubberBandClamp, rubberBandUnclamp} from '../motion/rubberBand';
+import {switchControl} from '../motion/uikit/switch';
+
+export interface SwitchTouchGeometry {
+ readonly trackWidth: number;
+ readonly trackHeight: number;
+ /** The thumb at rest, px. */
+ readonly thumbWidth: number;
+ readonly thumbHeight: number;
+ /** Gap between the thumb and the track's top, bottom and nearer end, px. */
+ readonly inset: number;
+ /** Offset of the thumb at the on end, px. */
+ readonly travel: number;
+ /**
+ * Scale of the lifted thumb, one value on both axes. It is UIKit's lift,
+ * capped so the thumb grows into at most half the gap on each side.
+ */
+ readonly liftScaleX: number;
+ readonly liftScaleY: number;
+ /**
+ * The drag's rubber-band dimension, px: UIKit's, scaled to the track. It
+ * never exceeds the gap the lift leaves (`inset` less the lifted growth).
+ * The band approaches its dimension and never reaches it, so a banded thumb
+ * stays inside the track.
+ */
+ readonly rubberBandDimension: number;
+ /** How far the finger goes toward the other end before a flip, px. */
+ readonly flipDistance: number;
+}
+
+const [UIKIT_TRACK_WIDTH, UIKIT_TRACK_HEIGHT] = switchControl.trackSize;
+const [UIKIT_THUMB_WIDTH, UIKIT_THUMB_HEIGHT] = switchControl.thumbSize;
+const [LIFTED_WIDTH, LIFTED_HEIGHT] = switchControl.liftedThumbSize;
+
+/**
+ * The thumb geometry in a track of this size: the thumb's measured box when
+ * given, UIKit's proportions otherwise.
+ */
+export function switchTouchGeometry(
+ trackWidth: number,
+ trackHeight: number,
+ thumb?: {readonly width: number; readonly height: number},
+): SwitchTouchGeometry {
+ const thumbHeight =
+ thumb?.height ?? (trackHeight * UIKIT_THUMB_HEIGHT) / UIKIT_TRACK_HEIGHT;
+ const thumbWidth =
+ thumb?.width ?? (trackWidth * UIKIT_THUMB_WIDTH) / UIKIT_TRACK_WIDTH;
+ const inset = Math.max(0, (trackHeight - thumbHeight) / 2);
+ // UIKit lifts to 58 × 38.3 from 37 × 24; here the lift fills at most half
+ // the gap on each side, on both axes alike.
+ const liftScale = Math.max(
+ 1,
+ Math.min(
+ LIFTED_WIDTH / UIKIT_THUMB_WIDTH,
+ LIFTED_HEIGHT / UIKIT_THUMB_HEIGHT,
+ thumbWidth > 0 ? 1 + inset / thumbWidth : 1,
+ thumbHeight > 0 ? 1 + inset / thumbHeight : 1,
+ ),
+ );
+ const liftGrowth = (thumbWidth * (liftScale - 1)) / 2;
+ return {
+ trackWidth,
+ trackHeight,
+ thumbWidth,
+ thumbHeight,
+ inset,
+ travel: Math.max(0, trackWidth - thumbWidth - 2 * inset),
+ liftScaleX: liftScale,
+ liftScaleY: liftScale,
+ rubberBandDimension: Math.max(
+ 0,
+ Math.min(
+ (switchControl.rubberBand.dimension * trackHeight) / UIKIT_TRACK_HEIGHT,
+ inset - liftGrowth,
+ ),
+ ),
+ flipDistance: Math.max(0, trackWidth - thumbWidth),
+ };
+}
+
+/**
+ * Where the drag puts the thumb's target. It is the offset at the landing,
+ * moved by the finger's translation and rubber-banded past either end.
+ *
+ * `start` is the thumb's offset on screen when the finger landed, mid-flight
+ * or banded. It is unbanded first, so a finger that grabs a moving thumb
+ * continues without a jump.
+ */
+export function dragTarget(
+ start: number,
+ translation: number,
+ geometry: SwitchTouchGeometry,
+): number {
+ const {travel, rubberBandDimension} = geometry;
+ const coefficient = switchControl.rubberBand.coefficient;
+ const raw =
+ rubberBandUnclamp(start, 0, travel, rubberBandDimension, coefficient) +
+ translation;
+ return rubberBandClamp(raw, 0, travel, rubberBandDimension, coefficient);
+}
+
+/** A drag's flip state: the side it shows and how it got there. */
+export interface SwitchFlip {
+ /** The value when the finger landed. */
+ readonly startedOn: boolean;
+ readonly isVisuallyOn: boolean;
+ /** The finger passed `flipDistance` on the last event: the next one flips. */
+ readonly isArmed: boolean;
+ /** The drag has flipped at least once. */
+ readonly didFlip: boolean;
+}
+
+export function startFlip(isOn: boolean): SwitchFlip {
+ return {startedOn: isOn, isVisuallyOn: isOn, isArmed: false, didFlip: false};
+}
+
+/**
+ * One touch event of the drag. `translation` is the finger's travel since it
+ * landed along the writing direction (positive toward the on end).
+ */
+export function stepFlip(
+ flip: SwitchFlip,
+ translation: number,
+ geometry: SwitchTouchGeometry,
+): SwitchFlip {
+ // Travel toward the other end: right from off, left from on.
+ const toward = flip.startedOn ? -translation : translation;
+ if (flip.isVisuallyOn !== flip.startedOn) {
+ return toward < 0
+ ? {...flip, isVisuallyOn: flip.startedOn, isArmed: false}
+ : flip;
+ }
+ const isPast = toward >= geometry.flipDistance;
+ if (flip.isArmed && isPast) {
+ return {
+ ...flip,
+ isVisuallyOn: !flip.startedOn,
+ isArmed: false,
+ didFlip: true,
+ };
+ }
+ 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
+ * and lifted outside toggles too, as UISwitch's does. A toggle is
+ * reversible, so a stray release costs one more tap.
+ */
+export function commitOnRelease(
+ flip: SwitchFlip | null,
+ isOn: boolean,
+): boolean {
+ return flip?.didFlip === true ? flip.isVisuallyOn : !isOn;
+}
+
+/**
+ * When the lifted thumb may settle, on the document timeline (ms). It is the
+ * release, but never sooner than the minimum lift time after the lift.
+ * A caller may pass the minimum it plays; the table's measured one by
+ * default.
+ */
+export function settleTime(
+ releaseTime: number,
+ liftTime: number,
+ minimumLiftMs: number = switchControl.minimumLiftMs,
+): number {
+ return Math.max(releaseTime, liftTime + minimumLiftMs);
+}
diff --git a/packages/core/src/Switch/useSwitchTouch.test.ts b/packages/core/src/Switch/useSwitchTouch.test.ts
new file mode 100644
index 0000000000..c8b2b3e44f
--- /dev/null
+++ b/packages/core/src/Switch/useSwitchTouch.test.ts
@@ -0,0 +1,238 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useSwitchTouch.test.ts
+ * @input vitest (jsdom), useSwitchTouch.ts's controller, and a recording
+ * stand-in for the compositor animator
+ * @output Unit tests for what Switch's touch presentation asks the animator
+ * to do: a value change mid-fade swaps the colour layer on its running
+ * clock (a rebase), never from rest
+ * @position Testing; the controller's calls, without a browser. The motion
+ * itself is proven in __tests__/Switch.interaction.browser.spec.ts and on
+ * the iOS simulator
+ *
+ * SYNC: useSwitchTouch.ts.
+ */
+
+import {afterEach, describe, expect, it, vi} from 'vitest';
+
+import type * as AnimatorModule from '../motion/animator';
+
+interface Call {
+ readonly name: string;
+ readonly args: unknown[];
+}
+
+interface FakeAnimator {
+ readonly element: Element;
+ readonly pseudoElement: string | undefined;
+ readonly calls: Call[];
+ readonly values: Record<string, number>;
+ readonly velocities: Record<string, number>;
+ /** `atRest` callers, resolved by the test (the fade landing). */
+ readonly rest: (() => void)[];
+}
+
+const animators: FakeAnimator[] = [];
+
+vi.mock('../motion/animator', async importOriginal => {
+ const actual = await importOriginal<typeof AnimatorModule>();
+ return {
+ ...actual,
+ createAnimator: (
+ element: Element,
+ options: {pseudoElement?: string} = {},
+ ) => {
+ const fake: FakeAnimator = {
+ element,
+ pseudoElement: options.pseudoElement,
+ calls: [],
+ values: {},
+ velocities: {},
+ rest: [],
+ };
+ animators.push(fake);
+ const record =
+ (name: string) =>
+ (...args: unknown[]) => {
+ fake.calls.push({name, args});
+ // The browser has not started the motion within a test.
+ return {
+ finished: Promise.resolve(),
+ started: new Promise<number>(() => {}),
+ };
+ };
+ return {
+ element,
+ get: (property: string) => fake.values[property] ?? 0,
+ getVelocity: (property: string) => fake.velocities[property] ?? 0,
+ set: record('set'),
+ animate: record('animate'),
+ play: record('play'),
+ rebase: record('rebase'),
+ decay: record('decay'),
+ stop: record('stop'),
+ atRest: async () =>
+ new Promise<void>(resolve => {
+ fake.rest.push(resolve);
+ }),
+ reducedMotion: () => 'off',
+ dispose: () => {},
+ };
+ },
+ };
+});
+
+const {SwitchTouchController} = await import('./useSwitchTouch');
+const {switchTouchGeometry} = await import('./switchTouch');
+const {trackStateOf} = await import('./switchFill');
+
+function mount() {
+ // The theme's two fills, as the track's classes paint them.
+ const style = document.createElement('style');
+ style.textContent =
+ '.off { background-color: rgb(212, 212, 212) } .on { background-color: rgb(27, 27, 27) }';
+ document.head.append(style);
+ const surface = document.createElement('div');
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ const track = document.createElement('div');
+ track.className = 'off';
+ const thumb = document.createElement('div');
+ track.append(thumb);
+ surface.append(input, track);
+ document.body.append(surface);
+ const controller = new SwitchTouchController(
+ false,
+ switchTouchGeometry(40, 24),
+ );
+ controller.setOtherTrack(trackStateOf({className: 'on'}));
+ controller.attach({surface, input, thumb, track}, 'touch');
+ const fade = animators.find(
+ animator =>
+ animator.element === track && animator.pseudoElement === '::after',
+ );
+ if (fade == null) {
+ throw new Error('no colour layer animator');
+ }
+ return {controller, fade, track};
+}
+
+/** The value the app renders: the track's class, then the controller. */
+function render(
+ controller: InstanceType<typeof SwitchTouchController>,
+ track: HTMLElement,
+ isOn: boolean,
+) {
+ track.className = isOn ? 'on' : 'off';
+ controller.setOtherTrack(trackStateOf({className: isOn ? 'off' : 'on'}));
+ controller.setValue(isOn);
+}
+
+/** Where the visuals head, as a release or a drag that flipped leaves it. */
+function headTo(
+ controller: InstanceType<typeof SwitchTouchController>,
+ isOn: boolean,
+) {
+ (controller as unknown as {isVisuallyOn: boolean}).isVisuallyOn = isOn;
+}
+
+const flush = async () => {
+ for (let i = 0; i < 3; i++) {
+ await Promise.resolve();
+ }
+};
+
+afterEach(() => {
+ animators.length = 0;
+ document.body.innerHTML = '';
+ document.head.innerHTML = '';
+});
+
+describe('the colour layer when the value changes', () => {
+ it('swaps on its running clock mid-fade when the visuals were not heading there: a rebase to the complement, never a set from rest', () => {
+ const {controller, fade} = mount();
+ // Mid-fade toward the other side: 0.3 of the other fill, rising.
+ fade.values.opacity = 0.3;
+ fade.velocities.opacity = 2;
+ fade.calls.length = 0;
+ controller.setValue(true);
+ // A set would end the running fade and start the swapped curve from rest,
+ // at the frame that commits it. A long task in that frame would make the
+ // track step back toward the fill it left.
+ expect(
+ fade.calls.filter(
+ call =>
+ call.name === 'set' &&
+ 'opacity' in (call.args[0] as Record<string, number>),
+ ),
+ ).toEqual([]);
+ const rebase = fade.calls.find(call => call.name === 'rebase');
+ expect(rebase?.args[0]).toEqual({opacity: expect.closeTo(0.4, 9)});
+ // The swapped curve continues from the swap, its velocity mirrored, and
+ // the layer ends clear. Neither carries a start of its own. The animator
+ // starts a curve that continues motion at the call, never before or after
+ // the frame on screen.
+ const animates = fade.calls.filter(call => call.name === 'animate');
+ expect(animates.length).toBeGreaterThan(0);
+ const [first] = animates;
+ expect((first.args[1] as {velocity?: unknown}).velocity).toEqual({
+ opacity: -2,
+ });
+ expect((rebase?.args[1] as {at?: number} | undefined)?.at).toBeUndefined();
+ for (const call of animates) {
+ expect((call.args[2] as {at?: number} | undefined)?.at).toBeUndefined();
+ }
+ expect(animates[animates.length - 1].args[0]).toEqual({opacity: 0});
+ });
+
+ it('holds the previous fill when the fade already heads to the change: no curve and no repaint in its frame', async () => {
+ const {controller, fade, track} = mount();
+ headTo(controller, true);
+ // Mid-fade toward on: 0.6 of the on fill, rising.
+ fade.values.opacity = 0.6;
+ fade.velocities.opacity = 1.5;
+ fade.calls.length = 0;
+ render(controller, track, true);
+ // The track keeps the off fill under the layer; the running fade is
+ // left alone. WebKit would play a curve built in a frame a long task
+ // holds from its start once the task ends (iOS 26.2).
+ expect(track.style.backgroundColor).toBe('rgb(212, 212, 212)');
+ expect(fade.calls).toEqual([]);
+ expect(fade.rest.length).toBe(1);
+ // The fade lands (opaque): the swap happens under it.
+ fade.values.opacity = 1;
+ fade.velocities.opacity = 0;
+ fade.rest[0]();
+ await flush();
+ expect(track.style.backgroundColor).toBe('');
+ const rebase = fade.calls.find(call => call.name === 'rebase');
+ expect(rebase?.args[0]).toEqual({opacity: -1});
+ const animates = fade.calls.filter(call => call.name === 'animate');
+ expect(animates[animates.length - 1]?.args[0]).toEqual({opacity: 0});
+ });
+
+ it('lands a held fill early, keeping the picture, when the next change or a new other state comes first', async () => {
+ const {controller, fade, track} = mount();
+ headTo(controller, true);
+ fade.values.opacity = 0.6;
+ render(controller, track, true);
+ expect(track.style.backgroundColor).toBe('rgb(212, 212, 212)');
+ // A re-render with the same other state keeps the hold.
+ controller.setOtherTrack(trackStateOf({className: 'off'}));
+ expect(track.style.backgroundColor).toBe('rgb(212, 212, 212)');
+ // A new other state (a theme or a state class changed) lands it now: the
+ // layer swaps to the complement where it is.
+ fade.calls.length = 0;
+ controller.setOtherTrack(trackStateOf({className: 'off', 'data-x': ''}));
+ expect(track.style.backgroundColor).toBe('');
+ expect(fade.calls.find(call => call.name === 'rebase')?.args[0]).toEqual({
+ opacity: expect.closeTo(-0.2, 9),
+ });
+ // Its late landing changes nothing.
+ fade.calls.length = 0;
+ fade.rest[0]();
+ await flush();
+ expect(fade.calls).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Switch/useSwitchTouch.ts b/packages/core/src/Switch/useSwitchTouch.ts
new file mode 100644
index 0000000000..42e92420c3
--- /dev/null
+++ b/packages/core/src/Switch/useSwitchTouch.ts
@@ -0,0 +1,1117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useSwitchTouch.ts
+ * @input Switch's parts (gesture surface, input, thumb and track), its value,
+ * whether it is interactive, the track's other state (switchFill.ts) and
+ * the thumb geometry (switchTouch.ts)
+ * @output Exports useSwitchTouch: Switch's gestures for a mouse, a pen and a
+ * finger, and its touch presentation under a coarse primary pointer
+ * @position DOM half of Switch's touch presentation, on the gesture system
+ * (../gestures) and the compositor animator (../motion/animator)
+ *
+ * SYNC: When modified, update switchTouch.ts, Switch.tsx
+ * and __tests__/Switch.interaction.browser.spec.ts.
+ */
+
+import {useMemo, useState, type RefObject} from 'react';
+import {getGestureHost} from '../gestures/GestureHost';
+import {createPressTracker, type ControlEvent} from '../gestures/PressTracker';
+import type {GestureTouch} from '../gestures/types';
+import {isRtlElement} from '../hooks/isRtlElement';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {
+ createAnimator,
+ type Animator,
+ type MotionCurve,
+} from '../motion/animator';
+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 {
+ BROWSER_CLICK_WAIT_MS,
+ commitOnRelease,
+ dragTarget,
+ settleTime,
+ startFlip,
+ stepFlip,
+ switchTouchGeometry,
+ type SwitchFlip,
+ type SwitchTouchGeometry,
+} from './switchTouch';
+import {
+ readFillOf,
+ sameTrackState,
+ trackStateOf,
+ type TrackState,
+} from './switchFill';
+
+export interface SwitchTouchParts {
+ /** Receives the touches: the input and the track. */
+ readonly surface: RefObject<HTMLElement | null>;
+ readonly input: RefObject<HTMLInputElement | null>;
+ /** Moves: the themed thumb itself. */
+ readonly thumb: RefObject<HTMLElement | null>;
+ /**
+ * The track: its `::after` is the fade layer over its own fill, showing
+ * the fill it is leaving or heading to (switchFill.ts).
+ */
+ readonly track: RefObject<HTMLElement | null>;
+}
+
+export interface SwitchTouchOptions {
+ readonly isOn: boolean;
+ /** False while disabled or busy: no touch is tracked. */
+ readonly isInteractive: boolean;
+ /**
+ * Disabled: the touch presentation is off and attaches nothing. A
+ * busy switch stays attached, so a change that starts a busy state still
+ * plays its release motion.
+ */
+ readonly isDisabled: boolean;
+ /** The track's box, px (width × height): the thumb geometry's scale. */
+ readonly trackSize: readonly [number, number];
+ /**
+ * The props the track renders with in its other state (its theme target
+ * and fill), for the fade layer's colour.
+ */
+ readonly otherTrackProps: object;
+}
+
+/** The fade layer's colour, set on the track for its ::after (Switch.tsx). */
+const FADE_FILL = '--_switch-fade-fill';
+/** The track's own fill while a change is held (inline, over its CSS). */
+const BASE_FILL = 'background-color';
+const TRAVEL = switchControl.travel;
+const TRACKING = switchControl.tracking;
+/**
+ * Horizontal travel at which the press begins if it has not (a pan
+ * begins here), px.
+ */
+const PAN_HYSTERESIS = UIKIT_GESTURES.pan.hysteresis.value;
+
+function now(): number {
+ return typeof performance === 'undefined' ? Date.now() : performance.now();
+}
+
+/**
+ * The lift spring until `holdSeconds`, then the settle spring from where the
+ * lift got to. It is one curve, so the settle starts on the compositor's
+ * clock.
+ */
+function liftThenSettle({
+ from,
+ velocity,
+ lifted,
+ rest,
+ holdSeconds,
+ threshold,
+ lift,
+ settle,
+}: {
+ from: number;
+ velocity: number;
+ lifted: number;
+ rest: number;
+ holdSeconds: number;
+ threshold: number;
+ /** The lift and settle springs as the theme sets them. */
+ lift: SpringDescription;
+ settle: SpringDescription;
+}): MotionCurve {
+ const hold = Math.max(0, holdSeconds);
+ const first = solveSpring(toSpring(lift), {from, to: lifted, velocity});
+ const second = solveSpring(toSpring(settle), {
+ from: first.value(hold),
+ to: rest,
+ velocity: first.velocity(hold),
+ });
+ return {
+ duration: hold + second.settleTime(threshold),
+ at: t => (t < hold ? first.value(t) : second.value(t - hold)),
+ velocity: t => (t < hold ? first.velocity(t) : second.velocity(t - hold)),
+ };
+}
+
+/**
+ * The switch's presentation: the touch presentation under a coarse primary
+ * pointer, or its own under a fine one.
+ */
+type SwitchPresentation = 'touch' | 'pointer';
+
+interface Elements {
+ surface: HTMLElement;
+ input: HTMLInputElement;
+ thumb: HTMLElement;
+ track: HTMLElement;
+}
+
+interface Drag {
+ /** The thumb's offset when the finger landed. */
+ readonly start: number;
+ flip: SwitchFlip;
+}
+
+/**
+ * The touch presentation of one switch: animators, recognizers and the
+ * gesture state. No React state: a gesture never renders. UISwitch on iOS
+ * 26.2 is the reference; every number is in motion/uikit/switch.ts.
+ *
+ * - The thumb's resting place is CSS (its inline-start inset). So the steady
+ * state needs no script and mirrors under RTL by itself. The animator only
+ * moves the thumb by a delta from that place (`translate`). When the value
+ * moves the CSS place, the delta is rebased in the same layout effect.
+ * Nothing moves on screen, and the velocity is kept.
+ * - Touches go to a press tracker, which never blocks a scroll. No
+ * recognizer claims the touch. `touch-action: pan-y` (Switch.tsx) keeps
+ * horizontal moves for the switch: a drag follows and flips it, and the
+ * release commits. A vertical drag is the page's scroll, and the switch
+ * yields.
+ * - A tap, a hold or a short drag activates through the browser's own click.
+ * The browser sends no click for a finger's hold, so the switch clicks its
+ * input once the click window passes. A mouse or a pen gets a click when
+ * it is released on the input. A drag that flipped the switch gets no
+ * click, so the switch clicks its input, and the shared click guard
+ * swallows the browser's late click. A finger's press slid off and lifted
+ * outside toggles too, as UISwitch's does. Forms, `onChange` and the
+ * keyboard stay the native checkbox's.
+ * - The drag never renders: each move retargets the thumb's tracking spring
+ * and steps the flip rule on the finger's travel.
+ * - The thumb lifts while a finger presses, into half of the gap around it,
+ * and its shadow fades in. At the release it settles back, no sooner than
+ * the minimum lift time. The lift and the settle are one curve, built at
+ * the release, so the settle starts on time on the compositor.
+ * - The track keeps its own fill in both states. A fade layer over it,
+ * painted with the track's other fill, fades the colour on the compositor.
+ * When the value changes, the layer swaps to the other fill and to the
+ * complement of its opacity. So nothing changes on screen. A change the
+ * fade already heads to swaps nothing: the track holds its previous fill
+ * inline until the fade lands. WebKit plays a curve built in a held frame
+ * only once the long task ends, so a swap there stepped the colour back.
+ * The layer is composited from the start (`will-change`, Switch.tsx), or
+ * iOS Safari runs its fade on the main thread.
+ * - Under reduced motion nothing travels or springs: a change plays the
+ * animator's Reduce Motion cross-fade. A dragging finger still moves the
+ * thumb: that is direct manipulation.
+ * - Under a fine primary pointer the switch keeps its own look. The same
+ * tracking, flip rule and release decide the value, with no animator, and
+ * the thumb moves when the value does. Only its press listens at rest. Its
+ * click listener comes with a press.
+ */
+export class SwitchTouchController {
+ private elements: Elements | null = null;
+ private geometry: SwitchTouchGeometry;
+ private isOn: boolean;
+ private isInteractive = true;
+ /** The side the visuals show or head to. */
+ private isVisuallyOn: boolean;
+ /** +1 left-to-right, −1 right-to-left. */
+ private direction = 1;
+ private thumb: Animator | null = null;
+ /** The fade layer: its opacity is how far the visuals are from the value. */
+ private fade: Animator | null = null;
+ /** The lifted shadow: the thumb's `::after`, faded in with the lift. */
+ private shadow: Animator | null = null;
+ /** When the thumb lifted (document timeline, ms); null while at rest. */
+ private liftTime: number | null = null;
+ /** When the running settle leaves the lift (settleTime), ms. */
+ private settleAt: number | null = null;
+ private otherTrack: TrackState | null = null;
+ /**
+ * A change landed mid-fade, and the fade already heads to it. The track's
+ * own fill stays the previous value's (inline) until the fade lands. So the
+ * change's frame builds no curve and repaints nothing. `baseHold` counts
+ * holds, so a settled one ignores its late landing.
+ */
+ private baseHeld = false;
+ private baseHold = 0;
+ private detachers: (() => void)[] = [];
+ /** When the press began (document timeline, ms); null with no press. */
+ private pressTime: number | null = null;
+ /** The thumb's offset when the current finger landed. */
+ private downOffset = 0;
+ private drag: Drag | null = null;
+ /** The finger's last travel along x, for a lift that reports none. */
+ private lastTravel = 0;
+ /**
+ * The press and the pan both report every touch event; the first report
+ * takes the step and this skips the second (cleared after the event).
+ */
+ private isStepping = false;
+ /** The current touch already ended in a release. */
+ private released = false;
+ /**
+ * Reduced motion: a release changed the value. The thumb's travel waits for
+ * the value to commit, so its one cross-fade lands in the new frame.
+ */
+ private pendingTravel = false;
+ /** Passive: a finger is down on the switch. */
+ 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;
+ private reconcileTimer: ReturnType<typeof setTimeout> | null = null;
+
+ constructor(isOn: boolean, geometry: SwitchTouchGeometry) {
+ this.isOn = isOn;
+ this.isVisuallyOn = isOn;
+ this.geometry = geometry;
+ }
+
+ get isAttached(): boolean {
+ return this.elements != null;
+ }
+
+ attach(elements: Elements, presentation: SwitchPresentation): void {
+ this.detach();
+ this.elements = elements;
+ this.presentation = presentation;
+ this.measureGeometry();
+ this.direction = isRtlElement(elements.surface) ? -1 : 1;
+ this.isVisuallyOn = this.isOn;
+ const host = getGestureHost(elements.surface.ownerDocument);
+ if (presentation === 'pointer') {
+ // The switch's own look: the gestures decide the value and the CSS
+ // shows it.
+ this.detachers = this.attachPassive(host, elements);
+ return;
+ }
+ registerSwitchTable();
+ this.thumb = createAnimator(elements.thumb);
+ // The layer rests clear (its class's opacity 0) while the visuals show
+ // the value; from here its opacity is the animator's.
+ this.fade = createAnimator(elements.track, {
+ pseudoElement: '::after',
+ initial: {opacity: 0},
+ });
+ this.fade.set({opacity: 0});
+ this.shadow = createAnimator(elements.thumb, {
+ pseudoElement: '::after',
+ initial: {opacity: 0},
+ });
+ this.shadow.set({opacity: 0});
+ this.paintFade();
+ this.detachers = this.attachPassive(host, elements);
+ }
+
+ /**
+ * Passive: UIControl's tracking, which never blocks a scroll. The press
+ * begins with the touch, or with the first horizontal move a pan would
+ * begin on. Inside a scroller the touch waits for the content delay. Every
+ * move steps the flip rule, and the release commits. A touch the browser
+ * takes for its scroll yields with no toggle.
+ */
+ private attachPassive(
+ host: ReturnType<typeof getGestureHost>,
+ elements: Elements,
+ ): (() => void)[] {
+ const {surface} = elements;
+ const tracker = createPressTracker({
+ view: surface,
+ getBounds: () => surface.getBoundingClientRect(),
+ isEnabled: () => this.isInteractive,
+ isBraking: () => host.isScrollBraking(surface),
+ // A held switch opens no menu (UISwitch shows none).
+ holdsContextMenu: () => this.pressTime != null,
+ onControlEvent: (event, touch) => this.onControlEvent(event, touch),
+ onHighlightChange: isHighlighted => {
+ if (isHighlighted && this.isTracking && this.pressTime == null) {
+ this.pressBegan(now());
+ }
+ },
+ });
+ // 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;
+ }
+
+ /** Undo everything: listeners, timers, animations and inline styles. */
+ detach(): void {
+ for (const detach of this.detachers) {
+ detach();
+ }
+ this.detachers = [];
+ this.listenForPress = null;
+ this.clearTimers();
+ for (const animator of [this.thumb, this.fade, this.shadow]) {
+ const element = animator?.element;
+ animator?.dispose();
+ if (element != null) {
+ for (const property of ['translate', 'scale', 'opacity']) {
+ element.style.removeProperty(property);
+ }
+ }
+ }
+ this.elements?.track.style.removeProperty(FADE_FILL);
+ this.elements?.track.style.removeProperty(BASE_FILL);
+ this.baseHeld = false;
+ this.baseHold++;
+ this.thumb = this.fade = this.shadow = null;
+ this.liftTime = null;
+ this.elements = null;
+ this.pressTime = null;
+ this.drag = null;
+ this.isTracking = false;
+ }
+
+ setInteractive(isInteractive: boolean): void {
+ this.isInteractive = isInteractive;
+ if (!isInteractive && this.pressTime != null) {
+ this.abandon(now());
+ }
+ }
+
+ /** The track's other state, re-rendered with each value. */
+ setOtherTrack(otherTrack: TrackState): void {
+ const previous = this.otherTrack;
+ this.otherTrack = otherTrack;
+ // A held fill was read from the previous other state; a re-render that
+ // keeps it keeps the hold.
+ if (this.baseHeld && !sameTrackState(previous, otherTrack)) {
+ this.landBase(now());
+ }
+ }
+
+ setGeometry(geometry: SwitchTouchGeometry): void {
+ this.geometry = geometry;
+ this.measureGeometry();
+ this.thumb?.set({x: 0, scaleX: 1, scaleY: 1});
+ }
+
+ /**
+ * The thumb geometry from the rendered boxes. The track's box lets a theme
+ * resize the track. The thumb's box is the circle of the current value. It
+ * rests by insets from the track's padding box, so padding does not move it.
+ */
+ private measureGeometry(): void {
+ const track = this.elements?.track;
+ const thumb = this.elements?.thumb;
+ if (track == null) {
+ return;
+ }
+ // Fractional boxes: the track's border box less its border (it has no
+ // transform). The thumb's used size comes from its computed style, which
+ // its scale does not change.
+ const box = track.getBoundingClientRect();
+ const trackWidth = box.width - 2 * track.clientLeft;
+ const trackHeight = box.height - 2 * track.clientTop;
+ if (trackWidth <= 0 || trackHeight <= 0) {
+ return;
+ }
+ const style = thumb == null ? null : getComputedStyle(thumb);
+ const thumbWidth = style == null ? NaN : parseFloat(style.width);
+ const thumbHeight = style == null ? NaN : parseFloat(style.height);
+ this.geometry = switchTouchGeometry(
+ trackWidth,
+ trackHeight,
+ thumbWidth > 0 && thumbHeight > 0
+ ? {width: thumbWidth, height: thumbHeight}
+ : undefined,
+ );
+ }
+
+ /**
+ * The rendered value changed. The CSS has already moved the thumb's
+ * resting place. So the thumb's delta is rebased first, and nothing moves on
+ * screen. Then the visuals head for the new value.
+ */
+ setValue(isOn: boolean): void {
+ if (isOn === this.isOn) {
+ return;
+ }
+ const previous = this.isOn;
+ this.isOn = isOn;
+ const thumb = this.thumb;
+ if (thumb == null) {
+ this.isVisuallyOn = isOn;
+ return;
+ }
+ const time = now();
+ // The thumb's CSS rest moved with the value: shift it back by as much,
+ // so nothing moves on screen. A spring keeps its target through the shift
+ // and is sent to the new rest below. A reduced-motion dip shifts whole,
+ // its end included, and keeps going.
+ const springs = thumb.reducedMotion() === 'off';
+ thumb.rebase({
+ x: this.direction * (this.rest(previous) - this.rest(isOn)),
+ });
+ // Each state has its own thumb size, the circle a mouse sees. The box the
+ // CSS now renders is the new value's. Its scale takes the old size over
+ // and grows or shrinks it from there.
+ const before = this.geometry;
+ this.measureGeometry();
+ if (springs) {
+ this.rescaleThumb(before, this.geometry, time);
+ }
+ // The track now shows the new value's fill. The fade layer swaps to the
+ // other fill and to the complement of its opacity. Nothing changes on
+ // screen, and the fade keeps heading where the visuals head.
+ const fade = this.fade;
+ if (fade != null) {
+ this.landBase(time);
+ // Already heading here (a release, a drag that flipped). The running
+ // fade carries the change over the previous fill, held as the track's
+ // own until it lands. WebKit plays a curve built in a held frame only
+ // once the long task ends. A swap here would step the colour back.
+ if (this.isVisuallyOn !== isOn || !this.holdBase()) {
+ this.swapFade(time);
+ }
+ }
+ const wasDragging = this.drag != null && !this.released;
+ if (wasDragging) {
+ // The app changed the value mid-gesture: the value wins and the
+ // gesture ends without committing.
+ this.drag = null;
+ this.released = true;
+ this.pressEnded();
+ }
+ // A release already sent the visuals here. Any other change, the app's or
+ // one mid-gesture, sends them now, and a spring heads for the new rest.
+ if (
+ springs ||
+ wasDragging ||
+ this.pendingTravel ||
+ this.isVisuallyOn !== isOn
+ ) {
+ const touchRelease = this.pendingTravel;
+ this.pendingTravel = false;
+ this.showSide(isOn, time, thumb.getVelocity('x', time), touchRelease);
+ }
+ }
+
+ // --- Touches ---------------------------------------------------------------
+
+ private touchDown(time: number): void {
+ this.landBase(time);
+ this.released = false;
+ this.pendingTravel = false;
+ this.drag = null;
+ this.lastTravel = 0;
+ this.downOffset = this.offsetAt(time);
+ }
+
+ /** Passive: a mouse, a pen or a finger on the switch, UIControl's events. */
+ private onControlEvent(event: ControlEvent, touch: GestureTouch): void {
+ const travel = touch.x - touch.startX;
+ // The switch reads the thumb when it handles the event. Its motion has no
+ // start of its own. A call that continues motion starts then, from the
+ // curve on screen. A call from rest starts at the frame that shows it, as
+ // Core Animation starts an animation at its commit. A busy main thread
+ // hands the switch an event late and commits its frame late. The motion
+ // is delayed, never stepped back or skipped into. The event's own time is
+ // the recognizers'.
+ const time = now();
+ switch (event) {
+ case 'touchDown':
+ this.isTracking = true;
+ this.startPressListeners();
+ this.touchDown(time);
+ return;
+ case 'touchDragInside':
+ case 'touchDragOutside':
+ if (this.released || !this.isInteractive) {
+ return;
+ }
+ if (this.pressTime == null) {
+ if (Math.abs(travel) < PAN_HYSTERESIS) {
+ return;
+ }
+ // A pan would begin here: the switch takes the horizontal drag.
+ this.pressBegan(time);
+ }
+ this.move(time, travel);
+ return;
+ case 'touchUpInside':
+ case 'touchUpOutside':
+ this.isTracking = false;
+ if (this.released || !this.isInteractive) {
+ return;
+ }
+ // The finger's lift is a step of its own: a flip armed by the last
+ // move happens here (a fast swipe flips on the lift).
+ this.move(time, travel);
+ if (this.drag?.flip.didFlip !== true && event === 'touchUpInside') {
+ // A tap, a hold or a short drag: the browser's click activates it.
+ // Only a finger's lift can come with no click (a hold). A mouse or a
+ // pen gets one whenever it is released on the input. With no click,
+ // it was released off the input, inside the tracking slop. The
+ // switch is then left alone, as the native checkbox is.
+ this.release(time, {
+ byBrowserClick: true,
+ clicksIfNoBrowserClick: touch.pointerType === 'touch',
+ });
+ this.endPressListeners(BROWSER_CLICK_WAIT_MS);
+ return;
+ }
+ if (this.drag?.flip.didFlip !== true && touch.pointerType !== 'touch') {
+ // A mouse or a pen slid off and released outside, with no flip:
+ // the switch is left alone, as the native checkbox is. Only a
+ // finger's press slid 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
+ // toggles as UISwitch's does. The switch decides this lift itself, so
+ // the shared click guard swallows the browser's click, if one comes.
+ // A drag back past the press commits nothing, and its click must not
+ // toggle either.
+ if (this.elements != null) {
+ 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
+ // took it: the switch yields.
+ this.isTracking = false;
+ if (!this.released) {
+ this.released = true;
+ this.abandon(time);
+ }
+ this.endPressListeners(0);
+ return;
+ case 'touchDragEnter':
+ case 'touchDragExit':
+ return;
+ }
+ }
+
+ /**
+ * One touch event of a held or dragged switch. It retargets the thumb at the
+ * finger (one style write) and steps the flip rule.
+ */
+ private move(time: number, travel: number | null): void {
+ const thumb = this.thumb;
+ if (this.isStepping) {
+ return;
+ }
+ this.isStepping = true;
+ queueMicrotask(() => {
+ this.isStepping = false;
+ });
+ const x = this.direction * (travel ?? this.lastTravel);
+ this.lastTravel = travel ?? this.lastTravel;
+ const drag = (this.drag ??= {
+ start: this.downOffset,
+ flip: startFlip(this.isOn),
+ });
+ // The thumb under the finger is direct manipulation, which reduced
+ // motion leaves alone. Under it the thumb is placed at once: the animator
+ // would cross-fade a move. Under a fine pointer nothing follows the
+ // pointer. The switch keeps its own look, and the value moves the thumb.
+ if (thumb != null) {
+ const target = this.toX(dragTarget(drag.start, x, this.geometry));
+ if (thumb.reducedMotion() === 'off') {
+ thumb.animate({x: target}, {spring: TRACKING});
+ } else {
+ thumb.set({x: target});
+ }
+ }
+ drag.flip = stepFlip(drag.flip, x, this.geometry);
+ if (drag.flip.isVisuallyOn !== this.isVisuallyOn) {
+ this.showWell(drag.flip.isVisuallyOn, time);
+ }
+ }
+
+ /**
+ * The finger lifted after a tap, a hold or a drag. `byBrowserClick`: the
+ * browser's own click activates the input, and the switch clicks it only
+ * if that click never comes.
+ */
+ private release(
+ time: number,
+ {
+ byBrowserClick = false,
+ clicksIfNoBrowserClick = true,
+ }: {byBrowserClick?: boolean; clicksIfNoBrowserClick?: boolean} = {},
+ ): void {
+ if (this.released) {
+ return;
+ }
+ this.released = true;
+ this.clearTimers();
+ const commit = commitOnRelease(this.drag?.flip ?? null, this.isOn);
+ this.drag = null;
+ if (this.pressTime == null) {
+ // A tap quicker than a scroller's content delay: the press begins now.
+ this.pressBegan(time);
+ }
+ if (
+ commit !== this.isOn &&
+ this.thumb != null &&
+ this.thumb.reducedMotion({touchRelease: true}) !== 'off'
+ ) {
+ // Under reduced motion the travel is one cross-fade, played when the
+ // value commits (setValue). It lands in the new value's frame. The
+ // colour starts now.
+ this.pendingTravel = true;
+ this.showWell(commit, time, true);
+ } else {
+ 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);
+ return;
+ }
+ if (commit !== this.isOn) {
+ // No click comes from the browser for this lift; the input's own click
+ // keeps every native path (form value, onChange, the label).
+ this.clickInput();
+ }
+ this.scheduleReconcile();
+ }
+
+ /**
+ * The switch's own click on its input. The shared click guard then swallows
+ * the browser's late click for the same lift, so the switch toggles once.
+ */
+ private clickInput(): void {
+ const input = this.elements?.input;
+ if (input == null) {
+ return;
+ }
+ armClickGuard(input.ownerDocument);
+ withoutClickGuard(() => input.click());
+ }
+
+ /** If the owner kept the old value, the visuals go back to it. */
+ private scheduleReconcile(): void {
+ if (this.reconcileTimer != null) {
+ clearTimeout(this.reconcileTimer);
+ }
+ this.reconcileTimer = setTimeout(() => {
+ this.reconcileTimer = null;
+ if (this.drag == null && this.isVisuallyOn !== this.isOn) {
+ this.pendingTravel = false;
+ this.showSide(this.isOn, now(), undefined, true);
+ }
+ }, 0);
+ }
+
+ /** The touch ended without a release (cancelled, or the switch turned off). */
+ private abandon(time: number): void {
+ this.drag = null;
+ this.showSide(this.isOn, time, undefined, true);
+ this.pressEnded(time, true);
+ }
+
+ // --- Visuals ---------------------------------------------------------------
+
+ private rest(isOn: boolean): number {
+ return isOn ? this.geometry.travel : 0;
+ }
+
+ /** The animator's x for a thumb offset, relative to its CSS place. */
+ private toX(offset: number): number {
+ return this.direction * (offset - this.rest(this.isOn));
+ }
+
+ /** The thumb's offset on screen at `time`, from the curve. */
+ private offsetAt(time: number): number {
+ const x = this.thumb?.get('x', time) ?? 0;
+ return this.rest(this.isOn) + this.direction * x;
+ }
+
+ private showWell(isOn: boolean, time: number, touchRelease = false): void {
+ this.isVisuallyOn = isOn;
+ this.paintFade();
+ this.animateFade(time, undefined, touchRelease);
+ }
+
+ /**
+ * The fade layer heads for the visuals, on UIKit's well springs (on:
+ * 0.68 s, off: 0.40 s). It is clear when they show the value. It is opaque,
+ * the other fill, when they show the other side.
+ */
+ private animateFade(
+ time: number,
+ velocity?: number,
+ touchRelease = false,
+ ): void {
+ // Under reduced motion the animator plays this as its cross-fade.
+ this.fade?.animate(
+ {opacity: this.isVisuallyOn === this.isOn ? 0 : 1},
+ {
+ spring: this.isVisuallyOn
+ ? switchControl.wellOn
+ : switchControl.wellOff,
+ velocity: velocity == null ? undefined : {opacity: velocity},
+ },
+ {touchRelease},
+ );
+ }
+
+ /**
+ * The track now shows the new value's fill. The fade layer swaps to the
+ * other fill and to the complement of its opacity, so nothing changes on
+ * screen. It keeps heading where the visuals head, on the running clock.
+ */
+ private swapFade(time: number): void {
+ const fade = this.fade;
+ if (fade == null) {
+ return;
+ }
+ const opacity = fade.get('opacity', time);
+ const fadeVelocity = fade.getVelocity('opacity', time);
+ this.paintFade();
+ fade.rebase({opacity: 1 - 2 * opacity});
+ this.animateFade(time, -fadeVelocity);
+ }
+
+ /**
+ * Holds the track's own fill at the previous value's (the other state's,
+ * now) until the fade lands. False when there is nothing to read it from.
+ */
+ private holdBase(): boolean {
+ const track = this.elements?.track;
+ const fade = this.fade;
+ if (track == null || fade == null || this.otherTrack == null) {
+ return false;
+ }
+ track.style.setProperty(BASE_FILL, readFillOf(track, this.otherTrack));
+ this.baseHeld = true;
+ const hold = ++this.baseHold;
+ void fade.atRest(['opacity']).then(() => {
+ if (hold === this.baseHold) {
+ this.landBase(now());
+ }
+ });
+ return true;
+ }
+
+ /**
+ * Ends a held fill: the track shows its value's fill again and the fade
+ * layer swaps under it. Once the fade has landed, the layer is opaque and
+ * nothing changes on screen. Called early, by a new touch, value or other
+ * state, the swap keeps the picture where it is.
+ */
+ private landBase(time: number): void {
+ if (!this.baseHeld) {
+ return;
+ }
+ this.baseHeld = false;
+ this.baseHold++;
+ this.elements?.track.style.removeProperty(BASE_FILL);
+ this.swapFade(time);
+ }
+
+ /** The fade layer's colour: the track's fill in its other state. */
+ private paintFade(): void {
+ const track = this.elements?.track;
+ if (track == null || this.fade == null || this.otherTrack == null) {
+ return;
+ }
+ track.style.setProperty(FADE_FILL, readFillOf(track, this.otherTrack));
+ }
+
+ /** Track color and thumb head for one side. */
+ private showSide(
+ isOn: boolean,
+ time: number,
+ velocity?: number,
+ touchRelease = false,
+ ): void {
+ if (isOn !== this.isVisuallyOn) {
+ this.showWell(isOn, time, touchRelease);
+ }
+ // Under reduced motion the animator cross-fades this travel: the thumb
+ // fades out where it is and back in at its rest.
+ this.thumb?.animate(
+ {x: this.toX(this.rest(isOn))},
+ {
+ spring: TRAVEL,
+ velocity: velocity == null ? undefined : {x: velocity},
+ },
+ {touchRelease},
+ );
+ }
+
+ /** The press began: the switch holds the touch and the thumb lifts. */
+ private pressBegan(time: number): void {
+ this.pressTime = time;
+ this.lift(time);
+ }
+
+ /** The press ended (a release, a cancel or the switch turning off). */
+ private pressEnded(time: number = now(), touchRelease = false): void {
+ this.pressTime = null;
+ this.settle(time, touchRelease);
+ }
+
+ /**
+ * The thumb grows about its center into half the gap around it, and its
+ * lifted shadow fades in. Under reduced motion nothing lifts: the lift is
+ * feedback with no fade of its own.
+ */
+ private lift(time: number): void {
+ if (this.thumb == null || this.thumb.reducedMotion() !== 'off') {
+ return;
+ }
+ this.liftTime = time;
+ const lift = this.thumb.animate(
+ {scaleX: this.geometry.liftScaleX, scaleY: this.geometry.liftScaleY},
+ {spring: switchControl.lift},
+ );
+ this.shadow?.animate({opacity: 1}, {spring: switchControl.lift});
+ // A lift from rest starts at the frame that shows it: the minimum lift
+ // counts from there.
+ void lift.started.then(start => {
+ if (this.liftTime === time) {
+ this.liftTime = start;
+ }
+ });
+ }
+
+ /**
+ * The thumb settles back after the press, no sooner than the minimum lift
+ * time after it lifted. One curve per property, built now, starts the
+ * settle on the compositor's clock.
+ */
+ private settle(time: number, touchRelease: boolean): void {
+ const liftTime = this.liftTime;
+ if (liftTime == null) {
+ return;
+ }
+ this.liftTime = null;
+ const lift = switchControl.lift;
+ const settle = switchControl.settle;
+ this.settleAt = settleTime(time, liftTime);
+ const hold = (this.settleAt - time) / 1000;
+ const play = (
+ animator: Animator | null,
+ property: 'scaleX' | 'scaleY' | 'opacity',
+ lifted: number,
+ rest: number,
+ threshold: number,
+ ) => {
+ if (animator == null) {
+ return;
+ }
+ animator.play(
+ {
+ [property]: liftThenSettle({
+ from: animator.get(property, time),
+ velocity: animator.getVelocity(property, time),
+ lifted,
+ rest,
+ holdSeconds: hold,
+ threshold,
+ lift,
+ settle,
+ }),
+ },
+ {touchRelease},
+ );
+ };
+ play(this.thumb, 'scaleX', this.geometry.liftScaleX, 1, 1e-4);
+ play(this.thumb, 'scaleY', this.geometry.liftScaleY, 1, 1e-4);
+ play(this.shadow, 'opacity', 1, 0, 1e-3);
+ }
+
+ /**
+ * The thumb's box changed size with the value: the on circle is larger.
+ * Its scale carries the size it showed, so nothing jumps. Then it heads for
+ * the new box through the settle, or to the lift a held press keeps.
+ */
+ private rescaleThumb(
+ before: SwitchTouchGeometry,
+ after: SwitchTouchGeometry,
+ time: number,
+ ): void {
+ const thumb = this.thumb;
+ if (
+ thumb == null ||
+ !(before.thumbWidth > 0 && before.thumbHeight > 0) ||
+ !(after.thumbWidth > 0 && after.thumbHeight > 0) ||
+ (before.thumbWidth === after.thumbWidth &&
+ before.thumbHeight === after.thumbHeight)
+ ) {
+ return;
+ }
+ const held = this.liftTime != null;
+ const hold =
+ this.settleAt == null ? 0 : Math.max(0, this.settleAt - time) / 1000;
+ for (const [property, factor, lifted] of [
+ ['scaleX', before.thumbWidth / after.thumbWidth, before.liftScaleX],
+ ['scaleY', before.thumbHeight / after.thumbHeight, before.liftScaleY],
+ ] as const) {
+ const keep = lifted * factor;
+ thumb.play({
+ [property]: liftThenSettle({
+ from: thumb.get(property, time) * factor,
+ velocity: thumb.getVelocity(property, time) * factor,
+ lifted: keep,
+ rest: held ? keep : 1,
+ holdSeconds: held ? 0 : hold,
+ threshold: 1e-4,
+ lift: switchControl.lift,
+ settle: switchControl.settle,
+ }),
+ });
+ }
+ }
+
+ private clearTimers(): void {
+ if (this.browserClickTimer != null) {
+ clearTimeout(this.browserClickTimer);
+ this.browserClickTimer = null;
+ }
+ if (this.reconcileTimer != null) {
+ clearTimeout(this.reconcileTimer);
+ this.reconcileTimer = null;
+ }
+ }
+}
+
+/**
+ * Switch's gestures, attached for every pointer, with the touch
+ * presentation under a coarse primary pointer. Its parts
+ * must be rendered (and styled for it) whether or not it is active; it only
+ * animates and listens.
+ */
+export function useSwitchTouch(
+ parts: SwitchTouchParts,
+ {
+ isOn,
+ isInteractive,
+ isDisabled,
+ trackSize,
+ otherTrackProps,
+ }: SwitchTouchOptions,
+): void {
+ const {isTouch} = useTouchPresentation();
+ const [trackWidth, trackHeight] = trackSize;
+ const geometry = useMemo(
+ () => switchTouchGeometry(trackWidth, trackHeight),
+ [trackWidth, trackHeight],
+ );
+ const otherTrack = trackStateOf(otherTrackProps);
+ const [controller] = useState(
+ () => new SwitchTouchController(isOn, geometry),
+ );
+
+ // Syncs the touch controller's animators with the value. It runs first: the
+ // thumb's CSS place and the track's fill have just changed with the value.
+ useIsomorphicLayoutEffect(() => {
+ controller.setOtherTrack(otherTrack);
+ controller.setValue(isOn);
+ });
+
+ // Syncs the controller's thumb geometry with the track's size.
+ useIsomorphicLayoutEffect(() => {
+ controller.setGeometry(geometry);
+ }, [controller, geometry]);
+
+ // Syncs whether the controller's gestures take a press.
+ useIsomorphicLayoutEffect(() => {
+ controller.setInteractive(isInteractive);
+ }, [controller, isInteractive]);
+
+ // Attaches the controller's DOM listeners and animators to the switch's
+ // parts, and detaches them on cleanup.
+ useIsomorphicLayoutEffect(() => {
+ const surface = parts.surface.current;
+ const input = parts.input.current;
+ const thumb = parts.thumb.current;
+ const track = parts.track.current;
+ // A disabled switch takes no press: no listener is active. A busy one
+ // stays attached (setInteractive ignores its presses),
+ // so the change that made it busy keeps its motion.
+ if (
+ isDisabled ||
+ surface == null ||
+ input == null ||
+ thumb == null ||
+ track == null
+ ) {
+ return undefined;
+ }
+ controller.attach(
+ {surface, input, thumb, track},
+ isTouch ? 'touch' : 'pointer',
+ );
+ return () => controller.detach();
+ }, [controller, isTouch, isDisabled, parts]);
+}
diff --git a/packages/core/src/__tests__/pressState.ts b/packages/core/src/__tests__/pressState.ts
index 4e5ee993cd..35e888a6df 100644
--- a/packages/core/src/__tests__/pressState.ts
+++ b/packages/core/src/__tests__/pressState.ts
@@ -6,7 +6,8 @@
* the press machine's release clock (utils/pressGesture.ts)
* @output Exports rulesDeclaredFor, rulesWithSelector, hasPressedArm,
* declaresPressedOverlay, readsPressStrength, afterPaintsPress,
- * pressArmsShadowedByDefault and hasReleaseFade test helpers
+ * pressArmsShadowedByDefault, hasReleaseFade and releasesOnLayer test
+ * helpers
* @position Shared test helper for asserting a control paints a pressed state
*
* jsdom does not compute `:active` (there is no real pointer), so a component
@@ -32,21 +33,56 @@ const PRESS_STRENGTH = '--astryx-press-alpha';
const PRESS_PAINT = '--_press-paint';
const FADING_ARM = '[data-astryx-press="fading"]';
-function walk(list: CSSRuleList, visit: (rule: CSSRule) => void): void {
+const selectorOf = (rule: string) => rule.slice(0, rule.indexOf('{'));
+const onPseudoElement = (rule: string) => selectorOf(rule).includes('::');
+const durationsOf = (rules: string[]) =>
+ rules.flatMap(rule => {
+ const match = rule.match(/animation-duration:\s*([^;}]+)/);
+ return match == null ? [] : [durationToMs(match[1])];
+ });
+const runsAnimation = (rule: string) => /animation-name:\s*(?!none)/.test(rule);
+const stopsAnimation = (rule: string) => /animation-name:\s*none\b/.test(rule);
+
+function walk(
+ list: CSSRuleList,
+ visit: (rule: CSSRule, conditions: string) => void,
+ conditions = '',
+): void {
for (const rule of Array.from(list)) {
- visit(rule);
+ visit(rule, conditions);
const nested = (rule as CSSGroupingRule).cssRules;
if (nested != null) {
- walk(nested, visit);
+ const media = (rule as CSSMediaRule).media?.mediaText ?? '';
+ walk(nested, visit, `${conditions} ${media}`);
}
}
}
+interface RuleFilter {
+ /** Skip rules inside an `@media` whose condition matches. */
+ outsideMedia?: RegExp;
+ /** Keep only rules inside an `@media` whose condition matches. */
+ insideMedia?: RegExp;
+}
+
+/** A coarse primary pointer's `@media` condition. */
+const COARSE_MEDIA = /\(pointer: coarse\)/;
+/** A Reduce Motion `@media` condition. */
+const REDUCED_MEDIA = /prefers-reduced-motion/;
+/** Rules for a coarse primary pointer, Reduce Motion's arms left out. */
+const UNDER_COARSE: RuleFilter = {
+ insideMedia: COARSE_MEDIA,
+ outsideMedia: REDUCED_MEDIA,
+};
+
/**
* Every injected style rule (rules nested in `@media` included) whose selector
* names one of the element's classes, as `selector {declarations}` text.
*/
-export function rulesDeclaredFor(el: Element): string[] {
+export function rulesDeclaredFor(
+ el: Element,
+ filter: RuleFilter = {},
+): string[] {
const classes = el.className
.split(/\s+/)
.filter(Boolean)
@@ -59,10 +95,16 @@ export function rulesDeclaredFor(el: Element): string[] {
} catch {
continue;
}
- walk(rules, rule => {
+ walk(rules, (rule, conditions) => {
if (!(rule instanceof CSSStyleRule)) {
return;
}
+ if (filter.outsideMedia?.test(conditions) === true) {
+ return;
+ }
+ if (filter.insideMedia != null && !filter.insideMedia.test(conditions)) {
+ return;
+ }
const selector = rule.selectorText;
if (classes.some(cls => selector.startsWith(cls))) {
out.push(`${selector} {${rule.style.cssText}}`);
@@ -73,8 +115,12 @@ export function rulesDeclaredFor(el: Element): string[] {
}
/** The rules on `el` whose selector matches `pseudo` (e.g. `:active`). */
-export function rulesWithSelector(el: Element, pseudo: string): string[] {
- return rulesDeclaredFor(el).filter(rule => {
+export function rulesWithSelector(
+ el: Element,
+ pseudo: string,
+ filter: RuleFilter = {},
+): string[] {
+ return rulesDeclaredFor(el, filter).filter(rule => {
const selector = rule.slice(0, rule.indexOf('{'));
return selector.includes(pseudo);
});
@@ -214,3 +260,46 @@ export function hasReleaseFade(el: Element): boolean {
!onArmAnimates
);
}
+
+/**
+ * Does the element release the press on a compositor layer? The layer runs
+ * an opacity keyframe animation on `pseudo`'s fading arm, for exactly
+ * `releaseMs` and filled both ways. Wherever the layer releases, the element
+ * runs no release of its own. A layer that exists only under a coarse
+ * primary pointer passes when the element's own release stops there too.
+ */
+export function releasesOnLayer(
+ el: Element,
+ pseudo: '::before' | '::after',
+ releaseMs: number,
+): boolean {
+ const fading = rulesWithSelector(el, FADING_ARM, {
+ outsideMedia: REDUCED_MEDIA,
+ });
+ const layer = fading.filter(rule => selectorOf(rule).includes(pseudo));
+ const durations = durationsOf(layer);
+ const layerReleases =
+ layer.some(runsAnimation) &&
+ layer.some(rule => /animation-fill-mode:\s*both/.test(rule)) &&
+ durations.length === 1 &&
+ durations[0] === releaseMs;
+ if (!layerReleases) {
+ return false;
+ }
+ const own = (rules: string[]) => rules.filter(rule => !onPseudoElement(rule));
+ if (!own(fading).some(runsAnimation)) {
+ return true;
+ }
+ // The element keeps its own release for a fine pointer: the layer's
+ // release must run only under a coarse one, where the element's stops.
+ const animates = (rules: string[]) =>
+ rules.filter(rule => rule.slice(rule.indexOf('{')).includes('animation-'));
+ const coarseFading = rulesWithSelector(el, FADING_ARM, UNDER_COARSE);
+ const coarseLayer = coarseFading.filter(rule =>
+ selectorOf(rule).includes(pseudo),
+ );
+ return (
+ animates(coarseLayer).length === animates(layer).length &&
+ own(coarseFading).some(stopsAnimation)
+ );
+}
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index ec80183bc1..47b5ec8f92 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -110,8 +110,9 @@
* click; a click held for a recognizer that may still recognize is
* replayed if they all fail. Keyboard and assistive-technology clicks
* (`detail === 0`) always pass.
- * - A `contextmenu` while a recognizer owns a touch is cancelled, so a long
- * press never also opens the browser's menu.
+ * - A `contextmenu` while a recognizer owns a touch, or while a press
+ * consumer holds the menu closed (`holdsContextMenu`), is cancelled. So a
+ * long press never also opens the browser's menu.
* - When the app loses focus (a window blur, a hidden page), every touch in
* flight is cancelled, as in UIKit; a finger the browser keeps alive lifts
* on nothing: its `touchend` is cancelled (`spec:AST-094` FR28).
@@ -3767,7 +3768,10 @@ export class GestureHost {
private readonly onContextMenu = (event: MouseEvent): void => {
for (const touch of this.arena.touches) {
- if (this.arena.isClaimed(touch.id)) {
+ if (
+ this.arena.isClaimed(touch.id) ||
+ this.arena.consumerOf(touch.id)?.holdsContextMenu?.(touch.id) === true
+ ) {
event.preventDefault();
return;
}
diff --git a/packages/core/src/gestures/PressTracker.ts b/packages/core/src/gestures/PressTracker.ts
index 3fd29986ed..4d8564ebc3 100644
--- a/packages/core/src/gestures/PressTracker.ts
+++ b/packages/core/src/gestures/PressTracker.ts
@@ -95,6 +95,12 @@ export interface PressTrackerOptions {
* does nothing passes none. @default undefined
*/
selectionLock?: SelectionLock;
+ /**
+ * Whether the press of `touchId` holds the browser's context menu closed
+ * now; the host then cancels it. For a control whose hold acts, such as a
+ * switch. @default undefined
+ */
+ holdsContextMenu?: (touchId: number) => boolean;
trackingExpansion?: number;
/**
* When the highlight waits `contentTouchDelay`: inside a scroller (a
@@ -312,6 +318,10 @@ export function createPressTracker(options: PressTrackerOptions): PressTracker {
return options.isEnabled?.() !== false;
},
+ holdsContextMenu(id: number): boolean {
+ return options.holdsContextMenu?.(id) === true;
+ },
+
touchBegan(touch: GestureTouch): void {
if (
touchId != null ||
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index 96976a66d6..e0af68c68e 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -2346,6 +2346,48 @@ describe('GestureHost', () => {
expect(during.defaultPrevented).toBe(true);
});
+ it('cancels the context menu while a press consumer holds it closed, and only while its touch is down', () => {
+ const {box} = mount('<div id="box"></div>');
+ let isHeld = false;
+ const tracker = createPressTracker({
+ getBounds: () => null,
+ holdsContextMenu: () => isHeld,
+ });
+ detachers.push(host.attachConsumer(box, tracker));
+ const opensMenu = () => {
+ const event = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ box.dispatchEvent(event);
+ return !event.defaultPrevented;
+ };
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ expect(opensMenu()).toBe(true);
+ isHeld = true;
+ expect(opensMenu()).toBe(false);
+ touch('touchend', box, [finger], [], 600);
+ expect(opensMenu()).toBe(true);
+ });
+
+ it('leaves the context menu to the browser for a press consumer that does not hold it', () => {
+ const {box} = mount('<div id="box"></div>');
+ detachers.push(
+ host.attachConsumer(box, createPressTracker({getBounds: () => null})),
+ );
+ const finger = {id: 1, x: 10, y: 10};
+ touch('touchstart', box, [finger], [finger], 0);
+ host.arena.advanceTime(600);
+ const event = new MouseEvent('contextmenu', {
+ bubbles: true,
+ cancelable: true,
+ });
+ box.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ touch('touchend', box, [finger], [], 700);
+ });
+
it('holds the click of a tap a double tap may claim, and replays it when the double tap fails', () => {
const {row, button} = mount(
'<div id="row"><button id="button">Go</button></div>',
diff --git a/packages/core/src/gestures/types.ts b/packages/core/src/gestures/types.ts
index 936707dd59..882614021f 100644
--- a/packages/core/src/gestures/types.ts
+++ b/packages/core/src/gestures/types.ts
@@ -202,6 +202,12 @@ export interface TouchConsumer {
* undefined and keeps the browser's long-press selection.
*/
readonly selectionLock?: SelectionLock;
+ /**
+ * Whether this touch's press holds the browser's context menu closed now.
+ * A control whose hold acts uses it (a switch's hold toggles it). The host
+ * then cancels the menu, as for a claimed touch.
+ */
+ holdsContextMenu?(touchId: number): boolean;
/**
* Whether the consumer takes touches now (a disabled control does not).
* The host listens only while something enabled is attached
diff --git a/packages/core/src/gestures/usePressTracker.ts b/packages/core/src/gestures/usePressTracker.ts
index 94f8250fcb..3e7b6ef3a1 100644
--- a/packages/core/src/gestures/usePressTracker.ts
+++ b/packages/core/src/gestures/usePressTracker.ts
@@ -132,6 +132,8 @@ export function usePressTracker(
recognizer,
),
isEnabled: () => optionsRef.current.isEnabled?.() ?? true,
+ holdsContextMenu: id =>
+ optionsRef.current.holdsContextMenu?.(id) === true,
// The caller's brake, or the host's: a touch that stops a flick
// presses nothing, as a UIKit control in a decelerating scroll view.
isBraking: touch => {
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index ced782e5fd..c9b0f16579 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -129,12 +129,13 @@ Subject "switch S": the first switch in Settings ▸ Accessibility ▸ Display &
Text Size (Bold Text row); a minimal host app holds a UISwitch on a plain view
where a switch outside any scroll view is needed.
-Captured (iOS 26.2 simulator, Oct 23 2026), with their values landing in the
-switch's own table: M-SW02, M-SW03, M-SW04, M-SW05, M-SW06, M-SW09 (UISwitch
-makes no haptic call), M-SW11 (Reduce Motion: the lift stays, the stretch
-goes), M-SW16 (iOS 26.2). Until that table lands they stay open here, and
-`springs.switchThumbMove` and `switchThumbStretch` keep WebKit's values.
-Partly: M-SW07 (a single tap only). Still open: M-SW17, and M-SW11's On/Off
+Captured (iOS 26.2 simulator, Oct 23 2026), with their values in the
+switch's own table (`uikit/switch.ts`): M-SW02, M-SW03, M-SW04, M-SW05,
+M-SW06, M-SW09 (UISwitch makes no haptic call), M-SW11 (Reduce Motion: the
+lift stays, the stretch goes), M-SW16 (iOS 26.2). `springs.switchThumbMove`
+holds the measured travel the switch's table reads; WebKit's
+`switchThumbStretch` is retired for the table's `lift`. Partly: M-SW07 (a single
+tap only). Still open: M-SW17, and M-SW11's On/Off
labels, Reduce Transparency and Bold Text.
| ID | Scene | Gesture | Extract | Method |
diff --git a/packages/core/src/motion/README.md b/packages/core/src/motion/README.md
index 9bd9891d94..6ac6f5e5da 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/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()`. |
| `resolveMotion.ts` | A role's value: its table value, as the per-role tables stay internal (`spec:AST-094` DEC-15). |
diff --git a/packages/core/src/motion/uikit/index.ts b/packages/core/src/motion/uikit/index.ts
index 16eb99bf9f..8245cc908e 100644
--- a/packages/core/src/motion/uikit/index.ts
+++ b/packages/core/src/motion/uikit/index.ts
@@ -4,9 +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` domain
- * and the gesture thresholds (one `UIKIT_*` group per recognizer, their
- * union `UIKIT_GESTURES`, and the haptic tables)
+ * …), `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)
* @position Entry of the UIKit constants table (motion/uikit). Internal to
* core: not exported from the package entry point
*
@@ -74,10 +75,10 @@ export {
SUB_MENU_BACK_SPRING,
SUB_MENU_OPEN_SPRING,
SWITCH_THUMB_MOVE_SPRING,
- SWITCH_THUMB_STRETCH_SPRING,
TIMED_CHANGE_SPRING,
VIEW_CHANGE_SPRING,
registerSpringsTable,
springs,
} from './springs';
+export {switchControl} from './switch';
export {registerTimingTable, timing} from './timing';
diff --git a/packages/core/src/motion/uikit/springs.ts b/packages/core/src/motion/uikit/springs.ts
index 4181606555..3a51fd9aa6 100644
--- a/packages/core/src/motion/uikit/springs.ts
+++ b/packages/core/src/motion/uikit/springs.ts
@@ -16,10 +16,10 @@
* uikit.test.ts enforces both.
*
* Most springs are measured on iOS 26.2 or documented by Apple; two are still
- * GUESSES (`segmentedThumb`, `banner`) and two come from WebKit
- * (`switchThumbMove`, `switchThumbStretch`). A guess starts from the
- * nearest sourced spring and names it, so a component built on the table
- * gets the right value the moment its measurement lands, without changing.
+ * 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.
*
* Press highlight in/out are fades, not springs: see timing.ts.
*
@@ -388,38 +388,25 @@ export const MENU_REDUCED_MOTION_SPRING = {
// ---------------------------------------------------------------------
/**
- * UISwitch thumb travelling between off and on.
- * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm
- * `thumbMoveSpring = SpringSolver(1.0, 438.649…, 31.4159…)`, "Values
- * chosen for consistency with UIKit" (= response 0.30 s, ratio 0.75);
- * its settling duration is WebKit's iOS switch duration 0.48801 s
- * (RenderThemeIOS.h). These are WebKit's iOS 18 values: UIKit's own
- * switch frames differ, and a switch reads its measured table instead.
- * @measure M-SW02
+ * UISwitch thumb travelling between off and on, measured: the switch table's
+ * `travel` reads this row, so the value has one home.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the lens's position behavior read on a tap (damping 1,
+ * response 0.3); the lens center after a 50 ms tap and after a 1 s hold
+ * fits one spring at 0.31 / 1 (rms 0.11 pt), Oct 23 2026
*/
export const SWITCH_THUMB_MOVE_SPRING = {
response: 0.3,
- dampingRatio: 0.75,
-} as const;
-
-/**
- * UISwitch thumb stretching while pressed and relaxing on release.
- * @source webkit Source/WebCore/rendering/cocoa/RenderThemeCocoa.mm
- * `thumbPressSpring = SpringSolver(1.0, 322.272…, 31.2364…)`, "Values
- * chosen for consistency with UIKit" (= response 0.35 s, ratio 0.87);
- * settles in WebKit's held duration 0.50740 s (RenderThemeIOS.h). As
- * for `switchThumbMove`, UIKit's own frames differ.
- * @measure M-SW03
- */
-export const SWITCH_THUMB_STRETCH_SPRING = {
- response: 0.35,
- dampingRatio: 0.87,
+ dampingRatio: 1,
} as const;
/**
* UISegmentedControl selection thumb sliding to a new segment.
- * @source GUESS — WebKit's UIKit-matched switch thumb spring, the nearest
- * sourced control thumb
+ * @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
*/
@@ -517,7 +504,6 @@ export const springs = {
contextMenuMorph: CONTEXT_MENU_MORPH_SPRING,
menuReducedMotion: MENU_REDUCED_MOTION_SPRING,
switchThumbMove: SWITCH_THUMB_MOVE_SPRING,
- switchThumbStretch: SWITCH_THUMB_STRETCH_SPRING,
segmentedThumb: SEGMENTED_THUMB_SPRING,
keyboard: KEYBOARD_SPRING,
banner: BANNER_SPRING,
diff --git a/packages/core/src/motion/uikit/switch.ts b/packages/core/src/motion/uikit/switch.ts
new file mode 100644
index 0000000000..bb161228fa
--- /dev/null
+++ b/packages/core/src/motion/uikit/switch.ts
@@ -0,0 +1,174 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file switch.ts
+ * @input The springs table's measured switch travel (springs.ts)
+ * @output Exports `switchControl`: UISwitch's geometry, the springs of its
+ * Liquid Glass thumb and of its track color, the drag's rubber band and
+ * flip distance, and the release timing
+ * @position The switch domain of the UIKit constants table (motion/uikit)
+ *
+ * The values are UISwitch's on iOS 26.2, read in a UIKit host app on the
+ * simulator. Lengths are in pt (CSS px). uikit.test.ts checks each `@source`.
+ *
+ * SYNC: When modified, update /packages/core/src/motion/MEASUREMENTS.md.
+ */
+
+import {registerMotionTable} from '../roles';
+import {SWITCH_THUMB_MOVE_SPRING} from './springs';
+
+/**
+ * UISwitch on iOS 26.2. Under a finger its white thumb lifts into a clear
+ * glass lens, and a drag moves it with a rubber band. The track colour slides
+ * on a spring of its own. UISwitch plays no haptic.
+ */
+export const switchControl = {
+ /**
+ * The control's size (width × height): the track.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, `UISwitch` frame 63 × 28 (intrinsic 61 × 28), track view
+ * 63 × 28 with corner radius 14, Oct 23 2026
+ */
+ trackSize: [63, 28],
+ /**
+ * The thumb at rest (width × height), inset equally from the track's top,
+ * bottom and nearer end; it never changes size between off and on.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, `_UILiquidLensView` frame 37 × 24 at x 2 (off) and
+ * x 24 (on) inside the 63 × 28 track, Oct 23 2026
+ */
+ thumbSize: [37, 24],
+ /**
+ * The thumb lifted under a finger (width × height). The lens grows about
+ * its own center, past the track, and holds this size while the finger
+ * stays down.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, lens bounds settled at 58 × 38.33 during a 1 s hold
+ * (center unmoved), Oct 23 2026
+ */
+ liftedThumbSize: [58, 38.333],
+ /**
+ * The lift: the thumb growing to `liftedThumbSize` while its white fill
+ * fades out and the clear glass fades in (one spring drives all three).
+ * Starts with the touch outside a scroll view, after its content delay
+ * inside one. UISwitch keeps it under Reduce Motion; core's Switch does not
+ * lift then.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, per-frame lens bounds during a 1 s hold fitted with one
+ * spring for width and height (rms 0.29 pt; the fill's and the glass's
+ * opacity overshoot by the same 13 %; the lens's settings read on a tap
+ * say damping 0.625, response 0.27, whose 8 % overshoot is short of the
+ * frames' 12 %), Oct 23 2026
+ */
+ lift: {response: 0.23, dampingRatio: 0.55},
+ /**
+ * The settle after the finger lifts: the lens shrinking back to
+ * `thumbSize` while the white fill returns over the glass.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the lens's spring settings read on a tap (damping 0.7,
+ * response 0.5); per-frame lens bounds after the lift of a 1 s hold fit
+ * one spring at 0.49 / 0.70 (rms 0.065 pt; the opacities undershoot by
+ * the same 4.5 %), Oct 23 2026
+ */
+ settle: {response: 0.5, dampingRatio: 0.7},
+ /**
+ * The settle never starts sooner than this after the lift began, so a
+ * quick tap still shows the lifted lens, in ms.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, a 50 ms tap: the lift→settle hand-off fitted at 235 ms
+ * after the lift began (rms 0.33 pt), Oct 23 2026
+ * @measure M-SW07
+ */
+ minimumLiftMs: 235,
+ /**
+ * The thumb travelling to the committed end after a release or a
+ * programmatic change. It starts from the thumb's own velocity.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the lens's position behavior read on a tap (damping 1,
+ * response 0.3); the lens center after a 50 ms tap and after a 1 s hold
+ * fits one spring at 0.31 / 1 (rms 0.11 pt), Oct 23 2026; the springs
+ * table's `SWITCH_THUMB_MOVE_SPRING` holds the one value
+ */
+ travel: SWITCH_THUMB_MOVE_SPRING,
+ /**
+ * During a drag the thumb chases the finger: each move retargets this
+ * spring at the finger's position, rubber-banded past either end.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, a 4 s drag off → on → past both ends: the lens center
+ * simulated as this spring chasing the rubber-banded finger fits every
+ * frame (rms 0.21 pt), Oct 23 2026
+ */
+ tracking: {response: 0.36, dampingRatio: 1},
+ /**
+ * The drag's rubber band past either end: UIScrollView's
+ * `(1 − 1 ÷ (x·c ÷ d + 1))·d`. The coefficient c and the dimension d are in
+ * pt for the 28 pt control. Scale d with the track height.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the same drag fit: c 0.55, d 11.75–12 pt, the
+ * translation measured from where the finger landed, Oct 23 2026
+ */
+ rubberBand: {coefficient: 0.55, dimension: 12},
+ /**
+ * A drag flips the switch by the finger, not the thumb. Once the finger is
+ * this far from where it landed, toward the other end, the switch shows
+ * the other side. The distance is the track width minus the thumb width
+ * (63 − 37 pt). Back past where it landed, the starting side shows again.
+ * Flips happen on touch events only, so a fast swipe flips on the lift.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, `UISwitchModernVisualElement` ivars per frame and the
+ * "SwitchWellPosition" springs during 1 pt-step drags: the same 26 pt for
+ * presses at x 8, 20.5 and 45, with and without a 400 ms hold, mirrored
+ * on an on switch; flipping back at the press point, Oct 23 2026
+ */
+ flipDistance: 26,
+ /**
+ * The track color turning on: the well image sliding in on a critically
+ * damped spring, starting when the switch flips (the lift of a tap).
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, `CASpringAnimation` "SwitchWellPosition" read: mass 1,
+ * stiffness 85.377, damping 18.480 (response 0.68 s), Oct 23 2026
+ */
+ wellOn: {mass: 1, stiffness: 85.37720070146501, damping: 18.47995678582231},
+ /**
+ * The track color turning off: the same well sliding back, faster.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, `CASpringAnimation` "SwitchWellPosition" read: mass 1,
+ * stiffness 246.740, damping 31.416 (response 0.40 s), Oct 23 2026
+ */
+ wellOff: {mass: 1, stiffness: 246.74011002723395, damping: 31.41592653589793},
+ /**
+ * The lifted lens's drop shadow: y offset and radius in pt, then black
+ * alpha; none at rest.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, the lens layer's presented `shadowOffset` (0, 7),
+ * `shadowRadius` 3, `shadowOpacity` 0.12 once lifted, 0 at rest,
+ * Oct 23 2026
+ */
+ liftedShadow: [7, 3, 0.12],
+ /**
+ * UISwitch plays no haptic on a tap, a hold or a drag.
+ * @source measured: UIKit lab (injected host app), iOS 26.2 simulator,
+ * iPhone 17 Pro, every `UIFeedbackGenerator` entry point hooked: no call
+ * on tap, hold, drag or flip, Oct 23 2026
+ */
+ haptic: 'none',
+} as const;
+
+/**
+ * Registers the switch table's motion roles as internal roles. Nothing
+ * registers on import: Switch's touch presentation calls it once before its
+ * first animation, and a second call does nothing.
+ */
+export function registerSwitchTable(): void {
+ registerMotionTable('switchControl', switchControl, {
+ roles: [
+ 'lift',
+ 'settle',
+ 'travel',
+ 'tracking',
+ 'wellOn',
+ 'wellOff',
+ 'minimumLiftMs',
+ ],
+ });
+}
diff --git a/packages/core/src/privateAttributes/pressHoldsDrag.stylex.ts b/packages/core/src/privateAttributes/pressHoldsDrag.stylex.ts
new file mode 100644
index 0000000000..7adfc6875f
--- /dev/null
+++ b/packages/core/src/privateAttributes/pressHoldsDrag.stylex.ts
@@ -0,0 +1,28 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file privateAttributes/pressHoldsDrag.stylex.ts
+ * @input Whether a pressable's own drag moves under the finger
+ * @output pressHoldsDragProps, which marks such a pressable, and
+ * holdsPressThroughDrag, which reads the mark
+ * @position Owner module of the private press-holds-drag attribute: the only
+ * file that writes its name. Switch marks its row; the press controller
+ * (utils/pressFeedback.ts) keeps the press painted through that row's
+ * drag. No package entry exports it.
+ */
+
+const PRESS_HOLDS_DRAG = 'data-astryx-press-holds-drag';
+
+/**
+ * Spread on a pressable whose own drag the finger moves, such as a Switch's
+ * thumb. The drag is not a scroll, so the press stays painted.
+ */
+export function pressHoldsDragProps(
+ holdsDrag: boolean,
+): Readonly<Record<string, string>> {
+ return holdsDrag ? {[PRESS_HOLDS_DRAG]: ''} : {};
+}
+
+/** Whether the press on `element` stays painted through its drag. */
+export function holdsPressThroughDrag(element: Element): boolean {
+ return element.hasAttribute(PRESS_HOLDS_DRAG);
+}
diff --git a/packages/core/src/utils/pressFeedback.test.ts b/packages/core/src/utils/pressFeedback.test.ts
index e34fca0be5..470126e029 100644
--- a/packages/core/src/utils/pressFeedback.test.ts
+++ b/packages/core/src/utils/pressFeedback.test.ts
@@ -216,6 +216,20 @@ describe('the press reaches the surface the finger landed on', () => {
expect(pressedRow()).toBe(1);
});
+ it('keeps the press painted through a drag on a surface that holds its drag, and still ends it on a cancel', () => {
+ const row = rows[0];
+ row.setAttribute('data-astryx-press-holds-drag', '');
+ press(row, 'pointerdown', 10, 10);
+ press(row, 'pointermove', 40, 10);
+ vi.advanceTimersByTime(PRESS_ONSET_MS);
+ expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ press(row, 'pointermove', 80, 10);
+ expect(row.getAttribute(PRESSED_ATTRIBUTE)).toBe('on');
+ press(row, 'pointercancel', 80, 10);
+ expect(row.hasAttribute(PRESSED_ATTRIBUTE)).toBe(false);
+ row.removeAttribute('data-astryx-press-holds-drag');
+ });
+
it('paints the innermost surface when they nest', () => {
const bubble = pressable('button');
rows[2].appendChild(bubble);
diff --git a/packages/core/src/utils/pressFeedback.ts b/packages/core/src/utils/pressFeedback.ts
index f5aa67975a..971d6aedbc 100644
--- a/packages/core/src/utils/pressFeedback.ts
+++ b/packages/core/src/utils/pressFeedback.ts
@@ -45,6 +45,7 @@ import {
import {isCoarsePointer, watchCoarsePointer} from './coarsePointer';
import {subscribeInput} from './inputStream';
import {TOUCH_QUERY} from './touchPresentation';
+import {holdsPressThroughDrag} from '../privateAttributes/pressHoldsDrag.stylex';
/**
* The marker the controller finds with `closest()`. Every Astryx component
@@ -441,6 +442,10 @@ function onPointerMove(event: PointerEvent): void {
) {
return;
}
+ // The finger drags the surface's own control: its travel keeps the press.
+ if (holdsPressThroughDrag(live.element)) {
+ return;
+ }
apply(
finger,
pressGestureStep(live.gesture, {
diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjs
index 358d4825ba..0765ababac 100644
--- a/scripts/build-css.test.mjs
+++ b/scripts/build-css.test.mjs
@@ -282,11 +282,17 @@ describe('build-css astryx.css', () => {
.map(line => line.match(/animation-duration:\s*([^;}]+)/)?.[1])
.filter(Boolean);
// One clock, the one the controller removes the attribute on, and its
- // Reduce Motion arm, which a tempo never lengthens past it (FR4).
+ // Reduce Motion arm, which a tempo never lengthens past it (FR4). A
+ // press layer that fades on the compositor (Switch's) runs on it too.
const releaseMs = await readReleaseMs();
- expect(durationsOf(false).map(toMs)).toEqual([releaseMs]);
- expect(durationsOf(true).map(toMs)).toEqual([releaseMs]);
- expect(durationsOf(true)[0]).toMatch(/^min\(/);
+ for (const reduced of [false, true]) {
+ const durations = durationsOf(reduced);
+ expect(durations.length).toBeGreaterThan(0);
+ expect(durations.map(toMs), durations.join(' | ')).toEqual(
+ durations.map(() => releaseMs),
+ );
+ }
+ expect(durationsOf(true).every(value => /^min\(/.test(value))).toBe(true);
// The onset is instant: nothing animates on the on arm.
const on = lines().filter(line =>
line.includes('[data-astryx-press="on"]'),
diff --git a/scripts/touch-support-bundle.test.mjs b/scripts/touch-support-bundle.test.mjs
index b5dc21da1b..521f329535 100644
--- a/scripts/touch-support-bundle.test.mjs
+++ b/scripts/touch-support-bundle.test.mjs
@@ -121,6 +121,8 @@ function filesUnder(dir, pattern) {
const GESTURE_USERS = new Set([
// Slider's thumb.
'Slider',
+ // Switch: its press tracking and its drag, for every pointer.
+ 'Switch',
]);
/** Public imports that carry no gesture code, whatever the list above says. */