@delacour/react-native-ui 0.7.0-alpha.20261104103056 → 0.7.0-alpha.20261104113139

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.7.0-alpha.20261104103056",
3
+ "version": "0.7.0-alpha.20261104113139",
4
4
  "description": "React Native UI components — Uniwind, Reanimated, Gesture Handler",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -182,8 +182,8 @@
182
182
  "expo-blur": ">=15",
183
183
  "@maplibre/maplibre-react-native": "^11.5.0",
184
184
  "@central-icons-react-native/round-outlined-radius-1-stroke-1.5": "^1.1",
185
- "@delacour/react-native-bottom-sheet": "0.7.0-alpha.20261104103056",
186
- "@delacour/react-native-charts": "0.7.0-alpha.20261104103056",
185
+ "@delacour/react-native-bottom-sheet": "0.7.0-alpha.20261104113139",
186
+ "@delacour/react-native-charts": "0.7.0-alpha.20261104113139",
187
187
  "@legendapp/list": ">=3.3",
188
188
  "react-native-skia": ">=3.9.0",
189
189
  "expo-linear-gradient": ">=15",
@@ -22,9 +22,12 @@ navigator. `DelacourProvider` cannot mount it without importing the engine. See
22
22
  | `bottom-sheet.tsx` | `BottomSheet` — the engine's root with this library's defaults: `bottomInset` from the safe area, the two haptics, the stale-keyboard guard. The `Object.assign` names every part |
23
23
  | `bottom-sheet.variants.ts` | The slotted `tv()` — `overlay`, `background` (with a `detached` variant), `handle`, `handleIndicator`, `content`, `scrollContent`, `steps`, `step`, `footer`, `stickyFooter`, `close`, `title` — and the numeric constants the engine's props take |
24
24
  | `bottom-sheet.variants.test.ts` | Every token the slots name exists in both themes; the rules below, pinned |
25
- | `bottom-sheet.render.test.tsx` | Mounted under Jest — trigger and Close open/shut it, defaultOpen, controlled isOpen, handle's adjustable role and escape, title, scrim semantics, parts outside the root throw |
25
+ | `bottom-sheet.render.test.tsx` | Mounted under Jest — trigger and Close open/shut it, defaultOpen, controlled isOpen, handle's adjustable role and escape, title, scrim semantics, parts outside the root throw, a fragment-wrapped handle, the app hidden under a modal sheet, back left to an open overlay |
26
26
  | `bottom-sheet-trigger.tsx` | `BottomSheet.Trigger` — this library's `Pressable`, or `asChild` to donate the press |
27
- | `bottom-sheet-overlay.tsx` | `BottomSheet.Overlay` — the engine's scrim in `bg-overlay`, opacity 1 |
27
+ | `bottom-sheet-portal.tsx` | `BottomSheet.Portal` — the engine's portal, plus whether it teleports to `"root"` |
28
+ | `bottom-sheet-overlay.tsx` | `BottomSheet.Overlay` — the engine's scrim in `bg-overlay`, opacity 1; registers the sheet as modal for screen readers |
29
+ | `bottom-sheet-provider.tsx` | `BottomSheetProvider` — the engine's provider, sharing teleport with `OverlayProvider`, hiding the app under a modal sheet |
30
+ | `bottom-sheet-modal.context.tsx` | **Leaf.** The modal-sheet registry context, the root-host context and `useHideAppWhileModal` |
28
31
  | `bottom-sheet-container.tsx` | `BottomSheet.Container` — the panel; writes `Background` and `Handle` when the caller writes neither |
29
32
  | `bottom-sheet-background.tsx` | `BottomSheet.Background` — `bg-popover`, top corners rounded, every corner when detached |
30
33
  | `bottom-sheet-handle.tsx` | `BottomSheet.Handle` — the engine's row with the pill inside it |
@@ -41,8 +44,9 @@ navigator. `DelacourProvider` cannot mount it without importing the engine. See
41
44
  | `bottom-sheet-steps.tsx` | `BottomSheet.Steps` and `BottomSheet.Step` — the multi-step body, gutter on the stack and vertical padding on each step |
42
45
  | `use-bottom-sheet-input.ts` | `useBottomSheetInput()` — the engine's `useBottomSheetTextInput` under the name this library shipped |
43
46
 
44
- `Portal`, `Host` and `Provider` are the engine's own, re-exported unchanged:
45
- none of them draws anything a class could reach.
47
+ `Host` is the engine's own, re-exported unchanged. `Portal` and `Provider`
48
+ wrap the engine's for screen-reader modality only; they draw nothing a class
49
+ could reach.
46
50
 
47
51
  ## Anatomy
48
52
 
@@ -101,7 +105,7 @@ read those before touching behaviour, because behaviour is not here.
101
105
  it, which is what makes that safe where it was not with the library this
102
106
  replaces.
103
107
  - **`Container` writes `Background` and `Handle` for you** when the children
104
- hold neither, detected by element type. Write either yourself and it writes
108
+ hold neither, detected by element type and inside fragments too. Write either yourself and it writes
105
109
  nothing: a custom handle with no surface is a decision. The three
106
110
  `*ClassName` props reach only the parts it writes.
107
111
  - **`Title` and `Description` are `Text` presets**, through the engine's
@@ -123,12 +127,28 @@ read those before touching behaviour, because behaviour is not here.
123
127
  the UI thread. And `useKeyboardAnimationGuard()` runs on mount, the same
124
128
  stale-keyboard repair `Screen.Footer` runs. `topInset` stays at the engine's
125
129
  zero, so a `%` snap point is the fraction of the window it always was.
130
+ - **Android back skips a sheet under an overlay.** Sheets and overlays keep
131
+ separate registries, and `BackHandler` calls the newest listener first. The
132
+ engine re-subscribes when its methods change, so after a parent render the
133
+ sheet's listener is newer than a dialog's. The root turns `closeOnBack` off
134
+ while `topOverlay()` of the `OverlayProvider` registry is set, so back closes
135
+ the dialog and not the sheet under it.
126
136
  - **`Footer.sticky` defaults to `false`**, matching `Screen.Footer`, and this is
127
137
  the one engine default the skin overrides. A pinned footer takes
128
138
  `padding={BOTTOM_SHEET_FOOTER_PADDING}` through the engine's prop rather
129
139
  than a class, so the padding is inside the box the snap point measures; the
130
140
  `stickyFooter` slot carries the gutter, the surface and the hairline, and
131
141
  the test asserts it carries no vertical padding.
142
+ - **A scrim makes the sheet modal for screen readers.** The panel's
143
+ `accessibilityViewIsModal` hides only its siblings in the teleport host, not
144
+ the app, and sheets are not in `OverlayProvider`'s registry. So while a sheet
145
+ with an `Overlay` is presented in the `"root"` host, the overlay registers
146
+ with `BottomSheetProvider`, which sets `accessibilityElementsHidden` and
147
+ `importantForAccessibility="no-hide-descendants"` on the view around its
148
+ children. The `"root"` host draws beside that view, so the sheet stays
149
+ reachable. An inline sheet, a sheet in another `BottomSheet.Host` (inside the
150
+ app view) and `enableTouchThrough` do not register. Under Jest's inline
151
+ teleport (`isTeleportInline()`) it hides nothing, as `OverlayProvider` does.
132
152
  - **The overlay's opacity is 1**, because `--overlay` carries its own alpha and
133
153
  the two theme variants carry different ones. `BOTTOM_SHEET_OVERLAY_OPACITY`
134
154
  and `BOTTOM_SHEET_BACKDROP_INDICES` restate the engine's defaults so a test
@@ -2,7 +2,7 @@ import {
2
2
  BottomSheet as Headless,
3
3
  type BottomSheetContainerProps as HeadlessProps,
4
4
  } from "@delacour/react-native-bottom-sheet";
5
- import { Children, isValidElement, type ReactElement, type ReactNode } from "react";
5
+ import { Children, Fragment, isValidElement, type ReactElement, type ReactNode } from "react";
6
6
  import { withUniwind } from "uniwind";
7
7
  import { cn } from "../../lib/cn";
8
8
  import { BottomSheetBackground } from "./bottom-sheet-background";
@@ -30,11 +30,20 @@ export type BottomSheetContainerProps = HeadlessProps & {
30
30
  handleIndicatorClassName?: string;
31
31
  };
32
32
 
33
- /** Whether any direct child is one of the two parts the container would otherwise write itself. */
34
- function hasSurfaceParts(children: ReactNode): boolean {
35
- return Children.toArray(children).some(
36
- (child) => isValidElement(child) && (child.type === BottomSheetBackground || child.type === BottomSheetHandle)
37
- );
33
+ /**
34
+ * Whether the children hold one of the two parts the container would
35
+ * otherwise write itself.
36
+ *
37
+ * `Children.toArray` does not open fragments, so this walks into them: a
38
+ * `<>{showHandle && <BottomSheet.Handle />}</>` must count, or the sheet gets
39
+ * a second handle and a second adjustable element for screen readers.
40
+ */
41
+ export function hasSurfaceParts(children: ReactNode): boolean {
42
+ return Children.toArray(children).some((child) => {
43
+ if (!isValidElement<{ children?: ReactNode }>(child)) return false;
44
+ if (child.type === Fragment) return hasSurfaceParts(child.props.children);
45
+ return child.type === BottomSheetBackground || child.type === BottomSheetHandle;
46
+ });
38
47
  }
39
48
 
40
49
  /**
@@ -44,7 +53,7 @@ function hasSurfaceParts(children: ReactNode): boolean {
44
53
  * sheet's geometry; this adds classes and the two parts every sheet has.
45
54
  *
46
55
  * **It writes `Background` and `Handle` for you** when the children hold
47
- * neither, so the common sheet is `Container > Content` and nothing else. Write
56
+ * neither (directly or inside a fragment), so the common sheet is `Container > Content` and nothing else. Write
48
57
  * either one yourself and it writes nothing — a container with a custom handle
49
58
  * and no surface is a decision, not an omission. The three `*ClassName` props
50
59
  * reach the parts it writes; a part you write takes its own `className`.
@@ -0,0 +1,44 @@
1
+ import { createContext, useContext, useEffect, useId } from "react";
2
+
3
+ /**
4
+ * What `BottomSheetProvider` shares so a sheet can hide the app behind it.
5
+ *
6
+ * `register` adds one modal sheet and returns its removal. While any is
7
+ * registered the provider hides its children from VoiceOver and TalkBack.
8
+ */
9
+ export type BottomSheetModalContextValue = {
10
+ register: (id: string) => () => void;
11
+ };
12
+
13
+ export const BottomSheetModalContext = createContext<BottomSheetModalContextValue | null>(null);
14
+ BottomSheetModalContext.displayName = "DelacourUI.BottomSheet.ModalContext";
15
+
16
+ /**
17
+ * Whether the nearest `BottomSheet.Portal` teleports to the `"root"` host.
18
+ *
19
+ * Only that host draws outside the provider's children. An inline sheet, or
20
+ * one in a `BottomSheet.Host` inside the app (a native modal screen), draws
21
+ * inside them, so hiding the app would hide the sheet too.
22
+ */
23
+ export const BottomSheetRootHostContext = createContext(false);
24
+ BottomSheetRootHostContext.displayName = "DelacourUI.BottomSheet.RootHostContext";
25
+
26
+ /** True inside a `BottomSheet.Portal` that teleports to `"root"`. */
27
+ export function useIsInRootHost(): boolean {
28
+ return useContext(BottomSheetRootHostContext);
29
+ }
30
+
31
+ /**
32
+ * Hides the app from screen readers while `isModal` is true.
33
+ *
34
+ * A no-op without a `BottomSheetProvider` above.
35
+ */
36
+ export function useHideAppWhileModal(isModal: boolean): void {
37
+ const id = useId();
38
+ const register = useContext(BottomSheetModalContext)?.register;
39
+
40
+ useEffect(() => {
41
+ if (!isModal || register === undefined) return;
42
+ return register(id);
43
+ }, [isModal, register, id]);
44
+ }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  BottomSheet as Headless,
3
3
  type BottomSheetOverlayProps as HeadlessProps,
4
+ useBottomSheetInternal,
4
5
  } from "@delacour/react-native-bottom-sheet";
5
6
  import type { ReactElement } from "react";
6
7
  import { withUniwind } from "uniwind";
@@ -9,6 +10,7 @@ import {
9
10
  BOTTOM_SHEET_OVERLAY_OPACITY,
10
11
  bottomSheetVariants,
11
12
  } from "./bottom-sheet.variants";
13
+ import { useHideAppWhileModal, useIsInRootHost } from "./bottom-sheet-modal.context";
12
14
 
13
15
  type StyledOverlayComponent = (props: HeadlessProps & { className?: string }) => ReactElement | null;
14
16
 
@@ -32,6 +34,13 @@ export type BottomSheetOverlayProps = HeadlessProps & {
32
34
  * Omit it and the sheet has no scrim at all. `pressBehavior="none"` keeps it
33
35
  * and makes it inert, for a sheet that must be answered.
34
36
  *
37
+ * **A scrim makes the sheet modal for screen readers.** While the sheet is
38
+ * presented in the `"root"` host, the overlay tells `BottomSheetProvider` to
39
+ * hide the app from VoiceOver and TalkBack. The panel's
40
+ * `accessibilityViewIsModal` hides only its siblings in the host, not the app.
41
+ * An inline sheet, a sheet in another host, and `enableTouchThrough` leave the
42
+ * app reachable.
43
+ *
35
44
  * @example
36
45
  * <BottomSheet.Overlay />
37
46
  *
@@ -42,14 +51,20 @@ export function BottomSheetOverlay({
42
51
  appearsOnIndex = BOTTOM_SHEET_BACKDROP_INDICES.appearsOnIndex,
43
52
  className,
44
53
  disappearsOnIndex = BOTTOM_SHEET_BACKDROP_INDICES.disappearsOnIndex,
54
+ enableTouchThrough = false,
45
55
  opacity = BOTTOM_SHEET_OVERLAY_OPACITY,
46
56
  ...props
47
57
  }: BottomSheetOverlayProps): ReactElement {
58
+ const { presented } = useBottomSheetInternal();
59
+ const isInRootHost = useIsInRootHost();
60
+ useHideAppWhileModal(presented && isInRootHost && !enableTouchThrough);
61
+
48
62
  return (
49
63
  <StyledOverlay
50
64
  appearsOnIndex={appearsOnIndex}
51
65
  className={bottomSheetVariants().overlay({ className })}
52
66
  disappearsOnIndex={disappearsOnIndex}
67
+ enableTouchThrough={enableTouchThrough}
53
68
  opacity={opacity}
54
69
  {...props}
55
70
  />
@@ -0,0 +1,41 @@
1
+ import {
2
+ type BottomSheetPortalProps,
3
+ BottomSheet as Headless,
4
+ useOptionalBottomSheetHostName,
5
+ } from "@delacour/react-native-bottom-sheet";
6
+ import type { ReactElement } from "react";
7
+ import { BottomSheetRootHostContext } from "./bottom-sheet-modal.context";
8
+
9
+ export type PortalDestination = {
10
+ inline: boolean;
11
+ hostName: string | undefined;
12
+ /** The nearest host name, or `null` without a `BottomSheetProvider`. */
13
+ nearest: string | null;
14
+ };
15
+
16
+ /**
17
+ * Whether a portal teleports to the `"root"` host. Mirrors the engine's own
18
+ * rule: it teleports unless `inline` or there is no provider, to `hostName`
19
+ * or else the nearest host.
20
+ */
21
+ export function teleportsToRoot({ inline, hostName, nearest }: PortalDestination): boolean {
22
+ if (inline || nearest === null) return false;
23
+ return (hostName ?? nearest) === "root";
24
+ }
25
+
26
+ /**
27
+ * The engine's portal, unchanged, plus one fact for the parts inside it:
28
+ * whether it draws in the `"root"` host. `BottomSheet.Overlay` reads it to
29
+ * decide if it may hide the app from screen readers.
30
+ */
31
+ export function BottomSheetPortal(props: BottomSheetPortalProps): ReactElement {
32
+ const nearest = useOptionalBottomSheetHostName();
33
+ const isRootHost = teleportsToRoot({ inline: props.inline ?? false, hostName: props.hostName, nearest });
34
+
35
+ return (
36
+ <BottomSheetRootHostContext.Provider value={isRootHost}>
37
+ <Headless.Portal {...props} />
38
+ </BottomSheetRootHostContext.Provider>
39
+ );
40
+ }
41
+ BottomSheetPortal.displayName = "DelacourUI.BottomSheet.Portal";
@@ -2,8 +2,11 @@ import {
2
2
  BottomSheetProvider as HeadlessProvider,
3
3
  type BottomSheetProviderProps as HeadlessProviderProps,
4
4
  } from "@delacour/react-native-bottom-sheet";
5
- import type { ReactElement } from "react";
5
+ import { type ReactElement, useCallback, useMemo, useState } from "react";
6
+ import { StyleSheet, View } from "react-native";
6
7
  import { TeleportProvidedContext, useIsTeleportProvided } from "../overlay/overlay.context";
8
+ import { isTeleportInline } from "../overlay/overlay-teleport";
9
+ import { BottomSheetModalContext, type BottomSheetModalContextValue } from "./bottom-sheet-modal.context";
7
10
 
8
11
  export type BottomSheetProviderProps = Omit<HeadlessProviderProps, "hasPortalProvider">;
9
12
 
@@ -18,6 +21,13 @@ export type BottomSheetProviderProps = Omit<HeadlessProviderProps, "hasPortalPro
18
21
  * overlays then share one `"root"` host, ordered by `zIndex` — every overlay's
19
22
  * band starts above every sheet's.
20
23
  *
24
+ * **It hides the app from screen readers under a modal sheet.** While a sheet
25
+ * with an `Overlay` is presented in the `"root"` host, the children are
26
+ * `accessibilityElementsHidden` and `no-hide-descendants`. The `"root"` host
27
+ * draws beside the children, not inside them, so the sheet stays reachable.
28
+ * `OverlayProvider` does the same for dialogs; the two registries are
29
+ * separate, so each hides for its own.
30
+ *
21
31
  * The overlay folder's context file is a leaf (rule 3): it imports nothing but
22
32
  * React, so this cross-folder import cannot close a cycle.
23
33
  *
@@ -32,11 +42,40 @@ export type BottomSheetProviderProps = Omit<HeadlessProviderProps, "hasPortalPro
32
42
  */
33
43
  export function BottomSheetProvider({ children }: BottomSheetProviderProps): ReactElement {
34
44
  const isTeleportProvided = useIsTeleportProvided();
45
+ const [modalSheets, setModalSheets] = useState<ReadonlySet<string>>(() => new Set());
46
+
47
+ const register = useCallback((id: string) => {
48
+ setModalSheets((current) => new Set(current).add(id));
49
+ return () =>
50
+ setModalSheets((current) => {
51
+ if (!current.has(id)) return current;
52
+ const next = new Set(current);
53
+ next.delete(id);
54
+ return next;
55
+ });
56
+ }, []);
57
+ const modal = useMemo<BottomSheetModalContextValue>(() => ({ register }), [register]);
58
+
59
+ // Under a teleport that draws in place (the Jest mock), the sheet is inside
60
+ // the view this hides, so hiding it would hide the sheet too.
61
+ const isAppHidden = modalSheets.size > 0 && !isTeleportInline();
35
62
 
36
63
  return (
37
64
  <HeadlessProvider hasPortalProvider={isTeleportProvided}>
38
- <TeleportProvidedContext.Provider value>{children}</TeleportProvidedContext.Provider>
65
+ <TeleportProvidedContext.Provider value>
66
+ <BottomSheetModalContext.Provider value={modal}>
67
+ <View
68
+ accessibilityElementsHidden={isAppHidden}
69
+ importantForAccessibility={isAppHidden ? "no-hide-descendants" : "auto"}
70
+ style={styles.fill}
71
+ >
72
+ {children}
73
+ </View>
74
+ </BottomSheetModalContext.Provider>
75
+ </TeleportProvidedContext.Provider>
39
76
  </HeadlessProvider>
40
77
  );
41
78
  }
79
+
80
+ const styles = StyleSheet.create({ fill: { flex: 1 } });
42
81
  BottomSheetProvider.displayName = "DelacourUI.BottomSheet.Provider";
@@ -1,10 +1,13 @@
1
1
  import { afterEach, beforeEach, describe, expect, jest, test } from "@jest/globals";
2
- import type { ReactElement, ReactNode } from "react";
2
+ import { Fragment, type ReactElement, type ReactNode } from "react";
3
+ import { BackHandler } from "react-native";
3
4
  import { fireEvent, renderWithProviders, screen } from "../../test/render";
4
5
  import { Button } from "../button";
5
- import { OverlayProvider } from "../overlay";
6
+ import { Overlay, OverlayProvider } from "../overlay";
7
+ import { TELEPORT_INLINE } from "../overlay/overlay-teleport";
6
8
  import { Text } from "../text";
7
9
  import { BottomSheet, type BottomSheetProps } from "./bottom-sheet";
10
+ import { teleportsToRoot } from "./bottom-sheet-portal";
8
11
  import { BottomSheetProvider } from "./bottom-sheet-provider";
9
12
 
10
13
  function Providers({ children }: { children: ReactNode }): ReactElement {
@@ -188,3 +191,130 @@ describe("BottomSheet", () => {
188
191
  });
189
192
  });
190
193
  });
194
+
195
+ describe("BottomSheet.Container", () => {
196
+ test("a Handle inside a fragment counts as written, so no second one is added", async () => {
197
+ const showHandle = true;
198
+ await renderWithProviders(
199
+ <BottomSheet defaultOpen>
200
+ <BottomSheet.Portal>
201
+ <BottomSheet.Container>
202
+ <Fragment key="surface">{showHandle && <BottomSheet.Handle />}</Fragment>
203
+ <BottomSheet.Content>
204
+ <BottomSheet.Title>One handle</BottomSheet.Title>
205
+ </BottomSheet.Content>
206
+ </BottomSheet.Container>
207
+ </BottomSheet.Portal>
208
+ </BottomSheet>,
209
+ { wrapper: Providers }
210
+ );
211
+ expect(screen.getAllByRole("adjustable")).toHaveLength(1);
212
+ });
213
+ });
214
+
215
+ /** Runs `body` as on a device, where teleport moves the sheet out of the app's view. */
216
+ async function withTeleportOutOfTree(body: () => Promise<void>): Promise<void> {
217
+ const flags = globalThis as unknown as Record<symbol, unknown>;
218
+ const previous = flags[TELEPORT_INLINE];
219
+ delete flags[TELEPORT_INLINE];
220
+ try {
221
+ await body();
222
+ } finally {
223
+ flags[TELEPORT_INLINE] = previous;
224
+ }
225
+ }
226
+
227
+ describe("BottomSheetProvider and screen readers", () => {
228
+ function App({ overlay, inline }: { overlay: boolean; inline?: boolean }): ReactElement {
229
+ return (
230
+ <>
231
+ <Text>app behind</Text>
232
+ <BottomSheet defaultOpen>
233
+ <BottomSheet.Portal inline={inline}>
234
+ {overlay ? <BottomSheet.Overlay /> : null}
235
+ <BottomSheet.Container>
236
+ <BottomSheet.Content>
237
+ <BottomSheet.Title>Sheet</BottomSheet.Title>
238
+ </BottomSheet.Content>
239
+ </BottomSheet.Container>
240
+ </BottomSheet.Portal>
241
+ </BottomSheet>
242
+ </>
243
+ );
244
+ }
245
+
246
+ test("an open sheet with a scrim hides the app when teleport moves it out of the app", async () => {
247
+ await withTeleportOutOfTree(async () => {
248
+ await renderWithProviders(<App overlay />, { wrapper: Providers });
249
+ expect(screen.queryByText("app behind")).toBeNull();
250
+ expect(screen.getByText("app behind", { includeHiddenElements: true })).toBeOnTheScreen();
251
+ });
252
+ });
253
+
254
+ test("a sheet with no scrim leaves the app reachable", async () => {
255
+ await withTeleportOutOfTree(async () => {
256
+ await renderWithProviders(<App overlay={false} />, { wrapper: Providers });
257
+ expect(screen.getByText("app behind")).toBeOnTheScreen();
258
+ });
259
+ });
260
+
261
+ test("an inline sheet leaves the app reachable", async () => {
262
+ await withTeleportOutOfTree(async () => {
263
+ await renderWithProviders(<App inline overlay />, { wrapper: Providers });
264
+ expect(screen.getByText("app behind")).toBeOnTheScreen();
265
+ });
266
+ });
267
+
268
+ test("only a portal teleported to the root host counts", () => {
269
+ expect(teleportsToRoot({ inline: false, hostName: undefined, nearest: "root" })).toBe(true);
270
+ expect(teleportsToRoot({ inline: true, hostName: undefined, nearest: "root" })).toBe(false);
271
+ expect(teleportsToRoot({ inline: false, hostName: undefined, nearest: null })).toBe(false);
272
+ expect(teleportsToRoot({ inline: false, hostName: "modal", nearest: "root" })).toBe(false);
273
+ });
274
+ });
275
+
276
+ describe("BottomSheet and Android back", () => {
277
+ afterEach(() => {
278
+ jest.restoreAllMocks();
279
+ });
280
+
281
+ function countBackSubscriptions(): { count: () => number } {
282
+ let count = 0;
283
+ jest.spyOn(BackHandler, "addEventListener").mockImplementation(() => {
284
+ count++;
285
+ return { remove: () => undefined };
286
+ });
287
+ return { count: () => count };
288
+ }
289
+
290
+ test("an open sheet answers back on its own", async () => {
291
+ const subscriptions = countBackSubscriptions();
292
+ await renderWithProviders(<FilterSheet defaultOpen />, { wrapper: Providers });
293
+ expect(subscriptions.count()).toBeGreaterThan(0);
294
+ });
295
+
296
+ test("a parent render with a new inline onOpenChange does not re-subscribe", async () => {
297
+ const subscriptions = countBackSubscriptions();
298
+ const { rerender } = await renderWithProviders(<FilterSheet defaultOpen onOpenChange={() => undefined} />, {
299
+ wrapper: Providers,
300
+ });
301
+ const before = subscriptions.count();
302
+ await rerender(<FilterSheet defaultOpen onOpenChange={() => undefined} />);
303
+ expect(subscriptions.count()).toBe(before);
304
+ });
305
+
306
+ test("a sheet under an open modal overlay leaves back to the overlay", async () => {
307
+ const subscriptions = countBackSubscriptions();
308
+ await renderWithProviders(
309
+ <>
310
+ <FilterSheet defaultOpen />
311
+ <Overlay.Portal layer="modal">
312
+ <Text>dialog</Text>
313
+ </Overlay.Portal>
314
+ </>,
315
+ { wrapper: Providers }
316
+ );
317
+ expect(screen.getByText("dialog")).toBeOnTheScreen();
318
+ expect(subscriptions.count()).toBe(0);
319
+ });
320
+ });
@@ -7,6 +7,8 @@ import type { ReactElement } from "react";
7
7
  import { Presets } from "react-native-pulsar";
8
8
  import { useSafeAreaInsets } from "react-native-safe-area-context";
9
9
  import { useKeyboardAnimationGuard } from "../../hooks/use-keyboard-state-sync";
10
+ import { useOptionalOverlay } from "../overlay/overlay.context";
11
+ import { topOverlay } from "../overlay/overlay-registry";
10
12
  import { BottomSheetBackground } from "./bottom-sheet-background";
11
13
  import { BottomSheetClose } from "./bottom-sheet-close";
12
14
  import { BottomSheetContainer } from "./bottom-sheet-container";
@@ -17,6 +19,7 @@ import { BottomSheetFooter } from "./bottom-sheet-footer";
17
19
  import { BottomSheetHandle } from "./bottom-sheet-handle";
18
20
  import { BottomSheetLegendList } from "./bottom-sheet-legend-list";
19
21
  import { BottomSheetOverlay } from "./bottom-sheet-overlay";
22
+ import { BottomSheetPortal } from "./bottom-sheet-portal";
20
23
  import { BottomSheetProvider } from "./bottom-sheet-provider";
21
24
  import { BottomSheetScrollView } from "./bottom-sheet-scroll-view";
22
25
  import { BottomSheetSectionList } from "./bottom-sheet-section-list";
@@ -49,7 +52,7 @@ const closeHaptic = Presets.System.impactLight;
49
52
  * The engine's root with this library's defaults on it. It renders no view of
50
53
  * its own.
51
54
  *
52
- * Three things happen here and nowhere else in the skin:
55
+ * Four things happen here and nowhere else in the skin:
53
56
  *
54
57
  * - **`bottomInset` defaults to the safe-area bottom**, read from
55
58
  * `useSafeAreaInsets()`. The engine reserves that band under the body or the
@@ -61,14 +64,25 @@ const closeHaptic = Presets.System.impactLight;
61
64
  * `KeyboardProvider`'s shared values are pinned open by a keyboard that
62
65
  * vanished without a `will` event would lift for a keyboard that is not
63
66
  * there; `Screen.Footer` runs the same repair for the same reason.
67
+ * - **Android back skips the sheet while an overlay is over it.** Under an
68
+ * `OverlayProvider`, `closeOnBack` is off while a modal or anchored overlay
69
+ * is open, so back closes the dialog and leaves the sheet under it.
64
70
  *
65
71
  * `topInset` is left at the engine's zero, so a `%` snap point is a fraction of the
66
72
  * whole window — the same fraction it was before this rewrite.
67
73
  */
68
- function BottomSheetRoot({ bottomInset, ...props }: BottomSheetProps): ReactElement {
74
+ function BottomSheetRoot({ bottomInset, closeOnBack = true, ...props }: BottomSheetProps): ReactElement {
69
75
  const insets = useSafeAreaInsets();
76
+ const overlays = useOptionalOverlay();
70
77
  useKeyboardAnimationGuard();
71
78
 
79
+ // Every overlay draws over every sheet, so while one that answers back is
80
+ // open the sheet must not. Sheets and overlays keep separate registries,
81
+ // and `BackHandler` calls the newest listener first: the engine
82
+ // re-subscribes whenever its methods change, so after any parent render
83
+ // the sheet's listener would be newer than the dialog's.
84
+ const isUnderOverlay = overlays !== null && topOverlay(overlays.state) !== null;
85
+
72
86
  // The haptics go before the spread, not into destructuring defaults: a
73
87
  // default also replaces an explicit `undefined`, which is the opt-out.
74
88
  return (
@@ -77,6 +91,7 @@ function BottomSheetRoot({ bottomInset, ...props }: BottomSheetProps): ReactElem
77
91
  onSnapPointHaptic={snapPointHaptic}
78
92
  {...props}
79
93
  bottomInset={bottomInset ?? insets.bottom}
94
+ closeOnBack={closeOnBack && !isUnderOverlay}
80
95
  />
81
96
  );
82
97
  }
@@ -134,7 +149,7 @@ export const BottomSheet = Object.assign(BottomSheetRoot, {
134
149
  /** The control that opens the sheet. `asChild` to make a `Button` the trigger. */
135
150
  Trigger: BottomSheetTrigger,
136
151
  /** Everything drawn above the app, teleported to the nearest host. `inline` to render in place. */
137
- Portal: Headless.Portal,
152
+ Portal: BottomSheetPortal,
138
153
  /** The scrim. Omit it and the sheet has none. */
139
154
  Overlay: BottomSheetOverlay,
140
155
  /** The panel that moves. Brings its own `Background` and `Handle` unless you write them. */
@@ -1,4 +1,4 @@
1
- import { useEffect, useRef } from "react";
1
+ import { useEffect, useRef, useState } from "react";
2
2
  import { type SharedValue, useFrameCallback, useSharedValue } from "react-native-reanimated";
3
3
  import { scheduleOnRN } from "react-native-worklets";
4
4
 
@@ -13,6 +13,15 @@ export type TextAnimationClockOptions = {
13
13
  onLimit?: () => void;
14
14
  };
15
15
 
16
+ export type TextAnimationClock = {
17
+ /** Milliseconds into the current run. */
18
+ elapsed: SharedValue<number>;
19
+ /** The run `elapsed` has been rewound for. Lags `runId` until the rewind lands. */
20
+ run: SharedValue<number>;
21
+ /** The run this render belongs to, counted during render. */
22
+ runId: number;
23
+ };
24
+
16
25
  /**
17
26
  * An elapsed-ms shared value that advances by each frame's `dt` while running.
18
27
  *
@@ -24,17 +33,26 @@ export type TextAnimationClockOptions = {
24
33
  * A run is identified by `runKey`. Changing it rewinds to 0, and a limit
25
34
  * crossed by an older run is dropped rather than reported, so an interrupted
26
35
  * animation never fires its predecessor's callback.
36
+ *
37
+ * The rewind runs in an effect, after the new render has committed, so a
38
+ * part drawn for the new run compares `run` with `runId` and holds its start
39
+ * until they match — new text never paints at the old run's end.
27
40
  */
28
41
  export function useTextAnimationClock({
29
42
  isRunning,
30
43
  runKey,
31
44
  limitMs,
32
45
  onLimit,
33
- }: TextAnimationClockOptions): SharedValue<number> {
46
+ }: TextAnimationClockOptions): TextAnimationClock {
34
47
  const elapsed = useSharedValue(0);
35
48
  const run = useSharedValue(0);
36
49
  const reported = useSharedValue(false);
37
50
  const runRef = useRef(0);
51
+ // Counted during render, so the units of a new run know it before they paint.
52
+ const [counted, setCounted] = useState({ runKey, id: 0 });
53
+ const current = counted.runKey === runKey ? counted : { runKey, id: counted.id + 1 };
54
+ if (current !== counted) setCounted(current);
55
+ const runId = current.id;
38
56
  const onLimitRef = useRef(onLimit);
39
57
 
40
58
  useEffect(() => {
@@ -60,21 +78,21 @@ export function useTextAnimationClock({
60
78
  elapsed.value = next;
61
79
  }, false);
62
80
 
63
- // biome-ignore lint/correctness/useExhaustiveDependencies: runKey is the trigger, not a value read here
81
+ // `run` is written last, so a frame between the writes still holds the start.
64
82
  useEffect(() => {
65
- runRef.current += 1;
66
- run.value = runRef.current;
83
+ runRef.current = runId;
67
84
  elapsed.value = 0;
68
85
  reported.value = false;
69
- }, [runKey, elapsed, reported, run]);
86
+ run.value = runId;
87
+ }, [runId, elapsed, reported, run]);
70
88
 
71
89
  // After the rewind above, so a new run is live again; a run that already
72
90
  // reached its limit stays off when `isRunning` flips back on.
73
- // biome-ignore lint/correctness/useExhaustiveDependencies: runKey is the trigger, not a value read here
91
+ // biome-ignore lint/correctness/useExhaustiveDependencies: runId is the trigger, not a value read here
74
92
  useEffect(() => {
75
93
  frame.setActive(isRunning && !reported.value);
76
94
  return () => frame.setActive(false);
77
- }, [frame, isRunning, reported, runKey]);
95
+ }, [frame, isRunning, reported, runId]);
78
96
 
79
- return elapsed;
97
+ return { elapsed, run, runId };
80
98
  }
@@ -10,6 +10,7 @@ import Animated, {
10
10
  } from "react-native-reanimated";
11
11
  import { useCalmMotion } from "../../hooks/use-calm-motion";
12
12
  import { cn } from "../../lib/cn";
13
+ import { TEXT_MAX_FONT_SIZE_MULTIPLIER } from "../text/text.variants";
13
14
  import type { TextAnimationBase } from "./text-animation.types";
14
15
  import {
15
16
  formatNumber,
@@ -177,6 +178,9 @@ export function TextAnimationRolling({
177
178
  accessibilityHint,
178
179
  }: TextAnimationRollingProps): ReactElement {
179
180
  const isCalm = useCalmMotion();
181
+ // One cap for the measuring digit, the wheels and the static cells, the
182
+ // same default the other parts use, so a balance never outgrows its card.
183
+ const fontCap = maxFontSizeMultiplier ?? TEXT_MAX_FONT_SIZE_MULTIPLIER;
180
184
  const textClass = cn(
181
185
  useTextAnimationClass({ variant, size, weight, color, align, transform, className }),
182
186
  "tabular-nums"
@@ -242,7 +246,7 @@ export function TextAnimationRolling({
242
246
  {...HIDDEN}
243
247
  allowFontScaling={allowFontScaling}
244
248
  className={cn(textClass, slots.layer(), "opacity-0")}
245
- maxFontSizeMultiplier={maxFontSizeMultiplier}
249
+ maxFontSizeMultiplier={fontCap}
246
250
  onLayout={onLayout}
247
251
  >
248
252
  0
@@ -259,7 +263,7 @@ export function TextAnimationRolling({
259
263
  isLate={hasMounted}
260
264
  key={key}
261
265
  lineHeight={lineHeight}
262
- maxFontSizeMultiplier={maxFontSizeMultiplier}
266
+ maxFontSizeMultiplier={fontCap}
263
267
  rank={rank}
264
268
  stagger={stagger}
265
269
  />
@@ -269,7 +273,7 @@ export function TextAnimationRolling({
269
273
  allowFontScaling={allowFontScaling}
270
274
  className={textClass}
271
275
  key={key}
272
- maxFontSizeMultiplier={maxFontSizeMultiplier}
276
+ maxFontSizeMultiplier={fontCap}
273
277
  >
274
278
  {cell.text}
275
279
  </NativeText>
@@ -9,9 +9,11 @@ import Animated, {
9
9
  } from "react-native-reanimated";
10
10
  import { useCalmMotion } from "../../hooks/use-calm-motion";
11
11
  import { cn } from "../../lib/cn";
12
+ import { TEXT_MAX_FONT_SIZE_MULTIPLIER } from "../text/text.variants";
12
13
  import type { TextAnimationBase } from "./text-animation.types";
13
14
  import {
14
15
  resolveNextPhrase,
16
+ resolveSwapProgress,
15
17
  resolveWidestPhrase,
16
18
  TEXT_ANIMATION_ROTATE_DISTANCE,
17
19
  TEXT_ANIMATION_ROTATE_INTERVAL_MS,
@@ -44,6 +46,11 @@ type RotatingLayerProps = {
44
46
  text: string;
45
47
  phase: "enter" | "exit";
46
48
  progress: SharedValue<number>;
49
+ /** The swap `progress` has been rewound for. */
50
+ swap: SharedValue<number>;
51
+ /** The swap this layer was rendered for — it holds its start until `swap` catches up. */
52
+ swapId: number;
53
+ isSwapping: boolean;
47
54
  distance: number;
48
55
  className: string;
49
56
  allowFontScaling?: boolean;
@@ -53,19 +60,23 @@ type RotatingLayerProps = {
53
60
  /**
54
61
  * One phrase over the slot — the one arriving or the one leaving. Both read
55
62
  * the same progress, so the swap is a single animation however fast the
56
- * interval runs.
63
+ * interval runs. Progress rewinds in an effect, after the layers mount, so a
64
+ * layer waits for `swap` to reach its own swap before it follows progress.
57
65
  */
58
66
  function TextAnimationRotatingLayer({
59
67
  text,
60
68
  phase,
61
69
  progress,
70
+ swap,
71
+ swapId,
72
+ isSwapping,
62
73
  distance,
63
74
  className,
64
75
  allowFontScaling,
65
76
  maxFontSizeMultiplier,
66
77
  }: RotatingLayerProps): ReactElement {
67
78
  const style = useAnimatedStyle(() => {
68
- const t = progress.value;
79
+ const t = resolveSwapProgress(isSwapping, swap.value, swapId, progress.value);
69
80
  if (phase === "enter") return { opacity: t, transform: [{ translateY: (1 - t) * distance }] };
70
81
  return { opacity: 1 - t, transform: [{ translateY: -t * distance }] };
71
82
  });
@@ -115,13 +126,16 @@ export function TextAnimationRotating({
115
126
  const isCalm = useCalmMotion();
116
127
  const textClass = useTextAnimationClass({ variant, size, weight, color, align, transform, className });
117
128
  const phrasesKey = phrases.join("\u0000");
118
- const [state, setState] = useState({ key: phrasesKey, index: 0, previous: -1 });
129
+ // `swapId` counts every swap, so each one's layers know which rewind is theirs.
130
+ const [state, setState] = useState({ key: phrasesKey, index: 0, previous: -1, swapId: 0 });
119
131
  // A new list starts over, committed during render, so switching away and
120
132
  // back never restores the old list's index or its transition.
121
- if (state.key !== phrasesKey) setState({ key: phrasesKey, index: 0, previous: -1 });
133
+ if (state.key !== phrasesKey) setState({ key: phrasesKey, index: 0, previous: -1, swapId: state.swapId });
122
134
  // Calm motion holds the first phrase with no swap in flight.
123
- const { index, previous } = state.key === phrasesKey && !isCalm ? state : { index: 0, previous: -1 };
135
+ const { index, previous, swapId } =
136
+ state.key === phrasesKey && !isCalm ? state : { index: 0, previous: -1, swapId: state.swapId };
124
137
  const progress = useSharedValue(1);
138
+ const swap = useSharedValue(0);
125
139
  const isRotating = isActive && !isCalm && phrases.length > 1;
126
140
 
127
141
  useEffect(() => {
@@ -130,7 +144,7 @@ export function TextAnimationRotating({
130
144
  setState((current) => {
131
145
  const from = current.key === phrasesKey ? current.index : 0;
132
146
  const next = resolveNextPhrase(from, phrases.length, true) ?? from;
133
- return { key: phrasesKey, index: next, previous: from };
147
+ return { key: phrasesKey, index: next, previous: from, swapId: current.swapId + 1 };
134
148
  });
135
149
  }, intervalMs);
136
150
  return () => clearInterval(timer);
@@ -139,18 +153,20 @@ export function TextAnimationRotating({
139
153
  // Turning calm motion on drops the rotated state, so resuming waits for the
140
154
  // next swap instead of replaying the transition that was cut short.
141
155
  useEffect(() => {
142
- if (isCalm) setState({ key: phrasesKey, index: 0, previous: -1 });
156
+ if (isCalm) setState((current) => ({ key: phrasesKey, index: 0, previous: -1, swapId: current.swapId }));
143
157
  }, [isCalm, phrasesKey]);
144
158
 
145
- // biome-ignore lint/correctness/useExhaustiveDependencies: a new index is the trigger, though only `previous` is read
159
+ // `swap` is written after the rewind, so a frame between the writes still
160
+ // holds the layers at their start.
146
161
  useEffect(() => {
147
162
  if (previous < 0) {
148
163
  progress.value = 1;
149
164
  return;
150
165
  }
151
166
  progress.value = 0;
167
+ swap.value = swapId;
152
168
  progress.value = withTiming(1, { duration: transitionMs, easing: Easing.out(Easing.cubic) });
153
- }, [index, previous, transitionMs, progress]);
169
+ }, [swapId, previous, transitionMs, progress, swap]);
154
170
 
155
171
  const [widths, setWidths] = useState<Readonly<Record<string, number>>>({});
156
172
  const guess = useMemo(() => resolveWidestPhrase(phrases), [phrases]);
@@ -175,7 +191,11 @@ export function TextAnimationRotating({
175
191
  const leaving = previous >= 0 ? phrases[previous] : undefined;
176
192
  const reserved = reserve === "widest" ? (phrases[widest] ?? shown) : shown;
177
193
  const distance = transition.kind === "slide" ? (transition.distance ?? TEXT_ANIMATION_ROTATE_DISTANCE) : 0;
178
- const textProps = { allowFontScaling, maxFontSizeMultiplier };
194
+ // The same default cap as the other parts, for the slot, the measures and the layers.
195
+ const textProps = {
196
+ allowFontScaling,
197
+ maxFontSizeMultiplier: maxFontSizeMultiplier ?? TEXT_MAX_FONT_SIZE_MULTIPLIER,
198
+ };
179
199
 
180
200
  // The in-flow copy sizes the slot; the hidden measures settle which phrase
181
201
  // really is widest once they have laid out; the layers draw over the slot.
@@ -213,8 +233,11 @@ export function TextAnimationRotating({
213
233
  {...textProps}
214
234
  className={textClass}
215
235
  distance={distance}
236
+ isSwapping
216
237
  key={`exit-${previous}`}
217
238
  progress={progress}
239
+ swap={swap}
240
+ swapId={swapId}
218
241
  phase="exit"
219
242
  text={leaving}
220
243
  />
@@ -223,8 +246,11 @@ export function TextAnimationRotating({
223
246
  {...textProps}
224
247
  className={textClass}
225
248
  distance={distance}
249
+ isSwapping={leaving !== undefined}
226
250
  key={`enter-${index}`}
227
251
  progress={progress}
252
+ swap={swap}
253
+ swapId={swapId}
228
254
  phase="enter"
229
255
  text={shown}
230
256
  />
@@ -202,7 +202,7 @@ export function TextAnimationTyping({
202
202
  const rest = resolveTypingRest(timeline);
203
203
  const runKey = `${phrasesKey}|${speed}|${eraseSpeed}|${holdMs}|${isLooping}|${isActive}`;
204
204
 
205
- const elapsed = useTextAnimationClock({
205
+ const { elapsed } = useTextAnimationClock({
206
206
  isRunning: isActive && !isCalm,
207
207
  runKey,
208
208
  limitMs: Number.POSITIVE_INFINITY,
@@ -5,7 +5,7 @@ import { resolveTextClass, TEXT_MAX_FONT_SIZE_MULTIPLIER } from "../text/text.va
5
5
  import type { TextAnimationBase } from "./text-animation.types";
6
6
  import {
7
7
  resolveEffectFrame,
8
- resolveUnitProgress,
8
+ resolveRunProgress,
9
9
  type TextAnimationEffect,
10
10
  type TypingSample,
11
11
  } from "./text-animation.variants";
@@ -42,6 +42,10 @@ export type TextAnimationUnitDrive =
42
42
  | {
43
43
  kind: "reveal";
44
44
  elapsed: SharedValue<number>;
45
+ /** The run the clock has rewound for. */
46
+ run: SharedValue<number>;
47
+ /** The run this unit was rendered for — it holds its start until `run` catches up. */
48
+ runId: number;
45
49
  delayMs: number;
46
50
  staggerMs: number;
47
51
  durationMs: number;
@@ -89,7 +93,16 @@ export function TextAnimationUnit({
89
93
  const shown = isAtRest || (sample.phraseIndex === drive.phraseIndex && drive.index < sample.visibleCount);
90
94
  return { opacity: shown ? 1 : 0 };
91
95
  }
92
- const t = isAtRest ? 1 : resolveUnitProgress(drive.elapsed.value, drive.delayMs, drive.staggerMs, drive.durationMs);
96
+ const t = isAtRest
97
+ ? 1
98
+ : resolveRunProgress(
99
+ drive.run.value,
100
+ drive.runId,
101
+ drive.elapsed.value,
102
+ drive.delayMs,
103
+ drive.staggerMs,
104
+ drive.durationMs
105
+ );
93
106
  const frame = resolveEffectFrame(drive.effect, t);
94
107
  return {
95
108
  opacity: frame.opacity,
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, jest, test } from "@jest/globals";
2
2
  import type { ReactElement, ReactNode } from "react";
3
3
  import { CalmMotionProvider } from "../../hooks/use-calm-motion";
4
4
  import { act, renderWithProviders, screen } from "../../test/render";
5
+ import { TEXT_MAX_FONT_SIZE_MULTIPLIER } from "../text/text.variants";
5
6
  import { TextAnimation } from "./text-animation";
6
7
 
7
8
  function Calm({ children }: { children: ReactNode }): ReactElement {
@@ -132,6 +133,12 @@ describe("TextAnimation.Rotating", () => {
132
133
  expect(screen.getAllByLabelText(/./)).toHaveLength(1);
133
134
  });
134
135
 
136
+ test("caps font scaling at the default every other part uses", async () => {
137
+ await renderWithProviders(<TextAnimation.Rotating phrases={["fast", "calm"]} />);
138
+ const texts = screen.getAllByText(/./, { includeHiddenElements: true });
139
+ for (const text of texts) expect(text.props.maxFontSizeMultiplier).toBe(TEXT_MAX_FONT_SIZE_MULTIPLIER);
140
+ });
141
+
135
142
  test("hides the layers and probes from assistive technology", async () => {
136
143
  await renderWithProviders(<TextAnimation.Rotating phrases={["fast", "calm"]} />);
137
144
  expect(screen.queryByText("fast")).not.toBeOnTheScreen();
@@ -263,6 +270,12 @@ describe("TextAnimation.Rolling", () => {
263
270
  expect(screen.getByRole("text", { name: "$12.5k" })).toBeOnTheScreen();
264
271
  });
265
272
 
273
+ test("caps font scaling at the default every other part uses", async () => {
274
+ await renderWithProviders(<TextAnimation.Rolling prefix="$" value={1284} />);
275
+ const texts = screen.getAllByText(/./, { includeHiddenElements: true });
276
+ for (const text of texts) expect(text.props.maxFontSizeMultiplier).toBe(TEXT_MAX_FONT_SIZE_MULTIPLIER);
277
+ });
278
+
266
279
  test("hides every wheel digit from assistive technology", async () => {
267
280
  await renderWithProviders(<TextAnimation.Rolling value={42} />);
268
281
  expect(screen.queryByText("4")).not.toBeOnTheScreen();
@@ -107,6 +107,8 @@ function buildPieces(text: string, split: "word" | "character"): { pieces: Revea
107
107
  type UnitShared = {
108
108
  className: string;
109
109
  elapsed: SharedValue<number>;
110
+ run: SharedValue<number>;
111
+ runId: number;
110
112
  delayMs: number;
111
113
  durationMs: number;
112
114
  effect: TextAnimationEffect;
@@ -124,6 +126,8 @@ function renderUnit(shared: UnitShared, key: string, text: string, index: number
124
126
  drive={{
125
127
  kind: "reveal",
126
128
  elapsed: shared.elapsed,
129
+ run: shared.run,
130
+ runId: shared.runId,
127
131
  delayMs: shared.delayMs,
128
132
  staggerMs: shared.delays[index] ?? 0,
129
133
  durationMs: shared.durationMs,
@@ -212,7 +216,7 @@ function TextAnimationReveal({
212
216
  // A `line` split has no units until the paragraph is measured, so its clock
213
217
  // waits for them rather than reaching a zero limit on an empty reveal.
214
218
  const isMeasured = split !== "line" || lines !== null;
215
- const elapsed = useTextAnimationClock({
219
+ const { elapsed, run, runId } = useTextAnimationClock({
216
220
  isRunning: isActive && !isCalm && isMeasured,
217
221
  runKey,
218
222
  limitMs: total,
@@ -228,6 +232,8 @@ function TextAnimationReveal({
228
232
  const shared: UnitShared = {
229
233
  className: textClass,
230
234
  elapsed,
235
+ run,
236
+ runId,
231
237
  delayMs,
232
238
  durationMs,
233
239
  effect,
@@ -16,8 +16,10 @@ import {
16
16
  resolveRollDirection,
17
17
  resolveRollTarget,
18
18
  resolveRowJustify,
19
+ resolveRunProgress,
19
20
  resolveStaggerDelay,
20
21
  resolveStaggerDelays,
22
+ resolveSwapProgress,
21
23
  resolveTotalDuration,
22
24
  resolveTypedPhrase,
23
25
  resolveTypedRange,
@@ -197,6 +199,17 @@ describe("resolveUnitProgress", () => {
197
199
  });
198
200
  });
199
201
 
202
+ describe("resolveRunProgress", () => {
203
+ test("holds a unit at its start until the clock has rewound for its run", () => {
204
+ expect(resolveRunProgress(1, 2, 5000, 0, 0, 300)).toBe(0);
205
+ });
206
+
207
+ test("follows the clock once the run is current", () => {
208
+ expect(resolveRunProgress(2, 2, 5000, 0, 0, 300)).toBe(1);
209
+ expect(resolveRunProgress(2, 2, 0, 0, 0, 300)).toBe(0);
210
+ });
211
+ });
212
+
200
213
  describe("resolveEffectFrame", () => {
201
214
  test("every effect rests at full opacity, no offset, full scale", () => {
202
215
  const effects = [
@@ -353,6 +366,20 @@ describe("resolveNextPhrase", () => {
353
366
  });
354
367
  });
355
368
 
369
+ describe("resolveSwapProgress", () => {
370
+ test("shows a phrase whole when no swap is in flight", () => {
371
+ expect(resolveSwapProgress(false, 0, 3, 0.4)).toBe(1);
372
+ });
373
+
374
+ test("holds a new swap at its start until progress has rewound for it", () => {
375
+ expect(resolveSwapProgress(true, 2, 3, 1)).toBe(0);
376
+ });
377
+
378
+ test("follows progress once the swap is current", () => {
379
+ expect(resolveSwapProgress(true, 3, 3, 0.4)).toBe(0.4);
380
+ });
381
+ });
382
+
356
383
  describe("resolveWidestPhrase", () => {
357
384
  test("picks the most graphemes, the first on a tie", () => {
358
385
  expect(resolveWidestPhrase(["fast", "reliable", "small", "accurate"])).toBe(1);
@@ -462,6 +489,12 @@ describe("resolveRollDirection", () => {
462
489
  expect(resolveRollDirection(2, 2)).toBe("up");
463
490
  expect(resolveRollDirection(2, 1)).toBe("down");
464
491
  });
492
+
493
+ test("follows the magnitude of a negative number, not its sign", () => {
494
+ expect(resolveRollDirection(-19, -20)).toBe("up");
495
+ expect(resolveRollDirection(-20, -19)).toBe("down");
496
+ expect(resolveRollDirection(-3, 3)).toBe("up");
497
+ });
465
498
  });
466
499
 
467
500
  describe("resolveWheelOffset", () => {
@@ -410,6 +410,35 @@ export function resolveUnitProgress(
410
410
  return easeOutCubic(linear);
411
411
  }
412
412
 
413
+ /**
414
+ * A rotating layer's progress. With no swap in flight the phrase shows whole;
415
+ * a layer rendered for a swap holds its start until progress has rewound for
416
+ * that swap, so the arriving phrase never paints a frame fully shown.
417
+ */
418
+ export function resolveSwapProgress(isSwapping: boolean, shownSwap: number, swapId: number, progress: number): number {
419
+ "worklet";
420
+ if (!isSwapping) return 1;
421
+ return shownSwap === swapId ? progress : 0;
422
+ }
423
+
424
+ /**
425
+ * A unit's progress on its own run. Until the clock has rewound for the run
426
+ * the unit was rendered for, it holds the unit at its start, so new text never
427
+ * paints a frame at the previous run's finished value.
428
+ */
429
+ export function resolveRunProgress(
430
+ shownRun: number,
431
+ runId: number,
432
+ elapsedMs: number,
433
+ delayMs: number,
434
+ staggerDelayMs: number,
435
+ durationMs: number
436
+ ): number {
437
+ "worklet";
438
+ if (shownRun !== runId) return 0;
439
+ return resolveUnitProgress(elapsedMs, delayMs, staggerDelayMs, durationMs);
440
+ }
441
+
413
442
  /**
414
443
  * What a unit looks like at progress `t`. Only opacity and transform — a
415
444
  * unit's layout is final from the first frame, so nothing reflows as it enters.
@@ -691,9 +720,13 @@ export function resolveRollTarget(currentPos: number, digit: number, direction:
691
720
  return base + delta;
692
721
  }
693
722
 
694
- /** Wheels roll up when the value grows or holds, down when it shrinks. */
723
+ /**
724
+ * Wheels roll up when the shown digits grow or hold, down when they shrink.
725
+ * The wheels draw the magnitude — the sign is a static cell — so −19 → −20
726
+ * rolls up, the short way, though the value went down.
727
+ */
695
728
  export function resolveRollDirection(previous: number, next: number): RollDirection {
696
- return next < previous ? "down" : "up";
729
+ return Math.abs(next) < Math.abs(previous) ? "down" : "up";
697
730
  }
698
731
 
699
732
  /**