@supatype/react-auth 0.3.6 → 0.8.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.
Files changed (72) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +13 -4
  3. package/.turbo/turbo-typecheck.log +2 -2
  4. package/LICENSE +1 -1
  5. package/README.md +103 -0
  6. package/dist/EmailLinkForm.d.ts +42 -0
  7. package/dist/EmailLinkForm.d.ts.map +1 -0
  8. package/dist/EmailLinkForm.js +14 -0
  9. package/dist/EmailLinkForm.js.map +1 -0
  10. package/dist/ForgotPasswordForm.d.ts +19 -0
  11. package/dist/ForgotPasswordForm.d.ts.map +1 -0
  12. package/dist/ForgotPasswordForm.js +33 -0
  13. package/dist/ForgotPasswordForm.js.map +1 -0
  14. package/dist/LoginForm.d.ts +4 -1
  15. package/dist/LoginForm.d.ts.map +1 -1
  16. package/dist/LoginForm.js +8 -24
  17. package/dist/LoginForm.js.map +1 -1
  18. package/dist/MagicLinkForm.d.ts +19 -0
  19. package/dist/MagicLinkForm.d.ts.map +1 -0
  20. package/dist/MagicLinkForm.js +33 -0
  21. package/dist/MagicLinkForm.js.map +1 -0
  22. package/dist/OAuthButton.d.ts +3 -2
  23. package/dist/OAuthButton.d.ts.map +1 -1
  24. package/dist/OAuthButton.js +79 -42
  25. package/dist/OAuthButton.js.map +1 -1
  26. package/dist/SignUpForm.d.ts +4 -1
  27. package/dist/SignUpForm.d.ts.map +1 -1
  28. package/dist/SignUpForm.js +13 -32
  29. package/dist/SignUpForm.js.map +1 -1
  30. package/dist/UpdatePasswordForm.d.ts +38 -0
  31. package/dist/UpdatePasswordForm.d.ts.map +1 -0
  32. package/dist/UpdatePasswordForm.js +36 -0
  33. package/dist/UpdatePasswordForm.js.map +1 -0
  34. package/dist/classNames.d.ts +36 -0
  35. package/dist/classNames.d.ts.map +1 -0
  36. package/dist/classNames.js +8 -0
  37. package/dist/classNames.js.map +1 -0
  38. package/dist/formParts.d.ts +68 -0
  39. package/dist/formParts.d.ts.map +1 -0
  40. package/dist/formParts.js +72 -0
  41. package/dist/formParts.js.map +1 -0
  42. package/dist/index.d.ts +9 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +4 -0
  45. package/dist/index.js.map +1 -1
  46. package/dist/usePasswordRecovery.d.ts +18 -0
  47. package/dist/usePasswordRecovery.d.ts.map +1 -0
  48. package/dist/usePasswordRecovery.js +27 -0
  49. package/dist/usePasswordRecovery.js.map +1 -0
  50. package/package.json +6 -4
  51. package/src/EmailLinkForm.tsx +62 -0
  52. package/src/ForgotPasswordForm.tsx +43 -0
  53. package/src/LoginForm.tsx +35 -62
  54. package/src/MagicLinkForm.tsx +43 -0
  55. package/src/OAuthButton.tsx +84 -60
  56. package/src/SignUpForm.tsx +40 -74
  57. package/src/UpdatePasswordForm.tsx +74 -0
  58. package/src/classNames.ts +41 -0
  59. package/src/formParts.tsx +153 -0
  60. package/src/index.ts +14 -0
  61. package/src/usePasswordRecovery.ts +32 -0
  62. package/tests/auth-ui.test.tsx +48 -0
  63. package/tests/email-link-forms.test.tsx +214 -0
  64. package/tests/helpers.tsx +41 -0
  65. package/tests/login-form.test.tsx +63 -0
  66. package/tests/oauth-button.test.tsx +75 -0
  67. package/tests/password-recovery.test.tsx +62 -0
  68. package/tests/props.ts +24 -0
  69. package/tests/signup-confirmation.test.tsx +50 -0
  70. package/tests/tsconfig.json +9 -0
  71. package/tsconfig.json +1 -1
  72. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,62 @@
1
+ import React, { useState } from "react"
2
+ import type { SupatypeError } from "@supatype/client"
3
+ import type { AuthFormClassNames } from "./classNames.js"
4
+ import { FormField, FormShell, FormMessage, useAuthSubmit, withDefaults, type Filled } from "./formParts.js"
5
+
6
+ export interface EmailLinkFormLabels {
7
+ title?: string | undefined
8
+ email?: string | undefined
9
+ submit?: string | undefined
10
+ /** Shown in place of the form once the email is on its way. */
11
+ successMessage?: string | undefined
12
+ }
13
+
14
+ /** Props shared by the forms that email the user a link: `ForgotPasswordForm` and `MagicLinkForm`. */
15
+ export interface EmailLinkFormProps {
16
+ /** Where the emailed link sends the browser once the auth server has checked it. */
17
+ redirectTo?: string | undefined
18
+ /** Called with the address once the auth service has accepted the request. */
19
+ onSuccess?: ((email: string) => void) | undefined
20
+ /** Called with the error returned by the auth service. */
21
+ onError?: ((error: SupatypeError) => void) | undefined
22
+ /** CSS class applied to the outermost <form> element. */
23
+ className?: string | undefined
24
+ /** Override display labels. */
25
+ labels?: EmailLinkFormLabels | undefined
26
+ /** Class names for the elements inside the form, so an app can style them with its own classes. */
27
+ classNames?: AuthFormClassNames | undefined
28
+ }
29
+
30
+ /** What one email-link form does: its input's id, its words, and the request it sends. */
31
+ export interface EmailLinkConfig {
32
+ inputId: string
33
+ labels: Filled<EmailLinkFormLabels>
34
+ busyLabel: string
35
+ send: (email: string) => Promise<{ data: unknown; error: SupatypeError | null }>
36
+ }
37
+
38
+ /** An email field and a submit button that send one request, then "check your email". */
39
+ export function EmailLinkForm({ props, config }: { props: EmailLinkFormProps; config: EmailLinkConfig }): React.ReactElement {
40
+ const { onSuccess, onError, className, classNames } = props
41
+ const l = withDefaults(config.labels, props.labels)
42
+ const [email, setEmail] = useState("")
43
+ const request = useAuthSubmit(() => config.send(email), { onDone: () => onSuccess?.(email), onError })
44
+
45
+ if (request.done) return <FormMessage text={l.successMessage} classNames={classNames} />
46
+
47
+ return (
48
+ <FormShell request={request} text={{ title: l.title, submit: l.submit, busy: config.busyLabel }} className={className} classNames={classNames}>
49
+ <FormField
50
+ id={config.inputId}
51
+ label={l.email}
52
+ classNames={classNames}
53
+ type="email"
54
+ autoComplete="email"
55
+ required
56
+ value={email}
57
+ onChange={(e) => setEmail(e.target.value)}
58
+ disabled={request.loading}
59
+ />
60
+ </FormShell>
61
+ )
62
+ }
@@ -0,0 +1,43 @@
1
+ import React from "react"
2
+ import { useSupatype } from "@supatype/react"
3
+ import { EmailLinkForm, type EmailLinkFormLabels, type EmailLinkFormProps } from "./EmailLinkForm.js"
4
+ import type { Filled } from "./formParts.js"
5
+
6
+ export type ForgotPasswordFormLabels = EmailLinkFormLabels
7
+ export type ForgotPasswordFormProps = EmailLinkFormProps
8
+
9
+ const DEFAULT_LABELS: Filled<ForgotPasswordFormLabels> = {
10
+ title: "Reset your password",
11
+ email: "Email address",
12
+ submit: "Send reset password instructions",
13
+ successMessage: "Check your email for the password reset link.",
14
+ }
15
+
16
+ /**
17
+ * Asks the auth service to email a password reset link (`resetPasswordForEmail`, `POST /recover`).
18
+ * Must be rendered inside a `<SupatypeProvider>`.
19
+ *
20
+ * The link signs the user in and the client emits `PASSWORD_RECOVERY`; render `UpdatePasswordForm`
21
+ * when it does. `redirectTo` is where the link lands when it is on the site URL's host (or the auth
22
+ * server's redirect allow list); otherwise the link lands on the site URL.
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * <ForgotPasswordForm redirectTo={`${window.location.origin}/reset`} />
27
+ * ```
28
+ */
29
+ export function ForgotPasswordForm(props: ForgotPasswordFormProps): React.ReactElement {
30
+ const { auth } = useSupatype()
31
+ const { redirectTo } = props
32
+ return (
33
+ <EmailLinkForm
34
+ props={props}
35
+ config={{
36
+ inputId: "st-forgot-email",
37
+ labels: DEFAULT_LABELS,
38
+ busyLabel: "Sending reset instructions…",
39
+ send: (email) => auth.resetPasswordForEmail(email, { redirectTo }),
40
+ }}
41
+ />
42
+ )
43
+ }
package/src/LoginForm.tsx CHANGED
@@ -1,6 +1,8 @@
1
- import React, { useState, type FormEvent } from "react"
1
+ import React, { useState } from "react"
2
2
  import type { Session, SupatypeError } from "@supatype/client"
3
3
  import { useAuth } from "@supatype/react"
4
+ import type { AuthFormClassNames } from "./classNames.js"
5
+ import { FormField, FormShell, useAuthSubmit, withDefaults, type Filled } from "./formParts.js"
4
6
 
5
7
  export interface LoginFormLabels {
6
8
  title?: string | undefined
@@ -19,9 +21,11 @@ export interface LoginFormProps {
19
21
  className?: string | undefined
20
22
  /** Override display labels. */
21
23
  labels?: LoginFormLabels | undefined
24
+ /** Class names for the elements inside the form, so an app can style them with its own classes. */
25
+ classNames?: AuthFormClassNames | undefined
22
26
  }
23
27
 
24
- const DEFAULT_LABELS: Required<LoginFormLabels> = {
28
+ const DEFAULT_LABELS: Filled<LoginFormLabels> = {
25
29
  title: "Sign in",
26
30
  email: "Email address",
27
31
  password: "Password",
@@ -41,72 +45,41 @@ const DEFAULT_LABELS: Required<LoginFormLabels> = {
41
45
  * />
42
46
  * ```
43
47
  */
44
- export function LoginForm({ onSuccess, onError, className, labels }: LoginFormProps): React.ReactElement {
48
+ export function LoginForm({ onSuccess, onError, className, classNames, labels }: LoginFormProps): React.ReactElement {
45
49
  const { signIn } = useAuth()
46
- const l = { ...DEFAULT_LABELS, ...labels }
50
+ const l = withDefaults(DEFAULT_LABELS, labels)
47
51
 
48
52
  const [email, setEmail] = useState("")
49
53
  const [password, setPassword] = useState("")
50
- const [loading, setLoading] = useState(false)
51
- const [errorMessage, setErrorMessage] = useState<string | null>(null)
52
-
53
- async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {
54
- e.preventDefault()
55
- setErrorMessage(null)
56
- setLoading(true)
57
- try {
58
- const { data, error } = await signIn({ email, password })
59
- if (error !== null) {
60
- const msg = `${l.errorPrefix}${error.message}`
61
- setErrorMessage(msg)
62
- onError?.(error)
63
- } else if (data.session !== null) {
64
- onSuccess?.(data.session)
65
- }
66
- } finally {
67
- setLoading(false)
68
- }
69
- }
54
+ const onDone = ({ session }: { session: Session | null }): void => { if (session !== null) onSuccess?.(session) }
55
+ const request = useAuthSubmit(() => signIn({ email, password }), { onDone, onError })
56
+ const errorMessage = request.errorMessage === null ? null : `${l.errorPrefix}${request.errorMessage}`
70
57
 
71
58
  return (
72
- <form onSubmit={(e) => { void handleSubmit(e) }} className={className} noValidate>
73
- <h2>{l.title}</h2>
74
-
75
- {errorMessage !== null && (
76
- <p role="alert" aria-live="polite" style={{ color: "red" }}>
77
- {errorMessage}
78
- </p>
79
- )}
80
-
81
- <div>
82
- <label htmlFor="st-login-email">{l.email}</label>
83
- <input
84
- id="st-login-email"
85
- type="email"
86
- autoComplete="email"
87
- required
88
- value={email}
89
- onChange={(e) => setEmail(e.target.value)}
90
- disabled={loading}
91
- />
92
- </div>
93
-
94
- <div>
95
- <label htmlFor="st-login-password">{l.password}</label>
96
- <input
97
- id="st-login-password"
98
- type="password"
99
- autoComplete="current-password"
100
- required
101
- value={password}
102
- onChange={(e) => setPassword(e.target.value)}
103
- disabled={loading}
104
- />
105
- </div>
59
+ <FormShell request={request} text={{ title: l.title, submit: l.submit, busy: "Signing in…" }} className={className} classNames={classNames} errorMessage={errorMessage}>
60
+ <FormField
61
+ id="st-login-email"
62
+ label={l.email}
63
+ classNames={classNames}
64
+ type="email"
65
+ autoComplete="email"
66
+ required
67
+ value={email}
68
+ onChange={(e) => setEmail(e.target.value)}
69
+ disabled={request.loading}
70
+ />
106
71
 
107
- <button type="submit" disabled={loading}>
108
- {loading ? "Signing in…" : l.submit}
109
- </button>
110
- </form>
72
+ <FormField
73
+ id="st-login-password"
74
+ label={l.password}
75
+ classNames={classNames}
76
+ type="password"
77
+ autoComplete="current-password"
78
+ required
79
+ value={password}
80
+ onChange={(e) => setPassword(e.target.value)}
81
+ disabled={request.loading}
82
+ />
83
+ </FormShell>
111
84
  )
112
85
  }
@@ -0,0 +1,43 @@
1
+ import React from "react"
2
+ import { useSupatype } from "@supatype/react"
3
+ import { EmailLinkForm, type EmailLinkFormLabels, type EmailLinkFormProps } from "./EmailLinkForm.js"
4
+ import type { Filled } from "./formParts.js"
5
+
6
+ export type MagicLinkFormLabels = EmailLinkFormLabels
7
+ export type MagicLinkFormProps = EmailLinkFormProps
8
+
9
+ const DEFAULT_LABELS: Filled<MagicLinkFormLabels> = {
10
+ title: "Sign in with a magic link",
11
+ email: "Email address",
12
+ submit: "Send magic link",
13
+ successMessage: "Check your email for the magic link.",
14
+ }
15
+
16
+ /**
17
+ * Emails the user a link that signs them in without a password (`signInWithOtp`, `POST /otp`).
18
+ * Must be rendered inside a `<SupatypeProvider>`.
19
+ *
20
+ * Following the link signs the user in on `redirectTo` (honoured on the site URL's host or the auth
21
+ * server's redirect allow list, else the site URL); the client reads the session from the URL on
22
+ * start and `useAuth()` shows the user.
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * <MagicLinkForm redirectTo={window.location.origin} />
27
+ * ```
28
+ */
29
+ export function MagicLinkForm(props: MagicLinkFormProps): React.ReactElement {
30
+ const { auth } = useSupatype()
31
+ const { redirectTo } = props
32
+ return (
33
+ <EmailLinkForm
34
+ props={props}
35
+ config={{
36
+ inputId: "st-magic-email",
37
+ labels: DEFAULT_LABELS,
38
+ busyLabel: "Sending magic link…",
39
+ send: (email) => auth.signInWithOtp({ email, options: { emailRedirectTo: redirectTo } }),
40
+ }}
41
+ />
42
+ )
43
+ }
@@ -12,7 +12,7 @@
12
12
  * ```
13
13
  */
14
14
 
15
- import React, { useState, type ReactNode } from "react"
15
+ import React, { useEffect, useRef, useState, type ReactNode } from "react"
16
16
  import { useAuth } from "@supatype/react"
17
17
 
18
18
  export interface OAuthButtonProps {
@@ -32,9 +32,16 @@ export interface OAuthButtonProps {
32
32
  disabled?: boolean | undefined
33
33
  }
34
34
 
35
- /** Capitalise the first letter of a string. */
36
- function capitalize(s: string): string {
37
- return s.charAt(0).toUpperCase() + s.slice(1)
35
+ /** Names whose capitalisation is not just a capital first letter. */
36
+ const PROVIDER_NAMES: Record<string, string> = {
37
+ github: "GitHub",
38
+ gitlab: "GitLab",
39
+ linkedin: "LinkedIn",
40
+ }
41
+
42
+ /** The provider's display name: its own spelling where known, else a capital first letter. */
43
+ function displayName(provider: string): string {
44
+ return PROVIDER_NAMES[provider.toLowerCase()] ?? provider.charAt(0).toUpperCase() + provider.slice(1)
38
45
  }
39
46
 
40
47
  /** Provider logo SVGs (inline to avoid external dependencies). */
@@ -47,54 +54,73 @@ const PROVIDER_ICONS: Record<string, string> = {
47
54
  '<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M17.05 20.28c-.98.95-2.05.88-3.08.4-1.09-.5-2.08-.53-3.23 0-1.44.62-2.2.44-3.06-.4C3.79 16.17 4.36 9.33 8.93 9.07c1.23.07 2.09.72 2.81.77.99-.2 1.94-.78 3.01-.7 1.28.1 2.24.6 2.87 1.52-2.63 1.57-2 5.07.63 6.06-.5 1.3-.99 2.58-2.19 3.56zM12.03 9c-.12-2.08 1.55-3.82 3.47-3.97.26 2.29-2.07 4.01-3.47 3.97z"/></svg>',
48
55
  }
49
56
 
57
+ /** Send the browser to the provider: this window, or a centred popup. */
58
+ function openOAuthUrl(url: string, provider: string, popup: boolean): void {
59
+ if (!popup) {
60
+ window.location.href = url
61
+ return
62
+ }
63
+ const width = 500
64
+ const height = 700
65
+ const left = window.screenX + (window.outerWidth - width) / 2
66
+ const top = window.screenY + (window.outerHeight - height) / 2
67
+ window.open(url, `supatype-oauth-${provider}`, `width=${width},height=${height},left=${left},top=${top}`)
68
+ }
69
+
70
+ /** The button's look when the app gives it no class. */
71
+ function defaultStyle(busy: boolean): React.CSSProperties {
72
+ return {
73
+ display: "inline-flex",
74
+ alignItems: "center",
75
+ gap: "8px",
76
+ padding: "10px 16px",
77
+ border: "1px solid #d1d5db",
78
+ borderRadius: "6px",
79
+ backgroundColor: "#fff",
80
+ color: "#374151",
81
+ fontSize: "14px",
82
+ fontWeight: 500,
83
+ cursor: busy ? "not-allowed" : "pointer",
84
+ opacity: busy ? 0.6 : 1,
85
+ transition: "background-color 0.15s, border-color 0.15s",
86
+ lineHeight: 1,
87
+ }
88
+ }
89
+
50
90
  /**
51
- * A pre-styled OAuth sign-in button with provider logo.
91
+ * Report a refusal the auth server sent back in the URL, when this button's provider started it.
92
+ *
93
+ * Through a ref so an inline `onError` does not report the same refusal on every render.
94
+ */
95
+ function useRedirectError(provider: string, onError: OAuthButtonProps["onError"]): void {
96
+ const { error } = useAuth()
97
+ const onErrorRef = useRef(onError)
98
+ onErrorRef.current = onError
99
+ useEffect(() => {
100
+ if (error !== null && error.provider === provider) onErrorRef.current?.(error)
101
+ }, [error, provider])
102
+ }
103
+
104
+ /**
105
+ * The button's click: ask for the provider's URL and go there, or report why not.
52
106
  *
53
- * Must be rendered inside a `<SupatypeProvider>`.
107
+ * Also reports a refusal the server sent back in the URL for this provider (`useRedirectError`).
54
108
  */
55
- export function OAuthButton({
56
- provider,
57
- redirectTo,
58
- className,
59
- children,
60
- onError,
61
- popup,
62
- disabled,
63
- }: OAuthButtonProps): React.ReactElement {
109
+ function useOAuthStart(props: OAuthButtonProps): { loading: boolean; start: () => Promise<void> } {
110
+ const { provider, redirectTo, onError, popup } = props
64
111
  const { signInWithOAuth } = useAuth()
65
112
  const [loading, setLoading] = useState(false)
113
+ useRedirectError(provider, onError)
66
114
 
67
- const providerName = capitalize(provider)
68
- const iconSvg = PROVIDER_ICONS[provider.toLowerCase()]
69
-
70
- async function handleClick(): Promise<void> {
115
+ async function start(): Promise<void> {
71
116
  setLoading(true)
72
117
  try {
73
118
  const { data, error } = await signInWithOAuth({
74
119
  provider,
75
120
  ...(redirectTo !== undefined && { options: { redirectTo } }),
76
121
  })
77
-
78
- if (error !== null) {
79
- onError?.(error)
80
- return
81
- }
82
-
83
- if (data.url) {
84
- if (popup === true) {
85
- const width = 500
86
- const height = 700
87
- const left = window.screenX + (window.outerWidth - width) / 2
88
- const top = window.screenY + (window.outerHeight - height) / 2
89
- window.open(
90
- data.url,
91
- `supatype-oauth-${provider}`,
92
- `width=${width},height=${height},left=${left},top=${top}`,
93
- )
94
- } else {
95
- window.location.href = data.url
96
- }
97
- }
122
+ if (error !== null) onError?.(error)
123
+ else if (data.url) openOAuthUrl(data.url, provider, popup === true)
98
124
  } catch (err) {
99
125
  onError?.({ message: err instanceof Error ? err.message : "OAuth failed" })
100
126
  } finally {
@@ -102,31 +128,29 @@ export function OAuthButton({
102
128
  }
103
129
  }
104
130
 
105
- const defaultStyle: React.CSSProperties = {
106
- display: "inline-flex",
107
- alignItems: "center",
108
- gap: "8px",
109
- padding: "10px 16px",
110
- border: "1px solid #d1d5db",
111
- borderRadius: "6px",
112
- backgroundColor: "#fff",
113
- color: "#374151",
114
- fontSize: "14px",
115
- fontWeight: 500,
116
- cursor: disabled === true || loading ? "not-allowed" : "pointer",
117
- opacity: disabled === true || loading ? 0.6 : 1,
118
- transition: "background-color 0.15s, border-color 0.15s",
119
- lineHeight: 1,
120
- }
131
+ return { loading, start }
132
+ }
133
+
134
+ /**
135
+ * A pre-styled OAuth sign-in button with provider logo.
136
+ *
137
+ * Must be rendered inside a `<SupatypeProvider>`. Its accessible name is its visible text, so a
138
+ * label passed as `children` is what a screen reader announces too.
139
+ */
140
+ export function OAuthButton(props: OAuthButtonProps): React.ReactElement {
141
+ const { provider, className, children, disabled } = props
142
+ const { loading, start } = useOAuthStart(props)
143
+ const providerName = displayName(provider)
144
+ const iconSvg = PROVIDER_ICONS[provider.toLowerCase()]
145
+ const busy = disabled === true || loading
121
146
 
122
147
  return (
123
148
  <button
124
149
  type="button"
125
150
  className={className}
126
- style={className !== undefined ? undefined : defaultStyle}
127
- onClick={() => { void handleClick() }}
128
- disabled={disabled === true || loading}
129
- aria-label={`Sign in with ${providerName}`}
151
+ style={className !== undefined ? undefined : defaultStyle(busy)}
152
+ onClick={() => { void start() }}
153
+ disabled={busy}
130
154
  >
131
155
  {iconSvg !== undefined && (
132
156
  <span
@@ -1,6 +1,8 @@
1
- import React, { useState, type FormEvent } from "react"
1
+ import React, { useState } from "react"
2
2
  import type { Session, SupatypeError } from "@supatype/client"
3
3
  import { useAuth } from "@supatype/react"
4
+ import type { AuthFormClassNames } from "./classNames.js"
5
+ import { FormField, FormShell, FormMessage, useAuthSubmit, withDefaults, type Filled } from "./formParts.js"
4
6
 
5
7
  export interface SignUpFormLabels {
6
8
  title?: string | undefined
@@ -19,6 +21,8 @@ export interface SignUpFormProps {
19
21
  className?: string | undefined
20
22
  /** Override display labels. */
21
23
  labels?: SignUpFormLabels | undefined
24
+ /** Class names for the elements inside the form, so an app can style them with its own classes. */
25
+ classNames?: AuthFormClassNames | undefined
22
26
  /**
23
27
  * Additional metadata stored on the user's `user_metadata`.
24
28
  * Merge with any custom fields collected in the form.
@@ -26,7 +30,7 @@ export interface SignUpFormProps {
26
30
  metadata?: Record<string, unknown> | undefined
27
31
  }
28
32
 
29
- const DEFAULT_LABELS: Required<SignUpFormLabels> = {
33
+ const DEFAULT_LABELS: Filled<SignUpFormLabels> = {
30
34
  title: "Create account",
31
35
  email: "Email address",
32
36
  password: "Password",
@@ -48,89 +52,51 @@ const DEFAULT_LABELS: Required<SignUpFormLabels> = {
48
52
  * />
49
53
  * ```
50
54
  */
51
- export function SignUpForm({ onSuccess, onError, className, labels, metadata }: SignUpFormProps): React.ReactElement {
55
+ export function SignUpForm({ onSuccess, onError, className, classNames, labels, metadata }: SignUpFormProps): React.ReactElement {
52
56
  const { signUp } = useAuth()
53
- const l = { ...DEFAULT_LABELS, ...labels }
57
+ const l = withDefaults(DEFAULT_LABELS, labels)
54
58
 
55
59
  const [email, setEmail] = useState("")
56
60
  const [password, setPassword] = useState("")
57
- const [loading, setLoading] = useState(false)
58
- const [errorMessage, setErrorMessage] = useState<string | null>(null)
59
61
  const [confirmed, setConfirmed] = useState(false)
60
-
61
- async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {
62
- e.preventDefault()
63
- setErrorMessage(null)
64
- setLoading(true)
65
- try {
66
- const { data, error } = await signUp({
67
- email,
68
- password,
69
- ...(metadata !== undefined && { options: { data: metadata } }),
70
- })
71
- if (error !== null) {
72
- setErrorMessage(error.message)
73
- onError?.(error)
74
- } else {
75
- if (data.session === null) {
76
- // Email confirmation required
77
- setConfirmed(true)
78
- }
79
- onSuccess?.(data.session)
80
- }
81
- } finally {
82
- setLoading(false)
83
- }
62
+ const options = metadata !== undefined ? { options: { data: metadata } } : {}
63
+ const onDone = ({ session }: { session: Session | null }): void => {
64
+ // No session: the project requires the email to be confirmed first.
65
+ if (session === null) setConfirmed(true)
66
+ onSuccess?.(session)
84
67
  }
68
+ const request = useAuthSubmit(() => signUp({ email, password, ...options }), { onDone, onError })
85
69
 
86
70
  if (confirmed) {
87
- return (
88
- <p role="status" aria-live="polite">
89
- {l.successMessage}
90
- </p>
91
- )
71
+ return <FormMessage text={l.successMessage} classNames={classNames} />
92
72
  }
93
73
 
94
74
  return (
95
- <form onSubmit={(e) => { void handleSubmit(e) }} className={className} noValidate>
96
- <h2>{l.title}</h2>
97
-
98
- {errorMessage !== null && (
99
- <p role="alert" aria-live="polite" style={{ color: "red" }}>
100
- {errorMessage}
101
- </p>
102
- )}
103
-
104
- <div>
105
- <label htmlFor="st-signup-email">{l.email}</label>
106
- <input
107
- id="st-signup-email"
108
- type="email"
109
- autoComplete="email"
110
- required
111
- value={email}
112
- onChange={(e) => setEmail(e.target.value)}
113
- disabled={loading}
114
- />
115
- </div>
116
-
117
- <div>
118
- <label htmlFor="st-signup-password">{l.password}</label>
119
- <input
120
- id="st-signup-password"
121
- type="password"
122
- autoComplete="new-password"
123
- required
124
- minLength={8}
125
- value={password}
126
- onChange={(e) => setPassword(e.target.value)}
127
- disabled={loading}
128
- />
129
- </div>
75
+ <FormShell request={request} text={{ title: l.title, submit: l.submit, busy: "Creating account…" }} className={className} classNames={classNames}>
76
+ <FormField
77
+ id="st-signup-email"
78
+ label={l.email}
79
+ classNames={classNames}
80
+ type="email"
81
+ autoComplete="email"
82
+ required
83
+ value={email}
84
+ onChange={(e) => setEmail(e.target.value)}
85
+ disabled={request.loading}
86
+ />
130
87
 
131
- <button type="submit" disabled={loading}>
132
- {loading ? "Creating account…" : l.submit}
133
- </button>
134
- </form>
88
+ <FormField
89
+ id="st-signup-password"
90
+ label={l.password}
91
+ classNames={classNames}
92
+ type="password"
93
+ autoComplete="new-password"
94
+ required
95
+ minLength={8}
96
+ value={password}
97
+ onChange={(e) => setPassword(e.target.value)}
98
+ disabled={request.loading}
99
+ />
100
+ </FormShell>
135
101
  )
136
102
  }