@delacour/react-native-ui 0.7.0-alpha.20261104102829 → 0.7.0-alpha.20261104102945

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.20261104102829",
3
+ "version": "0.7.0-alpha.20261104102945",
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.20261104102829",
186
- "@delacour/react-native-charts": "0.7.0-alpha.20261104102829",
185
+ "@delacour/react-native-bottom-sheet": "0.7.0-alpha.20261104102945",
186
+ "@delacour/react-native-charts": "0.7.0-alpha.20261104102945",
187
187
  "@legendapp/list": ">=3.3",
188
188
  "react-native-skia": ">=3.9.0",
189
189
  "expo-linear-gradient": ">=15",
@@ -78,7 +78,7 @@ export function DialogContent({
78
78
 
79
79
  const handleEntered = useCallback(() => focus(titleRef.current), [titleRef]);
80
80
  const handleExited = useCallback(() => focus(triggerRef.current), [triggerRef]);
81
- const { isPresent, isReduced, progress } = useOverlayPresence({
81
+ const { isPresent, isReduced, phase, progress } = useOverlayPresence({
82
82
  isOpen,
83
83
  onEntered: handleEntered,
84
84
  onExited: handleExited,
@@ -131,7 +131,7 @@ export function DialogContent({
131
131
  const onEscape = isDismissible ? close : undefined;
132
132
 
133
133
  return (
134
- <Overlay.Portal id={id} layer="modal">
134
+ <Overlay.Portal id={id} isExiting={phase === "exiting"} layer="modal">
135
135
  <Overlay.Scrim className={slots.scrim({ className: scrimClassName })} onDismiss={onEscape} progress={progress} />
136
136
  <View className={slots.positioner()} pointerEvents="box-none">
137
137
  <Animated.View
@@ -98,7 +98,7 @@ export function DrawerContent({
98
98
 
99
99
  const handleEntered = useCallback(() => focus(titleRef.current), [titleRef]);
100
100
  const handleExited = useCallback(() => focus(triggerRef.current), [triggerRef]);
101
- const { isPresent, isReduced, progress } = useOverlayPresence({
101
+ const { isPresent, isReduced, phase, progress } = useOverlayPresence({
102
102
  isOpen,
103
103
  onEntered: handleEntered,
104
104
  onExited: handleExited,
@@ -156,7 +156,7 @@ export function DrawerContent({
156
156
  };
157
157
 
158
158
  return (
159
- <Overlay.Portal id={id} layer="modal">
159
+ <Overlay.Portal id={id} isExiting={phase === "exiting"} layer="modal">
160
160
  <Overlay.Scrim
161
161
  className={slots.scrim({ className: scrimClassName })}
162
162
  onDismiss={onEscape}
@@ -16,16 +16,16 @@ imports an overlay never resolves it. The consequence is the same one thing to d
16
16
  | --- | --- |
17
17
  | `index.ts` | → `@delacour/react-native-ui/overlay` |
18
18
  | `overlay.tsx` | `Overlay` — the root is the provider: teleport's `PortalProvider` (skipped when one is already above), the registry and the touch-start fan-out; the `Object.assign` names `Portal` and `Scrim`. `OverlayProvider` is the same component, under the name a root layout reads best with |
19
- | `overlay-portal.tsx` | `Overlay.Portal` — registers while mounted, teleports to `"root"` in a `box-none` absolute fill carrying the registry's `zIndex`; inline without a provider |
19
+ | `overlay-portal.tsx` | `Overlay.Portal` — registers while mounted, reports `isExiting`, teleports to `"root"` in a `box-none` absolute fill carrying the registry's `zIndex`; inline without a provider |
20
20
  | `overlay-scrim.tsx` | `Overlay.Scrim` — `bg-overlay`, opacity follows presence, hidden from assistive technology |
21
21
  | `overlay.context.tsx` | **Leaf.** `OverlayContext`, `TeleportProvidedContext` and their hooks. `bottom-sheet/` imports it |
22
- | `overlay-registry.ts` | **Pure.** The z-order reducer, `zIndexOfOverlay`, `topOverlay`, `isTopOverlay`, `hasModalOverlay`, `OVERLAY_LAYER_BASE` |
22
+ | `overlay-registry.ts` | **Pure.** The z-order reducer, `zIndexOfOverlay`, `topOverlay`, `isTopOverlay`, `hasModalOverlay`, `topModalOverlay`, `isBelowTopModal`, `OVERLAY_LAYER_BASE` |
23
23
  | `overlay-presence.ts` | **Pure.** `reducePresence` — `closed → entering → open → exiting → closed`; `isCurrentFinish` |
24
24
  | `overlay-teleport.ts` | **Pure.** `TELEPORT_INLINE`, `isTeleportInline` — whether teleport draws an overlay in place, as its Jest mock does |
25
25
  | `overlay.variants.ts` | `overlayVariants` (`scrim`), `OVERLAY_MOTION`, `OVERLAY_SCRIM_TOKEN` |
26
26
  | `use-overlay-presence.ts` | `useOverlayPresence` — keeps an overlay mounted through its exit, drives `progress` 0 → 1 |
27
27
  | `use-overlay-back-handler.ts` | `useOverlayBackHandler` — Android back, only while the overlay is the top |
28
- | `overlay.render.test.tsx` | Mounted under Jest — provider and portal mounting, registry entry and z-order while mounted, scrim semantics and dismiss, app content hidden behind a modal only when teleport moves it out, presence unmount after exit, back handler (top-only, toast excluded), touch fan-out |
28
+ | `overlay.render.test.tsx` | Mounted under Jest — provider and portal mounting, registry entry and z-order while mounted, scrim semantics and dismiss, app content hidden behind a modal only when teleport moves it out and reachable again while it exits, a dialog under another dialog hidden, presence unmount after exit and one timing per transition under owner re-renders, back handler (top-only, toast excluded), touch fan-out |
29
29
  | `*.test.ts` | The registry, the presence machine, the scrim token and the motion constants |
30
30
 
31
31
  ## Design
@@ -75,11 +75,20 @@ imports an overlay never resolves it. The consequence is the same one thing to d
75
75
  the host, and VoiceOver or TalkBack could still reach the app behind a dialog. While
76
76
  `hasModalOverlay` is true the provider sets `accessibilityElementsHidden` and
77
77
  `importantForAccessibility="no-hide-descendants"` on that `View`. Overlays and sheets draw in the
78
- host, outside it, and stay reachable. **Not when teleport draws inline.** `react-native-teleport`'s
78
+ host, outside it, and stay reachable. **An exiting modal does not count.** Pass
79
+ `isExiting={phase === "exiting"}` to `Overlay.Portal`, as Dialog and Drawer do: the registry keeps
80
+ the entry, and its place in the z-order, until the portal unmounts, but the app is reachable again
81
+ from the start of the exit, so `onExited` can move focus back to the trigger. **Not when teleport draws inline.** `react-native-teleport`'s
79
82
  Jest mock renders a portal in place, inside that `View`, so hiding it would hide the dialog too
80
83
  and every query for it would fail. The test kit sets the global `TELEPORT_INLINE` symbol to say
81
84
  so, and the provider then leaves the app visible. It is a symbol on `globalThis`, not an import, so
82
85
  the test kit installs without Overlay.
86
+ - **Screen readers stay inside the top modal.** Hiding the app content does not hide a dialog under
87
+ another dialog: both draw in the `"root"` host. So each portal reads the registry: the top open modal's frame sets `accessibilityViewIsModal`, and every frame drawn
88
+ under it sets `accessibilityElementsHidden` and `importantForAccessibility="no-hide-descendants"`.
89
+ A popover or toast above the top dialog is in a higher band and stays reachable. When the top
90
+ dialog starts to exit, the one under it is the top again. A bottom sheet is not in this registry,
91
+ so a sheet under a dialog is not hidden yet.
83
92
  - **The portal's wrapper is `box-none`.** An overlay with no scrim — a toast, a tooltip — leaves
84
93
  the app under it interactive.
85
94
  - **The provider hears every touch that starts beneath it, and claims none.** Its children sit in a
@@ -101,5 +110,9 @@ imports an overlay never resolves it. The consequence is the same one thing to d
101
110
  ## Testing
102
111
 
103
112
  The registry, the presence machine, the scrim token and the motion constants are pure and unit-tested.
104
- The provider, the portal and the hooks are verified on a simulator through every overlay's
105
- gallery — the foundation has no gallery of its own, the way `DelacourProvider` has none.
113
+ The render tests mount the provider and portals under Jest: registry entry
114
+ and z-order, scrim, presence, back handler and touch fan-out, and what screen readers can reach while
115
+ a modal is open, exiting, or under another modal. `useOverlayPresence` is also tested with an owner
116
+ that re-renders every frame: one timing per transition and one on-time finish. The native teleport
117
+ host is not in Jest, so the provider, the portal and the hooks are also checked on a simulator through
118
+ every overlay's gallery — the foundation has no gallery of its own, the way `DelacourProvider` has none.
@@ -11,6 +11,7 @@ export type { OverlayPortalProps } from "./overlay-portal";
11
11
  export { isPresent, type PresenceEvent, type PresencePhase, presenceTarget, reducePresence } from "./overlay-presence";
12
12
  export {
13
13
  INITIAL_OVERLAY_REGISTRY,
14
+ isBelowTopModal,
14
15
  isTopOverlay,
15
16
  OVERLAY_LAYER_BASE,
16
17
  OVERLAY_LAYERS,
@@ -19,6 +20,7 @@ export {
19
20
  type OverlayRegistryEntry,
20
21
  type OverlayRegistryState,
21
22
  reduceOverlayRegistry,
23
+ topModalOverlay,
22
24
  topOverlay,
23
25
  zIndexOfOverlay,
24
26
  } from "./overlay-registry";
@@ -2,7 +2,7 @@ import { type ReactElement, type ReactNode, useEffect, useId } from "react";
2
2
  import { StyleSheet, View } from "react-native";
3
3
  import { Portal } from "react-native-teleport";
4
4
  import { useOptionalOverlay } from "./overlay.context";
5
- import { type OverlayLayer, zIndexOfOverlay } from "./overlay-registry";
5
+ import { isBelowTopModal, type OverlayLayer, topModalOverlay, zIndexOfOverlay } from "./overlay-registry";
6
6
 
7
7
  export type OverlayPortalProps = {
8
8
  /** Which band of the z-order this overlay draws in. */
@@ -14,6 +14,13 @@ export type OverlayPortalProps = {
14
14
  * `useId()` of the portal's own.
15
15
  */
16
16
  id?: string;
17
+ /**
18
+ * The overlay is playing its exit animation — pass
19
+ * `useOverlayPresence().phase === "exiting"`. An exiting modal stops hiding
20
+ * the app from screen readers, so `onExited` can move focus back to the
21
+ * trigger. Default false.
22
+ */
23
+ isExiting?: boolean;
17
24
  /** Render where it is written instead of teleporting. Default false. */
18
25
  isInline?: boolean;
19
26
  /** The teleport host. Default `"root"` — the one `OverlayProvider`'s teleport provider fills the app with. */
@@ -35,6 +42,10 @@ let hasWarnedMissingProvider = false;
35
42
  * an overlay with no scrim — a toast, a tooltip — leaves the app under it
36
43
  * interactive.
37
44
  *
45
+ * While a modal overlay is open above it, the frame is hidden from screen
46
+ * readers, so VoiceOver and TalkBack cannot leave the top dialog for one under
47
+ * it.
48
+ *
38
49
  * Without an `OverlayProvider` above, or with `isInline`, the children render
39
50
  * where they are written, in an absolute fill of the nearest positioned
40
51
  * ancestor — and the missing provider warns once in development.
@@ -43,6 +54,7 @@ export function OverlayPortal({
43
54
  layer,
44
55
  children,
45
56
  id,
57
+ isExiting = false,
46
58
  isInline = false,
47
59
  hostName = "root",
48
60
  }: OverlayPortalProps): ReactElement {
@@ -58,6 +70,11 @@ export function OverlayPortal({
58
70
  return () => dismissed(overlayId);
59
71
  }, [present, dismissed, overlayId, layer]);
60
72
 
73
+ const exiting = registry?.exiting;
74
+ useEffect(() => {
75
+ exiting?.(overlayId, isExiting);
76
+ }, [exiting, overlayId, isExiting]);
77
+
61
78
  useEffect(() => {
62
79
  if (!__DEV__ || registry !== null || isInline || hasWarnedMissingProvider) return;
63
80
  hasWarnedMissingProvider = true;
@@ -66,9 +83,20 @@ export function OverlayPortal({
66
83
  );
67
84
  }, [registry, isInline]);
68
85
 
86
+ // Screen readers stay inside the top modal. Its frame is modal for
87
+ // VoiceOver, and every frame drawn under it is hidden on both platforms:
88
+ // they share teleport's host, so hiding the app content does not cover them.
69
89
  const zIndex = registry === null ? 0 : zIndexOfOverlay(registry.state, overlayId);
90
+ const isTopModal = registry !== null && topModalOverlay(registry.state) === overlayId;
91
+ const isHidden = registry !== null && isBelowTopModal(registry.state, overlayId);
70
92
  const frame = (
71
- <View pointerEvents="box-none" style={[StyleSheet.absoluteFill, { zIndex }]}>
93
+ <View
94
+ accessibilityElementsHidden={isHidden}
95
+ accessibilityViewIsModal={isTopModal}
96
+ importantForAccessibility={isHidden ? "no-hide-descendants" : "auto"}
97
+ pointerEvents="box-none"
98
+ style={[StyleSheet.absoluteFill, { zIndex }]}
99
+ >
72
100
  {children}
73
101
  </View>
74
102
  );
@@ -2,10 +2,12 @@ import { describe, expect, test } from "bun:test";
2
2
  import {
3
3
  hasModalOverlay,
4
4
  INITIAL_OVERLAY_REGISTRY,
5
+ isBelowTopModal,
5
6
  isTopOverlay,
6
7
  OVERLAY_LAYER_BASE,
7
8
  type OverlayRegistryState,
8
9
  reduceOverlayRegistry,
10
+ topModalOverlay,
9
11
  topOverlay,
10
12
  zIndexOfOverlay,
11
13
  } from "./overlay-registry";
@@ -63,6 +65,28 @@ describe("reduceOverlayRegistry", () => {
63
65
  expect(reduceOverlayRegistry(state, { type: "close", id: "nope" })).toBe(state);
64
66
  });
65
67
 
68
+ test("an exiting overlay keeps its place in the z-order", () => {
69
+ const open = apply({ type: "open", id: "a", layer: "modal" }, { type: "open", id: "b", layer: "modal" });
70
+ const state = reduceOverlayRegistry(open, { type: "exiting", id: "a", isExiting: true });
71
+ expect(zIndexOfOverlay(state, "a")).toBe(zIndexOfOverlay(open, "a"));
72
+ expect(state.nextSeq).toBe(open.nextSeq);
73
+ });
74
+
75
+ test("re-stamping an exiting overlay keeps it exiting", () => {
76
+ const state = apply(
77
+ { type: "open", id: "a", layer: "modal" },
78
+ { type: "exiting", id: "a", isExiting: true },
79
+ { type: "open", id: "a", layer: "anchored" }
80
+ );
81
+ expect(state.open).toEqual([expect.objectContaining({ id: "a", layer: "anchored", isExiting: true })]);
82
+ });
83
+
84
+ test("an exiting that changes nothing returns the same state", () => {
85
+ const state = apply({ type: "open", id: "a", layer: "modal" });
86
+ expect(reduceOverlayRegistry(state, { type: "exiting", id: "a", isExiting: false })).toBe(state);
87
+ expect(reduceOverlayRegistry(state, { type: "exiting", id: "nope", isExiting: true })).toBe(state);
88
+ });
89
+
66
90
  test("a closed overlay has no z", () => {
67
91
  const state = apply({ type: "open", id: "a", layer: "modal" }, { type: "close", id: "a" });
68
92
  expect(zIndexOfOverlay(state, "a")).toBe(0);
@@ -112,9 +136,76 @@ describe("hasModalOverlay", () => {
112
136
  expect(hasModalOverlay(state)).toBe(false);
113
137
  });
114
138
 
139
+ test("is false while the only modal overlay is exiting, so focus can return to its trigger", () => {
140
+ const state = apply(
141
+ { type: "open", id: "dialog", layer: "modal" },
142
+ { type: "exiting", id: "dialog", isExiting: true }
143
+ );
144
+ expect(hasModalOverlay(state)).toBe(false);
145
+ });
146
+
147
+ test("is true again when an exiting modal reopens", () => {
148
+ const state = apply(
149
+ { type: "open", id: "dialog", layer: "modal" },
150
+ { type: "exiting", id: "dialog", isExiting: true },
151
+ { type: "exiting", id: "dialog", isExiting: false }
152
+ );
153
+ expect(hasModalOverlay(state)).toBe(true);
154
+ });
155
+
156
+ test("stays true while another modal overlay is still open", () => {
157
+ const state = apply(
158
+ { type: "open", id: "lower", layer: "modal" },
159
+ { type: "open", id: "upper", layer: "modal" },
160
+ { type: "exiting", id: "upper", isExiting: true }
161
+ );
162
+ expect(hasModalOverlay(state)).toBe(true);
163
+ });
164
+
115
165
  test("is false again once the last modal overlay closes", () => {
116
166
  let state = reduceOverlayRegistry(INITIAL_OVERLAY_REGISTRY, { type: "open", id: "dialog", layer: "modal" });
117
167
  state = reduceOverlayRegistry(state, { type: "close", id: "dialog" });
118
168
  expect(hasModalOverlay(state)).toBe(false);
119
169
  });
120
170
  });
171
+
172
+ describe("topModalOverlay / isBelowTopModal", () => {
173
+ test("is null with no modal open", () => {
174
+ const state = apply({ type: "open", id: "pop", layer: "anchored" });
175
+ expect(topModalOverlay(state)).toBeNull();
176
+ expect(isBelowTopModal(state, "pop")).toBe(false);
177
+ });
178
+
179
+ test("hides a dialog under another dialog, never the top one", () => {
180
+ const state = apply({ type: "open", id: "lower", layer: "modal" }, { type: "open", id: "upper", layer: "modal" });
181
+ expect(topModalOverlay(state)).toBe("upper");
182
+ expect(isBelowTopModal(state, "lower")).toBe(true);
183
+ expect(isBelowTopModal(state, "upper")).toBe(false);
184
+ });
185
+
186
+ test("leaves a popover or toast above the top dialog reachable", () => {
187
+ const state = apply(
188
+ { type: "open", id: "dialog", layer: "modal" },
189
+ { type: "open", id: "pop", layer: "anchored" },
190
+ { type: "open", id: "toast", layer: "toast" }
191
+ );
192
+ expect(isBelowTopModal(state, "pop")).toBe(false);
193
+ expect(isBelowTopModal(state, "toast")).toBe(false);
194
+ });
195
+
196
+ test("an exiting top dialog hands screen readers to the one under it", () => {
197
+ const state = apply(
198
+ { type: "open", id: "lower", layer: "modal" },
199
+ { type: "open", id: "upper", layer: "modal" },
200
+ { type: "exiting", id: "upper", isExiting: true }
201
+ );
202
+ expect(topModalOverlay(state)).toBe("lower");
203
+ expect(isBelowTopModal(state, "lower")).toBe(false);
204
+ expect(isBelowTopModal(state, "upper")).toBe(false);
205
+ });
206
+
207
+ test("an overlay that is not open is not below anything", () => {
208
+ const state = apply({ type: "open", id: "dialog", layer: "modal" });
209
+ expect(isBelowTopModal(state, "nope")).toBe(false);
210
+ });
211
+ });
@@ -26,6 +26,8 @@ export type OverlayRegistryEntry = {
26
26
  layer: OverlayLayer;
27
27
  /** Open order across every layer; later is larger. */
28
28
  seq: number;
29
+ /** Playing its exit animation: still drawn, no longer what the screen is about. */
30
+ isExiting: boolean;
29
31
  };
30
32
 
31
33
  export type OverlayRegistryState = {
@@ -35,30 +37,50 @@ export type OverlayRegistryState = {
35
37
 
36
38
  export const INITIAL_OVERLAY_REGISTRY: OverlayRegistryState = { nextSeq: 1, open: [] };
37
39
 
38
- export type OverlayRegistryAction = { type: "open"; id: string; layer: OverlayLayer } | { type: "close"; id: string };
40
+ export type OverlayRegistryAction =
41
+ | { type: "open"; id: string; layer: OverlayLayer }
42
+ | { type: "exiting"; id: string; isExiting: boolean }
43
+ | { type: "close"; id: string };
39
44
 
40
45
  /**
41
46
  * The registry as a pure reducer, so the z-order is testable without a renderer.
42
47
  *
43
48
  * An `open` stamps the next sequence number; an overlay already open is
44
- * re-stamped rather than duplicated, which brings it forward. A `close` of an
45
- * overlay that is not open returns the same state object, so an unmount racing
46
- * an exit causes no render.
49
+ * re-stamped rather than duplicated, which brings it forward and keeps its
50
+ * `isExiting`. An `exiting` marks an overlay that is animating closed, and
51
+ * keeps its place in the z-order. A `close` of an overlay that is not open, or an `exiting` that
52
+ * changes nothing, returns the same state object, so an unmount racing an exit
53
+ * causes no render.
47
54
  */
48
55
  export function reduceOverlayRegistry(
49
56
  state: OverlayRegistryState,
50
57
  action: OverlayRegistryAction
51
58
  ): OverlayRegistryState {
52
- if (action.type === "close") {
53
- if (!state.open.some((entry) => entry.id === action.id)) return state;
54
- return { ...state, open: state.open.filter((entry) => entry.id !== action.id) };
59
+ switch (action.type) {
60
+ case "close": {
61
+ if (!state.open.some((entry) => entry.id === action.id)) return state;
62
+ return { ...state, open: state.open.filter((entry) => entry.id !== action.id) };
63
+ }
64
+ case "exiting": {
65
+ const entry = state.open.find((candidate) => candidate.id === action.id);
66
+ if (entry === undefined || entry.isExiting === action.isExiting) return state;
67
+ return {
68
+ ...state,
69
+ open: state.open.map((candidate) =>
70
+ candidate === entry ? { ...candidate, isExiting: action.isExiting } : candidate
71
+ ),
72
+ };
73
+ }
74
+ case "open": {
75
+ const previous = state.open.find((entry) => entry.id === action.id);
76
+ const others = state.open.filter((entry) => entry !== previous);
77
+ const isExiting = previous?.isExiting ?? false;
78
+ return {
79
+ nextSeq: state.nextSeq + 1,
80
+ open: [...others, { id: action.id, layer: action.layer, seq: state.nextSeq, isExiting }],
81
+ };
82
+ }
55
83
  }
56
-
57
- const others = state.open.filter((entry) => entry.id !== action.id);
58
- return {
59
- nextSeq: state.nextSeq + 1,
60
- open: [...others, { id: action.id, layer: action.layer, seq: state.nextSeq }],
61
- };
62
84
  }
63
85
 
64
86
  /**
@@ -99,13 +121,51 @@ export function isTopOverlay(state: OverlayRegistryState, id: string): boolean {
99
121
  }
100
122
 
101
123
  /**
102
- * Whether a modal overlay is presented — open, or animating closed.
124
+ * Whether a modal overlay is open and not animating closed.
103
125
  *
104
126
  * Every overlay teleports into the `"root"` host, which sits beside the app
105
127
  * content, not above it in the view tree. A panel's `accessibilityViewIsModal`
106
128
  * hides only its own siblings in that host, so `OverlayProvider` uses this to
107
129
  * hide the app content from screen readers while a dialog or drawer is up.
130
+ *
131
+ * An exiting modal does not count. Its `onExited` is where a dialog moves
132
+ * focus back to its trigger, and the trigger must be reachable by then.
108
133
  */
109
134
  export function hasModalOverlay(state: OverlayRegistryState): boolean {
110
- return state.open.some((entry) => entry.layer === "modal");
135
+ return state.open.some((entry) => entry.layer === "modal" && !entry.isExiting);
136
+ }
137
+
138
+ /**
139
+ * The modal overlay drawn on top that is not animating closed, or `null`.
140
+ *
141
+ * Its portal frame is the one screen readers stay inside. A popover or toast
142
+ * above it is in a higher band and stays reachable.
143
+ */
144
+ export function topModalOverlay(state: OverlayRegistryState): string | null {
145
+ let top: string | null = null;
146
+ let topZ = 0;
147
+ for (const entry of state.open) {
148
+ if (entry.layer !== "modal" || entry.isExiting) continue;
149
+ const z = zIndexOfOverlay(state, entry.id);
150
+ if (z > topZ) {
151
+ top = entry.id;
152
+ topZ = z;
153
+ }
154
+ }
155
+ return top;
156
+ }
157
+
158
+ /**
159
+ * Whether `id` draws under the top modal overlay and must be hidden from
160
+ * screen readers.
161
+ *
162
+ * Every overlay draws in the same `"root"` host as the top modal, so hiding
163
+ * the app content does not hide a dialog under another dialog. Each portal
164
+ * reads this and hides its own frame.
165
+ */
166
+ export function isBelowTopModal(state: OverlayRegistryState, id: string): boolean {
167
+ const top = topModalOverlay(state);
168
+ if (top === null || top === id) return false;
169
+ const z = zIndexOfOverlay(state, id);
170
+ return z !== 0 && z < zIndexOfOverlay(state, top);
111
171
  }
@@ -7,6 +7,8 @@ export type OverlayContextValue = {
7
7
  state: OverlayRegistryState;
8
8
  /** A portal reports that its overlay is presented, and in which layer. */
9
9
  present: (id: string, layer: OverlayLayer) => void;
10
+ /** A portal reports that its overlay started, or stopped, animating closed. */
11
+ exiting: (id: string, isExiting: boolean) => void;
10
12
  /** The overlay's portal unmounted. */
11
13
  dismissed: (id: string) => void;
12
14
  /**
@@ -1,15 +1,23 @@
1
- import { afterEach, describe, expect, jest, test } from "@jest/globals";
1
+ import { afterEach, beforeEach, describe, expect, jest, test } from "@jest/globals";
2
2
  import { type ReactElement, type ReactNode, useState } from "react";
3
3
  import { BackHandler, Text, View } from "react-native";
4
- import { useSharedValue } from "react-native-reanimated";
5
- import { act, fireEvent, renderWithProviders, screen, waitFor } from "../../test/render";
4
+ import { useSharedValue, withTiming } from "react-native-reanimated";
5
+ import { act, fireEvent, renderHook, renderWithProviders, screen, waitFor } from "../../test/render";
6
6
  import { Overlay, OverlayProvider } from "./overlay";
7
7
  import { useOptionalOverlay } from "./overlay.context";
8
+ import { OVERLAY_MOTION } from "./overlay.variants";
8
9
  import { type OverlayLayer, zIndexOfOverlay } from "./overlay-registry";
9
10
  import { TELEPORT_INLINE } from "./overlay-teleport";
10
11
  import { useOverlayBackHandler } from "./use-overlay-back-handler";
11
12
  import { useOverlayPresence } from "./use-overlay-presence";
12
13
 
14
+ jest.mock("react-native-reanimated", () => {
15
+ const actual = jest.requireActual<typeof import("react-native-reanimated")>("react-native-reanimated");
16
+ return { ...actual, withTiming: jest.fn(actual.withTiming) };
17
+ });
18
+
19
+ const timing = jest.mocked(withTiming);
20
+
13
21
  type DemoProps = {
14
22
  name: string;
15
23
  layer?: OverlayLayer;
@@ -28,7 +36,7 @@ function Demo({
28
36
  onExited,
29
37
  }: DemoProps): ReactElement | null {
30
38
  const [isOpen, setIsOpen] = useState(defaultOpen);
31
- const { isPresent, progress } = useOverlayPresence({ isOpen, enterMs: 1, exitMs: 1, onExited });
39
+ const { isPresent, phase, progress } = useOverlayPresence({ isOpen, enterMs: 1, exitMs: 1, onExited });
32
40
  const close = () => {
33
41
  onDismiss?.();
34
42
  setIsOpen(false);
@@ -46,7 +54,7 @@ function Demo({
46
54
  <>
47
55
  <Text onPress={() => setIsOpen(true)}>{`open ${name}`}</Text>
48
56
  {isPresent ? (
49
- <Overlay.Portal id={name} layer={layer}>
57
+ <Overlay.Portal id={name} isExiting={phase === "exiting"} layer={layer}>
50
58
  <Overlay.Scrim onDismiss={close} progress={progress} testID={`${name}-scrim`} />
51
59
  <View testID={`${name}-panel`}>
52
60
  <Text>{`${name} panel`}</Text>
@@ -70,6 +78,13 @@ function ZIndexProbe({ id }: { id: string }): ReactElement {
70
78
 
71
79
  const scrim = (name: string) => screen.getByTestId(`${name}-scrim`, { includeHiddenElements: true });
72
80
 
81
+ /** The portal frame: the parent of the overlay's panel. */
82
+ function frame(name: string) {
83
+ const node = screen.getByTestId(`${name}-panel`, { includeHiddenElements: true }).parent;
84
+ if (node === null) throw new Error("no portal frame");
85
+ return node;
86
+ }
87
+
73
88
  afterEach(() => {
74
89
  jest.restoreAllMocks();
75
90
  });
@@ -188,6 +203,49 @@ describe("OverlayProvider and screen readers", () => {
188
203
  });
189
204
  });
190
205
 
206
+ test("the app content is reachable again when onExited fires, so focus can return to the trigger", async () => {
207
+ await withTeleportOutOfTree(async () => {
208
+ const reachableAtExit: boolean[] = [];
209
+ await renderWithProviders(
210
+ <Demo name="exit" onExited={() => reachableAtExit.push(screen.queryByText("open exit") !== null)} />,
211
+ { wrapper: Provider }
212
+ );
213
+ expect(screen.queryByText("open exit")).toBeNull();
214
+
215
+ await fireEvent.press(scrim("exit"));
216
+ expect(screen.getByText("open exit")).toBeOnTheScreen();
217
+ await waitFor(() => expect(reachableAtExit).toEqual([true]));
218
+ });
219
+ });
220
+
221
+ test("a dialog under another dialog is hidden and only the top one is modal", async () => {
222
+ await renderWithProviders(
223
+ <>
224
+ <Demo name="lower" />
225
+ <Demo name="upper" />
226
+ </>,
227
+ { wrapper: Provider }
228
+ );
229
+ expect(frame("lower").props.accessibilityElementsHidden).toBe(true);
230
+ expect(frame("lower").props.importantForAccessibility).toBe("no-hide-descendants");
231
+ expect(frame("lower").props.accessibilityViewIsModal).toBe(false);
232
+ expect(frame("upper").props.accessibilityElementsHidden).toBe(false);
233
+ expect(frame("upper").props.accessibilityViewIsModal).toBe(true);
234
+ });
235
+
236
+ test("the lower dialog is reachable again once the top one starts to exit", async () => {
237
+ await renderWithProviders(
238
+ <>
239
+ <Demo name="lower" />
240
+ <Demo name="upper" />
241
+ </>,
242
+ { wrapper: Provider }
243
+ );
244
+ await fireEvent.press(scrim("upper"));
245
+ expect(frame("lower").props.accessibilityElementsHidden).toBe(false);
246
+ expect(frame("lower").props.accessibilityViewIsModal).toBe(true);
247
+ });
248
+
191
249
  test("a toast does not hide the app content", async () => {
192
250
  await withTeleportOutOfTree(async () => {
193
251
  await renderWithProviders(<Demo name="toast" layer="toast" />, { wrapper: Provider });
@@ -246,6 +304,81 @@ describe("useOverlayPresence", () => {
246
304
  });
247
305
  });
248
306
 
307
+ const FRAME_MS = 16;
308
+
309
+ /**
310
+ * Re-renders the owner with a new inline callback every frame for most of the
311
+ * animation, then lets the rest of the original duration run. The timing must
312
+ * start once per transition, and the finish land once, on time, and call the
313
+ * latest callback.
314
+ */
315
+ async function rerenderEveryFrame(durationMs: number, rerender: (tick: number) => Promise<void>): Promise<void> {
316
+ let elapsed = 0;
317
+ let tick = 0;
318
+ while (elapsed + FRAME_MS < durationMs) {
319
+ await act(() => jest.advanceTimersByTime(FRAME_MS));
320
+ elapsed += FRAME_MS;
321
+ tick += 1;
322
+ await rerender(tick);
323
+ }
324
+ await act(() => jest.advanceTimersByTime(durationMs - elapsed + FRAME_MS * 2));
325
+ }
326
+
327
+ describe("useOverlayPresence with an owner that re-renders every frame", () => {
328
+ beforeEach(() => {
329
+ jest.useFakeTimers();
330
+ timing.mockClear();
331
+ });
332
+ afterEach(() => {
333
+ jest.useRealTimers();
334
+ });
335
+
336
+ test("starts one entrance timing and enters on time with a new inline onEntered", async () => {
337
+ const entered: number[] = [];
338
+ const { result, rerender } = await renderHook(
339
+ ({ tick }: { tick: number }) =>
340
+ useOverlayPresence({
341
+ isOpen: true,
342
+ onEntered: () => {
343
+ entered.push(tick);
344
+ },
345
+ }),
346
+ { initialProps: { tick: 0 } }
347
+ );
348
+
349
+ await rerenderEveryFrame(OVERLAY_MOTION.enterMs, (tick) => rerender({ tick }));
350
+
351
+ expect(result.current.phase).toBe("open");
352
+ expect(timing).toHaveBeenCalledTimes(1);
353
+ expect(entered).toHaveLength(1);
354
+ expect(entered[0]).toBeGreaterThan(0);
355
+ });
356
+
357
+ test("starts one exit timing and exits on time with a new inline onExited", async () => {
358
+ const exited: number[] = [];
359
+ const { result, rerender } = await renderHook(
360
+ ({ isOpen, tick }: { isOpen: boolean; tick: number }) =>
361
+ useOverlayPresence({
362
+ isOpen,
363
+ onExited: () => {
364
+ exited.push(tick);
365
+ },
366
+ }),
367
+ { initialProps: { isOpen: true, tick: 0 } }
368
+ );
369
+ await act(() => jest.advanceTimersByTime(OVERLAY_MOTION.enterMs + FRAME_MS * 2));
370
+ timing.mockClear();
371
+ await rerender({ isOpen: false, tick: 0 });
372
+
373
+ await rerenderEveryFrame(OVERLAY_MOTION.exitMs, (tick) => rerender({ isOpen: false, tick }));
374
+
375
+ expect(result.current.phase).toBe("closed");
376
+ expect(timing).toHaveBeenCalledTimes(1);
377
+ expect(exited).toHaveLength(1);
378
+ expect(exited[0]).toBeGreaterThan(0);
379
+ });
380
+ });
381
+
249
382
  describe("useOverlayBackHandler", () => {
250
383
  type BackPress = Parameters<typeof BackHandler.addEventListener>[1];
251
384
  const backEvent = { type: "hardwareBackPress", timeStamp: 0 };
@@ -12,6 +12,7 @@ import {
12
12
  hasModalOverlay,
13
13
  INITIAL_OVERLAY_REGISTRY,
14
14
  type OverlayLayer,
15
+ type OverlayRegistryAction,
15
16
  type OverlayRegistryState,
16
17
  reduceOverlayRegistry,
17
18
  } from "./overlay-registry";
@@ -32,12 +33,14 @@ function OverlayRoot({ children }: OverlayProviderProps): ReactElement {
32
33
  setState(current.current);
33
34
  }, []);
34
35
 
35
- const dismissed = useCallback((id: string) => {
36
- const next = reduceOverlayRegistry(current.current, { type: "close", id });
36
+ const apply = useCallback((action: OverlayRegistryAction) => {
37
+ const next = reduceOverlayRegistry(current.current, action);
37
38
  if (next === current.current) return;
38
39
  current.current = next;
39
40
  setState(next);
40
41
  }, []);
42
+ const exiting = useCallback((id: string, isExiting: boolean) => apply({ type: "exiting", id, isExiting }), [apply]);
43
+ const dismissed = useCallback((id: string) => apply({ type: "close", id }), [apply]);
41
44
 
42
45
  const touchListeners = useRef(new Set<() => void>());
43
46
  const subscribeTouchStart = useCallback((listener: () => void) => {
@@ -51,8 +54,8 @@ function OverlayRoot({ children }: OverlayProviderProps): ReactElement {
51
54
  }, []);
52
55
 
53
56
  const value = useMemo<OverlayContextValue>(
54
- () => ({ state, present, dismissed, subscribeTouchStart }),
55
- [state, present, dismissed, subscribeTouchStart]
57
+ () => ({ state, present, exiting, dismissed, subscribeTouchStart }),
58
+ [state, present, exiting, dismissed, subscribeTouchStart]
56
59
  );
57
60
 
58
61
  // `onTouchStart` is a bubbling touch event, not a responder claim: it fires
@@ -60,9 +63,10 @@ function OverlayRoot({ children }: OverlayProviderProps): ReactElement {
60
63
  // included, since teleport leaves the fiber where it was — and never stops
61
64
  // the touch reaching its target or a gesture handler.
62
65
  //
63
- // While a modal overlay is presented, the app content is hidden from
64
- // VoiceOver and TalkBack. The overlays draw in teleport's host, outside
65
- // this view in the native tree, so they stay reachable. Where teleport draws
66
+ // While a modal overlay is open, the app content is hidden from VoiceOver
67
+ // and TalkBack. The overlays draw in teleport's host, outside this view in
68
+ // the native tree, so they stay reachable. An exiting modal no longer hides
69
+ // it, so focus can return to the trigger in `onExited`. Where teleport draws
66
70
  // inline — the Jest mock does — the overlays are inside this view, so it
67
71
  // stays visible.
68
72
  const isAppHidden = hasModalOverlay(state) && !isTeleportInline();
@@ -100,8 +104,8 @@ const styles = StyleSheet.create({ fill: { flex: 1 } });
100
104
  * two native hosts with one name. And the overlay registry, which gives every
101
105
  * presented overlay a `zIndex` in its layer's band and tells each one whether it
102
106
  * is the top, the one Android's back button closes. While a modal overlay is
103
- * presented it hides the app content from screen readers, so focus cannot move
104
- * behind a dialog. It also hears every touch
107
+ * open, and not animating closed, it hides the app content from screen
108
+ * readers, so focus cannot move behind a dialog. It also hears every touch
105
109
  * that starts beneath it, without claiming one, so a tooltip can close on an
106
110
  * outside tap that still lands where it was aimed.
107
111
  *