@vvedantb/native-ui 0.28.0 → 0.30.0

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.
@@ -32,7 +32,10 @@ import {
32
32
  } from "./totp";
33
33
  import { GoogleSignInButton, type AuthNavigationOptions } from "./GoogleSignInButton";
34
34
 
35
- export type SignInMode = "sign-in" | "sign-up";
35
+ export type SignInMode = "sign-in" | "sign-up" | "reset-password";
36
+
37
+ /** The first factor that emails a password-reset code. */
38
+ const RESET_STRATEGY = "reset_password_email_code";
36
39
 
37
40
  /** The messages the screen can show. Generic: none names a provider. */
38
41
  export const AUTH_MESSAGES = {
@@ -66,6 +69,16 @@ export const AUTH_MESSAGES = {
66
69
  passwordTooShort: "Use a longer password",
67
70
  resetPasswordFailed: "Could not set the new password",
68
71
  setPassword: "Set password",
72
+ missingNewPassword: "Enter a new password",
73
+ confirmSignUpPasswordLabel: "Confirm password",
74
+ forgotPassword: "Forgot password?",
75
+ resetTitle: "Reset password",
76
+ resetSubtitle: "Enter your email and we will send you a code.",
77
+ resetNewPasswordDescription: "Choose a new password for your account.",
78
+ missingEmail: "Enter your email",
79
+ sendResetCode: "Send code",
80
+ sendResetFailed: "Could not send the code",
81
+ resendCode: "Send a new code",
69
82
  } as const;
70
83
 
71
84
  /**
@@ -104,11 +117,15 @@ function secondFactorCopy(strategy: SecondFactorStrategy, clientTrust: boolean)
104
117
  }
105
118
 
106
119
  export type SignInScreenProps = AuthNavigationOptions & {
107
- /** Default `"sign-in"`. `"sign-up"` creates the account and checks an emailed code. */
120
+ /**
121
+ * Default `"sign-in"`. `"sign-up"` creates the account and checks an emailed
122
+ * code. `"reset-password"` emails a code, checks it, then sets a new password
123
+ * and signs in.
124
+ */
108
125
  mode?: SignInMode;
109
- /** Default "Welcome back", or "Create account" in `sign-up`. */
126
+ /** Default "Welcome back", "Create account" in `sign-up`, or "Reset password" in `reset-password`. */
110
127
  title?: string;
111
- /** Default "Sign in to continue", or "Sign up to get started" in `sign-up`. */
128
+ /** Default "Sign in to continue", "Sign up to get started" in `sign-up`, or the reset hint in `reset-password`. */
112
129
  subtitle?: string;
113
130
  /** The app URL scheme, such as `"vibot"`, for the Google redirect `scheme://sso-callback`. */
114
131
  scheme: string;
@@ -120,9 +137,14 @@ export type SignInScreenProps = AuthNavigationOptions & {
120
137
  googleLabel?: string;
121
138
  /** In `sign-in`: the "Sign up" link in the footer. No link without it. */
122
139
  signUpHref?: Href;
123
- /** In `sign-up`: the "Sign in" link in the footer. No link without it. */
140
+ /** In `sign-up` and `reset-password`: the "Sign in" link in the footer. No link without it. */
124
141
  signInHref?: Href;
125
- /** Sign-up rejects a shorter password before sending it. Default: no check. */
142
+ /**
143
+ * In `sign-in`: the "Forgot password?" link under the password, to a route
144
+ * that renders `ResetPasswordScreen`. No link without it.
145
+ */
146
+ forgotPasswordHref?: Href;
147
+ /** Sign-up and the new-password step reject a shorter password before sending it. Default: no check. */
126
148
  minPasswordLength?: number;
127
149
  /** Default `"toast"`. `"inline"` shows errors under the fields. */
128
150
  errorDisplay?: "toast" | "inline";
@@ -158,7 +180,13 @@ export type SignInScreenProps = AuthNavigationOptions & {
158
180
  * code and checks it before the session starts. On success it calls
159
181
  * `onSuccess`, or `router.replace(afterAuthHref, replaceOptions)`.
160
182
  *
161
- * Forgot-password is not here: an app that needs it keeps its own screen.
183
+ * Sign-up has a confirm-password field: a mismatch blocks the submit and shows
184
+ * under the field, whatever `errorDisplay` is.
185
+ *
186
+ * `mode="reset-password"` (`ResetPasswordScreen`) is the forgot-password flow:
187
+ * email, then the emailed code, then a new password typed twice. It ends
188
+ * signed in, through the same second-factor step when the account has one.
189
+ * `forgotPasswordHref` links the sign-in form to it.
162
190
  */
163
191
  export function SignInScreen({
164
192
  mode = "sign-in",
@@ -173,6 +201,7 @@ export function SignInScreen({
173
201
  googleLabel,
174
202
  signUpHref,
175
203
  signInHref,
204
+ forgotPasswordHref,
176
205
  minPasswordLength,
177
206
  errorDisplay = "toast",
178
207
  testIDPrefix,
@@ -200,6 +229,11 @@ export function SignInScreen({
200
229
  const [pendingNewPassword, setPendingNewPassword] = useState(false);
201
230
  const [newPassword, setNewPassword] = useState("");
202
231
  const [confirmPassword, setConfirmPassword] = useState("");
232
+ const [signUpConfirm, setSignUpConfirm] = useState("");
233
+ const [mismatch, setMismatch] = useState(false);
234
+ const [pendingResetCode, setPendingResetCode] = useState(false);
235
+ const [resetLoading, setResetLoading] = useState(false);
236
+ const [resetCodeError, setResetCodeError] = useState("");
203
237
  const secondFactor = useSecondFactor({ stageTimeoutMs });
204
238
  const [error, setError] = useState("");
205
239
  const [submitting, setSubmitting] = useState(false);
@@ -207,6 +241,7 @@ export function SignInScreen({
207
241
  const passwordField = useRef<TextInput>(null);
208
242
  const confirmField = useRef<TextInput>(null);
209
243
  const signUp = mode === "sign-up";
244
+ const reset = mode === "reset-password";
210
245
  const id = (name: string) => `${testIDPrefix ?? mode}-${name}`;
211
246
 
212
247
  const fail = (heading: string, message: string) => {
@@ -289,9 +324,11 @@ export function SignInScreen({
289
324
  done();
290
325
  } else if (status === "needs_new_password") {
291
326
  setPendingFirstFactor(false);
327
+ setPendingResetCode(false);
292
328
  setPendingNewPassword(true);
293
329
  } else if (status === "needs_second_factor" || status === "needs_client_trust") {
294
330
  setPendingFirstFactor(false);
331
+ setPendingResetCode(false);
295
332
  await startSecondFactor(attempt, status === "needs_client_trust");
296
333
  } else if (status === "needs_first_factor" && afterCreate) {
297
334
  await startFirstFactor(attempt);
@@ -329,7 +366,7 @@ export function SignInScreen({
329
366
  const onNewPassword = async () => {
330
367
  const { isLoaded, signIn, setActive } = signInState;
331
368
  if (!isLoaded || !signIn || !setActive || submitting) return;
332
- if (!newPassword) return fail(AUTH_MESSAGES.resetPasswordFailed, AUTH_MESSAGES.missingFields);
369
+ if (!newPassword) return fail(AUTH_MESSAGES.resetPasswordFailed, AUTH_MESSAGES.missingNewPassword);
333
370
  if (minPasswordLength && newPassword.length < minPasswordLength) {
334
371
  return fail(AUTH_MESSAGES.resetPasswordFailed, `Use at least ${minPasswordLength} characters for the password`);
335
372
  }
@@ -344,9 +381,15 @@ export function SignInScreen({
344
381
  "reset-password",
345
382
  stageTimeoutMs,
346
383
  );
347
- if (result.status === "complete" && result.createdSessionId) {
384
+ // Clerk's `SignInStatus` omits `needs_client_trust`: widen before comparing.
385
+ const afterReset: string | null = result.status;
386
+ if (afterReset === "complete" && result.createdSessionId) {
348
387
  await withAuthTimeout(setActive({ session: result.createdSessionId }), "set-active", stageTimeoutMs);
349
388
  done();
389
+ } else if (afterReset === "needs_second_factor" || afterReset === "needs_client_trust") {
390
+ // A reset on an account with two-step verification: the code step, then the session.
391
+ setPendingNewPassword(false);
392
+ await startSecondFactor(result, afterReset === "needs_client_trust");
350
393
  } else if (onIncomplete) {
351
394
  onIncomplete(result);
352
395
  } else {
@@ -385,6 +428,80 @@ export function SignInScreen({
385
428
  }
386
429
  };
387
430
 
431
+ // Emails the reset code. Throws what the call throws.
432
+ const requestResetCode = async () => {
433
+ const { signIn } = signInState;
434
+ if (!signIn) return;
435
+ await withAuthTimeout(
436
+ signIn.create({ strategy: RESET_STRATEGY, identifier: email.trim() }),
437
+ "create",
438
+ stageTimeoutMs,
439
+ );
440
+ };
441
+
442
+ const onResetRequest = async () => {
443
+ const { isLoaded, signIn } = signInState;
444
+ if (!isLoaded || !signIn || submitting) return;
445
+ if (!email.trim()) return fail(AUTH_MESSAGES.sendResetFailed, AUTH_MESSAGES.missingEmail);
446
+ setSubmitting(true);
447
+ setError("");
448
+ try {
449
+ await requestResetCode();
450
+ setResetCodeError("");
451
+ setPendingResetCode(true);
452
+ } catch (caught) {
453
+ logAuthFailure("create", caught);
454
+ fail(AUTH_MESSAGES.sendResetFailed, authErrorMessage(caught, AUTH_MESSAGES.sendResetFailed));
455
+ } finally {
456
+ setSubmitting(false);
457
+ }
458
+ };
459
+
460
+ const onResetResend = async () => {
461
+ const { isLoaded, signIn } = signInState;
462
+ if (!isLoaded || !signIn || resetLoading) return;
463
+ setResetLoading(true);
464
+ setResetCodeError("");
465
+ try {
466
+ await requestResetCode();
467
+ } catch (caught) {
468
+ logAuthFailure("create", caught);
469
+ setResetCodeError(authErrorMessage(caught, AUTH_MESSAGES.sendResetFailed));
470
+ } finally {
471
+ setResetLoading(false);
472
+ }
473
+ };
474
+
475
+ // Checks the emailed code. A good code gives `needs_new_password`, which `routeAttempt` shows.
476
+ const onResetCode = async (resetCode: string) => {
477
+ const { isLoaded, signIn } = signInState;
478
+ if (!isLoaded || !signIn || resetLoading) return;
479
+ setResetLoading(true);
480
+ setResetCodeError("");
481
+ try {
482
+ const attempt: IncompleteSignIn = await withAuthTimeout(
483
+ signIn.attemptFirstFactor({ strategy: RESET_STRATEGY, code: resetCode }),
484
+ "attempt-first-factor",
485
+ stageTimeoutMs,
486
+ );
487
+ const status: string | null = attempt.status;
488
+ const known = ["complete", "needs_new_password", "needs_second_factor", "needs_client_trust"];
489
+ if (status && known.includes(status)) {
490
+ await routeAttempt(attempt, false);
491
+ } else if (onIncomplete) {
492
+ onIncomplete(attempt);
493
+ } else {
494
+ warnIncomplete(attempt);
495
+ setResetCodeError(AUTH_MESSAGES.needsAnotherStep);
496
+ }
497
+ } catch (caught) {
498
+ if (isAuthTimeoutError(caught)) logAuthFailure("attempt-first-factor", caught);
499
+ setResetCodeError(authErrorMessage(caught, AUTH_MESSAGES.verifyFailed));
500
+ } finally {
501
+ setResetLoading(false);
502
+ }
503
+ };
504
+
388
505
  const onSecondFactor = async (secondFactorCode: string) => {
389
506
  const result = await secondFactor.submit(secondFactorCode);
390
507
  if (result.ok) done();
@@ -395,6 +512,8 @@ export function SignInScreen({
395
512
  setPendingSecondFactor(false);
396
513
  setPendingFirstFactor(false);
397
514
  setFirstError("");
515
+ setPendingResetCode(false);
516
+ setResetCodeError("");
398
517
  setPendingNewPassword(false);
399
518
  setNewPassword("");
400
519
  setConfirmPassword("");
@@ -410,6 +529,12 @@ export function SignInScreen({
410
529
  if (minPasswordLength && password.length < minPasswordLength) {
411
530
  return fail(AUTH_MESSAGES.signUpFailed, `Use at least ${minPasswordLength} characters for the password`);
412
531
  }
532
+ if (password !== signUpConfirm) {
533
+ // Always under the confirm field, also with `errorDisplay="toast"`.
534
+ setError("");
535
+ setMismatch(true);
536
+ return;
537
+ }
413
538
  setSubmitting(true);
414
539
  setError("");
415
540
  try {
@@ -444,22 +569,23 @@ export function SignInScreen({
444
569
  }
445
570
  };
446
571
 
447
- const linkHref = signUp ? signInHref : signUpHref;
572
+ const toSignIn = signUp || reset;
573
+ const linkHref = toSignIn ? signInHref : signUpHref;
448
574
  const footerRow = (
449
575
  <>
450
576
  {linkHref && !pendingVerification ? (
451
577
  <>
452
578
  <Text className="font-instrument-sans text-sm" style={textStyle("muted", colorScheme)}>
453
- {signUp ? "Already have an account?" : "Don't have an account?"}
579
+ {reset ? "Remembered your password?" : signUp ? "Already have an account?" : "Don't have an account?"}
454
580
  </Text>
455
581
  <Button
456
- testID={id(signUp ? "sign-in-link" : "sign-up-link")}
582
+ testID={id(toSignIn ? "sign-in-link" : "sign-up-link")}
457
583
  variant="link"
458
584
  size="sm"
459
585
  fullWidth={false}
460
586
  onPress={() => router.push(linkHref)}
461
587
  >
462
- {signUp ? "Sign in" : "Sign up"}
588
+ {toSignIn ? "Sign in" : "Sign up"}
463
589
  </Button>
464
590
  </>
465
591
  ) : null}
@@ -473,7 +599,7 @@ export function SignInScreen({
473
599
  <AuthScreen
474
600
  testID={id("new-password-screen")}
475
601
  title={AUTH_MESSAGES.newPasswordTitle}
476
- subtitle={AUTH_MESSAGES.newPasswordDescription}
602
+ subtitle={reset ? AUTH_MESSAGES.resetNewPasswordDescription : AUTH_MESSAGES.newPasswordDescription}
477
603
  header={header}
478
604
  >
479
605
  <PasswordInput
@@ -508,12 +634,41 @@ export function SignInScreen({
508
634
  {AUTH_MESSAGES.setPassword}
509
635
  </Button>
510
636
  <Button testID={id("new-password-back")} variant="ghost" onPress={onSecondFactorBack}>
511
- Use a different account
637
+ {reset ? "Use a different email" : "Use a different account"}
512
638
  </Button>
513
639
  </AuthScreen>
514
640
  );
515
641
  }
516
642
 
643
+ if (pendingResetCode && !pendingSecondFactor) {
644
+ return (
645
+ <SecondFactorScreen
646
+ key="reset-code"
647
+ title={AUTH_MESSAGES.emailCodeTitle}
648
+ description={AUTH_MESSAGES.emailCodeDescription}
649
+ footer={
650
+ <Button
651
+ testID={id("resend")}
652
+ variant="link"
653
+ size="sm"
654
+ fullWidth={false}
655
+ disabled={resetLoading}
656
+ onPress={() => void onResetResend()}
657
+ >
658
+ {AUTH_MESSAGES.resendCode}
659
+ </Button>
660
+ }
661
+ onSubmit={onResetCode}
662
+ error={resetCodeError}
663
+ loading={resetLoading}
664
+ onBack={onSecondFactorBack}
665
+ backLabel="Use a different email"
666
+ header={header}
667
+ testIDPrefix={id("email-code")}
668
+ />
669
+ );
670
+ }
671
+
517
672
  if (pendingFirstFactor && !pendingSecondFactor && !pendingNewPassword) {
518
673
  const others = supportedFirstFactorStrategies(firstFactors).filter((strategy) => strategy !== firstStrategy);
519
674
  const switchTo = others[0] ?? null;
@@ -638,12 +793,14 @@ export function SignInScreen({
638
793
  return (
639
794
  <AuthScreen
640
795
  testID={id("screen")}
641
- title={title ?? (signUp ? "Create account" : "Welcome back")}
642
- subtitle={subtitle ?? (signUp ? "Sign up to get started" : "Sign in to continue")}
796
+ title={title ?? (reset ? AUTH_MESSAGES.resetTitle : signUp ? "Create account" : "Welcome back")}
797
+ subtitle={
798
+ subtitle ?? (reset ? AUTH_MESSAGES.resetSubtitle : signUp ? "Sign up to get started" : "Sign in to continue")
799
+ }
643
800
  header={header}
644
801
  footer={hasFooter ? footerRow : undefined}
645
802
  >
646
- {showGoogle ? (
803
+ {showGoogle && !reset ? (
647
804
  <>
648
805
  <GoogleSignInButton
649
806
  testID={id("google")}
@@ -666,33 +823,73 @@ export function SignInScreen({
666
823
  autoComplete="email"
667
824
  textContentType="emailAddress"
668
825
  keyboardType="email-address"
669
- returnKeyType="next"
670
- submitBehavior="submit"
671
- onSubmitEditing={() => passwordField.current?.focus()}
826
+ returnKeyType={reset ? "go" : "next"}
827
+ submitBehavior={reset ? undefined : "submit"}
828
+ onSubmitEditing={() => (reset ? void onResetRequest() : passwordField.current?.focus())}
672
829
  value={email}
673
830
  placeholder="Email"
674
831
  onChangeText={setEmail}
675
832
  />
676
- <PasswordInput
677
- testID={id("password")}
678
- ref={passwordField}
679
- accessibilityLabel="Password"
680
- autoCapitalize="none"
681
- autoComplete={signUp ? "new-password" : "password"}
682
- textContentType={signUp ? "newPassword" : "password"}
683
- returnKeyType="go"
684
- value={password}
685
- placeholder="Password"
686
- onChangeText={setPassword}
687
- onSubmitEditing={() => void (signUp ? onSignUp() : onSignIn())}
688
- />
833
+ {reset ? null : (
834
+ <PasswordInput
835
+ testID={id("password")}
836
+ ref={passwordField}
837
+ accessibilityLabel="Password"
838
+ autoCapitalize="none"
839
+ autoComplete={signUp ? "new-password" : "password"}
840
+ textContentType={signUp ? "newPassword" : "password"}
841
+ returnKeyType={signUp ? "next" : "go"}
842
+ submitBehavior={signUp ? "submit" : undefined}
843
+ value={password}
844
+ placeholder="Password"
845
+ onChangeText={(text) => {
846
+ setPassword(text);
847
+ setMismatch(false);
848
+ }}
849
+ onSubmitEditing={() => (signUp ? confirmField.current?.focus() : void onSignIn())}
850
+ />
851
+ )}
852
+ {signUp ? (
853
+ <>
854
+ <PasswordInput
855
+ testID={id("confirm-password")}
856
+ ref={confirmField}
857
+ accessibilityLabel={AUTH_MESSAGES.confirmSignUpPasswordLabel}
858
+ autoCapitalize="none"
859
+ autoComplete="new-password"
860
+ textContentType="newPassword"
861
+ returnKeyType="go"
862
+ value={signUpConfirm}
863
+ placeholder={AUTH_MESSAGES.confirmSignUpPasswordLabel}
864
+ onChangeText={(text) => {
865
+ setSignUpConfirm(text);
866
+ setMismatch(false);
867
+ }}
868
+ onSubmitEditing={() => void onSignUp()}
869
+ />
870
+ <FieldError testID={id("confirm-error")} message={mismatch ? AUTH_MESSAGES.passwordMismatch : ""} />
871
+ </>
872
+ ) : null}
873
+ {!signUp && !reset && forgotPasswordHref ? (
874
+ <View className="items-end">
875
+ <Button
876
+ testID={id("forgot-password")}
877
+ variant="link"
878
+ size="sm"
879
+ fullWidth={false}
880
+ onPress={() => router.push(forgotPasswordHref)}
881
+ >
882
+ {AUTH_MESSAGES.forgotPassword}
883
+ </Button>
884
+ </View>
885
+ ) : null}
689
886
  <FieldError testID={id("error")} message={error} />
690
887
  <Button
691
888
  testID={id("submit")}
692
889
  loading={submitting}
693
- onPress={() => void (signUp ? onSignUp() : onSignIn())}
890
+ onPress={() => void (reset ? onResetRequest() : signUp ? onSignUp() : onSignIn())}
694
891
  >
695
- {signUp ? "Create account" : "Sign in"}
892
+ {reset ? AUTH_MESSAGES.sendResetCode : signUp ? "Create account" : "Sign in"}
696
893
  </Button>
697
894
  {/* Bot protection mounts its widget here on web sign-up. */}
698
895
  {signUp ? <View nativeID="clerk-captcha" /> : null}
@@ -706,3 +903,10 @@ export type SignUpScreenProps = Omit<SignInScreenProps, "mode">;
706
903
  export function SignUpScreen(props: SignUpScreenProps) {
707
904
  return <SignInScreen {...props} mode="sign-up" />;
708
905
  }
906
+
907
+ export type ResetPasswordScreenProps = Omit<SignInScreenProps, "mode">;
908
+
909
+ /** `SignInScreen` with `mode="reset-password"`: the forgot-password flow. */
910
+ export function ResetPasswordScreen(props: ResetPasswordScreenProps) {
911
+ return <SignInScreen {...props} mode="reset-password" />;
912
+ }
package/src/auth/index.ts CHANGED
@@ -28,8 +28,14 @@ export type {
28
28
  GoogleSignInOptions,
29
29
  GoogleSignInButtonProps,
30
30
  } from "./GoogleSignInButton";
31
- export { SignInScreen, SignUpScreen, AUTH_MESSAGES } from "./SignInScreen";
32
- export type { IncompleteSignIn, SignInMode, SignInScreenProps, SignUpScreenProps } from "./SignInScreen";
31
+ export { SignInScreen, SignUpScreen, ResetPasswordScreen, AUTH_MESSAGES } from "./SignInScreen";
32
+ export type {
33
+ IncompleteSignIn,
34
+ ResetPasswordScreenProps,
35
+ SignInMode,
36
+ SignInScreenProps,
37
+ SignUpScreenProps,
38
+ } from "./SignInScreen";
33
39
  export { SecondFactorScreen } from "./SecondFactorScreen";
34
40
  export type { SecondFactorScreenProps } from "./SecondFactorScreen";
35
41
  export {
@@ -9,7 +9,6 @@ import {
9
9
  type ReactNode,
10
10
  } from "react";
11
11
  import {
12
- Modal,
13
12
  Pressable,
14
13
  StyleSheet,
15
14
  View,
@@ -36,6 +35,7 @@ import {
36
35
  useSheetDragState,
37
36
  } from "./sheet-drag";
38
37
  import { useControllableState } from "./use-controllable-state";
38
+ import { WindowLayer } from "./window-layer";
39
39
 
40
40
  type OverlayContextValue = {
41
41
  open: boolean;
@@ -116,22 +116,23 @@ export function OverlayClose(props: OverlayPressableProps & { part: string }) {
116
116
  }
117
117
 
118
118
  /**
119
- * RN `Modal` with a tinted backdrop, safe-area padding and keyboard avoidance
119
+ * A `WindowLayer` (in the app's window under `WindowLayerHost`, so a chat
120
+ * under it keeps its place; else a `Modal`) with a tinted backdrop, safe-area padding and keyboard avoidance
120
121
  * (`KeyboardAvoidingView`: frame by frame with `KeyboardControllerProvider`).
121
122
  * `placement="center"` centres the child (dialogs) inside the insets on every
122
123
  * side: the backdrop fades while the panel scales from 0.96 and fades in (200
123
- * ms on open, 150 ms on close), and the `Modal` stays up until it is out of
124
+ * ms on open, 150 ms on close), and the layer stays up until it is out of
124
125
  * sight. `"bottom"` pins it to the bottom
125
126
  * edge (sheets), which pad their own bottom inset: the sheet slides up on
126
127
  * open and back down on close, however it closes, and may be dragged down to
127
128
  * close (`SheetDragView`); the backdrop fades with the sheet's position. The
128
- * `Modal` stays up until the sheet is out of sight. The backdrop closes the
129
+ * layer stays up until the sheet is out of sight. The backdrop closes the
129
130
  * overlay only when `dismissible`; Android back and the VoiceOver escape
130
131
  * gesture always close it, as Escape does on the web. With Reduce Motion on,
131
132
  * overlays appear and leave in place. With the Gesture Handler parts
132
133
  * (`GestureHandlerProvider`), the content sits in its own root view: on
133
134
  * Android a `Modal` is a separate root, and without one there every gesture
134
- * in it silently does nothing.
135
+ * in it silently does nothing (the fallback `Modal`).
135
136
  */
136
137
  export function OverlayModal({
137
138
  part,
@@ -147,7 +148,8 @@ export function OverlayModal({
147
148
  onShow?: () => void;
148
149
  children: ReactNode;
149
150
  }) {
150
- const { open, setOpen } = useOverlay(part);
151
+ const overlay = useOverlay(part);
152
+ const { open, setOpen } = overlay;
151
153
  const reduceMotion = useReduceMotion();
152
154
  const slides = placement === "bottom" && !reduceMotion;
153
155
  const scales = placement === "center" && !reduceMotion;
@@ -158,15 +160,12 @@ export function OverlayModal({
158
160
  const close = () => setOpen(false);
159
161
  const ModalRoot = useContext(SheetGestureContext)?.ModalRoot ?? Fragment;
160
162
 
163
+ if (!shown) return null;
161
164
  return (
162
- <Modal
163
- visible={shown}
164
- transparent
165
- animationType="none"
166
- statusBarTranslucent
167
- onRequestClose={close}
168
- onShow={onShow}
169
- >
165
+ // The layer runs its own motion, so no fade; a layer loses the context
166
+ // between it and the host, so the open state is provided again.
167
+ <WindowLayer onRequestClose={close} onShow={onShow} fade={false}>
168
+ <OverlayContext.Provider value={overlay}>
170
169
  <ModalRoot>
171
170
  <OverlayModalBody
172
171
  placement={placement}
@@ -181,11 +180,12 @@ export function OverlayModal({
181
180
  {children}
182
181
  </OverlayModalBody>
183
182
  </ModalRoot>
184
- </Modal>
183
+ </OverlayContext.Provider>
184
+ </WindowLayer>
185
185
  );
186
186
  }
187
187
 
188
- /** The `Modal`'s content: mounted with each opening, so a sheet starts below the screen (or at rest). */
188
+ /** The layer's content: mounted with each opening, so a sheet starts below the screen (or at rest). */
189
189
  function OverlayModalBody({
190
190
  part,
191
191
  placement,
@@ -232,7 +232,7 @@ function OverlayModalBody({
232
232
  }, [open, slides]);
233
233
  // The same for a centred dialog, from wherever `progress` is. Opened again
234
234
  // while it leaves, it turns back at once, and the exit callback reports
235
- // `finished` false, so the `Modal` stays up.
235
+ // `finished` false, so the layer stays up.
236
236
  useEffect(() => {
237
237
  if (!scales) return;
238
238
  if (open) {
@@ -254,7 +254,7 @@ function OverlayModalBody({
254
254
  is the measured overlap, so it drops to 0 where the window does
255
255
  resize. Frame by frame with `KeyboardControllerProvider`. */}
256
256
  <KeyboardAvoidingView style={styles.fill}>
257
- {/* A `Modal` is its own window: a dock it opened from does not lift what is in it. */}
257
+ {/* Over the app, not in the dock it opened from: the dock's lift is not for it. */}
258
258
  <KeyboardLiftContext.Provider value={false}>
259
259
  <Animated.View
260
260
  pointerEvents="box-none"
@@ -10,7 +10,7 @@ import { useReduceMotion } from "../useReduceMotion";
10
10
  // the app instead, so the focus never moves. Without a host, `WindowLayer`
11
11
  // falls back to a `Modal`, so an app that mounts none keeps working.
12
12
 
13
- type Layer = { id: string; node: ReactNode; onRequestClose: () => void };
13
+ type Layer = { id: string; node: ReactNode; onRequestClose: () => void; onShow?: () => void; fade: boolean };
14
14
 
15
15
  const EMPTY: readonly Layer[] = [];
16
16
  let layers: readonly Layer[] = EMPTY;
@@ -34,7 +34,17 @@ const upsert = (layer: Layer) => {
34
34
  emit();
35
35
  };
36
36
 
37
+ // Layers that have called `onShow` once, as a Modal does once per opening.
38
+ const announced = new Set<string>();
39
+
40
+ const showOnce = (layer: Layer) => {
41
+ if (announced.has(layer.id)) return;
42
+ announced.add(layer.id);
43
+ layer.onShow?.();
44
+ };
45
+
37
46
  const remove = (id: string) => {
47
+ announced.delete(id);
38
48
  if (!layers.some((item) => item.id === id)) return;
39
49
  layers = layers.filter((item) => item.id !== id);
40
50
  emit();
@@ -68,7 +78,8 @@ const hostRef = (view: View | null) => {
68
78
  */
69
79
  export function WindowLayerHost({ children }: { children: ReactNode }) {
70
80
  const shown = useSyncExternalStore(subscribe, () => layers, () => EMPTY);
71
- // The layers fade in and out as a Modal's `fade`; with Reduce Motion they appear at once.
81
+ // The layers fade in and out as a Modal's `fade`, unless they move on their
82
+ // own (`fade={false}`); with Reduce Motion they appear at once.
72
83
  const enter = FadeIn.duration(200).reduceMotion(ReduceMotion.System);
73
84
  const exit = FadeOut.duration(150).reduceMotion(ReduceMotion.System);
74
85
  return (
@@ -81,7 +92,14 @@ export function WindowLayerHost({ children }: { children: ReactNode }) {
81
92
  {children}
82
93
  </View>
83
94
  {shown.map((layer) => (
84
- <Animated.View key={layer.id} entering={enter} exiting={exit} style={StyleSheet.absoluteFill} pointerEvents="box-none">
95
+ <Animated.View
96
+ key={layer.id}
97
+ entering={layer.fade ? enter : undefined}
98
+ exiting={layer.fade ? exit : undefined}
99
+ onLayout={() => showOnce(layer)}
100
+ style={StyleSheet.absoluteFill}
101
+ pointerEvents="box-none"
102
+ >
85
103
  {layer.node}
86
104
  </Animated.View>
87
105
  ))}
@@ -94,16 +112,23 @@ export function WindowLayerHost({ children }: { children: ReactNode }) {
94
112
  * `WindowLayerHost` when the app has one, else a transparent `Modal` (with
95
113
  * `onDismiss` there). Render it only while the overlay shows. Android back
96
114
  * calls `onRequestClose`. Its children keep the providers above the host, not
97
- * those between the host and this element.
115
+ * those between the host and this element: an overlay with its own context
116
+ * (a Dialog's open state, a menu's) provides it again inside.
98
117
  */
99
118
  export function WindowLayer({
100
119
  onRequestClose,
101
120
  onDismiss,
121
+ onShow,
122
+ fade = true,
102
123
  children,
103
124
  }: {
104
125
  onRequestClose: () => void;
105
126
  /** The fallback Modal's dismiss (iOS); a layer is gone as it unmounts. */
106
127
  onDismiss?: () => void;
128
+ /** Once the layer is on screen, as a Modal's `onShow`. */
129
+ onShow?: () => void;
130
+ /** Fade in and out. `false` for an overlay that runs its own motion. Default `true`. */
131
+ fade?: boolean;
107
132
  children: ReactNode;
108
133
  }) {
109
134
  const id = useId();
@@ -112,8 +137,8 @@ export function WindowLayer({
112
137
  // A portal has to hand the host its children after each render: an external
113
138
  // store fed from an effect, the one sync React offers for it.
114
139
  useLayoutEffect(() => {
115
- if (hosted) upsert({ id, node: children, onRequestClose });
116
- }, [hosted, id, children, onRequestClose]);
140
+ if (hosted) upsert({ id, node: children, onRequestClose, onShow, fade });
141
+ }, [hosted, id, children, onRequestClose, onShow, fade]);
117
142
  useLayoutEffect(() => () => remove(id), [id]);
118
143
  if (hosted) return null;
119
144
  return (
@@ -121,9 +146,10 @@ export function WindowLayer({
121
146
  visible
122
147
  transparent
123
148
  statusBarTranslucent
124
- animationType={reduceMotion ? "none" : "fade"}
149
+ animationType={fade && !reduceMotion ? "fade" : "none"}
125
150
  onRequestClose={onRequestClose}
126
151
  onDismiss={onDismiss}
152
+ onShow={onShow}
127
153
  >
128
154
  {children}
129
155
  </Modal>