@jsb188/auth-web 1.1.11 → 1.1.13

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