@delacour/react-native-ui 0.10.0-alpha.20261120160127 → 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 +3 -3
- package/src/components/switch/AGENTS.md +35 -8
- package/src/components/switch/switch-thumb.tsx +12 -9
- package/src/components/switch/switch.render.test.tsx +116 -2
- package/src/components/switch/switch.tsx +50 -18
- package/src/components/switch/switch.variants.test.ts +203 -20
- package/src/components/switch/switch.variants.ts +69 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@delacour/react-native-ui",
|
|
3
|
-
"version": "0.
|
|
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.
|
|
190
|
-
"@delacour/react-native-charts": "0.
|
|
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, the `Field.Label` name, a caller's `accessibilityState
|
|
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
|
|
|
@@ -54,6 +54,12 @@ section to read first — what follows is only where a switch differs.
|
|
|
54
54
|
release.** The root tracks the furthest the finger got on either axis, resets
|
|
55
55
|
it in `onBegin`, and passes it at release. A slow drag out and back to near its
|
|
56
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.
|
|
57
63
|
- **The value is settled in `onFinalize`, and only there.** Unlike a slider there
|
|
58
64
|
is nothing to write on `onBegin`: a switch has no position to move a handle to,
|
|
59
65
|
only a state to end up in. `onFinalize` is still the callback because it is the
|
|
@@ -106,10 +112,9 @@ section to read first — what follows is only where a switch differs.
|
|
|
106
112
|
- **The knob draws no border and no shadow.** A border is a second line where
|
|
107
113
|
there is already a boundary, and against a saturated track it reads as a dark
|
|
108
114
|
ring rather than as definition; `Slider`'s handle dropped its own for the same
|
|
109
|
-
reason. Contrast at rest comes from the
|
|
110
|
-
`SWITCH_TRACK_REST_TOKEN` is `input
|
|
111
|
-
step
|
|
112
|
-
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.
|
|
113
118
|
- **The track and its touch padding ride in the same size cell**, summing to 44pt
|
|
114
119
|
at every size, and the test asserts the sum rather than the parts — `Slider`'s
|
|
115
120
|
rule, and the trap it names: split them across two variants and a shorter track
|
|
@@ -121,7 +126,7 @@ section to read first — what follows is only where a switch differs.
|
|
|
121
126
|
none of it.** The track, the thumb and both content layers fade between two
|
|
122
127
|
token *values* off the one `progress`, and a colour being interpolated cannot
|
|
123
128
|
be a class — `Checkbox`'s border, four times over. The slot set keeps
|
|
124
|
-
`bg-
|
|
129
|
+
`bg-input` and `bg-muted-foreground` as the resting appearance those styles start
|
|
125
130
|
from and names no colour anywhere else; the maps are the single source. There
|
|
126
131
|
is deliberately **no `color` axis in the `tv()`** — a `bg-*` per colour there
|
|
127
132
|
would be a second source for one surface, which is how a class and a style end
|
|
@@ -131,6 +136,17 @@ section to read first — what follows is only where a switch differs.
|
|
|
131
136
|
theme forces: there is no `--foreground-foreground`, and `background` is
|
|
132
137
|
what content drawn on the page's ink actually is. A test pins the whole map
|
|
133
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.
|
|
134
150
|
- **`Switch.StartContent` and `.EndContent` crossfade themselves.** Start sits at
|
|
135
151
|
the leading edge, which the knob vacates as the switch turns **on**, so it fades
|
|
136
152
|
in with `progress`; end is the mirror. That is the whole reason both can be
|
|
@@ -194,7 +210,15 @@ section to read first — what follows is only where a switch differs.
|
|
|
194
210
|
`onAccessibilityTap` and an `activate` entry in `accessibilityActions` are what
|
|
195
211
|
actually flip it, on iOS and Android respectively. Without them the switch would
|
|
196
212
|
announce its state and offer no way to change it — the same gap
|
|
197
|
-
`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.
|
|
198
222
|
- **The root is marked `accessible`, and that one word is load-bearing.** Without
|
|
199
223
|
it the view is not an accessibility element on iOS at all, so the role and the
|
|
200
224
|
checked state written beside it never reach VoiceOver. It also merges the track
|
|
@@ -220,7 +244,10 @@ section to read first — what follows is only where a switch differs.
|
|
|
220
244
|
same size and colour the only symptom is that **anything inside the caller's
|
|
221
245
|
knob disappears**. `displayName` survives all of it — rule 12 requires one, present and unique — so that is
|
|
222
246
|
what `isSwitchThumbElement` asks for, with reference equality kept only as the
|
|
223
|
-
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.
|
|
224
251
|
|
|
225
252
|
**[`Radio`](../radio/AGENTS.md) and `ListGroup` still ask the unsafe question**
|
|
226
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
|
|
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
|
*
|
|
@@ -71,24 +71,27 @@ export function SwitchThumb({ className, children, onLayout, ...props }: SwitchT
|
|
|
71
71
|
const activeColor = useThemeColor(tokens.active) ?? "transparent";
|
|
72
72
|
|
|
73
73
|
const thumbStyle = useAnimatedStyle(() => {
|
|
74
|
-
const measured = trackWidth.value;
|
|
75
74
|
const travel = switchTravel({
|
|
76
75
|
inset: SWITCH_THUMB_INSET,
|
|
77
76
|
thumbWidth: thumbWidth.value,
|
|
78
|
-
trackWidth:
|
|
77
|
+
trackWidth: trackWidth.value,
|
|
79
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;
|
|
80
82
|
|
|
81
83
|
return {
|
|
82
84
|
backgroundColor: interpolateColor(progress.value, [0, 1], [restColor, activeColor]),
|
|
83
|
-
opacity:
|
|
85
|
+
opacity: isMeasured ? 1 : 0,
|
|
84
86
|
transform: [{ translateX: progress.value * travel }],
|
|
85
87
|
};
|
|
86
88
|
});
|
|
87
89
|
|
|
88
|
-
// A glyph on the knob takes the *track*'s colour, not the knob's own: it is
|
|
89
|
-
// drawn on the knob, so it has to contrast with
|
|
90
|
-
//
|
|
91
|
-
//
|
|
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.
|
|
92
95
|
const slots = switchVariants({ isDisabled, size });
|
|
93
96
|
const glyphColor = useThemeColor(resolveSwitchTrackTokens({ color, isInvalid }).active);
|
|
94
97
|
const glyphClassName = slots.glyph();
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { describe, expect, jest, test } from "@jest/globals";
|
|
1
|
+
import { afterEach, describe, expect, jest, test } from "@jest/globals";
|
|
2
|
+
import { Platform } from "react-native";
|
|
2
3
|
import { State } from "react-native-gesture-handler";
|
|
3
4
|
import { fireGestureHandler, getByGestureTestId } from "react-native-gesture-handler/jest-utils";
|
|
4
5
|
import { act, fireEvent, renderWithProviders, screen, waitFor } from "../../test/render";
|
|
@@ -10,6 +11,11 @@ const layout = (width: number) => ({ nativeEvent: { layout: { height: 0, width,
|
|
|
10
11
|
|
|
11
12
|
type Instance = ReturnType<typeof screen.getByTestId>;
|
|
12
13
|
|
|
14
|
+
// Puts back a `Platform.OS` a test replaced.
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
jest.restoreAllMocks();
|
|
17
|
+
});
|
|
18
|
+
|
|
13
19
|
/** The track is the root's only child: the node that clips the thumb and reports the travel. */
|
|
14
20
|
const track = (id = "switch"): Instance => {
|
|
15
21
|
const [first] = screen.getByTestId(id).children;
|
|
@@ -24,6 +30,11 @@ const translateX = (element: Instance): number | undefined => {
|
|
|
24
30
|
return jestAnimatedStyle?.value.transform?.[0]?.translateX;
|
|
25
31
|
};
|
|
26
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
|
+
|
|
27
38
|
type PanStep = { state: State; translationX?: number; translationY?: number };
|
|
28
39
|
|
|
29
40
|
/** Sends one pan to the switch, filling in what each step leaves out. */
|
|
@@ -70,7 +81,7 @@ describe("Switch", () => {
|
|
|
70
81
|
const view = await renderWithProviders(
|
|
71
82
|
<Switch accessibilityLabel="Wi-Fi" isSelected={false} onSelectedChange={onSelectedChange} />
|
|
72
83
|
);
|
|
73
|
-
await fireEvent(screen.getByRole("switch"), "
|
|
84
|
+
await fireEvent(screen.getByRole("switch"), "accessibilityTap");
|
|
74
85
|
expect(onSelectedChange).toHaveBeenCalledWith(true);
|
|
75
86
|
expect(screen.getByRole("switch")).not.toBeChecked();
|
|
76
87
|
|
|
@@ -89,6 +100,45 @@ describe("Switch", () => {
|
|
|
89
100
|
});
|
|
90
101
|
|
|
91
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
|
+
|
|
92
142
|
test("calls a caller's onLayout and still measures itself", async () => {
|
|
93
143
|
const onLayout = jest.fn();
|
|
94
144
|
await renderWithProviders(
|
|
@@ -122,6 +172,47 @@ describe("Switch accessibility", () => {
|
|
|
122
172
|
});
|
|
123
173
|
});
|
|
124
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
|
+
|
|
125
216
|
test("is named by a sibling Field.Label", async () => {
|
|
126
217
|
await renderWithProviders(
|
|
127
218
|
<Field>
|
|
@@ -224,4 +315,27 @@ describe("Switch gesture", () => {
|
|
|
224
315
|
|
|
225
316
|
expect(onSelectedChange).not.toHaveBeenCalled();
|
|
226
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
|
+
});
|
|
227
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,7 +11,7 @@ import {
|
|
|
9
11
|
useRef,
|
|
10
12
|
useState,
|
|
11
13
|
} from "react";
|
|
12
|
-
import type
|
|
14
|
+
import { type AccessibilityActionEvent, type LayoutChangeEvent, Platform, type ViewProps } from "react-native";
|
|
13
15
|
import { Gesture, GestureDetector, State } from "react-native-gesture-handler";
|
|
14
16
|
import Animated, {
|
|
15
17
|
cancelAnimation,
|
|
@@ -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,8 +74,10 @@ function SwitchRoot({
|
|
|
71
74
|
isInvalid,
|
|
72
75
|
haptic = "selection",
|
|
73
76
|
className,
|
|
77
|
+
accessibilityActions,
|
|
74
78
|
accessibilityLabel,
|
|
75
79
|
accessibilityState,
|
|
80
|
+
onAccessibilityAction,
|
|
76
81
|
children,
|
|
77
82
|
...props
|
|
78
83
|
}: SwitchProps): ReactElement {
|
|
@@ -102,6 +107,9 @@ function SwitchRoot({
|
|
|
102
107
|
// whole gesture. Read at release rather than the final translation, so a drag
|
|
103
108
|
// out and back to its start is still a drag and not a tap.
|
|
104
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);
|
|
105
113
|
|
|
106
114
|
// A ref rather than state: the pan reads it twice a drag and nothing renders
|
|
107
115
|
// differently for it, so a re-render on touch-down would be pure cost.
|
|
@@ -156,6 +164,7 @@ function SwitchRoot({
|
|
|
156
164
|
"worklet";
|
|
157
165
|
grabbed.value = progress.value;
|
|
158
166
|
peakDistance.value = 0;
|
|
167
|
+
peakHorizontal.value = 0;
|
|
159
168
|
isPressed.value = withSpring(1, SWITCH_PRESS_SPRING);
|
|
160
169
|
scheduleOnRN(setDragging, true);
|
|
161
170
|
})
|
|
@@ -164,6 +173,7 @@ function SwitchRoot({
|
|
|
164
173
|
// Before the travel check: a vertical swipe moves no thumb but still
|
|
165
174
|
// counts as movement.
|
|
166
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));
|
|
167
177
|
|
|
168
178
|
const travel = switchTravel({
|
|
169
179
|
inset: SWITCH_THUMB_INSET,
|
|
@@ -194,6 +204,7 @@ function SwitchRoot({
|
|
|
194
204
|
// returns near its start does not read as a tap either.
|
|
195
205
|
const target = resolveSwitchRelease({
|
|
196
206
|
distance: Math.max(peakDistance.value, Math.abs(event.translationX), Math.abs(event.translationY)),
|
|
207
|
+
horizontalDistance: Math.max(peakHorizontal.value, Math.abs(event.translationX)),
|
|
197
208
|
progress: progress.value,
|
|
198
209
|
velocity: event.velocityX,
|
|
199
210
|
wasSelected: selected,
|
|
@@ -222,6 +233,7 @@ function SwitchRoot({
|
|
|
222
233
|
isGestureDisabled,
|
|
223
234
|
isPressed,
|
|
224
235
|
peakDistance,
|
|
236
|
+
peakHorizontal,
|
|
225
237
|
progress,
|
|
226
238
|
selected,
|
|
227
239
|
setDragging,
|
|
@@ -297,11 +309,24 @@ function SwitchRoot({
|
|
|
297
309
|
const content = useMemo(() => withThumb(children), [children]);
|
|
298
310
|
const slots = switchVariants({ isDisabled: axes.isDisabled, size: axes.size });
|
|
299
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
|
+
);
|
|
300
321
|
const handleAccessibilityAction = useCallback(
|
|
301
322
|
(event: AccessibilityActionEvent) => {
|
|
302
|
-
if (event.nativeEvent.actionName === "activate")
|
|
323
|
+
if (activation.routesActivate && event.nativeEvent.actionName === "activate") {
|
|
324
|
+
toggle();
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
onAccessibilityAction?.(event);
|
|
303
328
|
},
|
|
304
|
-
[toggle]
|
|
329
|
+
[activation.routesActivate, onAccessibilityAction, toggle]
|
|
305
330
|
);
|
|
306
331
|
|
|
307
332
|
// `accessibilityState` is merged, not replaced: a caller's `busy` must not
|
|
@@ -314,7 +339,7 @@ function SwitchRoot({
|
|
|
314
339
|
<SwitchProvider value={context}>
|
|
315
340
|
<GestureDetector gesture={gesture}>
|
|
316
341
|
<Animated.View
|
|
317
|
-
accessibilityActions={
|
|
342
|
+
accessibilityActions={activation.accessibilityActions}
|
|
318
343
|
accessibilityLabel={accessibilityLabel ?? field?.label ?? undefined}
|
|
319
344
|
accessibilityRole="switch"
|
|
320
345
|
accessibilityState={{ ...accessibilityState, checked: selected, disabled: axes.isDisabled }}
|
|
@@ -336,19 +361,6 @@ function SwitchRoot({
|
|
|
336
361
|
);
|
|
337
362
|
}
|
|
338
363
|
|
|
339
|
-
/**
|
|
340
|
-
* The one action an assistive double-tap on a `switch` maps to.
|
|
341
|
-
*
|
|
342
|
-
* Module scope on purpose: a fresh array each render is a new prop every commit,
|
|
343
|
-
* and React Native sends the whole accessibility config across on any change.
|
|
344
|
-
*
|
|
345
|
-
* It exists at all because the root is not a `Pressable` — there is no touch
|
|
346
|
-
* responder for TalkBack's activation to land on, so without this the switch
|
|
347
|
-
* would announce its state and offer no way to change it. `onAccessibilityTap`
|
|
348
|
-
* is the iOS half of the same gap.
|
|
349
|
-
*/
|
|
350
|
-
const ACCESSIBILITY_ACTIONS = [{ name: "activate" }] as const;
|
|
351
|
-
|
|
352
364
|
/** Read inside the pan's worklets, so it is a plain number captured once. */
|
|
353
365
|
const PAN_CANCELLED = State.CANCELLED;
|
|
354
366
|
|
|
@@ -372,7 +384,7 @@ const PAN_CANCELLED = State.CANCELLED;
|
|
|
372
384
|
* children, and importing it from a part would close a cycle. See AGENTS.md.
|
|
373
385
|
*/
|
|
374
386
|
function withThumb(children: ReactNode): ReactNode {
|
|
375
|
-
const items =
|
|
387
|
+
const items = flattenFragments(children);
|
|
376
388
|
const isThumb = items.map(isSwitchThumbElement);
|
|
377
389
|
|
|
378
390
|
if (!hasThumbChild(isThumb)) return [...items, <SwitchThumb key="thumb" />];
|
|
@@ -380,6 +392,26 @@ function withThumb(children: ReactNode): ReactNode {
|
|
|
380
392
|
return [...items.filter((_, index) => !isThumb[index]), ...items.filter((_, index) => isThumb[index])];
|
|
381
393
|
}
|
|
382
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
|
+
|
|
383
415
|
/**
|
|
384
416
|
* Whether a child is a `Switch.Thumb`.
|
|
385
417
|
*
|
|
@@ -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
|
-
|
|
234
|
-
|
|
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(
|
|
435
|
-
|
|
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(
|
|
444
|
-
|
|
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(
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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(
|
|
459
|
-
|
|
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(
|
|
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(
|
|
472
|
-
|
|
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(
|
|
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(
|
|
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
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
* the
|
|
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
|
-
/**
|
|
163
|
-
|
|
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-
|
|
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. */
|
|
@@ -445,10 +453,13 @@ export function switchTravel({
|
|
|
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
455
|
* past the control into a toggle. It is also the peak over the gesture, not the
|
|
448
|
-
* translation at release, so a drag out and back is not a tap. A
|
|
449
|
-
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
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.
|
|
452
463
|
*
|
|
453
464
|
* Marked `"worklet"` and written flat — it calls nothing, not even to clamp.
|
|
454
465
|
* A module-scope worklet is rewritten into a factory call that runs at import
|
|
@@ -461,17 +472,21 @@ export function switchTravel({
|
|
|
461
472
|
export function resolveSwitchRelease({
|
|
462
473
|
progress,
|
|
463
474
|
distance,
|
|
475
|
+
horizontalDistance,
|
|
464
476
|
velocity,
|
|
465
477
|
wasSelected,
|
|
466
478
|
}: {
|
|
467
479
|
progress: number;
|
|
468
480
|
/** The furthest the finger got over the gesture, in points, on whichever axis moved further. */
|
|
469
481
|
distance: number;
|
|
482
|
+
/** The furthest the finger got along the track over the gesture, in points. */
|
|
483
|
+
horizontalDistance: number;
|
|
470
484
|
velocity: number;
|
|
471
485
|
wasSelected: boolean;
|
|
472
486
|
}): boolean {
|
|
473
487
|
"worklet";
|
|
474
488
|
if (distance < SWITCH_TAP_SLOP) return !wasSelected;
|
|
489
|
+
if (horizontalDistance < SWITCH_TAP_SLOP) return wasSelected;
|
|
475
490
|
if (velocity > SWITCH_FLING_VELOCITY) return true;
|
|
476
491
|
if (velocity < -SWITCH_FLING_VELOCITY) return false;
|
|
477
492
|
return progress > 0.5;
|
|
@@ -511,3 +526,45 @@ export function resolveSwitchContentTreatment({
|
|
|
511
526
|
}
|
|
512
527
|
|
|
513
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
|
+
}
|