@delacour/react-native-ui 0.10.0-alpha.20261120132923 → 0.11.0-alpha.20261120181844

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@delacour/react-native-ui",
3
- "version": "0.10.0-alpha.20261120132923",
3
+ "version": "0.11.0-alpha.20261120181844",
4
4
  "description": "React Native UI components — Uniwind, Reanimated, Gesture Handler",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -186,8 +186,8 @@
186
186
  "expo-blur": ">=15",
187
187
  "@maplibre/maplibre-react-native": "^11.5.0",
188
188
  "@central-icons-react-native/round-outlined-radius-1-stroke-1.5": "^1.1",
189
- "@delacour/react-native-bottom-sheet": "0.10.0-alpha.20261120132923",
190
- "@delacour/react-native-charts": "0.10.0-alpha.20261120132923",
189
+ "@delacour/react-native-bottom-sheet": "0.11.0-alpha.20261120181844",
190
+ "@delacour/react-native-charts": "0.11.0-alpha.20261120181844",
191
191
  "@legendapp/list": ">=3.3",
192
192
  "react-native-skia": ">=3.9.0",
193
193
  "expo-linear-gradient": ">=15",
@@ -21,7 +21,7 @@ section to read first — what follows is only where a switch differs.
21
21
  | `switch.types.ts` | Prop types shared by two or more parts |
22
22
  | `switch.variants.ts` | Pure `tv()` slots + the release worklet, no RN imports |
23
23
  | `switch.variants.test.ts` | |
24
- | `switch.render.test.tsx` | Mounted under Jest — role, checked and disabled state, controlled and uncontrolled, assistive activation |
24
+ | `switch.render.test.tsx` | Mounted under Jest — role, checked and disabled state, controlled and uncontrolled, assistive activation and no iOS custom action, the `Field.Label` name, a caller's `accessibilityState`, `Switch.Thumb` `onLayout`, the thumb hidden until both widths are measured, and a thumb found inside a fragment. The pan is driven with `fireGestureHandler` — tap, drag out and back on either axis, cancel, disabled |
25
25
 
26
26
  ## Design
27
27
 
@@ -50,11 +50,30 @@ section to read first — what follows is only where a switch differs.
50
50
  the control a tap and toggle it. Reading both means such a swipe is movement
51
51
  with no travel, which settles back to the state it started in — the switch is
52
52
  left alone.
53
+ - **`distance` is the peak over the whole gesture, not the translation at
54
+ release.** The root tracks the furthest the finger got on either axis, resets
55
+ it in `onBegin`, and passes it at release. A slow drag out and back to near its
56
+ start is still a drag, and it settles by position instead of toggling.
57
+ - **A swipe that never moved along the track keeps the state.** The root also
58
+ tracks the peak horizontal displacement and passes it as `horizontalDistance`.
59
+ Past the tap slop but under it horizontally, the release returns the state it
60
+ started in, without reading the position. A swipe caught while the thumb is
61
+ still springing towards a new state would otherwise settle by a position that
62
+ has not caught up, and flip the switch back.
53
63
  - **The value is settled in `onFinalize`, and only there.** Unlike a slider there
54
64
  is nothing to write on `onBegin`: a switch has no position to move a handle to,
55
65
  only a state to end up in. `onFinalize` is still the callback because it is the
56
66
  one that fires on every path, the never-activated one included — which is
57
67
  exactly the path a stationary tap takes.
68
+ - **A cancelled pan commits nothing.** `onFinalize` also runs when the system,
69
+ a parent, or a disable under the finger cancels the pan. On `CANCELLED`, or
70
+ when the switch is disabled, it springs the thumb back to the current state,
71
+ releases the press scale and clears the drag flag, with no haptic and no
72
+ change. It checks `CANCELLED` only, never `success`: on iOS a stationary press
73
+ never activates the pan and finalizes as `FAILED`, and that press is the tap.
74
+ - **The pan carries ``.withTestId(`${testID}-pan`)``** when the root has a
75
+ `testID`, so a render test can drive it with `fireGestureHandler`. No visual
76
+ effect.
58
77
  - **`isDisabled` is checked in `toggle`, not only on the pan.** `.enabled()` gates
59
78
  the gesture, but a screen reader's activation and an enclosing `Field`'s label
60
79
  press both arrive through `toggle`, so a guard on the pan alone let a disabled
@@ -93,10 +112,9 @@ section to read first — what follows is only where a switch differs.
93
112
  - **The knob draws no border and no shadow.** A border is a second line where
94
113
  there is already a boundary, and against a saturated track it reads as a dark
95
114
  ring rather than as definition; `Slider`'s handle dropped its own for the same
96
- reason. Contrast at rest comes from the track instead, which is why
97
- `SWITCH_TRACK_REST_TOKEN` is `input` — the chrome a field's own box wears, a
98
- step darker than the page in light and a step lighter in dark, so a knob
99
- painted the page's own colour reads against it at either end of the theme.
115
+ reason. Contrast at rest comes from the knob's own colour instead (see
116
+ Colour). `SWITCH_TRACK_REST_TOKEN` is `input`, the chrome a field's own box
117
+ wears, a step away from the page, so the off pill still has a shape.
100
118
  - **The track and its touch padding ride in the same size cell**, summing to 44pt
101
119
  at every size, and the test asserts the sum rather than the parts — `Slider`'s
102
120
  rule, and the trap it names: split them across two variants and a shorter track
@@ -108,7 +126,7 @@ section to read first — what follows is only where a switch differs.
108
126
  none of it.** The track, the thumb and both content layers fade between two
109
127
  token *values* off the one `progress`, and a colour being interpolated cannot
110
128
  be a class — `Checkbox`'s border, four times over. The slot set keeps
111
- `bg-secondary` and `bg-background` as the resting appearance those styles start
129
+ `bg-input` and `bg-muted-foreground` as the resting appearance those styles start
112
130
  from and names no colour anywhere else; the maps are the single source. There
113
131
  is deliberately **no `color` axis in the `tv()`** — a `bg-*` per colour there
114
132
  would be a second source for one surface, which is how a class and a style end
@@ -118,6 +136,17 @@ section to read first — what follows is only where a switch differs.
118
136
  theme forces: there is no `--foreground-foreground`, and `background` is
119
137
  what content drawn on the page's ink actually is. A test pins the whole map
120
138
  against the track's.
139
+ - **The resting knob is `muted-foreground`, for contrast.** With no On/Off text
140
+ beside it, the knob is the only sign of the state, so it must reach 3:1
141
+ against the resting track and the surface behind it (WCAG 1.4.11). A knob in
142
+ the page's own colour reached 1.21:1 on the light `input` track and 1.47:1 on
143
+ the dark one; the grey knob reaches 3.76:1 and 4.39:1 at the least. A test
144
+ computes the ratios from `theme.css`, and another holds the slot class to the
145
+ token. One known gap: a glyph *inside* the knob takes the track's on colour (a
146
+ prop, so it cannot fade with the knob). That colour reads on the on knob but
147
+ not on the grey off knob — about 2.5:1 for `default` in dark, and near 1:1 for
148
+ the semantic colours — so keep knob glyphs decorative. Content in
149
+ `Switch.StartContent` and `.EndContent` sits on the track and is unaffected.
121
150
  - **`Switch.StartContent` and `.EndContent` crossfade themselves.** Start sits at
122
151
  the leading edge, which the knob vacates as the switch turns **on**, so it fades
123
152
  in with `progress`; end is the mirror. That is the whole reason both can be
@@ -181,15 +210,25 @@ section to read first — what follows is only where a switch differs.
181
210
  `onAccessibilityTap` and an `activate` entry in `accessibilityActions` are what
182
211
  actually flip it, on iOS and Android respectively. Without them the switch would
183
212
  announce its state and offer no way to change it — the same gap
184
- `Slider.Thumb`'s `adjustable` actions close.
213
+ `Slider.Thumb`'s `adjustable` actions close. The `activate` entry is listed on
214
+ Android only (`resolveSwitchActivation`): Fabric shows every listed
215
+ action in the iOS rotor, so on iOS it would add a literal "activate" entry
216
+ next to the double-tap that `onAccessibilityTap` already handles —
217
+ `Pressable`'s `resolvePressableActivation` makes the same split. A caller's
218
+ own `accessibilityActions` and `onAccessibilityAction` are merged in, not
219
+ spread over the built-ins: `activate` is appended after the caller's actions
220
+ and routed to the toggle, and every other action reaches the caller's handler.
221
+ A caller that lists `activate` itself owns it. This is `Pressable`'s rule too.
185
222
  - **The root is marked `accessible`, and that one word is load-bearing.** Without
186
223
  it the view is not an accessibility element on iOS at all, so the role and the
187
224
  checked state written beside it never reach VoiceOver. It also merges the track
188
225
  and its layers into the single element a control should be.
189
226
  - **There is no `Switch.Label` and no `Switch.Group`.** The track is a fixed pill
190
227
  and a label cannot sit inside it, so the name is a `Field.Label` or a
191
- `ListGroup.ItemTitle` a row away — and unlike `Slider`, the switch **does**
192
- register `field.registerPress`, because a row-wide press means exactly what a
228
+ `ListGroup.ItemTitle` a row away. Inside a `Field`, the switch takes the
229
+ `Field.Label` text as its `accessibilityLabel` unless one is passed, because a
230
+ sibling label is outside the switch's accessibility element. Unlike `Slider`,
231
+ the switch **does** register `field.registerPress`, because a row-wide press means exactly what a
193
232
  tap on the pill means. A switch is a binary preference, not one of a set, so
194
233
  there is nothing for a group to own; the axis ladder is two rungs, the switch's
195
234
  own props then an enclosing `Field`.
@@ -205,7 +244,10 @@ section to read first — what follows is only where a switch differs.
205
244
  same size and colour the only symptom is that **anything inside the caller's
206
245
  knob disappears**. `displayName` survives all of it — rule 12 requires one, present and unique — so that is
207
246
  what `isSwitchThumbElement` asks for, with reference equality kept only as the
208
- fast path.
247
+ fast path. Fragments are opened first (`flattenFragments`), because
248
+ `Children.toArray` stops at one: a thumb written inside `<>…</>` would
249
+ otherwise go undetected and get the same second knob on top of it. A child
250
+ lifted out of a fragment is re-keyed with the fragment's key in front.
209
251
 
210
252
  **[`Radio`](../radio/AGENTS.md) and `ListGroup` still ask the unsafe question**
211
253
  (`radio.tsx`'s indicator detection, and the divider and icon-swap walks
@@ -37,8 +37,8 @@ export type SwitchThumbProps = Omit<ViewProps, "children" | "style"> & {
37
37
  *
38
38
  * **The colour is not a class.** It fades between two token *values* as the
39
39
  * switch travels, and a colour being interpolated cannot be a class — the rule
40
- * `Checkbox`'s border already follows. The `thumb` slot keeps `bg-background` as
41
- * the resting appearance this style starts from, and nothing else names a
40
+ * `Checkbox`'s border already follows. The `thumb` slot keeps
41
+ * `bg-muted-foreground` as the resting appearance this style starts from, and nothing else names a
42
42
  * background; two sources for one surface is how a class and a style end up
43
43
  * disagreeing for a frame on every toggle.
44
44
  *
@@ -52,14 +52,18 @@ export type SwitchThumbProps = Omit<ViewProps, "children" | "style"> & {
52
52
  * of the knob rather than an acknowledgement of the press. The outermost node is
53
53
  * the one thing nothing can crop, so that is where the press feedback lives.
54
54
  */
55
- export function SwitchThumb({ className, children, ...props }: SwitchThumbProps): ReactElement {
55
+ export function SwitchThumb({ className, children, onLayout, ...props }: SwitchThumbProps): ReactElement {
56
56
  const { color, size, isInvalid, isDisabled, progress, trackWidth, thumbWidth } = useSwitchPart("Switch.Thumb");
57
57
 
58
+ // The caller's handler runs as well as the measurement, never instead of it:
59
+ // with the width left at zero the travel is the whole track, and an on-state
60
+ // knob slides out past the clipped end.
58
61
  const handleLayout = useCallback(
59
62
  (event: LayoutChangeEvent) => {
60
63
  thumbWidth.value = event.nativeEvent.layout.width;
64
+ onLayout?.(event);
61
65
  },
62
- [thumbWidth]
66
+ [onLayout, thumbWidth]
63
67
  );
64
68
 
65
69
  const tokens = resolveSwitchThumbTokens({ color, isInvalid });
@@ -67,24 +71,27 @@ export function SwitchThumb({ className, children, ...props }: SwitchThumbProps)
67
71
  const activeColor = useThemeColor(tokens.active) ?? "transparent";
68
72
 
69
73
  const thumbStyle = useAnimatedStyle(() => {
70
- const measured = trackWidth.value;
71
74
  const travel = switchTravel({
72
75
  inset: SWITCH_THUMB_INSET,
73
76
  thumbWidth: thumbWidth.value,
74
- trackWidth: measured,
77
+ trackWidth: trackWidth.value,
75
78
  });
79
+ // Both widths, in either order: with only the track measured the travel is
80
+ // the whole track, and an on-state knob would paint past the clipped end.
81
+ const isMeasured = trackWidth.value > 0 && thumbWidth.value > 0;
76
82
 
77
83
  return {
78
84
  backgroundColor: interpolateColor(progress.value, [0, 1], [restColor, activeColor]),
79
- opacity: measured > 0 ? 1 : 0,
85
+ opacity: isMeasured ? 1 : 0,
80
86
  transform: [{ translateX: progress.value * travel }],
81
87
  };
82
88
  });
83
89
 
84
- // A glyph on the knob takes the *track*'s colour, not the knob's own: it is
85
- // drawn on the knob, so it has to contrast with it, and the one value that
86
- // reads at both ends is the colour the track fades to. Static rather than
87
- // interpolated because an `Icon`'s colour is a prop, not a style.
90
+ // A glyph on the knob takes the *track*'s on colour, not the knob's own: it is
91
+ // drawn on the knob, so it has to contrast with the on knob, which is that
92
+ // colour's foreground. Static rather than interpolated because an `Icon`'s
93
+ // colour is a prop, not a style — so it cannot follow the knob to its grey off
94
+ // state, where it falls well under 3:1. Keep knob glyphs decorative.
88
95
  const slots = switchVariants({ isDisabled, size });
89
96
  const glyphColor = useThemeColor(resolveSwitchTrackTokens({ color, isInvalid }).active);
90
97
  const glyphClassName = slots.glyph();
@@ -1,6 +1,60 @@
1
- import { describe, expect, jest, test } from "@jest/globals";
2
- import { fireEvent, renderWithProviders, screen } from "../../test/render";
1
+ import { afterEach, describe, expect, jest, test } from "@jest/globals";
2
+ import { Platform } from "react-native";
3
+ import { State } from "react-native-gesture-handler";
4
+ import { fireGestureHandler, getByGestureTestId } from "react-native-gesture-handler/jest-utils";
5
+ import { act, fireEvent, renderWithProviders, screen, waitFor } from "../../test/render";
6
+ import { Field } from "../field";
3
7
  import { Switch } from "./switch";
8
+ import { SWITCH_THUMB_INSET } from "./switch.variants";
9
+
10
+ const layout = (width: number) => ({ nativeEvent: { layout: { height: 0, width, x: 0, y: 0 } } });
11
+
12
+ type Instance = ReturnType<typeof screen.getByTestId>;
13
+
14
+ // Puts back a `Platform.OS` a test replaced.
15
+ afterEach(() => {
16
+ jest.restoreAllMocks();
17
+ });
18
+
19
+ /** The track is the root's only child: the node that clips the thumb and reports the travel. */
20
+ const track = (id = "switch"): Instance => {
21
+ const [first] = screen.getByTestId(id).children;
22
+ if (typeof first === "string" || first === undefined) throw new Error("the switch root holds no track");
23
+ return first;
24
+ };
25
+
26
+ const translateX = (element: Instance): number | undefined => {
27
+ const { jestAnimatedStyle } = element.props as {
28
+ jestAnimatedStyle?: { value: { transform?: { translateX?: number }[] } };
29
+ };
30
+ return jestAnimatedStyle?.value.transform?.[0]?.translateX;
31
+ };
32
+
33
+ const opacity = (element: Instance): number | undefined => {
34
+ const { jestAnimatedStyle } = element.props as { jestAnimatedStyle?: { value: { opacity?: number } } };
35
+ return jestAnimatedStyle?.value.opacity;
36
+ };
37
+
38
+ type PanStep = { state: State; translationX?: number; translationY?: number };
39
+
40
+ /** Sends one pan to the switch, filling in what each step leaves out. */
41
+ const pan = async (steps: PanStep[], id = "switch"): Promise<void> => {
42
+ await act(async () => {
43
+ fireGestureHandler(
44
+ getByGestureTestId(`${id}-pan`),
45
+ steps.map((step) => ({ translationX: 0, translationY: 0, velocityX: 0, velocityY: 0, ...step }))
46
+ );
47
+ });
48
+ };
49
+
50
+ type MeasuredProps = { defaultSelected?: boolean; isDisabled?: boolean; onSelectedChange: (next: boolean) => void };
51
+
52
+ /** A switch with a measured track, so a drag moves the thumb the way it does on a device. */
53
+ const renderMeasured = async (props: MeasuredProps) => {
54
+ const view = await renderWithProviders(<Switch {...props} testID="switch" />);
55
+ await fireEvent(track(), "layout", layout(52));
56
+ return view;
57
+ };
4
58
 
5
59
  describe("Switch", () => {
6
60
  test("is a switch whose state is announced", async () => {
@@ -27,7 +81,7 @@ describe("Switch", () => {
27
81
  const view = await renderWithProviders(
28
82
  <Switch accessibilityLabel="Wi-Fi" isSelected={false} onSelectedChange={onSelectedChange} />
29
83
  );
30
- await fireEvent(screen.getByRole("switch"), "accessibilityAction", { nativeEvent: { actionName: "activate" } });
84
+ await fireEvent(screen.getByRole("switch"), "accessibilityTap");
31
85
  expect(onSelectedChange).toHaveBeenCalledWith(true);
32
86
  expect(screen.getByRole("switch")).not.toBeChecked();
33
87
 
@@ -44,3 +98,244 @@ describe("Switch", () => {
44
98
  expect(onSelectedChange).not.toHaveBeenCalled();
45
99
  });
46
100
  });
101
+
102
+ describe("Switch.Thumb", () => {
103
+ // The first layout's frame is waited for through the travel it writes — the
104
+ // whole track less the insets while the thumb is unmeasured, nothing while the
105
+ // track is — so the opacity is read after the style ran, not before it.
106
+ test.each([
107
+ ["the track", "the thumb", 52 - 2 * SWITCH_THUMB_INSET],
108
+ ["the thumb", "the track", 0],
109
+ ])("stays hidden when %s reports before %s, then shows at its measured place", async (first, _second, travel) => {
110
+ await renderWithProviders(
111
+ <Switch defaultSelected testID="switch">
112
+ <Switch.Thumb testID="thumb" />
113
+ </Switch>
114
+ );
115
+ const thumb = () => screen.getByTestId("thumb");
116
+ const measureTrack = () => fireEvent(track(), "layout", layout(52));
117
+ const measureThumb = () => fireEvent(thumb(), "layout", layout(24));
118
+
119
+ await (first === "the track" ? measureTrack() : measureThumb());
120
+ await waitFor(() => expect(translateX(thumb())).toBe(travel));
121
+ expect(opacity(thumb())).toBe(0);
122
+
123
+ await (first === "the track" ? measureThumb() : measureTrack());
124
+ await waitFor(() => expect(opacity(thumb())).toBe(1));
125
+ await waitFor(() => expect(translateX(thumb())).toBe(52 - 24 - 2 * SWITCH_THUMB_INSET));
126
+ });
127
+
128
+ test("finds a thumb written inside a fragment, and adds no second one", async () => {
129
+ // Built apart from the switch so the fragment is the one child it receives.
130
+ const parts = (
131
+ <>
132
+ <Switch.Thumb testID="thumb" />
133
+ <Switch.StartContent testID="start" />
134
+ </>
135
+ );
136
+ await renderWithProviders(<Switch testID="switch">{parts}</Switch>);
137
+
138
+ const layers = track().children.filter((child) => typeof child !== "string");
139
+ expect(layers.map((layer) => layer.props.testID)).toEqual(["start", "thumb"]);
140
+ });
141
+
142
+ test("calls a caller's onLayout and still measures itself", async () => {
143
+ const onLayout = jest.fn();
144
+ await renderWithProviders(
145
+ <Switch defaultSelected testID="switch">
146
+ <Switch.Thumb onLayout={onLayout} testID="thumb" />
147
+ </Switch>
148
+ );
149
+
150
+ await fireEvent(track(), "layout", layout(52));
151
+ await fireEvent(screen.getByTestId("thumb"), "layout", layout(24));
152
+
153
+ expect(onLayout).toHaveBeenCalledTimes(1);
154
+ // An on-state thumb sits one travel along. With its own width unmeasured
155
+ // the travel would be the whole track less the insets, and the knob would
156
+ // slide out past the clipped end. Waited for, because under Jest Reanimated
157
+ // runs the style mapper on the next animation frame, not inside the event.
158
+ await waitFor(() => expect(translateX(screen.getByTestId("thumb"))).toBe(52 - 24 - 2 * SWITCH_THUMB_INSET));
159
+ });
160
+ });
161
+
162
+ describe("Switch accessibility", () => {
163
+ test("keeps reporting checked and disabled when the caller passes its own accessibilityState", async () => {
164
+ await renderWithProviders(
165
+ <Switch accessibilityState={{ busy: true }} defaultSelected isDisabled testID="switch" />
166
+ );
167
+
168
+ expect(screen.getByTestId("switch").props.accessibilityState).toEqual({
169
+ busy: true,
170
+ checked: true,
171
+ disabled: true,
172
+ });
173
+ });
174
+
175
+ test("offers no custom accessibility action on iOS, where onAccessibilityTap activates it", async () => {
176
+ await renderWithProviders(<Switch accessibilityLabel="Wi-Fi" testID="switch" />);
177
+
178
+ expect(screen.getByTestId("switch").props.accessibilityActions).toBeUndefined();
179
+ });
180
+
181
+ test.each(["ios", "android"] as const)(
182
+ "on %s, a caller's custom action reaches its handler and activation still toggles",
183
+ async (os) => {
184
+ jest.replaceProperty(Platform, "OS", os);
185
+ const onAccessibilityAction = jest.fn();
186
+ const onSelectedChange = jest.fn();
187
+ await renderWithProviders(
188
+ <Switch
189
+ accessibilityActions={[{ label: "Help", name: "help" }]}
190
+ accessibilityLabel="Wi-Fi"
191
+ onAccessibilityAction={onAccessibilityAction}
192
+ onSelectedChange={onSelectedChange}
193
+ testID="switch"
194
+ />
195
+ );
196
+ const control = screen.getByTestId("switch");
197
+
198
+ await fireEvent(control, "accessibilityAction", { nativeEvent: { actionName: "help" } });
199
+ expect(onAccessibilityAction).toHaveBeenCalledTimes(1);
200
+ expect(onSelectedChange).not.toHaveBeenCalled();
201
+
202
+ // TalkBack activates through the `activate` action, VoiceOver through
203
+ // `onAccessibilityTap`.
204
+ if (os === "android") {
205
+ expect(control.props.accessibilityActions).toEqual([{ label: "Help", name: "help" }, { name: "activate" }]);
206
+ await fireEvent(control, "accessibilityAction", { nativeEvent: { actionName: "activate" } });
207
+ } else {
208
+ expect(control.props.accessibilityActions).toEqual([{ label: "Help", name: "help" }]);
209
+ await fireEvent(control, "accessibilityTap");
210
+ }
211
+ expect(onSelectedChange).toHaveBeenCalledWith(true);
212
+ expect(onAccessibilityAction).toHaveBeenCalledTimes(1);
213
+ }
214
+ );
215
+
216
+ test("is named by a sibling Field.Label", async () => {
217
+ await renderWithProviders(
218
+ <Field>
219
+ <Field.Label>Notifications</Field.Label>
220
+ <Switch />
221
+ </Field>
222
+ );
223
+
224
+ expect(screen.getByRole("switch", { name: "Notifications" })).toBeOnTheScreen();
225
+ });
226
+
227
+ test("keeps an explicit accessibilityLabel over the Field.Label", async () => {
228
+ await renderWithProviders(
229
+ <Field>
230
+ <Field.Label>Notifications</Field.Label>
231
+ <Switch accessibilityLabel="Push alerts" />
232
+ </Field>
233
+ );
234
+
235
+ expect(screen.getByRole("switch", { name: "Push alerts" })).toBeOnTheScreen();
236
+ });
237
+ });
238
+
239
+ describe("Switch gesture", () => {
240
+ test("a stationary press toggles", async () => {
241
+ const onSelectedChange = jest.fn();
242
+ await renderMeasured({ onSelectedChange });
243
+
244
+ await pan([{ state: State.BEGAN }, { state: State.END }]);
245
+
246
+ expect(onSelectedChange).toHaveBeenCalledWith(true);
247
+ });
248
+
249
+ test("a horizontal drag out and back is not a tap", async () => {
250
+ const onSelectedChange = jest.fn();
251
+ await renderMeasured({ onSelectedChange });
252
+
253
+ await pan([
254
+ { state: State.BEGAN },
255
+ { state: State.ACTIVE },
256
+ { state: State.ACTIVE, translationX: 12 },
257
+ { state: State.ACTIVE, translationX: 1 },
258
+ { state: State.END, translationX: 1 },
259
+ ]);
260
+
261
+ expect(onSelectedChange).not.toHaveBeenCalled();
262
+ });
263
+
264
+ test("a vertical drag out and back is not a tap", async () => {
265
+ const onSelectedChange = jest.fn();
266
+ await renderMeasured({ defaultSelected: true, onSelectedChange });
267
+
268
+ await pan([
269
+ { state: State.BEGAN },
270
+ { state: State.ACTIVE },
271
+ { state: State.ACTIVE, translationY: 30 },
272
+ { state: State.ACTIVE, translationY: 1 },
273
+ { state: State.END, translationY: 1 },
274
+ ]);
275
+
276
+ expect(onSelectedChange).not.toHaveBeenCalled();
277
+ });
278
+
279
+ test("a pan cancelled before it moved changes nothing", async () => {
280
+ const onSelectedChange = jest.fn();
281
+ await renderMeasured({ onSelectedChange });
282
+
283
+ await pan([{ state: State.BEGAN }, { state: State.CANCELLED }]);
284
+
285
+ expect(onSelectedChange).not.toHaveBeenCalled();
286
+ expect(screen.getByTestId("switch").props.accessibilityState).toMatchObject({ checked: false });
287
+ });
288
+
289
+ test("a pan cancelled after a drag past half way changes nothing", async () => {
290
+ const onSelectedChange = jest.fn();
291
+ await renderMeasured({ onSelectedChange });
292
+
293
+ await pan([
294
+ { state: State.BEGAN },
295
+ { state: State.ACTIVE },
296
+ { state: State.ACTIVE, translationX: 40 },
297
+ { state: State.CANCELLED, translationX: 40 },
298
+ ]);
299
+
300
+ expect(onSelectedChange).not.toHaveBeenCalled();
301
+ expect(screen.getByTestId("switch").props.accessibilityState).toMatchObject({ checked: false });
302
+ });
303
+
304
+ // `fireGestureHandler` ends every sequence it is given, so one gesture cannot
305
+ // span the rerender, and it skips a disabled pan. This checks that a pan sent
306
+ // to a switch disabled after mount commits nothing. The `onFinalize` guard for
307
+ // a native pan disabled under the finger is not reachable from here.
308
+ test("a pan that finalizes after the switch was disabled changes nothing", async () => {
309
+ const onSelectedChange = jest.fn();
310
+ const view = await renderMeasured({ onSelectedChange });
311
+
312
+ await view.rerender(<Switch isDisabled onSelectedChange={onSelectedChange} testID="switch" />);
313
+ await pan([{ state: State.BEGAN }, { state: State.CANCELLED }]);
314
+ await pan([{ state: State.BEGAN }, { state: State.END }]);
315
+
316
+ expect(onSelectedChange).not.toHaveBeenCalled();
317
+ });
318
+
319
+ test.each([
320
+ ["springing on", false, true],
321
+ ["springing off", true, false],
322
+ ])("a vertical swipe caught while %s keeps the state", async (_, from, to) => {
323
+ const onSelectedChange = jest.fn();
324
+ const view = await renderWithProviders(
325
+ <Switch isSelected={from} onSelectedChange={onSelectedChange} testID="switch" />
326
+ );
327
+ await fireEvent(track(), "layout", layout(52));
328
+
329
+ // The prop flips and the thumb starts springing; the swipe lands before it
330
+ // has crossed half way, so its position still says the old state.
331
+ await view.rerender(<Switch isSelected={to} onSelectedChange={onSelectedChange} testID="switch" />);
332
+ await pan([
333
+ { state: State.BEGAN },
334
+ { state: State.ACTIVE },
335
+ { state: State.ACTIVE, translationY: 30 },
336
+ { state: State.END, translationY: 30 },
337
+ ]);
338
+
339
+ expect(onSelectedChange).not.toHaveBeenCalled();
340
+ });
341
+ });
@@ -1,5 +1,7 @@
1
1
  import {
2
2
  Children,
3
+ cloneElement,
4
+ Fragment,
3
5
  isValidElement,
4
6
  type ReactElement,
5
7
  type ReactNode,
@@ -9,8 +11,8 @@ import {
9
11
  useRef,
10
12
  useState,
11
13
  } from "react";
12
- import type { AccessibilityActionEvent, LayoutChangeEvent, ViewProps } from "react-native";
13
- import { Gesture, GestureDetector } from "react-native-gesture-handler";
14
+ import { type AccessibilityActionEvent, type LayoutChangeEvent, Platform, type ViewProps } from "react-native";
15
+ import { Gesture, GestureDetector, State } from "react-native-gesture-handler";
14
16
  import Animated, {
15
17
  cancelAnimation,
16
18
  interpolateColor,
@@ -26,6 +28,7 @@ import { type HapticFeedback, playHaptic } from "../pressable";
26
28
  import { type SwitchContextValue, SwitchProvider } from "./switch.context";
27
29
  import {
28
30
  hasThumbChild,
31
+ resolveSwitchActivation,
29
32
  resolveSwitchAxes,
30
33
  resolveSwitchRelease,
31
34
  resolveSwitchTrackTokens,
@@ -71,6 +74,10 @@ function SwitchRoot({
71
74
  isInvalid,
72
75
  haptic = "selection",
73
76
  className,
77
+ accessibilityActions,
78
+ accessibilityLabel,
79
+ accessibilityState,
80
+ onAccessibilityAction,
74
81
  children,
75
82
  ...props
76
83
  }: SwitchProps): ReactElement {
@@ -96,6 +103,13 @@ function SwitchRoot({
96
103
  // rather than state: nothing renders differently for it, so a commit on every
97
104
  // touch would be pure cost.
98
105
  const isPressed = useSharedValue(0);
106
+ // The furthest the finger got from where it landed, on either axis, over the
107
+ // whole gesture. Read at release rather than the final translation, so a drag
108
+ // out and back to its start is still a drag and not a tap.
109
+ const peakDistance = useSharedValue(0);
110
+ // The same peak along the track only. A swipe that never moved along it has
111
+ // no intent to change the state, whatever the thumb's position says.
112
+ const peakHorizontal = useSharedValue(0);
99
113
 
100
114
  // A ref rather than state: the pan reads it twice a drag and nothing renders
101
115
  // differently for it, so a re-render on touch-down would be pure cost.
@@ -139,56 +153,94 @@ function SwitchRoot({
139
153
  [trackWidth]
140
154
  );
141
155
 
142
- const gesture = useMemo(
143
- () =>
144
- Gesture.Pan()
145
- .enabled(!axes.isDisabled)
146
- .minDistance(0)
147
- .shouldCancelWhenOutside(false)
148
- .onBegin(() => {
149
- "worklet";
150
- grabbed.value = progress.value;
151
- isPressed.value = withSpring(1, SWITCH_PRESS_SPRING);
152
- scheduleOnRN(setDragging, true);
153
- })
154
- .onUpdate((event) => {
155
- "worklet";
156
- const travel = switchTravel({
157
- inset: SWITCH_THUMB_INSET,
158
- thumbWidth: thumbWidth.value,
159
- trackWidth: trackWidth.value,
160
- });
161
- if (travel <= 0) return;
162
-
163
- progress.value = Math.min(1, Math.max(0, grabbed.value + event.translationX / travel));
164
- })
165
- .onFinalize((event) => {
166
- "worklet";
167
- // Whichever axis moved further. A vertical swipe that began on the
168
- // switch has to count as movement, or every attempt to scroll past
169
- // the control would read as a tap and toggle it.
170
- const target = resolveSwitchRelease({
171
- distance: Math.max(Math.abs(event.translationX), Math.abs(event.translationY)),
172
- progress: progress.value,
173
- velocity: event.velocityX,
174
- wasSelected: selected,
175
- });
176
-
177
- progress.value = withSpring(target ? 1 : 0, SWITCH_THUMB_SPRING);
156
+ const testID = props.testID;
157
+ const isGestureDisabled = axes.isDisabled;
158
+ const gesture = useMemo(() => {
159
+ const pan = Gesture.Pan()
160
+ .enabled(!isGestureDisabled)
161
+ .minDistance(0)
162
+ .shouldCancelWhenOutside(false)
163
+ .onBegin(() => {
164
+ "worklet";
165
+ grabbed.value = progress.value;
166
+ peakDistance.value = 0;
167
+ peakHorizontal.value = 0;
168
+ isPressed.value = withSpring(1, SWITCH_PRESS_SPRING);
169
+ scheduleOnRN(setDragging, true);
170
+ })
171
+ .onUpdate((event) => {
172
+ "worklet";
173
+ // Before the travel check: a vertical swipe moves no thumb but still
174
+ // counts as movement.
175
+ peakDistance.value = Math.max(peakDistance.value, Math.abs(event.translationX), Math.abs(event.translationY));
176
+ peakHorizontal.value = Math.max(peakHorizontal.value, Math.abs(event.translationX));
177
+
178
+ const travel = switchTravel({
179
+ inset: SWITCH_THUMB_INSET,
180
+ thumbWidth: thumbWidth.value,
181
+ trackWidth: trackWidth.value,
182
+ });
183
+ if (travel <= 0) return;
184
+
185
+ progress.value = Math.min(1, Math.max(0, grabbed.value + event.translationX / travel));
186
+ })
187
+ .onFinalize((event) => {
188
+ "worklet";
189
+ // A cancelled pan (the system took the touch, a parent claimed it, or
190
+ // the switch was disabled under the finger) commits nothing. Only
191
+ // CANCELLED: on iOS a stationary press never activates the pan and
192
+ // finalizes as FAILED, and that press is the tap.
193
+ if (event.state === PAN_CANCELLED || isGestureDisabled) {
194
+ progress.value = withSpring(selected ? 1 : 0, SWITCH_THUMB_SPRING);
178
195
  isPressed.value = withSpring(0, SWITCH_PRESS_SPRING);
179
- // At the commit, never at the grab. A drag taken half way and
180
- // released back has changed nothing, and a switch that buzzed for it
181
- // would be reporting a state change that did not happen.
182
- if (haptic !== false && target !== selected) playHaptic(haptic);
183
-
184
- // Order matters: the root must have stopped treating this as a live
185
- // drag before `commit` asks it to re-sync. `scheduleOnRN` keeps them
186
- // in the order they were queued.
187
196
  scheduleOnRN(setDragging, false);
188
- scheduleOnRN(commit, target);
189
- }),
190
- [axes.isDisabled, commit, grabbed, haptic, isPressed, progress, selected, setDragging, thumbWidth, trackWidth]
191
- );
197
+ return;
198
+ }
199
+
200
+ // The furthest the gesture got on whichever axis moved further. A
201
+ // vertical swipe that began on the switch has to count as movement, or
202
+ // every attempt to scroll past the control would read as a tap and
203
+ // toggle it. The peak, not the final translation, so a slow drag that
204
+ // returns near its start does not read as a tap either.
205
+ const target = resolveSwitchRelease({
206
+ distance: Math.max(peakDistance.value, Math.abs(event.translationX), Math.abs(event.translationY)),
207
+ horizontalDistance: Math.max(peakHorizontal.value, Math.abs(event.translationX)),
208
+ progress: progress.value,
209
+ velocity: event.velocityX,
210
+ wasSelected: selected,
211
+ });
212
+
213
+ progress.value = withSpring(target ? 1 : 0, SWITCH_THUMB_SPRING);
214
+ isPressed.value = withSpring(0, SWITCH_PRESS_SPRING);
215
+ // At the commit, never at the grab. A drag taken half way and
216
+ // released back has changed nothing, and a switch that buzzed for it
217
+ // would be reporting a state change that did not happen.
218
+ if (haptic !== false && target !== selected) playHaptic(haptic);
219
+
220
+ // Order matters: the root must have stopped treating this as a live
221
+ // drag before `commit` asks it to re-sync. `scheduleOnRN` keeps them
222
+ // in the order they were queued.
223
+ scheduleOnRN(setDragging, false);
224
+ scheduleOnRN(commit, target);
225
+ });
226
+
227
+ // Lets a render test drive the pan through `fireGestureHandler`.
228
+ return testID ? pan.withTestId(`${testID}-pan`) : pan;
229
+ }, [
230
+ commit,
231
+ grabbed,
232
+ haptic,
233
+ isGestureDisabled,
234
+ isPressed,
235
+ peakDistance,
236
+ peakHorizontal,
237
+ progress,
238
+ selected,
239
+ setDragging,
240
+ testID,
241
+ thumbWidth,
242
+ trackWidth,
243
+ ]);
192
244
 
193
245
  // Guarded here rather than at each caller: the pan is gated by `.enabled()`,
194
246
  // but a screen reader's activation and an enclosing `Field`'s label press
@@ -257,20 +309,40 @@ function SwitchRoot({
257
309
  const content = useMemo(() => withThumb(children), [children]);
258
310
  const slots = switchVariants({ isDisabled: axes.isDisabled, size: axes.size });
259
311
 
312
+ // Merged with the caller's actions, never replaced by them: see
313
+ // `resolveSwitchActivation`. `activate` is consumed only when the switch added
314
+ // it; every other action, and an `activate` the caller owns, reaches the
315
+ // caller's own handler. `Platform.OS` is read here rather than at module scope
316
+ // so a test can replace it.
317
+ const activation = useMemo(
318
+ () => resolveSwitchActivation({ accessibilityActions, platform: Platform.OS }),
319
+ [accessibilityActions]
320
+ );
260
321
  const handleAccessibilityAction = useCallback(
261
322
  (event: AccessibilityActionEvent) => {
262
- if (event.nativeEvent.actionName === "activate") toggle();
323
+ if (activation.routesActivate && event.nativeEvent.actionName === "activate") {
324
+ toggle();
325
+ return;
326
+ }
327
+ onAccessibilityAction?.(event);
263
328
  },
264
- [toggle]
329
+ [activation.routesActivate, onAccessibilityAction, toggle]
265
330
  );
266
331
 
332
+ // `accessibilityState` is merged, not replaced: a caller's `busy` must not
333
+ // drop the checked and disabled state a screen reader announces.
334
+ //
335
+ // The name falls back to the enclosing `Field.Label`. That label is a sibling,
336
+ // outside this element, so `accessible` alone would leave the switch unnamed.
337
+ // An explicit `accessibilityLabel` still wins.
267
338
  return (
268
339
  <SwitchProvider value={context}>
269
340
  <GestureDetector gesture={gesture}>
270
341
  <Animated.View
271
- accessibilityActions={ACCESSIBILITY_ACTIONS}
342
+ accessibilityActions={activation.accessibilityActions}
343
+ accessibilityLabel={accessibilityLabel ?? field?.label ?? undefined}
272
344
  accessibilityRole="switch"
273
- accessibilityState={{ checked: selected, disabled: axes.isDisabled }}
345
+ accessibilityState={{ ...accessibilityState, checked: selected, disabled: axes.isDisabled }}
274
346
  // Without this the view is not an accessibility element on iOS, and
275
347
  // the role and the state above never reach VoiceOver. It also merges
276
348
  // the parts into one element, which is what a control should be.
@@ -289,18 +361,8 @@ function SwitchRoot({
289
361
  );
290
362
  }
291
363
 
292
- /**
293
- * The one action an assistive double-tap on a `switch` maps to.
294
- *
295
- * Module scope on purpose: a fresh array each render is a new prop every commit,
296
- * and React Native sends the whole accessibility config across on any change.
297
- *
298
- * It exists at all because the root is not a `Pressable` — there is no touch
299
- * responder for TalkBack's activation to land on, so without this the switch
300
- * would announce its state and offer no way to change it. `onAccessibilityTap`
301
- * is the iOS half of the same gap.
302
- */
303
- const ACCESSIBILITY_ACTIONS = [{ name: "activate" }] as const;
364
+ /** Read inside the pan's worklets, so it is a plain number captured once. */
365
+ const PAN_CANCELLED = State.CANCELLED;
304
366
 
305
367
  /**
306
368
  * Composes a `Switch.Thumb` in, and puts it last however it was written.
@@ -322,7 +384,7 @@ const ACCESSIBILITY_ACTIONS = [{ name: "activate" }] as const;
322
384
  * children, and importing it from a part would close a cycle. See AGENTS.md.
323
385
  */
324
386
  function withThumb(children: ReactNode): ReactNode {
325
- const items = Children.toArray(children);
387
+ const items = flattenFragments(children);
326
388
  const isThumb = items.map(isSwitchThumbElement);
327
389
 
328
390
  if (!hasThumbChild(isThumb)) return [...items, <SwitchThumb key="thumb" />];
@@ -330,6 +392,26 @@ function withThumb(children: ReactNode): ReactNode {
330
392
  return [...items.filter((_, index) => !isThumb[index]), ...items.filter((_, index) => isThumb[index])];
331
393
  }
332
394
 
395
+ /**
396
+ * The children with every fragment opened up, at any depth.
397
+ *
398
+ * `Children.toArray` stops at a fragment, so a `Switch.Thumb` written inside
399
+ * `<>…</>` would go undetected: a second thumb would be composed in over it,
400
+ * hiding anything inside the caller's knob, and both would write the one
401
+ * measured width. Opening fragments here lets {@link withThumb} see every part.
402
+ *
403
+ * A child taken out of a fragment is re-keyed with the fragment's key in front,
404
+ * so keys stay unique across the flattened list and stable between renders.
405
+ */
406
+ function flattenFragments(children: ReactNode, keyPrefix = ""): ReactNode[] {
407
+ return Children.toArray(children).flatMap((child) => {
408
+ if (!isValidElement<{ children?: ReactNode }>(child)) return [child];
409
+ const key = `${keyPrefix}${String(child.key)}`;
410
+ if (child.type === Fragment) return flattenFragments(child.props.children, key);
411
+ return keyPrefix ? [cloneElement(child, { key })] : [child];
412
+ });
413
+ }
414
+
333
415
  /**
334
416
  * Whether a child is a `Switch.Thumb`.
335
417
  *
@@ -386,6 +468,8 @@ function isSwitchThumbElement(child: ReactNode): boolean {
386
468
  *
387
469
  * There is no `Switch.Label`: the track is a fixed pill and a label cannot sit
388
470
  * inside it, so the name is a `Field.Label` or a `ListGroup.ItemTitle` a row away.
471
+ * Inside a `Field`, the `Field.Label` text becomes the switch's accessible name
472
+ * unless an `accessibilityLabel` is passed.
389
473
  * A switch with no label anywhere near it needs an `accessibilityLabel`, the same
390
474
  * rule an icon-sized `Button` follows.
391
475
  *
@@ -1,8 +1,9 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { declarationCount, TOKENS_CSS } from "../../styles/theme-tokens.test";
2
+ import { declarationCount, type ThemeVariant, TOKENS_CSS, tokenValue } from "../../styles/theme-tokens.test";
3
3
  import { ICON_SIZES } from "../icon/icon.variants";
4
4
  import {
5
5
  hasThumbChild,
6
+ resolveSwitchActivation,
6
7
  resolveSwitchAxes,
7
8
  resolveSwitchContentTreatment,
8
9
  resolveSwitchRelease,
@@ -35,6 +36,77 @@ import {
35
36
  /** The minimum a touch target may be, in points. Apple's number, and Android's. */
36
37
  const MINIMUM_TARGET = 44;
37
38
 
39
+ /** An sRGB colour, gamma-encoded, each channel 0–1, with its alpha. */
40
+ type Srgba = { rgb: [number, number, number]; alpha: number };
41
+
42
+ /** A CSS number that may be written as a percentage, as a fraction of `whole`. */
43
+ function cssNumber(value: string, whole: number): number {
44
+ return value.endsWith("%") ? (Number.parseFloat(value) / 100) * whole : Number.parseFloat(value);
45
+ }
46
+
47
+ /**
48
+ * An `oklch(L C H / A)` value as gamma-encoded sRGB, clamped into gamut.
49
+ *
50
+ * OKLCH to OKLab to linear sRGB, with Björn Ottosson's published matrices, then
51
+ * the sRGB transfer curve. `theme.css` writes every colour this way, so this is
52
+ * the one form the contrast check has to read.
53
+ */
54
+ function parseOklch(value: string): Srgba {
55
+ const match = value.match(/^oklch\(\s*([\d.]+%?)\s+([\d.]+%?)\s+([\d.]+)(?:\s*\/\s*([\d.]+%?))?\s*\)$/);
56
+ if (!match) throw new Error(`not an oklch() colour: ${value}`);
57
+ const [, lightness = "0", chroma = "0", hue = "0", alpha] = match;
58
+ const l = cssNumber(lightness, 1);
59
+ const c = cssNumber(chroma, 0.4);
60
+ const h = (Number.parseFloat(hue) * Math.PI) / 180;
61
+ const a = c * Math.cos(h);
62
+ const b = c * Math.sin(h);
63
+
64
+ const lms = [
65
+ (l + 0.3963377774 * a + 0.2158037573 * b) ** 3,
66
+ (l - 0.1055613458 * a - 0.0638541728 * b) ** 3,
67
+ (l - 0.0894841775 * a - 1.291485548 * b) ** 3,
68
+ ] as const;
69
+ const linear = [
70
+ 4.0767416621 * lms[0] - 3.3077115913 * lms[1] + 0.2309699292 * lms[2],
71
+ -1.2684380046 * lms[0] + 2.6097574011 * lms[1] - 0.3413193965 * lms[2],
72
+ -0.0041960863 * lms[0] - 0.7034186147 * lms[1] + 1.707614701 * lms[2],
73
+ ] as const;
74
+ const encode = (channel: number): number => {
75
+ const clamped = Math.min(1, Math.max(0, channel));
76
+ return clamped <= 0.0031308 ? 12.92 * clamped : 1.055 * clamped ** (1 / 2.4) - 0.055;
77
+ };
78
+
79
+ return {
80
+ rgb: [encode(linear[0]), encode(linear[1]), encode(linear[2])],
81
+ alpha: alpha === undefined ? 1 : cssNumber(alpha, 1),
82
+ };
83
+ }
84
+
85
+ /** A colour painted over an opaque one, blended the way the GPU does, in encoded sRGB. */
86
+ function composite(top: Srgba, behind: Srgba): Srgba {
87
+ const mix = (index: 0 | 1 | 2): number => top.rgb[index] * top.alpha + behind.rgb[index] * (1 - top.alpha);
88
+ return { rgb: [mix(0), mix(1), mix(2)], alpha: 1 };
89
+ }
90
+
91
+ /** WCAG relative luminance of an opaque sRGB colour. */
92
+ function luminance({ rgb }: Srgba): number {
93
+ const [r = 0, g = 0, b = 0] = rgb.map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
94
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
95
+ }
96
+
97
+ /** WCAG contrast ratio between two opaque colours. */
98
+ function contrastRatio(a: Srgba, b: Srgba): number {
99
+ const [light = 0, dark = 0] = [luminance(a), luminance(b)].sort((x, y) => y - x);
100
+ return (light + 0.05) / (dark + 0.05);
101
+ }
102
+
103
+ /** A token's colour in one theme, read from `theme.css`. */
104
+ function themeColor(variant: ThemeVariant, token: string): Srgba {
105
+ const value = tokenValue(variant, token);
106
+ if (value === undefined) throw new Error(`theme.css declares no --${token} in ${variant}`);
107
+ return parseOklch(value);
108
+ }
109
+
38
110
  /** Tailwind's spacing step, in points — `h-6` is six of them. */
39
111
  const SPACING_STEP = 4;
40
112
 
@@ -230,8 +302,10 @@ describe("switchVariants slots", () => {
230
302
  // produce for a frame on every toggle.
231
303
  for (const size of SWITCH_SIZES) {
232
304
  const slots = slotsFor(size);
233
- expect(cls(slots.track())).toMatch(/\bbg-input\b/);
234
- expect(cls(slots.thumb())).toMatch(/\bbg-background\b/);
305
+ // The resting class is the resting token, so the first frame and the
306
+ // interpolated style start from the same colour.
307
+ expect(cls(slots.track()).split(" ")).toContain(`bg-${SWITCH_TRACK_REST_TOKEN}`);
308
+ expect(cls(slots.thumb()).split(" ")).toContain(`bg-${SWITCH_THUMB_REST_TOKEN}`);
235
309
  expect(cls(slots.track())).not.toMatch(/\bbg-(primary|success|warning|destructive|info)\b/);
236
310
  expect(cls(slots.thumb())).not.toMatch(/\bbg-(primary|success|warning|destructive|info)\b/);
237
311
  }
@@ -322,6 +396,21 @@ describe("switch colour tokens", () => {
322
396
  }
323
397
  });
324
398
 
399
+ test("the resting thumb reads at 3:1 or more against the resting track and the surface under it", () => {
400
+ // With no On/Off text beside it, the knob is the only sign of the state, so
401
+ // it has to meet the 3:1 non-text contrast minimum (WCAG 1.4.11). The dark
402
+ // track is translucent, so it is measured over each surface a switch sits on.
403
+ for (const variant of ["light", "dark"] as const) {
404
+ const thumb = themeColor(variant, SWITCH_THUMB_REST_TOKEN);
405
+ for (const surface of ["background", "card"]) {
406
+ const behind = themeColor(variant, surface);
407
+ const track = composite(themeColor(variant, SWITCH_TRACK_REST_TOKEN), behind);
408
+ expect(contrastRatio(thumb, track)).toBeGreaterThanOrEqual(3);
409
+ expect(contrastRatio(thumb, behind)).toBeGreaterThanOrEqual(3);
410
+ }
411
+ }
412
+ });
413
+
325
414
  test("every token named is declared in both variants of theme.css", () => {
326
415
  // A token no theme emits resolves to undefined, is dropped, and the surface
327
416
  // silently keeps whatever it started as.
@@ -431,8 +520,12 @@ describe("resolveSwitchRelease", () => {
431
520
  test("a release that barely moved is a tap, and toggles", () => {
432
521
  // This is what lets one Gesture.Pan() serve both gestures rather than
433
522
  // racing a Tap against it.
434
- expect(resolveSwitchRelease({ progress: 0, distance: 0, velocity: 0, wasSelected: false })).toBe(true);
435
- expect(resolveSwitchRelease({ progress: 1, distance: 0, velocity: 0, wasSelected: true })).toBe(false);
523
+ expect(
524
+ resolveSwitchRelease({ progress: 0, distance: 0, horizontalDistance: 0, velocity: 0, wasSelected: false })
525
+ ).toBe(true);
526
+ expect(
527
+ resolveSwitchRelease({ progress: 1, distance: 0, horizontalDistance: 0, velocity: 0, wasSelected: true })
528
+ ).toBe(false);
436
529
  });
437
530
 
438
531
  test("a vertical swipe over the switch is not a tap and changes nothing", () => {
@@ -440,45 +533,95 @@ describe("resolveSwitchRelease", () => {
440
533
  // but it did move, so reading the along-track translation alone would have
441
534
  // called this a tap and toggled on every attempt to scroll past.
442
535
  const scroll = SWITCH_TAP_SLOP + 30;
443
- expect(resolveSwitchRelease({ progress: 0, distance: scroll, velocity: 0, wasSelected: false })).toBe(false);
444
- expect(resolveSwitchRelease({ progress: 1, distance: scroll, velocity: 0, wasSelected: true })).toBe(true);
536
+ expect(
537
+ resolveSwitchRelease({ progress: 0, distance: scroll, horizontalDistance: 0, velocity: 0, wasSelected: false })
538
+ ).toBe(false);
539
+ expect(
540
+ resolveSwitchRelease({ progress: 1, distance: scroll, horizontalDistance: 0, velocity: 0, wasSelected: true })
541
+ ).toBe(true);
445
542
  });
446
543
 
447
544
  test("the tap slop is a tolerance, and a hair past it is not a tap", () => {
448
- expect(resolveSwitchRelease({ progress: 0, distance: SWITCH_TAP_SLOP - 1, velocity: 0, wasSelected: false })).toBe(
449
- true
450
- );
451
- expect(resolveSwitchRelease({ progress: 0, distance: SWITCH_TAP_SLOP, velocity: 0, wasSelected: false })).toBe(
452
- false
453
- );
545
+ expect(
546
+ resolveSwitchRelease({
547
+ progress: 0,
548
+ distance: SWITCH_TAP_SLOP - 1,
549
+ horizontalDistance: SWITCH_TAP_SLOP - 1,
550
+ velocity: 0,
551
+ wasSelected: false,
552
+ })
553
+ ).toBe(true);
554
+ expect(
555
+ resolveSwitchRelease({
556
+ progress: 0,
557
+ distance: SWITCH_TAP_SLOP,
558
+ horizontalDistance: SWITCH_TAP_SLOP,
559
+ velocity: 0,
560
+ wasSelected: false,
561
+ })
562
+ ).toBe(false);
454
563
  });
455
564
 
456
565
  test("a drag past the slop is settled by position, not by the state it started in", () => {
457
566
  const past = SWITCH_TAP_SLOP + 1;
458
- expect(resolveSwitchRelease({ progress: 0.2, distance: past, velocity: 0, wasSelected: false })).toBe(false);
459
- expect(resolveSwitchRelease({ progress: 0.8, distance: past, velocity: 0, wasSelected: false })).toBe(true);
567
+ expect(
568
+ resolveSwitchRelease({ progress: 0.2, distance: past, horizontalDistance: past, velocity: 0, wasSelected: false })
569
+ ).toBe(false);
570
+ expect(
571
+ resolveSwitchRelease({ progress: 0.8, distance: past, horizontalDistance: past, velocity: 0, wasSelected: false })
572
+ ).toBe(true);
460
573
  });
461
574
 
462
575
  test("a drag out and back commits nothing", () => {
463
576
  // It travelled, so it is not a tap; it came back, so position says off.
464
- expect(resolveSwitchRelease({ progress: 0.05, distance: 40, velocity: 0, wasSelected: false })).toBe(false);
577
+ expect(
578
+ resolveSwitchRelease({ progress: 0.05, distance: 40, horizontalDistance: 40, velocity: 0, wasSelected: false })
579
+ ).toBe(false);
465
580
  });
466
581
 
467
582
  test("a flick beats the position it stopped at", () => {
468
583
  // The one case where position is the wrong question: let go fast enough and
469
584
  // the switch goes the way the finger was going.
470
585
  const fling = SWITCH_FLING_VELOCITY + 1;
471
- expect(resolveSwitchRelease({ progress: 0.1, distance: 10, velocity: fling, wasSelected: false })).toBe(true);
472
- expect(resolveSwitchRelease({ progress: 0.9, distance: 10, velocity: -fling, wasSelected: true })).toBe(false);
586
+ expect(
587
+ resolveSwitchRelease({ progress: 0.1, distance: 10, horizontalDistance: 10, velocity: fling, wasSelected: false })
588
+ ).toBe(true);
589
+ expect(
590
+ resolveSwitchRelease({ progress: 0.9, distance: 10, horizontalDistance: 10, velocity: -fling, wasSelected: true })
591
+ ).toBe(false);
473
592
  });
474
593
 
475
594
  test("a slow release below the fling threshold is left to the position", () => {
476
595
  const slow = SWITCH_FLING_VELOCITY - 1;
477
- expect(resolveSwitchRelease({ progress: 0.1, distance: 10, velocity: slow, wasSelected: false })).toBe(false);
596
+ expect(
597
+ resolveSwitchRelease({ progress: 0.1, distance: 10, horizontalDistance: 10, velocity: slow, wasSelected: false })
598
+ ).toBe(false);
599
+ });
600
+
601
+ test("a vertical swipe keeps the state even when the thumb is caught mid-animation", () => {
602
+ // Grabbed while springing on (progress still 0.2) or off (still 0.8): the
603
+ // position has not caught up with the state, so settling by position would
604
+ // flip it. With no movement along the track there is no intent to change it.
605
+ const scroll = SWITCH_TAP_SLOP + 30;
606
+ expect(
607
+ resolveSwitchRelease({ progress: 0.2, distance: scroll, horizontalDistance: 0, velocity: 0, wasSelected: true })
608
+ ).toBe(true);
609
+ expect(
610
+ resolveSwitchRelease({ progress: 0.8, distance: scroll, horizontalDistance: 0, velocity: 0, wasSelected: false })
611
+ ).toBe(false);
612
+ });
613
+
614
+ test("a horizontal drag out and back is still settled by position", () => {
615
+ const out = SWITCH_TAP_SLOP + 10;
616
+ expect(
617
+ resolveSwitchRelease({ progress: 0.05, distance: out, horizontalDistance: out, velocity: 0, wasSelected: true })
618
+ ).toBe(false);
478
619
  });
479
620
 
480
621
  test("exactly half way settles off, so the midpoint is not a coin toss", () => {
481
- expect(resolveSwitchRelease({ progress: 0.5, distance: 20, velocity: 0, wasSelected: false })).toBe(false);
622
+ expect(
623
+ resolveSwitchRelease({ progress: 0.5, distance: 20, horizontalDistance: 20, velocity: 0, wasSelected: false })
624
+ ).toBe(false);
482
625
  });
483
626
  });
484
627
 
@@ -564,3 +707,43 @@ describe("content treatment", () => {
564
707
  }
565
708
  });
566
709
  });
710
+
711
+ describe("resolveSwitchActivation", () => {
712
+ test("Android lists 'activate', so a TalkBack double-tap reaches the toggle", () => {
713
+ expect(resolveSwitchActivation({ platform: "android" })).toEqual({
714
+ accessibilityActions: [{ name: "activate" }],
715
+ routesActivate: true,
716
+ });
717
+ });
718
+
719
+ test("iOS lists nothing, so the VoiceOver rotor gains no literal 'activate' entry", () => {
720
+ // `onAccessibilityTap` already answers a VoiceOver double-tap there.
721
+ expect(resolveSwitchActivation({ platform: "ios" })).toEqual({
722
+ accessibilityActions: undefined,
723
+ routesActivate: false,
724
+ });
725
+ });
726
+
727
+ test("Android appends 'activate' after a caller's own actions instead of dropping it", () => {
728
+ expect(
729
+ resolveSwitchActivation({ accessibilityActions: [{ label: "Help", name: "help" }], platform: "android" })
730
+ ).toEqual({ accessibilityActions: [{ label: "Help", name: "help" }, { name: "activate" }], routesActivate: true });
731
+ });
732
+
733
+ test("iOS leaves a caller's own actions untouched", () => {
734
+ const actions = [{ label: "Help", name: "help" }];
735
+ expect(resolveSwitchActivation({ accessibilityActions: actions, platform: "ios" }).accessibilityActions).toBe(
736
+ actions
737
+ );
738
+ });
739
+
740
+ test("a caller that lists 'activate' owns it, so the switch never toggles twice", () => {
741
+ const actions = [{ name: "activate" }];
742
+ for (const platform of ["ios", "android"]) {
743
+ expect(resolveSwitchActivation({ accessibilityActions: actions, platform })).toEqual({
744
+ accessibilityActions: actions,
745
+ routesActivate: false,
746
+ });
747
+ }
748
+ });
749
+ });
@@ -128,11 +128,10 @@ export const SWITCH_TRACK_TOKEN: Record<SwitchColor, string> = {
128
128
  /**
129
129
  * The track a switch that is off wears.
130
130
  *
131
- * `input` rather than `secondary`, and it is the token that makes the knob
132
- * legible without a border: it is the chrome a field's own box wears, a step
133
- * darker than the page in light and a step lighter in dark, so a knob painted
134
- * the page's own colour reads against it at either end of the theme. `secondary`
135
- * sits too close to the surface behind it for that.
131
+ * `input` rather than `secondary`: it is the chrome a field's own box wears, a
132
+ * step away from the page, so the off pill still has a shape. `secondary` sits
133
+ * too close to the surface behind it for that. The knob, not the track, carries
134
+ * the contrast: see {@link SWITCH_THUMB_REST_TOKEN}.
136
135
  */
137
136
  export const SWITCH_TRACK_REST_TOKEN = "input";
138
137
 
@@ -159,8 +158,17 @@ export const SWITCH_THUMB_TOKEN: Record<SwitchColor, string> = {
159
158
  info: "info-foreground",
160
159
  };
161
160
 
162
- /** The thumb a switch that is off wears. */
163
- export const SWITCH_THUMB_REST_TOKEN = "background";
161
+ /**
162
+ * The thumb a switch that is off wears.
163
+ *
164
+ * `muted-foreground`, not `background`. With no On/Off text beside it, the knob
165
+ * is the only sign of the state, so it must meet the 3:1 non-text contrast
166
+ * minimum (WCAG 1.4.11) against the resting track and the surface behind it. A
167
+ * knob in the page's own colour reached 1.21:1 on the light `input` track and
168
+ * 1.47:1 on the dark one; this reaches 3.76:1 and 4.39:1 at the least. A test
169
+ * computes the ratios from `theme.css`.
170
+ */
171
+ export const SWITCH_THUMB_REST_TOKEN = "muted-foreground";
164
172
 
165
173
  /** The thumb, on or off, once the switch is reporting an invalid value. */
166
174
  export const SWITCH_INVALID_THUMB_TOKEN = "destructive-foreground";
@@ -279,7 +287,7 @@ export const switchVariants = tv({
279
287
  /** The capsule. Its colour is an animated style, never a class. */
280
288
  track: "relative justify-center overflow-hidden rounded-full bg-input",
281
289
  /** The knob. Its position and its colour are one animated style. */
282
- thumb: "absolute left-0.75 items-center justify-center rounded-full bg-background",
290
+ thumb: "absolute left-0.75 items-center justify-center rounded-full bg-muted-foreground",
283
291
  /** Behind the thumb at the leading edge. Revealed as the switch turns on. */
284
292
  startContent: "absolute left-0.75 items-center justify-center",
285
293
  /** Behind the thumb at the trailing edge. Revealed as the switch turns off. */
@@ -444,9 +452,14 @@ export function switchTravel({
444
452
  * racing a `Tap` against it. `distance` is deliberately not the along-track
445
453
  * translation: a vertical swipe that began on the switch moves nothing
446
454
  * horizontally, and reading only that axis would turn every attempt to scroll
447
- * past the control into a toggle. A release travelling fast is a **flick**, and
448
- * goes the way the finger was going however short of half way it stopped.
449
- * Anything else is settled by position.
455
+ * past the control into a toggle. It is also the peak over the gesture, not the
456
+ * translation at release, so a drag out and back is not a tap. A gesture past
457
+ * the slop that never moved **along the track** (`horizontalDistance` under the
458
+ * slop) is a scroll, not a drag, and keeps the state: grabbed mid-animation, the
459
+ * thumb's position can still say the old state, and settling by it would flip
460
+ * the switch. A release travelling fast is a **flick**, and goes the way the
461
+ * finger was going however short of half way it stopped. Anything else is
462
+ * settled by position.
450
463
  *
451
464
  * Marked `"worklet"` and written flat — it calls nothing, not even to clamp.
452
465
  * A module-scope worklet is rewritten into a factory call that runs at import
@@ -459,17 +472,21 @@ export function switchTravel({
459
472
  export function resolveSwitchRelease({
460
473
  progress,
461
474
  distance,
475
+ horizontalDistance,
462
476
  velocity,
463
477
  wasSelected,
464
478
  }: {
465
479
  progress: number;
466
- /** How far the finger moved, in points, on whichever axis moved further. */
480
+ /** The furthest the finger got over the gesture, in points, on whichever axis moved further. */
467
481
  distance: number;
482
+ /** The furthest the finger got along the track over the gesture, in points. */
483
+ horizontalDistance: number;
468
484
  velocity: number;
469
485
  wasSelected: boolean;
470
486
  }): boolean {
471
487
  "worklet";
472
488
  if (distance < SWITCH_TAP_SLOP) return !wasSelected;
489
+ if (horizontalDistance < SWITCH_TAP_SLOP) return wasSelected;
473
490
  if (velocity > SWITCH_FLING_VELOCITY) return true;
474
491
  if (velocity < -SWITCH_FLING_VELOCITY) return false;
475
492
  return progress > 0.5;
@@ -509,3 +526,45 @@ export function resolveSwitchContentTreatment({
509
526
  }
510
527
 
511
528
  export type SwitchVariantProps = VariantProps<typeof switchVariants>;
529
+
530
+ /** The one built-in action. Module scope, so the list keeps one identity. */
531
+ const SWITCH_ACTIVATE_ACTION = { name: "activate" } as const;
532
+ const SWITCH_ANDROID_ACCESSIBILITY_ACTIONS = [SWITCH_ACTIVATE_ACTION] as const;
533
+
534
+ /** An accessibility action as React Native takes it. Structural, so this file stays pure. */
535
+ export type SwitchAccessibilityAction = { readonly name: string; readonly label?: string };
536
+
537
+ /**
538
+ * The accessibility actions the root lists, and whether it routes `activate` to
539
+ * its own toggle. The caller's actions are merged in, never dropped.
540
+ *
541
+ * **Android** appends `activate` after the caller's actions. The root is not a
542
+ * `Pressable`, so a TalkBack double-tap reaches `onAccessibilityAction` only
543
+ * when `activate` is listed. Without it the switch would announce its state and
544
+ * offer no way to change it.
545
+ *
546
+ * **iOS** keeps the caller's actions as they are and adds nothing.
547
+ * `onAccessibilityTap` already answers a VoiceOver double-tap, and Fabric shows
548
+ * every listed action as a rotor custom action, so `activate` would add a
549
+ * literal "activate" entry. `Pressable` makes the same split for the same reason.
550
+ *
551
+ * A caller that lists `activate` itself owns it on both platforms, and the
552
+ * switch routes nothing for it, so one activation never toggles twice. This is
553
+ * the rule `resolvePressableActivation` follows.
554
+ *
555
+ * Takes the platform rather than reading `Platform.OS`, so the file stays pure.
556
+ */
557
+ export function resolveSwitchActivation<A extends SwitchAccessibilityAction>({
558
+ accessibilityActions,
559
+ platform,
560
+ }: {
561
+ accessibilityActions?: readonly A[];
562
+ platform: string;
563
+ }): { accessibilityActions: readonly (A | typeof SWITCH_ACTIVATE_ACTION)[] | undefined; routesActivate: boolean } {
564
+ const ownsActivate = accessibilityActions?.some((action) => action.name === "activate") === true;
565
+ if (platform !== "android" || ownsActivate) return { accessibilityActions, routesActivate: false };
566
+ if (accessibilityActions === undefined || accessibilityActions.length === 0) {
567
+ return { accessibilityActions: SWITCH_ANDROID_ACCESSIBILITY_ACTIONS, routesActivate: true };
568
+ }
569
+ return { accessibilityActions: [...accessibilityActions, SWITCH_ACTIVATE_ACTION], routesActivate: true };
570
+ }