ferst-core 0.17.0 → 0.18.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.
@@ -1,392 +1,395 @@
1
- /**
2
- * The members' account page (`/account`, the Ferst Members module): a React island
3
- * (docs/BLOCK-ARCHITECTURE.md §8), drawn in the browser only, since all of it depends on who the
4
- * visitor is.
5
- *
6
- * Signed out, it is the sign-in card: an email, the organisation's terms box when it has terms, then
7
- * the code sent to that email. There is no password, ever; a new person's first code makes them a
8
- * member when the organisation lets them join. Signed in, it shows who they are and where they stand
9
- * (a member, waiting for approval, or a guest who booked and may join), their name, signing out, and
10
- * deleting their account. `?next=` brings them back to the page that sent them, on this site only.
11
- *
12
- * Every call is the site's own `/ferst-api/members/…` (same-origin, the session a first-party
13
- * cookie); lib/members-account reads every answer and holds the words. React Aria gives the fields,
14
- * the tick box and the buttons their keyboard and screen-reader behaviour. It brings no look of its
15
- * own: the page's CSS (components/MembersAccount.astro) styles it from the site's tokens.
16
- */
17
- import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react';
18
- import { Button, Checkbox, Form, Input, Label, Text, TextField } from 'react-aria-components';
19
- import { MEMBERS_ME, accountLinkText, isLocalHost, readMembersAnswer, type MembersAnswer } from '../../lib/members';
20
- import {
21
- ACCOUNT_TEXT as T, MEMBERS_JOIN, MEMBERS_SIGN_IN, MEMBERS_SIGN_OUT, MEMBERS_START, MEMBERS_VERIFY, canJoin, cleanCode, cleanName,
22
- hasTerms, looksLikeEmail, readCard, readDone, readJoin, readMe, readRename, readStart, readVerify, safeNext, type Joining, type Member,
23
- type SignInCard,
24
- } from '../../lib/members-account';
25
-
26
- type Screen = 'loading' | 'local' | 'unavailable' | 'email' | 'code' | 'account';
27
- type Notice = { tone: 'info' | 'done' | 'error'; text: string } | null;
28
- type Errors = Partial<Record<'email' | 'agree' | 'code' | 'name' | 'confirm', string>>;
29
- interface Me { member: Member; org: string; joining: Joining }
30
-
31
- /** One call to the members service, as the site's own address; null when the network failed. */
32
- async function call(method: string, url: string, body?: unknown): Promise<MembersAnswer | null> {
33
- try {
34
- const res = await fetch(url, {
35
- method,
36
- credentials: 'same-origin',
37
- headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
38
- body: body === undefined ? undefined : JSON.stringify(body),
39
- });
40
- return await readMembersAnswer(res);
41
- } catch {
42
- return null;
43
- }
44
- }
45
-
46
- /** The header's account link follows along: the member's first name, or "Sign in". */
47
- function tellHeader(member: Member | null) {
48
- const text = accountLinkText(member ? { status: 200, body: { member: { display_name: member.displayName } } } : { status: 401, body: {} });
49
- if (text) document.querySelectorAll('[data-members-account]').forEach((a) => { a.textContent = text; });
50
- }
51
-
52
- /** A field's error, read out as it appears and tied to the field (React Aria's errorMessage slot). */
53
- const FieldError = ({ text }: { text?: string }) =>
54
- text ? <Text slot="errorMessage" className="m-account__error" role="alert">{text}</Text> : null;
55
-
56
- export default function MembersAccount() {
57
- const local = useRef(import.meta.env.DEV || isLocalHost(location.hostname)).current;
58
- const next = useRef(safeNext(new URLSearchParams(location.search).get('next'))).current;
59
-
60
- const [screen, setScreen] = useState<Screen>('loading');
61
- const [card, setCard] = useState<SignInCard | null>(null);
62
- const [me, setMe] = useState<Me | null>(null);
63
- const [email, setEmail] = useState('');
64
- const [agree, setAgree] = useState(false);
65
- const [signinId, setSigninId] = useState('');
66
- const [code, setCode] = useState('');
67
- const [name, setName] = useState('');
68
- const [confirm, setConfirm] = useState('');
69
- const [deleting, setDeleting] = useState(false);
70
- const [welcome, setWelcome] = useState<string | null>(null);
71
- const [notice, setNotice] = useState<Notice>(null);
72
- const [errors, setErrors] = useState<Errors>({});
73
- const [busy, setBusy] = useState<string | null>(null);
74
-
75
- const heading = useRef<HTMLHeadingElement>(null);
76
- const codeField = useRef<HTMLInputElement>(null);
77
- const emailField = useRef<HTMLInputElement>(null);
78
- /** Moving focus follows the visitor's own actions, never the first load. */
79
- const moved = useRef(false);
80
-
81
- useEffect(() => { void load(); }, []);
82
-
83
- // A new step: the code field when a code is on its way, else the step's heading.
84
- useEffect(() => {
85
- if (!moved.current) return;
86
- if (screen === 'code') codeField.current?.focus();
87
- else heading.current?.focus();
88
- }, [screen]);
89
-
90
- async function load() {
91
- const v = readMe(await call('GET', MEMBERS_ME), local);
92
- if (v.kind === 'member') {
93
- showAccount(v);
94
- // A guest may join: the card says whether the organisation has terms to agree to.
95
- if (canJoin(v.member, v.joining)) {
96
- const c = readCard(await call('GET', MEMBERS_SIGN_IN), local);
97
- if (c.kind === 'card') setCard(c.card);
98
- }
99
- return;
100
- }
101
- if (v.kind === 'signed-out') return showCard(null);
102
- setScreen(v.kind);
103
- }
104
-
105
- function showAccount(m: Me) {
106
- setMe(m);
107
- setName(m.member.displayName ?? '');
108
- setErrors({});
109
- setScreen('account');
110
- }
111
-
112
- /** Back to the sign-in card, with what just happened (signed out, deleted). */
113
- async function showCard(said: Notice) {
114
- const v = readCard(await call('GET', MEMBERS_SIGN_IN), local);
115
- setMe(null);
116
- setWelcome(null);
117
- setDeleting(false);
118
- setConfirm('');
119
- setCode('');
120
- setAgree(false);
121
- setErrors({});
122
- if (v.kind !== 'card') return setScreen(v.kind);
123
- setCard(v.card);
124
- setNotice(said);
125
- setScreen('email');
126
- }
127
-
128
- function act<R>(what: string, run: () => Promise<R>) {
129
- moved.current = true;
130
- setBusy(what);
131
- return run().finally(() => setBusy(null));
132
- }
133
-
134
- async function startSignIn(again = false) {
135
- const id = readStart(await call('POST', MEMBERS_START, { email: email.trim(), ...(hasTerms(card) ? { agree } : {}) }));
136
- if (!id) return setNotice({ tone: 'error', text: T.tryAgain });
137
- setSigninId(id);
138
- setCode('');
139
- setErrors({});
140
- setNotice(again ? { tone: 'info', text: T.newCodeSent } : null);
141
- if (again) codeField.current?.focus();
142
- setScreen('code');
143
- }
144
-
145
- function onEmail(e: FormEvent) {
146
- e.preventDefault();
147
- const found: Errors = {};
148
- if (!looksLikeEmail(email)) found.email = T.emailInvalid;
149
- if (hasTerms(card) && !agree) found.agree = T.agreeNeeded;
150
- setErrors(found);
151
- if (found.email) return emailField.current?.focus();
152
- if (found.agree) return;
153
- void act('start', () => startSignIn());
154
- }
155
-
156
- function onCode(e: FormEvent) {
157
- e.preventDefault();
158
- const c = cleanCode(code);
159
- if (!c) {
160
- setErrors({ code: T.codeInvalid });
161
- return codeField.current?.focus();
162
- }
163
- void act('verify', async () => {
164
- const out = readVerify(await call('POST', MEMBERS_VERIFY, { signin_id: signinId, code: c }));
165
- setNotice(null);
166
- if (out.kind === 'signed-in') {
167
- tellHeader(out.member);
168
- // Straight back to the page that sent them, unless there's a welcome to read first.
169
- if (next && out.member.status === 'active' && !out.welcome) {
170
- location.assign(next);
171
- return new Promise<void>(() => {}); // stay busy while the page changes
172
- }
173
- setWelcome(out.welcome);
174
- return showAccount({ member: out.member, org: card?.org ?? '', joining: card?.joining ?? 'open' });
175
- }
176
- if (out.kind === 'new-code') {
177
- setCode('');
178
- setErrors({});
179
- setNotice({ tone: 'info', text: T.newCodeToFinish });
180
- return;
181
- }
182
- if (out.kind === 'try-again') {
183
- setErrors({});
184
- setNotice({ tone: 'error', text: T.tryAgain });
185
- return;
186
- }
187
- setErrors({ code: out.kind === 'wrong-code' ? T.wrongCode(out.triesLeft) : T.expired });
188
- codeField.current?.select();
189
- });
190
- }
191
-
192
- function otherEmail() {
193
- moved.current = true;
194
- setErrors({});
195
- setNotice(null);
196
- setCode('');
197
- setScreen('email');
198
- }
199
-
200
- function onJoin(e: FormEvent) {
201
- e.preventDefault();
202
- if (!me) return;
203
- if (hasTerms(card) && !agree) return setErrors({ agree: T.agreeNeeded });
204
- void act('join', async () => {
205
- const out = readJoin(await call('POST', MEMBERS_JOIN, hasTerms(card) ? { agree } : {}));
206
- if (out.kind === 'joined') {
207
- setWelcome(out.welcome);
208
- setNotice(null);
209
- return showAccount({ ...me, member: out.member });
210
- }
211
- if (out.kind === 'signed-out') return showCard({ tone: 'info', text: T.signInAgain });
212
- if (out.kind === 'agree') return setErrors({ agree: T.agreeNeeded });
213
- setNotice({ tone: 'error', text: out.kind === 'invite-only' ? T.inviteOnly : T.tryAgain });
214
- });
215
- }
216
-
217
- function onName(e: FormEvent) {
218
- e.preventDefault();
219
- const clean = cleanName(name);
220
- if (!clean) return setErrors({ name: T.nameInvalid });
221
- void act('name', async () => {
222
- const out = readRename(await call('PATCH', MEMBERS_ME, { display_name: clean }));
223
- if (out.kind === 'saved' && me) {
224
- tellHeader(out.member);
225
- setMe({ ...me, member: out.member });
226
- setErrors({});
227
- return setNotice({ tone: 'done', text: T.nameSaved });
228
- }
229
- if (out.kind === 'signed-out') return showCard({ tone: 'info', text: T.signInAgain });
230
- if (out.kind === 'invalid') return setErrors({ name: T.nameInvalid });
231
- setNotice({ tone: 'error', text: T.tryAgain });
232
- });
233
- }
234
-
235
- function signOut() {
236
- void act('sign-out', async () => {
237
- const out = readDone(await call('POST', MEMBERS_SIGN_OUT));
238
- if (out === 'try-again') return setNotice({ tone: 'error', text: T.tryAgain });
239
- tellHeader(null);
240
- await showCard({ tone: 'done', text: T.signedOut });
241
- });
242
- }
243
-
244
- function onDelete(e: FormEvent) {
245
- e.preventDefault();
246
- if (confirm.trim().toLowerCase() !== 'delete') return;
247
- void act('delete', async () => {
248
- const out = readDone(await call('DELETE', MEMBERS_ME, { confirm: 'delete' }));
249
- if (out === 'try-again') return setNotice({ tone: 'error', text: T.deleteLater });
250
- tellHeader(null);
251
- await showCard(out === 'done' ? { tone: 'done', text: T.deleted } : { tone: 'info', text: T.signInAgain });
252
- });
253
- }
254
-
255
- const agreeBox = card && hasTerms(card) && (
256
- <div className="m-account__agree">
257
- <Checkbox
258
- className="m-account__check"
259
- isSelected={agree}
260
- onChange={(v) => { setAgree(v); setErrors((x) => ({ ...x, agree: undefined })); }}
261
- isInvalid={Boolean(errors.agree)}
262
- aria-describedby={errors.agree ? 'm-account-agree-error' : undefined}
263
- >
264
- <span className="m-account__box" aria-hidden="true">
265
- <svg viewBox="0 0 18 18"><polyline points="3.5 9.5 7.5 13 14.5 5" /></svg>
266
- </span>
267
- <span>{T.agree(card.org, card)}</span>
268
- </Checkbox>
269
- <p className="m-account__links">
270
- {card.termsUrl && <ExternalLink href={card.termsUrl}>{T.terms}</ExternalLink>}
271
- {card.privacyUrl && <ExternalLink href={card.privacyUrl}>{T.privacy}</ExternalLink>}
272
- </p>
273
- {errors.agree && <p id="m-account-agree-error" className="m-account__error" role="alert">{errors.agree}</p>}
274
- </div>
275
- );
276
-
277
- let body: ReactNode = null;
278
- if (screen === 'local' || screen === 'unavailable') {
279
- body = <p className="m-account__notice">{screen === 'local' ? T.local : T.unavailable}</p>;
280
- } else if (screen === 'email' && card) {
281
- body = (
282
- <div className="m-account__card">
283
- <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.signInTitle(card.org, card.joining)}</h2>
284
- <p className="m-account__intro">{T.signInIntro(card.org, card.joining)}</p>
285
- <Form className="m-account__form" onSubmit={onEmail} validationBehavior="aria">
286
- <TextField className="m-account__field" name="email" type="email" autoComplete="email" value={email} onChange={setEmail} isInvalid={Boolean(errors.email)} isRequired>
287
- <Label className="m-account__label">{T.email}</Label>
288
- <Input className="m-account__input" ref={emailField} spellCheck={false} />
289
- <FieldError text={errors.email} />
290
- </TextField>
291
- {agreeBox}
292
- <Button type="submit" className="m-account__go" isPending={busy === 'start'}>{T.continue}</Button>
293
- </Form>
294
- </div>
295
- );
296
- } else if (screen === 'code') {
297
- body = (
298
- <div className="m-account__card">
299
- <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.codeTitle}</h2>
300
- <p className="m-account__intro">{T.codeSent(email.trim())}</p>
301
- <Form className="m-account__form" onSubmit={onCode} validationBehavior="aria">
302
- <TextField className="m-account__field" name="code" value={code} onChange={setCode} isInvalid={Boolean(errors.code)} isRequired>
303
- <Label className="m-account__label">{T.code}</Label>
304
- <Input className="m-account__input m-account__input--code" ref={codeField} inputMode="numeric" autoComplete="one-time-code" maxLength={12} spellCheck={false} />
305
- <Text slot="description" className="m-account__hint">{T.codeHint}</Text>
306
- <FieldError text={errors.code} />
307
- </TextField>
308
- <Button type="submit" className="m-account__go" isPending={busy === 'verify'}>{T.signIn}</Button>
309
- </Form>
310
- <div className="m-account__row">
311
- <Button className="m-account__link" onPress={() => void act('resend', () => startSignIn(true))} isPending={busy === 'resend'}>{T.newCode}</Button>
312
- <Button className="m-account__link" onPress={otherEmail}>{T.otherEmail}</Button>
313
- </div>
314
- </div>
315
- );
316
- } else if (screen === 'account' && me) {
317
- const { member, org, joining } = me;
318
- body = (
319
- <>
320
- <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.signedInAs(member)}</h2>
321
- <p className="m-account__status" data-status={member.status}>{T.status(member, org, joining)}</p>
322
- {welcome && <p className="m-account__welcome">{welcome}</p>}
323
- {canJoin(member, joining) && (
324
- <Form className="m-account__form m-account__join" onSubmit={onJoin} validationBehavior="aria">
325
- {agreeBox}
326
- <Button type="submit" className="m-account__go" isPending={busy === 'join'}>{T.join(org)}</Button>
327
- </Form>
328
- )}
329
- {next && <p><a className="m-account__back" href={next}>{T.back}</a></p>}
330
-
331
- <section className="m-account__part" aria-labelledby="m-account-name">
332
- <h2 id="m-account-name" className="m-account__part-title">{T.nameTitle}</h2>
333
- <Form className="m-account__form m-account__form--row" onSubmit={onName} validationBehavior="aria">
334
- <TextField className="m-account__field" name="display_name" autoComplete="name" value={name} onChange={setName} isInvalid={Boolean(errors.name)} maxLength={60}>
335
- <Label className="m-account__label">{T.name}</Label>
336
- <Input className="m-account__input" />
337
- <Text slot="description" className="m-account__hint">{T.nameHint}</Text>
338
- <FieldError text={errors.name} />
339
- </TextField>
340
- <Button type="submit" className="m-account__plain" isPending={busy === 'name'}>{T.saveName}</Button>
341
- </Form>
342
- </section>
343
-
344
- <div className="m-account__part m-account__row">
345
- <Button className="m-account__plain" onPress={signOut} isPending={busy === 'sign-out'}>{T.signOut}</Button>
346
- <Button
347
- className="m-account__link m-account__link--danger"
348
- aria-expanded={deleting}
349
- aria-controls="m-account-delete"
350
- onPress={() => { setDeleting((d) => !d); setConfirm(''); }}
351
- >
352
- {T.deleteOpen}
353
- </Button>
354
- </div>
355
- {deleting && (
356
- <Form id="m-account-delete" className="m-account__form m-account__delete" onSubmit={onDelete} validationBehavior="aria">
357
- <p className="m-account__intro">{T.deleteWarning(org)}</p>
358
- <TextField className="m-account__field" name="confirm" value={confirm} onChange={setConfirm} autoComplete="off">
359
- <Label className="m-account__label">{T.deleteConfirm}</Label>
360
- <Input className="m-account__input" spellCheck={false} />
361
- </TextField>
362
- <div className="m-account__row">
363
- <Button type="submit" className="m-account__danger" isDisabled={confirm.trim().toLowerCase() !== 'delete'} isPending={busy === 'delete'}>{T.deleteGo}</Button>
364
- <Button className="m-account__link" onPress={() => { setDeleting(false); setConfirm(''); }}>{T.deleteKeep}</Button>
365
- </div>
366
- </Form>
367
- )}
368
- </>
369
- );
370
- }
371
-
372
- if (screen === 'loading' || !body) return <p className="m-account__wait" role="status">{T.loading}</p>;
373
- return (
374
- <div className="m-account__app" data-account-ready>
375
- {/* One region for what just happened, kept across steps so a screen reader hears it. */}
376
- <div className="m-account__live" role="status">
377
- {notice && <p className={`m-account__notice m-account__notice--${notice.tone}`}>{notice.text}</p>}
378
- </div>
379
- {body}
380
- </div>
381
- );
382
- }
383
-
384
- /** A link to the organisation's own terms, opening beside the card so nothing typed is lost. */
385
- function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
386
- return (
387
- <a href={href} target="_blank" rel="noopener noreferrer">
388
- {children}
389
- <span className="m-account__sr"> {T.opensNewTab}</span>
390
- </a>
391
- );
392
- }
1
+ /**
2
+ * The members' account page (`/account`, the Ferst Members module): a React island
3
+ * (docs/BLOCK-ARCHITECTURE.md §8), drawn in the browser only, since all of it depends on who the
4
+ * visitor is.
5
+ *
6
+ * Signed out, it is the sign-in card: an email, the organisation's terms box when it has terms, then
7
+ * the code sent to that email. There is no password, ever; a new person's first code makes them a
8
+ * member when the organisation lets them join. Signed in, it shows who they are and where they stand
9
+ * (a member, waiting for approval, or a guest who booked and may join), their name, signing out, and
10
+ * deleting their account. `?next=` brings them back to the page that sent them, on this site only.
11
+ *
12
+ * Every call is the site's own `/ferst-api/members/…` (same-origin, the session a first-party
13
+ * cookie); lib/members-account reads every answer and holds the words. React Aria gives the fields,
14
+ * the tick box and the buttons their keyboard and screen-reader behaviour. It brings no look of its
15
+ * own: the page's CSS (components/MembersAccount.astro) styles it from the site's tokens.
16
+ */
17
+ import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react';
18
+ import { Button, Checkbox, Form, Input, Label, Text, TextField } from 'react-aria-components';
19
+ import { MEMBERS_ME, accountLinkText, isLocalHost, readMembersAnswer, rememberAccountLabel, type MembersAnswer } from '../../lib/members';
20
+ import {
21
+ ACCOUNT_TEXT as T, MEMBERS_JOIN, MEMBERS_SIGN_IN, MEMBERS_SIGN_OUT, MEMBERS_START, MEMBERS_VERIFY, canJoin, cleanCode, cleanName,
22
+ hasTerms, looksLikeEmail, readCard, readDone, readJoin, readMe, readRename, readStart, readVerify, safeNext, type Joining, type Member,
23
+ type SignInCard,
24
+ } from '../../lib/members-account';
25
+
26
+ type Screen = 'loading' | 'local' | 'unavailable' | 'email' | 'code' | 'account';
27
+ type Notice = { tone: 'info' | 'done' | 'error'; text: string } | null;
28
+ type Errors = Partial<Record<'email' | 'agree' | 'code' | 'name' | 'confirm', string>>;
29
+ interface Me { member: Member; org: string; joining: Joining }
30
+
31
+ /** One call to the members service, as the site's own address; null when the network failed. */
32
+ async function call(method: string, url: string, body?: unknown): Promise<MembersAnswer | null> {
33
+ try {
34
+ const res = await fetch(url, {
35
+ method,
36
+ credentials: 'same-origin',
37
+ headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
38
+ body: body === undefined ? undefined : JSON.stringify(body),
39
+ });
40
+ return await readMembersAnswer(res);
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /** The header's account link follows along: the member's first name, or "Sign in". */
47
+ function tellHeader(member: Member | null) {
48
+ const text = accountLinkText(member ? { status: 200, body: { member: { display_name: member.displayName } } } : { status: 401, body: {} });
49
+ if (!text) return;
50
+ document.querySelectorAll('[data-members-account]').forEach((a) => { a.textContent = text; });
51
+ rememberAccountLabel(text);
52
+ }
53
+
54
+ /** A field's error, read out as it appears and tied to the field (React Aria's errorMessage slot). */
55
+ const FieldError = ({ text }: { text?: string }) =>
56
+ text ? <Text slot="errorMessage" className="m-account__error" role="alert">{text}</Text> : null;
57
+
58
+ export default function MembersAccount() {
59
+ const local = useRef(import.meta.env.DEV || isLocalHost(location.hostname)).current;
60
+ const next = useRef(safeNext(new URLSearchParams(location.search).get('next'))).current;
61
+
62
+ const [screen, setScreen] = useState<Screen>('loading');
63
+ const [card, setCard] = useState<SignInCard | null>(null);
64
+ const [me, setMe] = useState<Me | null>(null);
65
+ const [email, setEmail] = useState('');
66
+ const [agree, setAgree] = useState(false);
67
+ const [signinId, setSigninId] = useState('');
68
+ const [code, setCode] = useState('');
69
+ const [name, setName] = useState('');
70
+ const [confirm, setConfirm] = useState('');
71
+ const [deleting, setDeleting] = useState(false);
72
+ const [welcome, setWelcome] = useState<string | null>(null);
73
+ const [notice, setNotice] = useState<Notice>(null);
74
+ const [errors, setErrors] = useState<Errors>({});
75
+ const [busy, setBusy] = useState<string | null>(null);
76
+
77
+ const heading = useRef<HTMLHeadingElement>(null);
78
+ const codeField = useRef<HTMLInputElement>(null);
79
+ const emailField = useRef<HTMLInputElement>(null);
80
+ /** Moving focus follows the visitor's own actions, never the first load. */
81
+ const moved = useRef(false);
82
+
83
+ useEffect(() => { void load(); }, []);
84
+
85
+ // A new step: the code field when a code is on its way, else the step's heading.
86
+ useEffect(() => {
87
+ if (!moved.current) return;
88
+ if (screen === 'code') codeField.current?.focus();
89
+ else heading.current?.focus();
90
+ }, [screen]);
91
+
92
+ async function load() {
93
+ const v = readMe(await call('GET', MEMBERS_ME), local);
94
+ if (v.kind === 'member') {
95
+ showAccount(v);
96
+ // A guest may join: the card says whether the organisation has terms to agree to.
97
+ if (canJoin(v.member, v.joining)) {
98
+ const c = readCard(await call('GET', MEMBERS_SIGN_IN), local);
99
+ if (c.kind === 'card') setCard(c.card);
100
+ }
101
+ return;
102
+ }
103
+ if (v.kind === 'signed-out') return showCard(null);
104
+ setScreen(v.kind);
105
+ }
106
+
107
+ function showAccount(m: Me) {
108
+ setMe(m);
109
+ setName(m.member.displayName ?? '');
110
+ setErrors({});
111
+ setScreen('account');
112
+ }
113
+
114
+ /** Back to the sign-in card, with what just happened (signed out, deleted). */
115
+ async function showCard(said: Notice) {
116
+ const v = readCard(await call('GET', MEMBERS_SIGN_IN), local);
117
+ setMe(null);
118
+ setWelcome(null);
119
+ setDeleting(false);
120
+ setConfirm('');
121
+ setCode('');
122
+ setAgree(false);
123
+ setErrors({});
124
+ if (v.kind !== 'card') return setScreen(v.kind);
125
+ setCard(v.card);
126
+ setNotice(said);
127
+ setScreen('email');
128
+ }
129
+
130
+ function act<R>(what: string, run: () => Promise<R>) {
131
+ moved.current = true;
132
+ setBusy(what);
133
+ return run().finally(() => setBusy(null));
134
+ }
135
+
136
+ async function startSignIn(again = false) {
137
+ const id = readStart(await call('POST', MEMBERS_START, { email: email.trim(), ...(hasTerms(card) ? { agree } : {}) }));
138
+ if (!id) return setNotice({ tone: 'error', text: T.tryAgain });
139
+ setSigninId(id);
140
+ setCode('');
141
+ setErrors({});
142
+ setNotice(again ? { tone: 'info', text: T.newCodeSent } : null);
143
+ if (again) codeField.current?.focus();
144
+ setScreen('code');
145
+ }
146
+
147
+ function onEmail(e: FormEvent) {
148
+ e.preventDefault();
149
+ const found: Errors = {};
150
+ if (!looksLikeEmail(email)) found.email = T.emailInvalid;
151
+ if (hasTerms(card) && !agree) found.agree = T.agreeNeeded;
152
+ setErrors(found);
153
+ if (found.email) return emailField.current?.focus();
154
+ if (found.agree) return;
155
+ void act('start', () => startSignIn());
156
+ }
157
+
158
+ function onCode(e: FormEvent) {
159
+ e.preventDefault();
160
+ const c = cleanCode(code);
161
+ if (!c) {
162
+ setErrors({ code: T.codeInvalid });
163
+ return codeField.current?.focus();
164
+ }
165
+ void act('verify', async () => {
166
+ const out = readVerify(await call('POST', MEMBERS_VERIFY, { signin_id: signinId, code: c }));
167
+ setNotice(null);
168
+ if (out.kind === 'signed-in') {
169
+ tellHeader(out.member);
170
+ // Straight back to the page that sent them, unless there's a welcome to read first.
171
+ if (next && out.member.status === 'active' && !out.welcome) {
172
+ location.assign(next);
173
+ return new Promise<void>(() => {}); // stay busy while the page changes
174
+ }
175
+ setWelcome(out.welcome);
176
+ return showAccount({ member: out.member, org: card?.org ?? '', joining: card?.joining ?? 'open' });
177
+ }
178
+ if (out.kind === 'new-code') {
179
+ setCode('');
180
+ setErrors({});
181
+ setNotice({ tone: 'info', text: T.newCodeToFinish });
182
+ return;
183
+ }
184
+ if (out.kind === 'try-again') {
185
+ setErrors({});
186
+ setNotice({ tone: 'error', text: T.tryAgain });
187
+ return;
188
+ }
189
+ setErrors({ code: out.kind === 'wrong-code' ? T.wrongCode(out.triesLeft) : T.expired });
190
+ codeField.current?.select();
191
+ });
192
+ }
193
+
194
+ function otherEmail() {
195
+ moved.current = true;
196
+ setErrors({});
197
+ setNotice(null);
198
+ setCode('');
199
+ setScreen('email');
200
+ }
201
+
202
+ function onJoin(e: FormEvent) {
203
+ e.preventDefault();
204
+ if (!me) return;
205
+ if (hasTerms(card) && !agree) return setErrors({ agree: T.agreeNeeded });
206
+ void act('join', async () => {
207
+ const out = readJoin(await call('POST', MEMBERS_JOIN, hasTerms(card) ? { agree } : {}));
208
+ if (out.kind === 'joined') {
209
+ setWelcome(out.welcome);
210
+ setNotice(null);
211
+ return showAccount({ ...me, member: out.member });
212
+ }
213
+ if (out.kind === 'signed-out') return showCard({ tone: 'info', text: T.signInAgain });
214
+ if (out.kind === 'agree') return setErrors({ agree: T.agreeNeeded });
215
+ setNotice({ tone: 'error', text: out.kind === 'invite-only' ? T.inviteOnly : out.kind === 'paused' ? T.paused(me.org) : T.tryAgain });
216
+ });
217
+ }
218
+
219
+ function onName(e: FormEvent) {
220
+ e.preventDefault();
221
+ const clean = cleanName(name);
222
+ if (!clean) return setErrors({ name: T.nameInvalid });
223
+ void act('name', async () => {
224
+ const out = readRename(await call('PATCH', MEMBERS_ME, { display_name: clean }));
225
+ if (out.kind === 'saved' && me) {
226
+ tellHeader(out.member);
227
+ setMe({ ...me, member: out.member });
228
+ setErrors({});
229
+ return setNotice({ tone: 'done', text: T.nameSaved });
230
+ }
231
+ if (out.kind === 'signed-out') return showCard({ tone: 'info', text: T.signInAgain });
232
+ if (out.kind === 'invalid') return setErrors({ name: T.nameInvalid });
233
+ setNotice({ tone: 'error', text: T.tryAgain });
234
+ });
235
+ }
236
+
237
+ function signOut() {
238
+ void act('sign-out', async () => {
239
+ const out = readDone(await call('POST', MEMBERS_SIGN_OUT));
240
+ if (out === 'try-again') return setNotice({ tone: 'error', text: T.tryAgain });
241
+ tellHeader(null);
242
+ await showCard({ tone: 'done', text: T.signedOut });
243
+ });
244
+ }
245
+
246
+ function onDelete(e: FormEvent) {
247
+ e.preventDefault();
248
+ if (confirm.trim().toLowerCase() !== 'delete') return;
249
+ void act('delete', async () => {
250
+ const out = readDone(await call('DELETE', MEMBERS_ME, { confirm: 'delete' }));
251
+ if (out === 'try-again') return setNotice({ tone: 'error', text: T.deleteLater });
252
+ tellHeader(null);
253
+ await showCard(out === 'done' ? { tone: 'done', text: T.deleted } : { tone: 'info', text: T.signInAgain });
254
+ });
255
+ }
256
+
257
+ const agreeBox = card && hasTerms(card) && (
258
+ <div className="m-account__agree">
259
+ <Checkbox
260
+ className="m-account__check"
261
+ isSelected={agree}
262
+ onChange={(v) => { setAgree(v); setErrors((x) => ({ ...x, agree: undefined })); }}
263
+ isInvalid={Boolean(errors.agree)}
264
+ aria-describedby={errors.agree ? 'm-account-agree-error' : undefined}
265
+ >
266
+ <span className="m-account__box" aria-hidden="true">
267
+ <svg viewBox="0 0 18 18"><polyline points="3.5 9.5 7.5 13 14.5 5" /></svg>
268
+ </span>
269
+ <span>{T.agree(card.org, card)}</span>
270
+ </Checkbox>
271
+ <p className="m-account__links">
272
+ {card.termsUrl && <ExternalLink href={card.termsUrl}>{T.terms}</ExternalLink>}
273
+ {card.privacyUrl && <ExternalLink href={card.privacyUrl}>{T.privacy}</ExternalLink>}
274
+ </p>
275
+ {errors.agree && <p id="m-account-agree-error" className="m-account__error" role="alert">{errors.agree}</p>}
276
+ </div>
277
+ );
278
+
279
+ let body: ReactNode = null;
280
+ if (screen === 'local' || screen === 'unavailable') {
281
+ body = <p className="m-account__notice">{screen === 'local' ? T.local : T.unavailable}</p>;
282
+ } else if (screen === 'email' && card) {
283
+ body = (
284
+ <div className="m-account__card">
285
+ <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.signInTitle(card.org, card.joining, card.joiningPaused)}</h2>
286
+ <p className="m-account__intro">{T.signInIntro(card.org, card.joining, card.joiningPaused)}</p>
287
+ <Form className="m-account__form" onSubmit={onEmail} validationBehavior="aria">
288
+ <TextField className="m-account__field" name="email" type="email" autoComplete="email" value={email} onChange={setEmail} isInvalid={Boolean(errors.email)} isRequired>
289
+ <Label className="m-account__label">{T.email}</Label>
290
+ <Input className="m-account__input" ref={emailField} spellCheck={false} />
291
+ <FieldError text={errors.email} />
292
+ </TextField>
293
+ {agreeBox}
294
+ <Button type="submit" className="m-account__go" isPending={busy === 'start'}>{T.continue}</Button>
295
+ </Form>
296
+ </div>
297
+ );
298
+ } else if (screen === 'code') {
299
+ body = (
300
+ <div className="m-account__card">
301
+ <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.codeTitle}</h2>
302
+ <p className="m-account__intro">{T.codeSent(email.trim())}</p>
303
+ <Form className="m-account__form" onSubmit={onCode} validationBehavior="aria">
304
+ <TextField className="m-account__field" name="code" value={code} onChange={setCode} isInvalid={Boolean(errors.code)} isRequired>
305
+ <Label className="m-account__label">{T.code}</Label>
306
+ <Input className="m-account__input m-account__input--code" ref={codeField} inputMode="numeric" autoComplete="one-time-code" maxLength={12} spellCheck={false} />
307
+ <Text slot="description" className="m-account__hint">{T.codeHint}</Text>
308
+ <FieldError text={errors.code} />
309
+ </TextField>
310
+ <Button type="submit" className="m-account__go" isPending={busy === 'verify'}>{T.signIn}</Button>
311
+ </Form>
312
+ <div className="m-account__row">
313
+ <Button className="m-account__link" onPress={() => void act('resend', () => startSignIn(true))} isPending={busy === 'resend'}>{T.newCode}</Button>
314
+ <Button className="m-account__link" onPress={otherEmail}>{T.otherEmail}</Button>
315
+ </div>
316
+ </div>
317
+ );
318
+ } else if (screen === 'account' && me) {
319
+ const { member, org, joining } = me;
320
+ body = (
321
+ <>
322
+ <h2 className="m-account__step" ref={heading} tabIndex={-1}>{T.signedInAs(member)}</h2>
323
+ <p className="m-account__status" data-status={member.status}>{T.status(member, org, joining)}</p>
324
+ {welcome && <p className="m-account__welcome">{welcome}</p>}
325
+ {canJoin(member, joining) && card?.joiningPaused && <p className="m-account__status">{T.paused(org)}</p>}
326
+ {canJoin(member, joining) && !card?.joiningPaused && (
327
+ <Form className="m-account__form m-account__join" onSubmit={onJoin} validationBehavior="aria">
328
+ {agreeBox}
329
+ <Button type="submit" className="m-account__go" isPending={busy === 'join'}>{T.join(org)}</Button>
330
+ </Form>
331
+ )}
332
+ {next && <p><a className="m-account__back" href={next}>{T.back}</a></p>}
333
+
334
+ <section className="m-account__part" aria-labelledby="m-account-name">
335
+ <h2 id="m-account-name" className="m-account__part-title">{T.nameTitle}</h2>
336
+ <Form className="m-account__form m-account__form--row" onSubmit={onName} validationBehavior="aria">
337
+ <TextField className="m-account__field" name="display_name" autoComplete="name" value={name} onChange={setName} isInvalid={Boolean(errors.name)} maxLength={60}>
338
+ <Label className="m-account__label">{T.name}</Label>
339
+ <Input className="m-account__input" />
340
+ <Text slot="description" className="m-account__hint">{T.nameHint}</Text>
341
+ <FieldError text={errors.name} />
342
+ </TextField>
343
+ <Button type="submit" className="m-account__plain" isPending={busy === 'name'}>{T.saveName}</Button>
344
+ </Form>
345
+ </section>
346
+
347
+ <div className="m-account__part m-account__row">
348
+ <Button className="m-account__plain" onPress={signOut} isPending={busy === 'sign-out'}>{T.signOut}</Button>
349
+ <Button
350
+ className="m-account__link m-account__link--danger"
351
+ aria-expanded={deleting}
352
+ aria-controls="m-account-delete"
353
+ onPress={() => { setDeleting((d) => !d); setConfirm(''); }}
354
+ >
355
+ {T.deleteOpen}
356
+ </Button>
357
+ </div>
358
+ {deleting && (
359
+ <Form id="m-account-delete" className="m-account__form m-account__delete" onSubmit={onDelete} validationBehavior="aria">
360
+ <p className="m-account__intro">{T.deleteWarning(org)}</p>
361
+ <TextField className="m-account__field" name="confirm" value={confirm} onChange={setConfirm} autoComplete="off">
362
+ <Label className="m-account__label">{T.deleteConfirm}</Label>
363
+ <Input className="m-account__input" spellCheck={false} />
364
+ </TextField>
365
+ <div className="m-account__row">
366
+ <Button type="submit" className="m-account__danger" isDisabled={confirm.trim().toLowerCase() !== 'delete'} isPending={busy === 'delete'}>{T.deleteGo}</Button>
367
+ <Button className="m-account__link" onPress={() => { setDeleting(false); setConfirm(''); }}>{T.deleteKeep}</Button>
368
+ </div>
369
+ </Form>
370
+ )}
371
+ </>
372
+ );
373
+ }
374
+
375
+ if (screen === 'loading' || !body) return <p className="m-account__wait" role="status">{T.loading}</p>;
376
+ return (
377
+ <div className="m-account__app" data-account-ready>
378
+ {/* One region for what just happened, kept across steps so a screen reader hears it. */}
379
+ <div className="m-account__live" role="status">
380
+ {notice && <p className={`m-account__notice m-account__notice--${notice.tone}`}>{notice.text}</p>}
381
+ </div>
382
+ {body}
383
+ </div>
384
+ );
385
+ }
386
+
387
+ /** A link to the organisation's own terms, opening beside the card so nothing typed is lost. */
388
+ function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
389
+ return (
390
+ <a href={href} target="_blank" rel="noopener noreferrer">
391
+ {children}
392
+ <span className="m-account__sr"> {T.opensNewTab}</span>
393
+ </a>
394
+ );
395
+ }