@jsb188/auth-web 1.1.11 → 1.1.12

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,24 +1,30 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
- import { useCurrentAccount } from '@jsb188/react/states';
2
+ import { cn } from '@jsb188/app/utils/string.ts';
3
+ import { useOrgRelFromMyOrganizations } from '@jsb188/graphql/hooks/use-organization-qry';
4
+ import { AppContext, onAccountLogin, useCurrentAccount, usePopOverActions, usePopOverEvent } from '@jsb188/react/states';
5
+ import { PopOverButton, TooltipButton } from '@jsb188/react-web/modules/PopOver';
6
+ import { Icon } from '@jsb188/react-web/svgs/Icon';
3
7
  import { AvatarImg } from '@jsb188/react-web/ui/Avatar';
4
- import { PageFormHeaderOAuthButton } from '@jsb188/react-web/ui/PageFormUI';
5
- import { TextWithLinks } from '@jsb188/react-web/ui/Markdown';
6
- import { memo, useCallback, type ReactNode } from 'react';
7
- import {
8
- useContinueWithGoogle,
9
- useContinueWithMicrosoft,
10
- } from '../hooks/use-oauth';
8
+ import { ActivityDots, ActivityIndicator } from '@jsb188/react-web/ui/Loading';
9
+ import Markdown, { TextWithLinks } from '@jsb188/react-web/ui/Markdown';
10
+ import { memo, type ReactNode, useCallback, useContext, useEffect, useId, useState } from 'react';
11
+ import { useAuthenticationPopup } from '../hooks/use-auth-popup.ts';
12
+ import { useContinueWithGoogle, useContinueWithMicrosoft } from '../hooks/use-oauth';
13
+ import type { AuthPopupCompletionMessage } from '../utils/authPopup.ts';
11
14
 
12
15
  /**
13
16
  * Types
14
17
  */
15
18
 
16
19
  interface InlineAuthFormProps {
20
+ className?: string;
21
+ // Display the organization-loading state while the caller resolves authentication.
22
+ loading?: boolean;
17
23
  // Sign-in button labels; a null/absent label hides that provider's button
18
24
  googleLabel?: string | null;
19
25
  microsoftLabel?: string | null;
20
- // Verified email of a temporary (account-less) respondent token holder; shown
21
- // as the identity when there is no signed-in account
26
+ phoneLabel?: string | null;
27
+ // Verified email of a temporary account-less respondent token holder
22
28
  respondentEmail?: string | null;
23
29
  // Respondent status / helper text shown next to the buttons; a plain string
24
30
  // is parsed for inline links, a node is rendered as-is
@@ -26,136 +32,428 @@ interface InlineAuthFormProps {
26
32
  // When true, an OAuth-verified email with no account does not error; the
27
33
  // server returns a temporary respondent token (ANYONE web forms)
28
34
  authenticateOnly?: boolean;
35
+ // Keep OAuth verification available to signed-in accounts whose primary
36
+ // email cannot yet prove a respondent identity.
37
+ requireVerifiedEmail?: boolean;
38
+ // Require a real account identity and disable temporary verified-email
39
+ // respondent authentication.
40
+ requireOrgAuth?: boolean;
41
+ // When supplied, the route owns respondent identity selection and this
42
+ // module only renders that explicit choice.
43
+ identityMode?: 'NONE' | 'ACCOUNT' | 'RESPONDENT';
29
44
  // Public web form context (contact-gated account creation / respondent token)
30
45
  formPublicId?: string | null;
46
+ // Same-origin sign-in route opened for password and phone authentication
47
+ authenticationPopupHref?: string | null;
48
+ authenticationPopupLabel?: string;
49
+ // Same-origin route that revokes the current account session
50
+ signOutHref?: string;
31
51
  // Called after a real account sign-in flips the app into a logged-in state,
32
52
  // with the fresh auth token (e.g. to silently persist the SSR session cookie)
33
- onSignedIn?: (
34
- token: string,
35
- sessionBootstrapToken?: string | null,
36
- sessionPersisted?: boolean,
37
- ) => boolean | Promise<boolean>;
53
+ onSignedIn?: (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) => boolean | Promise<boolean>;
38
54
  // Called when authenticateOnly returned a temporary form respondent token
39
55
  onRespondentToken?: (token: string, email: string | null) => void;
40
56
  }
41
57
 
42
58
  /*
43
- * Inline Google/Microsoft sign-in that keeps the user on the current page.
59
+ * Render one compact provider action for the inline authentication form.
60
+ */
61
+ const InlineAuthFormOAuthButtonUI = memo(
62
+ (p: { disabled?: boolean; iconClassName?: string; iconName: string; label: string; loading?: boolean; onClick: () => void }) => {
63
+ return (
64
+ <button
65
+ aria-label={p.label}
66
+ className='btn outline av av_sm r h_center no_shrink bg'
67
+ disabled={p.disabled || p.loading}
68
+ onClick={p.onClick}
69
+ title={p.label}
70
+ type='button'
71
+ >
72
+ {p.loading ? (
73
+ <ActivityDots />
74
+ ) : (
75
+ <span className={p.iconClassName ?? 'ic_sm'}>
76
+ <Icon
77
+ name={p.iconName}
78
+ tryColor
79
+ />
80
+ </span>
81
+ )}
82
+ </button>
83
+ );
84
+ },
85
+ );
86
+
87
+ InlineAuthFormOAuthButtonUI.displayName = 'InlineAuthFormOAuthButtonUI';
88
+
89
+ /*
90
+ * Inline provider and popup sign-in that keeps the user on the current page.
44
91
  * The OAuth popup authenticates the user and the underlying hooks flip the
45
92
  * shared app state to logged-in (via onAccountLogin) with no navigation.
46
93
  * ANYONE web forms may pass authenticateOnly to accept account-less
47
94
  * respondents via a temporary token instead of forcing account creation.
48
95
  */
49
96
 
50
- const InlineAuthForm = (p: InlineAuthFormProps) => {
97
+ const InlineAuthForm = memo((p: InlineAuthFormProps) => {
51
98
  const {
52
99
  googleLabel,
53
100
  microsoftLabel,
101
+ phoneLabel,
54
102
  respondentEmail,
55
103
  accountMessage,
56
104
  authenticateOnly,
105
+ authenticationPopupHref,
106
+ authenticationPopupLabel = i18n.t('auth.sign_in'),
57
107
  formPublicId,
108
+ signOutHref = '/signout',
58
109
  onSignedIn,
59
110
  onRespondentToken,
111
+ requireOrgAuth,
112
+ requireVerifiedEmail,
113
+ identityMode,
60
114
  } = p;
115
+ const { dispatchApp } = useContext(AppContext);
116
+ const loginOptionsId = useId();
117
+ const [showLoginOptions, setShowLoginOptions] = useState(false);
118
+ const loginOptionsEvent = usePopOverEvent({ popOverId: loginOptionsId });
119
+ const { acknowledgePopOverEvent } = usePopOverActions();
61
120
 
62
- // A signed-in account takes precedence; otherwise a temporary respondent
63
- // token holder is identified by their verified email
64
- const { isLoggedIn, displayName, labelName } = useCurrentAccount();
65
- const signedInName = isLoggedIn
66
- ? displayName || labelName
67
- : respondentEmail || null;
121
+ /* Reveal the existing provider buttons after selecting the scoped menu action. */
122
+ useEffect(() => {
123
+ if (!loginOptionsEvent) return;
124
+ // Revealing the providers unmounts PopOverButton, whose cleanup starts the dismissal animation.
125
+ if (loginOptionsEvent.name === 'more_login_options') setShowLoginOptions(true);
126
+ acknowledgePopOverEvent(loginOptionsEvent.eventId);
127
+ }, [loginOptionsEvent]);
128
+
129
+ // The route-controlled mode takes precedence when supplied; other callers
130
+ // retain the component's account-first fallback behavior.
131
+ const { account, isLoggedIn, displayName, labelName, primaryOrganizationId } = useCurrentAccount();
132
+ const { myOrganizations, organization: primaryOrganization } = useOrgRelFromMyOrganizations(
133
+ requireOrgAuth ? primaryOrganizationId : null,
134
+ );
135
+ const primaryOrganizationName = primaryOrganization?.name || null;
136
+ const canSwitchOrganizations = !!requireOrgAuth && (myOrganizations?.length || 0) > 1;
137
+ const accountCanRespond = isLoggedIn && (!requireVerifiedEmail || (!!account?.email?.address && account.email.verified));
138
+ const accountRequiresEmailVerification = isLoggedIn && requireVerifiedEmail && !accountCanRespond;
139
+ const signedInName = identityMode
140
+ ? identityMode === 'ACCOUNT'
141
+ ? displayName || labelName
142
+ : identityMode === 'RESPONDENT'
143
+ ? respondentEmail || null
144
+ : null
145
+ : accountCanRespond
146
+ ? displayName || labelName
147
+ : respondentEmail || null;
148
+ const isNonUserEmailRespondent = !requireOrgAuth && identityMode === 'RESPONDENT' && !!respondentEmail;
149
+ const effectiveAuthenticateOnly = !requireOrgAuth && authenticateOnly;
150
+ const canUseEmail = !!effectiveAuthenticateOnly && !!formPublicId && !!onRespondentToken;
151
+ const showLoggedOutPrompt = !isLoggedIn && !!authenticationPopupHref && !isNonUserEmailRespondent;
152
+ const showSignedInIdentity = !!signedInName && !showLoggedOutPrompt && (!requireOrgAuth || !!primaryOrganizationName);
153
+ const showProviderActions = !isLoggedIn && (isNonUserEmailRespondent || showLoggedOutPrompt || !signedInName);
154
+ const organizationIdentityLoading = !!requireOrgAuth && isLoggedIn && (!myOrganizations || !primaryOrganization);
68
155
 
69
156
  /*
70
157
  * A real account sign-in already applied the logged-in app state; hand the
71
158
  * token to the caller for any follow-up (e.g. persisting the session cookie).
72
159
  */
73
160
  const onFinishSignIn = useCallback(
74
- (
75
- token: string,
76
- sessionBootstrapToken?: string | null,
77
- sessionPersisted?: boolean,
78
- ) => onSignedIn?.(token, sessionBootstrapToken, sessionPersisted) ?? false,
161
+ (token: string, sessionBootstrapToken?: string | null, sessionPersisted?: boolean) =>
162
+ onSignedIn?.(token, sessionBootstrapToken, sessionPersisted) ?? false,
79
163
  [onSignedIn],
80
164
  );
81
165
 
166
+ /*
167
+ * Apply the popup's cookie-backed account result through the same inline
168
+ * adoption flow used by provider authentication.
169
+ */
170
+ const onPopupAuthenticated = useCallback(
171
+ async (auth: any) => {
172
+ const authenticated = await onFinishSignIn(auth.token, null, true);
173
+ if (!authenticated) {
174
+ return false;
175
+ }
176
+
177
+ onAccountLogin({ ...auth, sessionBootstrapToken: null }, dispatchApp);
178
+ return true;
179
+ },
180
+ [dispatchApp, onFinishSignIn],
181
+ );
182
+ /* Adopt popup email verification without establishing an account session. */
183
+ const onPopupRespondentAuthenticated = useCallback(
184
+ (token: string, email: string) => {
185
+ if (!accountCanRespond && canUseEmail) onRespondentToken?.(token, email);
186
+ },
187
+ [accountCanRespond, canUseEmail, onRespondentToken],
188
+ );
189
+ const { openAuthenticationPopup, popupOpen } = useAuthenticationPopup({
190
+ href: authenticationPopupHref,
191
+ formPublicId: canUseEmail ? formPublicId : null,
192
+ onRespondentAuthenticated: canUseEmail ? onPopupRespondentAuthenticated : undefined,
193
+ onAuthenticated: onPopupAuthenticated,
194
+ });
195
+
196
+ /*
197
+ * Adopt a primary organization change without re-running the route's sign-in
198
+ * completion behavior for an account that was already authenticated.
199
+ */
200
+ const onOrganizationPopupAuthenticated = useCallback(
201
+ async (auth: any, completionMessage: AuthPopupCompletionMessage) => {
202
+ if (!auth.token || !auth.account?.id) {
203
+ return false;
204
+ }
205
+
206
+ onAccountLogin(
207
+ {
208
+ ...auth,
209
+ primaryOrganizationId: completionMessage.primaryOrganizationId || auth.primaryOrganizationId,
210
+ sessionBootstrapToken: null,
211
+ },
212
+ dispatchApp,
213
+ );
214
+ return true;
215
+ },
216
+ [dispatchApp],
217
+ );
218
+ const { openAuthenticationPopup: openOrganizationPopup, popupOpen: organizationPopupOpen } = useAuthenticationPopup({
219
+ href: canSwitchOrganizations ? '/auth/switch-orgs' : null,
220
+ onAuthenticated: onOrganizationPopupAuthenticated,
221
+ });
222
+ const [promptBeforeSignIn, promptAfterSignIn] = i18n
223
+ .t('auth.sign_in_to_complete_form', { signIn: '__SIGN_IN__' })
224
+ .split('__SIGN_IN__');
225
+
82
226
  const {
83
227
  onInitiateGoogleSignIn,
84
228
  oauthButtonDisabled: googleDisabled,
85
229
  waitingForOAuth: googleLoading,
86
- } = useContinueWithGoogle({ onFinishSignIn, onRespondentToken });
230
+ } = useContinueWithGoogle({
231
+ onFinishSignIn,
232
+ onRespondentToken: requireOrgAuth ? undefined : onRespondentToken,
233
+ });
87
234
  const {
88
235
  onInitiateMicrosoftSignIn,
89
236
  oauthButtonDisabled: microsoftDisabled,
90
237
  waitingForOAuth: microsoftLoading,
91
- } = useContinueWithMicrosoft({ onFinishSignIn, onRespondentToken });
238
+ } = useContinueWithMicrosoft({
239
+ onFinishSignIn,
240
+ onRespondentToken: requireOrgAuth ? undefined : onRespondentToken,
241
+ });
92
242
 
93
243
  const onGoogle = useCallback(() => {
94
- onInitiateGoogleSignIn(
95
- undefined,
96
- null,
97
- formPublicId ?? null,
98
- authenticateOnly,
99
- );
100
- }, [onInitiateGoogleSignIn, formPublicId, authenticateOnly]);
244
+ onInitiateGoogleSignIn(undefined, null, formPublicId ?? null, effectiveAuthenticateOnly);
245
+ }, [onInitiateGoogleSignIn, formPublicId, effectiveAuthenticateOnly]);
101
246
 
102
247
  const onMicrosoft = useCallback(() => {
103
- onInitiateMicrosoftSignIn(
104
- undefined,
105
- undefined,
106
- formPublicId ?? null,
107
- authenticateOnly,
248
+ onInitiateMicrosoftSignIn(undefined, undefined, formPublicId ?? null, effectiveAuthenticateOnly);
249
+ }, [onInitiateMicrosoftSignIn, formPublicId, effectiveAuthenticateOnly]);
250
+
251
+ /*
252
+ * Open the same email sign-in popup from the text link and email icon.
253
+ */
254
+ const onSignIn = useCallback(() => {
255
+ openAuthenticationPopup();
256
+ }, [openAuthenticationPopup]);
257
+
258
+ /*
259
+ * Open popup authentication directly on its phone verification screen.
260
+ */
261
+ const onPhone = useCallback(() => {
262
+ openAuthenticationPopup({ initialAuthMethod: 'phone' });
263
+ }, [openAuthenticationPopup]);
264
+
265
+ /*
266
+ * Open the authenticated primary organization selector in a popup window.
267
+ */
268
+ const onSwitchOrganization = useCallback(() => {
269
+ openOrganizationPopup();
270
+ }, [openOrganizationPopup]);
271
+
272
+ /*
273
+ * Navigate through the configured sign-out route from the icon action.
274
+ */
275
+ const onSignOut = useCallback(() => {
276
+ globalThis.location.assign(signOutHref);
277
+ }, [signOutHref]);
278
+
279
+ if (p.loading || organizationIdentityLoading) {
280
+ return (
281
+ <div
282
+ aria-busy='true'
283
+ className={cn('h_spread gap_sm min_w_0', p.className)}
284
+ >
285
+ <ActivityIndicator
286
+ className='ml_df'
287
+ size='sm'
288
+ />
289
+ {isLoggedIn && (
290
+ <a
291
+ className='text ft_sm cl_md link mx_df'
292
+ href={signOutHref}
293
+ >
294
+ {i18n.t('auth.sign_out')}
295
+ </a>
296
+ )}
297
+ </div>
108
298
  );
109
- }, [onInitiateMicrosoftSignIn, formPublicId, authenticateOnly]);
299
+ }
110
300
 
111
301
  return (
112
- <div className="h_item gap_sm min_w_0 f_wrap rel">
113
- {signedInName ? (
114
- <div className="h_item gap_8 min_w_0">
115
- <AvatarImg
116
- className="shift_up"
117
- displayName={signedInName}
118
- size="small"
119
- letterBackgroundClassName="bd_2 bd_lt bg"
120
- />
121
- <p className="ft_medium">
122
- {i18n.t('auth.logged_in_as_', { name: signedInName })}
123
- </p>
302
+ <div className={cn('h_spread gap_sm min_w_0 f_wrap rel', p.className)}>
303
+ {showSignedInIdentity ? (
304
+ <div className='h_item gap_8 min_w_0'>
305
+ {isNonUserEmailRespondent ? (
306
+ <Markdown
307
+ as='p'
308
+ preset='content_description'
309
+ className='cl_md ml_xs'
310
+ >
311
+ {i18n.t('auth.signed_in_as_email', {
312
+ emailAddress: respondentEmail,
313
+ })}
314
+ </Markdown>
315
+ ) : (
316
+ <>
317
+ <AvatarImg
318
+ className='shift_up'
319
+ displayName={signedInName}
320
+ size='small'
321
+ letterBackgroundClassName='bd_2 bd_lt bg'
322
+ />
323
+ <p className='ft_medium'>
324
+ {i18n.t(requireOrgAuth ? 'auth.logged_in_as_org_' : 'auth.logged_in_as_', {
325
+ name: signedInName,
326
+ orgName: primaryOrganizationName || '',
327
+ })}
328
+ </p>
329
+ </>
330
+ )}
124
331
  </div>
125
- ) : (
126
- (!!googleLabel || !!microsoftLabel) && (
127
- <div className="h_item gap_5 no_shrink">
128
- {!!googleLabel && (
129
- <PageFormHeaderOAuthButton
130
- iconName="brand-google-color"
131
- label={googleLabel}
332
+ ) : accountRequiresEmailVerification && !canUseEmail ? (
333
+ <TextWithLinks
334
+ as='p'
335
+ className='cl_md ml_xs'
336
+ linkClassName='u cl_bd'
337
+ >
338
+ {i18n.t('auth.verify_email_to_fill_form')}
339
+ </TextWithLinks>
340
+ ) : showLoggedOutPrompt || (accountRequiresEmailVerification && canUseEmail) ? (
341
+ <p className='ft_sm cl_md mx_df'>
342
+ {promptBeforeSignIn}
343
+ <button
344
+ className='text ft_sm cl_md link'
345
+ disabled={showLoggedOutPrompt ? googleDisabled || googleLoading : popupOpen}
346
+ onClick={showLoggedOutPrompt ? onGoogle : onSignIn}
347
+ type='button'
348
+ >
349
+ {showLoggedOutPrompt ? i18n.t('auth.sign_in_to_google') : authenticationPopupLabel}
350
+ </button>
351
+ {promptAfterSignIn}
352
+ </p>
353
+ ) : null}
354
+ <div className='h_item gap_5 no_shrink'>
355
+ {!isLoggedIn && !showLoginOptions ? (
356
+ <PopOverButton
357
+ as='button'
358
+ id={loginOptionsId}
359
+ position='bottom_right'
360
+ ariaLabel={i18n.t('auth.more_login_options')}
361
+ className='av av_sm h_center no_shrink link bg_hv r'
362
+ iface={{
363
+ name: 'PO_LIST',
364
+ variables: {
365
+ options: [{ __type: 'LIST_ITEM', name: 'more_login_options', value: true, text: i18n.t('auth.more_login_options') }],
366
+ },
367
+ }}
368
+ >
369
+ <span className='ic_sm'>
370
+ <Icon name='dots-vertical-filled' />
371
+ </span>
372
+ </PopOverButton>
373
+ ) : (
374
+ <>
375
+ {canUseEmail && !accountCanRespond ? (
376
+ <InlineAuthFormOAuthButtonUI
377
+ disabled={popupOpen}
378
+ iconName='read-email-at'
379
+ label={i18n.t('auth.sign_in_with_email')}
380
+ onClick={onSignIn}
381
+ />
382
+ ) : null}
383
+ {showProviderActions && phoneLabel && authenticationPopupHref ? (
384
+ <InlineAuthFormOAuthButtonUI
385
+ disabled={popupOpen}
386
+ iconName='phone-circle'
387
+ iconClassName='ic_df shift_up'
388
+ label={phoneLabel}
389
+ onClick={onPhone}
390
+ />
391
+ ) : null}
392
+ {showProviderActions && googleLabel ? (
393
+ <InlineAuthFormOAuthButtonUI
132
394
  disabled={googleDisabled}
395
+ iconName='brand-google-color'
396
+ label={googleLabel}
133
397
  loading={googleLoading}
134
398
  onClick={onGoogle}
135
399
  />
136
- )}
137
- {!!microsoftLabel && (
138
- <PageFormHeaderOAuthButton
139
- iconName="brand-microsoft-color"
140
- label={microsoftLabel}
400
+ ) : null}
401
+ {showProviderActions && microsoftLabel ? (
402
+ <InlineAuthFormOAuthButtonUI
141
403
  disabled={microsoftDisabled}
404
+ iconName='brand-microsoft-color'
405
+ label={microsoftLabel}
142
406
  loading={microsoftLoading}
143
407
  onClick={onMicrosoft}
144
408
  />
145
- )}
146
- </div>
147
- )
148
- )}
409
+ ) : null}
410
+ </>
411
+ )}
412
+ {isLoggedIn && canSwitchOrganizations ? (
413
+ <button
414
+ className='text ft_sm cl_md link ml_df'
415
+ disabled={organizationPopupOpen}
416
+ onClick={onSwitchOrganization}
417
+ type='button'
418
+ >
419
+ {i18n.t('org.switch_organization')}
420
+ </button>
421
+ ) : null}
422
+ {isLoggedIn && canSwitchOrganizations ? (
423
+ <TooltipButton
424
+ ariaLabel={i18n.t('auth.sign_out')}
425
+ className='cl_md link ml_5 mr_df ic_sm h_center lh_1 no_shrink'
426
+ message={i18n.t('auth.sign_out')}
427
+ onClick={onSignOut}
428
+ position='top'
429
+ >
430
+ <Icon name='box-arrow-right' />
431
+ </TooltipButton>
432
+ ) : isLoggedIn ? (
433
+ <a
434
+ className='text ft_sm cl_md link mx_df'
435
+ href={signOutHref}
436
+ >
437
+ {i18n.t('auth.sign_out')}
438
+ </a>
439
+ ) : null}
440
+ </div>
149
441
  {!!accountMessage &&
150
442
  (typeof accountMessage === 'string' ? (
151
- <TextWithLinks as="p" className="cl_md ml_xs" linkClassName="u cl_df">
443
+ <TextWithLinks
444
+ as='p'
445
+ className='cl_md ml_xs'
446
+ linkClassName='u cl_df'
447
+ >
152
448
  {accountMessage}
153
449
  </TextWithLinks>
154
450
  ) : (
155
- <p className="cl_md ft_md">{accountMessage}</p>
451
+ <p className='cl_md ft_md'>{accountMessage}</p>
156
452
  ))}
157
453
  </div>
158
454
  );
159
- };
455
+ });
456
+
457
+ InlineAuthForm.displayName = 'InlineAuthForm';
160
458
 
161
- export default memo(InlineAuthForm);
459
+ export default InlineAuthForm;
@@ -1,17 +1,11 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
2
  import type { AccountSessionData } from '@jsb188/app/types/auth.d.ts';
3
- import {
4
- useRevokeMyAccountSession,
5
- useRevokeMyOtherAccountSessions,
6
- } from '@jsb188/graphql/hooks/use-auth-mtn';
3
+ import { useRevokeMyAccountSession, useRevokeMyOtherAccountSessions } from '@jsb188/graphql/hooks/use-auth-mtn';
7
4
  import { useMyAccountSessions } from '@jsb188/graphql/hooks/use-auth-qry';
8
5
  import { FullWidthButton } from '@jsb188/react-web/ui/Button';
9
6
  import { BigLoading } from '@jsb188/react-web/ui/Loading';
10
7
  import { useMemo, useState } from 'react';
11
- import {
12
- type ManagedSessionListItem,
13
- ManagedSessionListUI,
14
- } from '../ui/ManagedSessionUI.tsx';
8
+ import { type ManagedSessionListItem, ManagedSessionListUI } from '../ui/ManagedSessionUI.tsx';
15
9
 
16
10
  /*
17
11
  * Format one managed-session timestamp for the current browser locale.
@@ -24,25 +18,18 @@ function formatManagedSessionDate(value?: string | null) {
24
18
  /*
25
19
  * Convert server session rows into display-ready immutable list items.
26
20
  */
27
- export function mapManagedSessionItems(
28
- sessions?: AccountSessionData[] | null,
29
- ): ManagedSessionListItem[] {
30
- return (sessions || [])
21
+ export function mapManagedSessionItems(sessions?: AccountSessionData[] | null): ManagedSessionListItem[] {
22
+ if (!sessions?.length) return [];
23
+ return sessions
31
24
  .filter((session) => !session.revokedAt)
32
25
  .map((session) => ({
33
26
  ...session,
34
- displayName:
35
- session.deviceName ||
36
- session.userAgent ||
37
- i18n.t('account.session_unknown_device'),
27
+ displayName: session.deviceName || session.userAgent || i18n.t('account.session_unknown_device'),
38
28
  displayExpiresAt: formatManagedSessionDate(session.absoluteExpiresAt),
39
29
  displayLastActivityAt: formatManagedSessionDate(session.lastActivityAt),
40
30
  }))
41
31
  .sort(
42
- (a, b) =>
43
- Number(b.current) - Number(a.current) ||
44
- new Date(b.lastActivityAt).getTime() -
45
- new Date(a.lastActivityAt).getTime(),
32
+ (a, b) => Number(b.current) - Number(a.current) || new Date(b.lastActivityAt).getTime() - new Date(a.lastActivityAt).getTime(),
46
33
  );
47
34
  }
48
35
 
@@ -52,35 +39,28 @@ export function mapManagedSessionItems(
52
39
  export function ManagedSessions() {
53
40
  const { accountSessions, loading } = useMyAccountSessions();
54
41
  const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
55
- const [revokedSessionIds, setRevokedSessionIds] = useState<Set<string>>(
56
- () => new Set(),
57
- );
42
+ const [revokedSessionIds, setRevokedSessionIds] = useState<Set<string>>(() => new Set());
58
43
  const [hideOtherSessions, setHideOtherSessions] = useState(false);
59
44
  const { revokeMyAccountSession } = useRevokeMyAccountSession({
60
45
  onCompleted: (data, _error, variables) => {
61
46
  if (data?.revokeMyAccountSession && variables?.sessionId) {
62
- setRevokedSessionIds((current) =>
63
- new Set(current).add(variables.sessionId),
64
- );
47
+ setRevokedSessionIds((current) => new Set(current).add(variables.sessionId));
65
48
  }
66
49
  setSavingSessionId(null);
67
50
  },
68
51
  onError: () => setSavingSessionId(null),
69
52
  });
70
- const { revokeMyOtherAccountSessions, saving: savingOthers } =
71
- useRevokeMyOtherAccountSessions({
72
- onCompleted: (data) => {
73
- if (data?.revokeMyOtherAccountSessions) {
74
- setHideOtherSessions(true);
75
- }
76
- },
77
- });
53
+ const { revokeMyOtherAccountSessions, saving: savingOthers } = useRevokeMyOtherAccountSessions({
54
+ onCompleted: (data) => {
55
+ if (data?.revokeMyOtherAccountSessions) {
56
+ setHideOtherSessions(true);
57
+ }
58
+ },
59
+ });
78
60
  const items = useMemo(
79
61
  () =>
80
62
  mapManagedSessionItems(accountSessions).filter(
81
- (session) =>
82
- !revokedSessionIds.has(session.id) &&
83
- (!hideOtherSessions || session.current),
63
+ (session) => !revokedSessionIds.has(session.id) && (!hideOtherSessions || session.current),
84
64
  ),
85
65
  [accountSessions, hideOtherSessions, revokedSessionIds],
86
66
  );
@@ -99,15 +79,15 @@ export function ManagedSessions() {
99
79
 
100
80
  if (loading && !accountSessions) {
101
81
  return (
102
- <div className="h_160 v_center">
82
+ <div className='h_160 v_center'>
103
83
  <BigLoading />
104
84
  </div>
105
85
  );
106
86
  }
107
87
 
108
88
  return (
109
- <div className="max_w_600">
110
- <p className="cl_lt mb_sm">{i18n.t('account.sessions_desc')}</p>
89
+ <div className='max_w_600'>
90
+ <p className='cl_lt mb_sm'>{i18n.t('account.sessions_desc')}</p>
111
91
  <ManagedSessionListUI
112
92
  items={items}
113
93
  emptyText={i18n.t('account.session_none')}
@@ -121,8 +101,8 @@ export function ManagedSessions() {
121
101
  {items.length <= 1 ? null : (
122
102
  <FullWidthButton
123
103
  fullWidth={false}
124
- className="mt_md"
125
- preset="outline"
104
+ className='mt_md'
105
+ preset='outline'
126
106
  loading={savingOthers}
127
107
  disabled={savingOthers}
128
108
  onClick={() => revokeMyOtherAccountSessions()}