@molecule/app-auth-modal-svelte 0.0.0-stage → 1.1.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.
- package/LICENSE +202 -0
- package/README.md +275 -2
- package/dist/AuthModal.svelte +374 -0
- package/dist/AuthModal.svelte.d.ts +5 -0
- package/dist/AuthModal.svelte.d.ts.map +1 -0
- package/dist/AuthModalMount.svelte +129 -0
- package/dist/AuthModalMount.svelte.d.ts +5 -0
- package/dist/AuthModalMount.svelte.d.ts.map +1 -0
- package/dist/components.d.ts +9 -0
- package/dist/components.d.ts.map +1 -0
- package/dist/components.js +8 -0
- package/dist/cta-intercept.d.ts +39 -0
- package/dist/cta-intercept.d.ts.map +1 -0
- package/dist/cta-intercept.js +57 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +53 -0
- package/dist/types.d.ts +100 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/value.d.ts +32 -0
- package/dist/value.d.ts.map +1 -0
- package/dist/value.js +36 -0
- package/package.json +80 -4
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
AuthModal: the Svelte counterpart of `@molecule/app-auth-modal-react`'s
|
|
3
|
+
`AuthModal` — in-app login / signup tabs rendered in a Modal overlay, so the
|
|
4
|
+
user authenticates without leaving the page. Same props (React names), same
|
|
5
|
+
ClassMap tokens, same i18n keys, and the same DOM for the same input; the
|
|
6
|
+
auth hooks (`useLogin` / `useSignup` / `useOAuth` / `useAuth`) come from
|
|
7
|
+
`@molecule/app-svelte`, and OAuth runs in a popup so social login never
|
|
8
|
+
navigates the host either.
|
|
9
|
+
-->
|
|
10
|
+
<script lang="ts">
|
|
11
|
+
import { untrack } from 'svelte'
|
|
12
|
+
import { writable } from 'svelte/store'
|
|
13
|
+
|
|
14
|
+
import { useAuthFormState } from '@molecule/app-auth-shell-svelte'
|
|
15
|
+
import { OAuthButtons, OAuthDivider } from '@molecule/app-oauth-buttons-svelte'
|
|
16
|
+
import {
|
|
17
|
+
useAuth,
|
|
18
|
+
useAuthClient,
|
|
19
|
+
useI18nError,
|
|
20
|
+
useLogin,
|
|
21
|
+
useOAuth,
|
|
22
|
+
useSignup,
|
|
23
|
+
useTranslation,
|
|
24
|
+
} from '@molecule/app-svelte'
|
|
25
|
+
import { getClassMap } from '@molecule/app-ui'
|
|
26
|
+
import { Button, Icon, Modal } from '@molecule/app-ui-svelte'
|
|
27
|
+
|
|
28
|
+
import type { AuthModalMode } from './cta-intercept.js'
|
|
29
|
+
import type { AuthModalProps } from './types.js'
|
|
30
|
+
import { reactInputValue } from './value.js'
|
|
31
|
+
|
|
32
|
+
let {
|
|
33
|
+
open,
|
|
34
|
+
onClose,
|
|
35
|
+
initialMode = 'signup',
|
|
36
|
+
oauthConfig,
|
|
37
|
+
onBeforeAuth,
|
|
38
|
+
onAuthenticated,
|
|
39
|
+
captchaSlot,
|
|
40
|
+
captchaSolved = true,
|
|
41
|
+
}: AuthModalProps = $props()
|
|
42
|
+
|
|
43
|
+
const cm = $derived(getClassMap())
|
|
44
|
+
const { t } = useTranslation()
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Matches phones (narrow viewport) OR touch-first devices (coarse primary
|
|
48
|
+
* pointer) — the contexts where a sub-16px input font makes iOS Safari zoom
|
|
49
|
+
* the whole page on focus. SSR-safe (`false` until mounted) and subscribes
|
|
50
|
+
* to media-query changes, like React's local hook.
|
|
51
|
+
*/
|
|
52
|
+
let isTouchFirst = $state(false)
|
|
53
|
+
$effect(() => {
|
|
54
|
+
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return
|
|
55
|
+
const mql = window.matchMedia('(max-width: 767px), (pointer: coarse)')
|
|
56
|
+
const onChange = (e: MediaQueryListEvent): void => {
|
|
57
|
+
isTouchFirst = e.matches
|
|
58
|
+
}
|
|
59
|
+
isTouchFirst = mql.matches
|
|
60
|
+
mql.addEventListener('change', onChange)
|
|
61
|
+
return () => {
|
|
62
|
+
mql.removeEventListener('change', onChange)
|
|
63
|
+
}
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
// React's `useState(initialMode)`: read once, then owned by the component.
|
|
67
|
+
let mode = $state<AuthModalMode>(untrack(() => initialMode))
|
|
68
|
+
const { refresh } = useAuth()
|
|
69
|
+
const authClient = useAuthClient()
|
|
70
|
+
const { status: loginStatus, error: loginError, login } = useLogin()
|
|
71
|
+
const { status: signupStatus, error: signupError, signup } = useSignup()
|
|
72
|
+
const { fields, setField, clear } = useAuthFormState()
|
|
73
|
+
let password = $state('')
|
|
74
|
+
let name = $state('')
|
|
75
|
+
let twoFactorToken = $state('')
|
|
76
|
+
let oauthError = $state<string | null>(null)
|
|
77
|
+
// Post-auth confirmation ("Signed up!" / "Logged in!") shown briefly before
|
|
78
|
+
// the modal closes — without it the modal just vanished, which read as
|
|
79
|
+
// "nothing happened".
|
|
80
|
+
let succeeded = $state(false)
|
|
81
|
+
// The email input element, for the dialog focus pattern below.
|
|
82
|
+
let emailEl = $state<HTMLInputElement | null>(null)
|
|
83
|
+
|
|
84
|
+
const isSignup = $derived(mode === 'signup')
|
|
85
|
+
const busy = $derived((isSignup ? $signupStatus : $loginStatus) === 'pending')
|
|
86
|
+
const email = $derived($fields.email ?? '')
|
|
87
|
+
// Universal post-auth state: every label below reads a `$derived`, so a
|
|
88
|
+
// locale switch re-runs it the way React's render-time `t` call does.
|
|
89
|
+
const signupTitle = $derived(
|
|
90
|
+
t('auth.modal.signupTitle', undefined, { defaultValue: 'Create your account' }),
|
|
91
|
+
)
|
|
92
|
+
const loginTitle = $derived(t('auth.modal.loginTitle', undefined, { defaultValue: 'Log in' }))
|
|
93
|
+
const signupBlurb = $derived(
|
|
94
|
+
t('auth.modal.signupBlurb', undefined, { defaultValue: 'Sign up to keep your work.' }),
|
|
95
|
+
)
|
|
96
|
+
const loginBlurb = $derived(
|
|
97
|
+
t('auth.modal.loginBlurb', undefined, { defaultValue: 'Log in to keep your work.' }),
|
|
98
|
+
)
|
|
99
|
+
const namePlaceholder = $derived(
|
|
100
|
+
t('auth.signup.name', undefined, { defaultValue: 'Name (optional)' }),
|
|
101
|
+
)
|
|
102
|
+
const emailPlaceholder = $derived(t('auth.login.email', undefined, { defaultValue: 'Email' }))
|
|
103
|
+
const passwordPlaceholder = $derived(
|
|
104
|
+
t('auth.login.password', undefined, { defaultValue: 'Password' }),
|
|
105
|
+
)
|
|
106
|
+
const twoFactorPlaceholder = $derived(
|
|
107
|
+
t('auth.login.twoFactor', undefined, { defaultValue: 'Two-Factor Token (If enabled)' }),
|
|
108
|
+
)
|
|
109
|
+
const workingLabel = $derived(
|
|
110
|
+
t('auth.modal.working', undefined, { defaultValue: 'Just a moment…' }),
|
|
111
|
+
)
|
|
112
|
+
const signUpLabel = $derived(t('auth.login.signUp', undefined, { defaultValue: 'Sign up' }))
|
|
113
|
+
const logInLabel = $derived(t('auth.login.logIn', undefined, { defaultValue: 'Log in' }))
|
|
114
|
+
const signedUpLabel = $derived(
|
|
115
|
+
t('auth.modal.signedUp', undefined, { defaultValue: 'Signed up!' }),
|
|
116
|
+
)
|
|
117
|
+
const loggedInLabel = $derived(
|
|
118
|
+
t('auth.modal.loggedIn', undefined, { defaultValue: 'Logged in!' }),
|
|
119
|
+
)
|
|
120
|
+
const loggedInAs = $derived(
|
|
121
|
+
t(
|
|
122
|
+
'auth.modal.loggedInAs',
|
|
123
|
+
{ who: whoJustAuthenticated() },
|
|
124
|
+
{ defaultValue: 'Logged in as {{who}}' },
|
|
125
|
+
),
|
|
126
|
+
)
|
|
127
|
+
const haveAccountLabel = $derived(
|
|
128
|
+
t('auth.modal.haveAccount', undefined, { defaultValue: 'Already have an account? Log in' }),
|
|
129
|
+
)
|
|
130
|
+
const needAccountLabel = $derived(
|
|
131
|
+
t('auth.modal.needAccount', undefined, { defaultValue: "Don't have an account? Sign up" }),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
// The i18n-translated error text (React's `useI18nError`). `MaybeReadable`
|
|
135
|
+
// takes a store: this one mirrors whichever hook error the current mode
|
|
136
|
+
// shows, re-pushed by the effect when the mode or the errors change.
|
|
137
|
+
const selectedError = writable<Error | null | undefined>(null)
|
|
138
|
+
$effect(() => {
|
|
139
|
+
selectedError.set(isSignup ? $signupError : $loginError)
|
|
140
|
+
})
|
|
141
|
+
const i18nError = useI18nError(selectedError)
|
|
142
|
+
const errorMessage = $derived($i18nError)
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Who just authenticated — shown under the headline so the confirmation
|
|
146
|
+
* names the account, not just the outcome (React reads the client in the
|
|
147
|
+
* success render; the success view is the only place this is shown).
|
|
148
|
+
* @returns The profile display name, or ''.
|
|
149
|
+
*/
|
|
150
|
+
function whoJustAuthenticated(): string {
|
|
151
|
+
const profile = authClient.getUser() as {
|
|
152
|
+
name?: string | null
|
|
153
|
+
email?: string | null
|
|
154
|
+
username?: string | null
|
|
155
|
+
} | null
|
|
156
|
+
return profile?.name || profile?.email || profile?.username || ''
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Dialog pattern (WAI-ARIA): when the modal opens, keyboard and
|
|
160
|
+
// screen-reader users land on the form's primary field instead of on the
|
|
161
|
+
// page behind the overlay. This replaces the `autofocus` attribute, which
|
|
162
|
+
// jsx-a11y/no-autofocus bars: the attribute fires on EVERY mount of the
|
|
163
|
+
// input (e.g. the brief remount after the mode switches), while this effect
|
|
164
|
+
// runs exactly once per open transition — after the Modal child's own
|
|
165
|
+
// focus-trap effect (Svelte runs child effects first, like React), so the
|
|
166
|
+
// email field wins in both signup and login mode.
|
|
167
|
+
$effect(() => {
|
|
168
|
+
if (open) emailEl?.focus()
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
// Universal post-auth: refresh the session (guards + plan current), show a
|
|
172
|
+
// brief confirmation, run the app's hook, then close — all in place, no
|
|
173
|
+
// navigation.
|
|
174
|
+
/**
|
|
175
|
+
* Universal post-auth: refreshes the session, shows the brief confirmation,
|
|
176
|
+
* runs the app's `onAuthenticated` hook, then closes — all in place.
|
|
177
|
+
*/
|
|
178
|
+
async function finishAuth(): Promise<void> {
|
|
179
|
+
try {
|
|
180
|
+
await refresh()
|
|
181
|
+
} catch (error) {
|
|
182
|
+
// Every path into finishAuth (password login/signup response, OAuth popup
|
|
183
|
+
// relay) has already established the session client-side, so the refresh
|
|
184
|
+
// is a freshness pass — a failure here (e.g. an API with neither a
|
|
185
|
+
// refresh endpoint nor cookie restore) must NOT strand an authenticated
|
|
186
|
+
// user in the modal with their account already created. Only a genuinely
|
|
187
|
+
// absent session is a real failure.
|
|
188
|
+
if (!authClient.isAuthenticated()) throw error
|
|
189
|
+
}
|
|
190
|
+
succeeded = true
|
|
191
|
+
// Hold the confirmation on screen while the app hook runs; whichever
|
|
192
|
+
// finishes last gates the close.
|
|
193
|
+
const minDisplay = new Promise((resolve) => setTimeout(resolve, 1000))
|
|
194
|
+
await onAuthenticated?.()
|
|
195
|
+
await minDisplay
|
|
196
|
+
onClose?.()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// OAuth (popup): success/error land back on THIS page; wire them into the
|
|
200
|
+
// hook. `MaybeReadable` takes a plain value or a store — a store of the
|
|
201
|
+
// composed config is what reaches the hook live (React re-creates the
|
|
202
|
+
// config object every render): the effect below re-pushes it whenever the
|
|
203
|
+
// `oauthConfig` prop changes. The result is read off the object —
|
|
204
|
+
// `providers` is a live getter there.
|
|
205
|
+
const handleOauthSuccess = (): void => {
|
|
206
|
+
// Surface a finishAuth failure (no session established) in the modal
|
|
207
|
+
// instead of dying as an unhandled rejection.
|
|
208
|
+
finishAuth().catch((error: unknown) => {
|
|
209
|
+
oauthError = error instanceof Error ? error.message : String(error)
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
const handleOauthError = (message: string): void => {
|
|
213
|
+
oauthError = message
|
|
214
|
+
}
|
|
215
|
+
// The initial capture is intentional: this seed makes the first render show
|
|
216
|
+
// the prop's provider list, and the effect below re-pushes the composed
|
|
217
|
+
// config whenever the prop changes afterwards.
|
|
218
|
+
// svelte-ignore state_referenced_locally
|
|
219
|
+
const composedOauthConfig = writable({
|
|
220
|
+
...oauthConfig,
|
|
221
|
+
onSuccess: handleOauthSuccess,
|
|
222
|
+
onError: handleOauthError,
|
|
223
|
+
})
|
|
224
|
+
$effect(() => {
|
|
225
|
+
composedOauthConfig.set({
|
|
226
|
+
...oauthConfig,
|
|
227
|
+
onSuccess: handleOauthSuccess,
|
|
228
|
+
onError: handleOauthError,
|
|
229
|
+
})
|
|
230
|
+
})
|
|
231
|
+
const oauth = useOAuth(composedOauthConfig)
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* The form's submit: runs `onBeforeAuth`, signs in / signs up through the
|
|
235
|
+
* hooks, clears the shared email and finishes in place.
|
|
236
|
+
*
|
|
237
|
+
* @param event - The submit event.
|
|
238
|
+
*/
|
|
239
|
+
async function handleSubmit(event: SubmitEvent): Promise<void> {
|
|
240
|
+
event.preventDefault()
|
|
241
|
+
onBeforeAuth?.()
|
|
242
|
+
try {
|
|
243
|
+
if (isSignup) await signup({ email: $fields.email ?? '', password, name: name || undefined })
|
|
244
|
+
else await login({ email: $fields.email ?? '', password })
|
|
245
|
+
clear()
|
|
246
|
+
await finishAuth()
|
|
247
|
+
} catch (_error) {
|
|
248
|
+
// Auth errors are captured in the hook's error state and shown below; we
|
|
249
|
+
// deliberately do NOT navigate or reload on failure or success.
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The shared input inline style, sized for the current viewport class. */
|
|
254
|
+
const fieldStyle = $derived(
|
|
255
|
+
`width: 100%; padding: 10px 12px; border-radius: 6px; border: 1px solid var(--mol-color-border, rgba(127,127,127,0.3)); background: var(--mol-color-surface-secondary, rgba(127,127,127,0.06)); color: inherit; outline: none; font-size: ${isTouchFirst ? '16px' : '14px'}`,
|
|
256
|
+
)
|
|
257
|
+
</script>
|
|
258
|
+
|
|
259
|
+
<Modal
|
|
260
|
+
{open}
|
|
261
|
+
onClose={() => onClose?.()}
|
|
262
|
+
size="sm"
|
|
263
|
+
title={isSignup ? signupTitle : loginTitle}
|
|
264
|
+
data-mol-id="auth-modal"
|
|
265
|
+
>
|
|
266
|
+
<div data-mol-id="auth-modal-body" style="display: flex; flex-direction: column">
|
|
267
|
+
{#if succeeded}
|
|
268
|
+
<div
|
|
269
|
+
data-mol-id="auth-modal-success"
|
|
270
|
+
style="display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 26px 0px 18px; text-align: center"
|
|
271
|
+
>
|
|
272
|
+
<Icon name="check-circle" size={44} className={cm.textSuccess} aria-hidden="true" />
|
|
273
|
+
<div style="font-size: 17px; font-weight: 600">
|
|
274
|
+
{isSignup ? signedUpLabel : loggedInLabel}
|
|
275
|
+
</div>
|
|
276
|
+
{#if whoJustAuthenticated() !== ''}
|
|
277
|
+
<div class={cm.textMuted} style="font-size: 13px">{loggedInAs}</div>
|
|
278
|
+
{/if}
|
|
279
|
+
</div>
|
|
280
|
+
{:else}
|
|
281
|
+
<div class={cm.textMuted} style="margin-bottom: 12px; font-size: 13px; line-height: 1.45">
|
|
282
|
+
{isSignup ? signupBlurb : loginBlurb}
|
|
283
|
+
</div>
|
|
284
|
+
<form style="display: grid; gap: 10px" onsubmit={(e) => void handleSubmit(e)}>
|
|
285
|
+
{#if isSignup}
|
|
286
|
+
<input
|
|
287
|
+
type="text"
|
|
288
|
+
use:reactInputValue={{ value: name }}
|
|
289
|
+
oninput={(e) => (name = e.currentTarget.value)}
|
|
290
|
+
autocomplete="name"
|
|
291
|
+
data-mol-id="auth-modal-name"
|
|
292
|
+
placeholder={namePlaceholder}
|
|
293
|
+
style={fieldStyle}
|
|
294
|
+
/>
|
|
295
|
+
{/if}
|
|
296
|
+
<input
|
|
297
|
+
type="email"
|
|
298
|
+
use:reactInputValue={{ value: email }}
|
|
299
|
+
oninput={(e) => setField('email', e.currentTarget.value)}
|
|
300
|
+
autocomplete="email"
|
|
301
|
+
bind:this={emailEl}
|
|
302
|
+
required
|
|
303
|
+
data-mol-id="auth-modal-email"
|
|
304
|
+
placeholder={emailPlaceholder}
|
|
305
|
+
style={fieldStyle}
|
|
306
|
+
/>
|
|
307
|
+
<input
|
|
308
|
+
type="password"
|
|
309
|
+
use:reactInputValue={{ value: password }}
|
|
310
|
+
oninput={(e) => (password = e.currentTarget.value)}
|
|
311
|
+
autocomplete={isSignup ? 'new-password' : 'current-password'}
|
|
312
|
+
required
|
|
313
|
+
data-mol-id="auth-modal-password"
|
|
314
|
+
placeholder={passwordPlaceholder}
|
|
315
|
+
style={fieldStyle}
|
|
316
|
+
/>
|
|
317
|
+
{#if !isSignup}
|
|
318
|
+
<input
|
|
319
|
+
type="text"
|
|
320
|
+
inputmode="numeric"
|
|
321
|
+
use:reactInputValue={{ value: twoFactorToken }}
|
|
322
|
+
oninput={(e) => (twoFactorToken = e.currentTarget.value)}
|
|
323
|
+
autocomplete="one-time-code"
|
|
324
|
+
data-mol-id="auth-modal-2fa"
|
|
325
|
+
placeholder={twoFactorPlaceholder}
|
|
326
|
+
style={fieldStyle}
|
|
327
|
+
/>
|
|
328
|
+
{/if}
|
|
329
|
+
<!-- Human-verification challenge — signup only (login is not gated). -->
|
|
330
|
+
{#if isSignup && captchaSlot}
|
|
331
|
+
<div data-mol-id="auth-modal-captcha" style="display: grid; margin-top: 2px">
|
|
332
|
+
{#if typeof captchaSlot === 'function'}{@render captchaSlot()}{:else}{captchaSlot}{/if}
|
|
333
|
+
</div>
|
|
334
|
+
{/if}
|
|
335
|
+
<Button
|
|
336
|
+
type="submit"
|
|
337
|
+
size="lg"
|
|
338
|
+
color="success"
|
|
339
|
+
disabled={busy || (isSignup && !captchaSolved)}
|
|
340
|
+
data-mol-id="auth-modal-submit"
|
|
341
|
+
style={{ width: '100%', marginTop: '2px' }}
|
|
342
|
+
>
|
|
343
|
+
{busy ? workingLabel : isSignup ? signUpLabel : logInLabel}
|
|
344
|
+
</Button>
|
|
345
|
+
{#if errorMessage || oauthError}
|
|
346
|
+
<div class={cm.authFormError}>{errorMessage || oauthError}</div>
|
|
347
|
+
{/if}
|
|
348
|
+
</form>
|
|
349
|
+
{#if oauth.providers.length > 0}
|
|
350
|
+
<div style="margin-top: 4px">
|
|
351
|
+
<OAuthDivider />
|
|
352
|
+
<!-- Popup OAuth — never navigates the host. -->
|
|
353
|
+
<OAuthButtons
|
|
354
|
+
providers={oauth.providers}
|
|
355
|
+
onSelect={(provider) => {
|
|
356
|
+
oauthError = null
|
|
357
|
+
onBeforeAuth?.()
|
|
358
|
+
oauth.loginViaPopup(provider)
|
|
359
|
+
}}
|
|
360
|
+
/>
|
|
361
|
+
</div>
|
|
362
|
+
{/if}
|
|
363
|
+
<button
|
|
364
|
+
type="button"
|
|
365
|
+
data-mol-id="auth-modal-switch"
|
|
366
|
+
onclick={() => (mode = isSignup ? 'login' : 'signup')}
|
|
367
|
+
class={cm.cn(cm.button({ variant: 'ghost', size: 'sm' }))}
|
|
368
|
+
style="margin-top: 12px; align-self: center"
|
|
369
|
+
>
|
|
370
|
+
{isSignup ? haveAccountLabel : needAccountLabel}
|
|
371
|
+
</button>
|
|
372
|
+
{/if}
|
|
373
|
+
</div>
|
|
374
|
+
</Modal>
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AuthModal.svelte.d.ts","sourceRoot":"","sources":["../src/AuthModal.svelte"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AA+ShD,QAAA,MAAM,SAAS,oDAAwC,CAAC;AACxD,KAAK,SAAS,GAAG,UAAU,CAAC,OAAO,SAAS,CAAC,CAAC;AAC9C,eAAe,SAAS,CAAC"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
AuthModalMount: the Svelte counterpart of
|
|
3
|
+
`@molecule/app-auth-modal-react`'s `AuthModalMount` — one mount that renders
|
|
4
|
+
the (initially hidden) AuthModal and installs a capture-phase document click
|
|
5
|
+
handler opening it for in-app `/login` / `/signup` links (and routing
|
|
6
|
+
`/pricing` / `/billing` clicks to `onUpgradeIntercept`, else a new tab with a
|
|
7
|
+
focus-return session refresh). Same props (React names), same DOM for the
|
|
8
|
+
same input, same navigation calls.
|
|
9
|
+
-->
|
|
10
|
+
<script lang="ts">
|
|
11
|
+
import { useAuth } from '@molecule/app-svelte'
|
|
12
|
+
|
|
13
|
+
import AuthModal from './AuthModal.svelte'
|
|
14
|
+
import {
|
|
15
|
+
type AuthModalMode,
|
|
16
|
+
authModeForHref,
|
|
17
|
+
DEFAULT_AUTH_PATHS,
|
|
18
|
+
DEFAULT_UPGRADE_PATHS,
|
|
19
|
+
upgradePathForHref,
|
|
20
|
+
} from './cta-intercept.js'
|
|
21
|
+
import type { AuthModalMountProps } from './types.js'
|
|
22
|
+
|
|
23
|
+
let {
|
|
24
|
+
oauthConfig,
|
|
25
|
+
onBeforeAuth,
|
|
26
|
+
onAuthenticated,
|
|
27
|
+
onUpgradeReturn,
|
|
28
|
+
onUpgradeIntercept,
|
|
29
|
+
captchaSlot,
|
|
30
|
+
captchaSolved,
|
|
31
|
+
authPaths,
|
|
32
|
+
upgradePaths,
|
|
33
|
+
}: AuthModalMountProps = $props()
|
|
34
|
+
|
|
35
|
+
const { refresh } = useAuth()
|
|
36
|
+
let open = $state(false)
|
|
37
|
+
let mode = $state<AuthModalMode>('signup')
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Opens the modal on the given form (React's `openAuth`).
|
|
41
|
+
*
|
|
42
|
+
* @param next - The form to show.
|
|
43
|
+
*/
|
|
44
|
+
function openAuth(next: AuthModalMode): void {
|
|
45
|
+
mode = next
|
|
46
|
+
open = true
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Set when the user opens the upgrade/billing flow in a new tab, so we
|
|
50
|
+
// refresh when they return (a completed upgrade reflects with no manual
|
|
51
|
+
// reload).
|
|
52
|
+
let upgradeTabOpened = false
|
|
53
|
+
/**
|
|
54
|
+
* The window focus return: refresh the session and run `onUpgradeReturn`,
|
|
55
|
+
* but only after an upgrade tab was opened here.
|
|
56
|
+
*/
|
|
57
|
+
function onFocus(): void {
|
|
58
|
+
if (!upgradeTabOpened) return
|
|
59
|
+
upgradeTabOpened = false
|
|
60
|
+
refresh().catch((_error: unknown) => {
|
|
61
|
+
// Best-effort freshness pass: the user may have returned without a
|
|
62
|
+
// session to refresh (never logged in, or the API has no refresh
|
|
63
|
+
// path) — not an error worth surfacing on a simple tab focus.
|
|
64
|
+
})
|
|
65
|
+
onUpgradeReturn?.()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Intercept clicks on the in-app /login, /signup (→ modal) and /pricing,
|
|
69
|
+
// /billing (→ host's onUpgradeIntercept, else a new tab) CTAs — plain
|
|
70
|
+
// <a href> links from anywhere in the app, incl. ones opened with
|
|
71
|
+
// target="_blank". Capture-phase + preventDefault stops navigation. Plain
|
|
72
|
+
// left-clicks only — a modifier/middle click still opens the real page.
|
|
73
|
+
/**
|
|
74
|
+
* The capture-phase click interceptor (React's document click effect).
|
|
75
|
+
*
|
|
76
|
+
* @param e - The click event.
|
|
77
|
+
*/
|
|
78
|
+
function onClick(e: MouseEvent): void {
|
|
79
|
+
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
|
|
80
|
+
return
|
|
81
|
+
const anchor = (e.target as HTMLElement | null)?.closest('a[href]') as HTMLAnchorElement | null
|
|
82
|
+
if (!anchor) return
|
|
83
|
+
const href = anchor.getAttribute('href')
|
|
84
|
+
const origin = window.location.origin
|
|
85
|
+
const authMode = authModeForHref(href, origin, authPaths ?? DEFAULT_AUTH_PATHS)
|
|
86
|
+
if (authMode) {
|
|
87
|
+
e.preventDefault()
|
|
88
|
+
e.stopPropagation()
|
|
89
|
+
openAuth(authMode)
|
|
90
|
+
return
|
|
91
|
+
}
|
|
92
|
+
const upgradePath = upgradePathForHref(href, origin, upgradePaths ?? DEFAULT_UPGRADE_PATHS)
|
|
93
|
+
if (upgradePath) {
|
|
94
|
+
e.preventDefault()
|
|
95
|
+
e.stopPropagation()
|
|
96
|
+
if (onUpgradeIntercept) {
|
|
97
|
+
onUpgradeIntercept(upgradePath)
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
upgradeTabOpened = true
|
|
101
|
+
window.open(upgradePath, '_blank', 'noopener,noreferrer')
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// The listeners read the current props at call time (React re-subscribes
|
|
106
|
+
// when they change); the effect itself runs once per mount.
|
|
107
|
+
$effect(() => {
|
|
108
|
+
window.addEventListener('focus', onFocus)
|
|
109
|
+
document.addEventListener('click', onClick, true)
|
|
110
|
+
return () => {
|
|
111
|
+
window.removeEventListener('focus', onFocus)
|
|
112
|
+
document.removeEventListener('click', onClick, true)
|
|
113
|
+
}
|
|
114
|
+
})
|
|
115
|
+
</script>
|
|
116
|
+
|
|
117
|
+
<!-- Mounted only while open so the auth hooks don't run on every app render. -->
|
|
118
|
+
{#if open}
|
|
119
|
+
<AuthModal
|
|
120
|
+
{open}
|
|
121
|
+
onClose={() => (open = false)}
|
|
122
|
+
initialMode={mode}
|
|
123
|
+
{oauthConfig}
|
|
124
|
+
{onBeforeAuth}
|
|
125
|
+
{onAuthenticated}
|
|
126
|
+
{captchaSlot}
|
|
127
|
+
{captchaSolved}
|
|
128
|
+
/>
|
|
129
|
+
{/if}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AuthModalMountProps } from './types.js';
|
|
2
|
+
declare const AuthModalMount: import("svelte").Component<AuthModalMountProps, {}, "">;
|
|
3
|
+
type AuthModalMount = ReturnType<typeof AuthModalMount>;
|
|
4
|
+
export default AuthModalMount;
|
|
5
|
+
//# sourceMappingURL=AuthModalMount.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AuthModalMount.svelte.d.ts","sourceRoot":"","sources":["../src/AuthModalMount.svelte"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AA+GtD,QAAA,MAAM,cAAc,yDAAwC,CAAC;AAC7D,KAAK,cAAc,GAAG,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC;AACxD,eAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's components: one Svelte 5 component per React component in
|
|
3
|
+
* `@molecule/app-auth-modal-react`, under the same React name.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export { default as AuthModal } from './AuthModal.svelte';
|
|
8
|
+
export { default as AuthModalMount } from './AuthModalMount.svelte';
|
|
9
|
+
//# sourceMappingURL=components.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components.d.ts","sourceRoot":"","sources":["../src/components.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,yBAAyB,CAAA"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package's components: one Svelte 5 component per React component in
|
|
3
|
+
* `@molecule/app-auth-modal-react`, under the same React name.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
export { default as AuthModal } from './AuthModal.svelte';
|
|
8
|
+
export { default as AuthModalMount } from './AuthModalMount.svelte';
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure routing decisions for the in-app auth/upgrade click-interceptor.
|
|
3
|
+
*
|
|
4
|
+
* A click on an in-app `/login` or `/signup` link opens the {@link AuthModal}
|
|
5
|
+
* instead of navigating; a click on `/pricing` or `/billing` opens the upgrade
|
|
6
|
+
* flow without navigating the current tab — the host's `onUpgradeIntercept`
|
|
7
|
+
* (e.g. an in-app modal) when provided, else a new tab. These helpers turn a
|
|
8
|
+
* clicked link's href into that decision so the interceptor stays trivial and
|
|
9
|
+
* unit-testable.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
/** Which form {@link AuthModal} should show. */
|
|
14
|
+
export type AuthModalMode = 'login' | 'signup';
|
|
15
|
+
/** The default in-app auth routes that open the modal. */
|
|
16
|
+
export declare const DEFAULT_AUTH_PATHS: Readonly<Record<string, AuthModalMode>>;
|
|
17
|
+
/** The default routes that open the upgrade/billing flow (modal or new tab). */
|
|
18
|
+
export declare const DEFAULT_UPGRADE_PATHS: readonly string[];
|
|
19
|
+
/**
|
|
20
|
+
* Map a CTA link's href to the auth mode it should open, or `null` if it is not
|
|
21
|
+
* an auth link (so the interceptor leaves it alone).
|
|
22
|
+
*
|
|
23
|
+
* @param href - The clicked anchor's href (relative or absolute).
|
|
24
|
+
* @param origin - The page origin to resolve a relative href against.
|
|
25
|
+
* @param authPaths - Path→mode map (defaults to {@link DEFAULT_AUTH_PATHS}).
|
|
26
|
+
* @returns `'login'` / `'signup'`, else `null`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function authModeForHref(href: string | null | undefined, origin: string, authPaths?: Readonly<Record<string, AuthModalMode>>): AuthModalMode | null;
|
|
29
|
+
/**
|
|
30
|
+
* Whether a CTA link's href points at the upgrade/billing flow (which the
|
|
31
|
+
* interceptor hands to the host's `onUpgradeIntercept`, else opens in a new tab).
|
|
32
|
+
*
|
|
33
|
+
* @param href - The clicked anchor's href (relative or absolute).
|
|
34
|
+
* @param origin - The page origin to resolve a relative href against.
|
|
35
|
+
* @param upgradePaths - The upgrade paths (defaults to {@link DEFAULT_UPGRADE_PATHS}).
|
|
36
|
+
* @returns The matched pathname, else `null`.
|
|
37
|
+
*/
|
|
38
|
+
export declare function upgradePathForHref(href: string | null | undefined, origin: string, upgradePaths?: readonly string[]): string | null;
|
|
39
|
+
//# sourceMappingURL=cta-intercept.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cta-intercept.d.ts","sourceRoot":"","sources":["../src/cta-intercept.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,gDAAgD;AAChD,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,QAAQ,CAAA;AAE9C,0DAA0D;AAC1D,eAAO,MAAM,kBAAkB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAGtE,CAAA;AAED,gFAAgF;AAChF,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAA6B,CAAA;AAahF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,EACd,SAAS,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAsB,GACtE,aAAa,GAAG,IAAI,CAGtB;AAED;;;;;;;;GAQG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC/B,MAAM,EAAE,MAAM,EACd,YAAY,GAAE,SAAS,MAAM,EAA0B,GACtD,MAAM,GAAG,IAAI,CAGf"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure routing decisions for the in-app auth/upgrade click-interceptor.
|
|
3
|
+
*
|
|
4
|
+
* A click on an in-app `/login` or `/signup` link opens the {@link AuthModal}
|
|
5
|
+
* instead of navigating; a click on `/pricing` or `/billing` opens the upgrade
|
|
6
|
+
* flow without navigating the current tab — the host's `onUpgradeIntercept`
|
|
7
|
+
* (e.g. an in-app modal) when provided, else a new tab. These helpers turn a
|
|
8
|
+
* clicked link's href into that decision so the interceptor stays trivial and
|
|
9
|
+
* unit-testable.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
/** The default in-app auth routes that open the modal. */
|
|
14
|
+
export const DEFAULT_AUTH_PATHS = {
|
|
15
|
+
'/login': 'login',
|
|
16
|
+
'/signup': 'signup',
|
|
17
|
+
};
|
|
18
|
+
/** The default routes that open the upgrade/billing flow (modal or new tab). */
|
|
19
|
+
export const DEFAULT_UPGRADE_PATHS = ['/pricing', '/billing'];
|
|
20
|
+
/** Resolve an href to its pathname against `origin`, or `null` if malformed. */
|
|
21
|
+
function pathOf(href, origin) {
|
|
22
|
+
if (!href)
|
|
23
|
+
return null;
|
|
24
|
+
try {
|
|
25
|
+
return new URL(href, origin).pathname;
|
|
26
|
+
}
|
|
27
|
+
catch (_error) {
|
|
28
|
+
// A malformed href is not an in-app CTA — leave it alone (intentional noop).
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Map a CTA link's href to the auth mode it should open, or `null` if it is not
|
|
34
|
+
* an auth link (so the interceptor leaves it alone).
|
|
35
|
+
*
|
|
36
|
+
* @param href - The clicked anchor's href (relative or absolute).
|
|
37
|
+
* @param origin - The page origin to resolve a relative href against.
|
|
38
|
+
* @param authPaths - Path→mode map (defaults to {@link DEFAULT_AUTH_PATHS}).
|
|
39
|
+
* @returns `'login'` / `'signup'`, else `null`.
|
|
40
|
+
*/
|
|
41
|
+
export function authModeForHref(href, origin, authPaths = DEFAULT_AUTH_PATHS) {
|
|
42
|
+
const path = pathOf(href, origin);
|
|
43
|
+
return path != null ? (authPaths[path] ?? null) : null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether a CTA link's href points at the upgrade/billing flow (which the
|
|
47
|
+
* interceptor hands to the host's `onUpgradeIntercept`, else opens in a new tab).
|
|
48
|
+
*
|
|
49
|
+
* @param href - The clicked anchor's href (relative or absolute).
|
|
50
|
+
* @param origin - The page origin to resolve a relative href against.
|
|
51
|
+
* @param upgradePaths - The upgrade paths (defaults to {@link DEFAULT_UPGRADE_PATHS}).
|
|
52
|
+
* @returns The matched pathname, else `null`.
|
|
53
|
+
*/
|
|
54
|
+
export function upgradePathForHref(href, origin, upgradePaths = DEFAULT_UPGRADE_PATHS) {
|
|
55
|
+
const path = pathOf(href, origin);
|
|
56
|
+
return path != null && upgradePaths.includes(path) ? path : null;
|
|
57
|
+
}
|