A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): add the full-screen account switcher overlay
Hampus994bee5ea2c1
diff --git a/fluxer_app/src/features/auth/commands/AccountSwitcherModalCommands.tsx b/fluxer_app/src/features/auth/commands/AccountSwitcherModalCommands.tsxindex 70ce47903..a7d70fa0a 100644--- a/fluxer_app/src/features/auth/commands/AccountSwitcherModalCommands.tsx+++ b/fluxer_app/src/features/auth/commands/AccountSwitcherModalCommands.tsx@@ -1,27 +1,62 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {AccountSwitcherModalProps} from '@app/features/auth/components/accounts/AccountSwitcherModal';+import type {+ AccountSwitcherInitialView,+ AccountSwitcherModalProps,+} from '@app/features/auth/components/accounts/AccountSwitcherModal';import {Logger} from '@app/features/platform/utils/AppLogger';import {loadLazyModule} from '@app/features/platform/utils/LazyModuleLoader';import * as ModalCommands from '@app/features/ui/commands/ModalCommands';import {modal} from '@app/features/ui/commands/ModalCommands';+import Modal from '@app/features/ui/state/Modal';const logger = new Logger('AccountSwitcherModalCommands');+const ACCOUNT_SWITCHER_MODAL_KEY = 'account-switcher';+let openSerial = 0;-export function openAccountSwitcherModal(props: AccountSwitcherModalProps, key: string | null): void {+interface AccountSwitcherOpenOptions extends Partial<Omit<AccountSwitcherModalProps, 'initialView'>> {+ readonly view?: AccountSwitcherInitialView;+}++function resolveProps(options: AccountSwitcherOpenOptions): AccountSwitcherModalProps {+ const {view, ...props} = options;+ return {+ closeCurrentAccountOnSelect: props.closeCurrentAccountOnSelect ?? true,+ initialReloginAccount: props.initialReloginAccount ?? null,+ redirectAfterLogin: props.redirectAfterLogin ?? null,+ switchAccount: props.switchAccount ?? null,+ initialView: view ?? 'accounts',+ focusAccountKey: props.focusAccountKey ?? null,+ 'data-flx': props['data-flx'],+ };+}++export function openAccountSwitcherModal(options: AccountSwitcherOpenOptions = {}, key: string | null = null): void {+ const props = resolveProps(options);+ openSerial += 1;+ const instanceKey = openSerial;void loadLazyModule(() => import('@app/features/auth/components/accounts/AccountSwitcherModal')).then(({default: AccountSwitcherModal}) => {const render = modal(() => (<AccountSwitcherModal+ key={instanceKey}data-flx="auth.account-switcher-modal-commands.open-account-switcher-modal.account-switcher-modal"{...props}/>));- if (key === null) {- ModalCommands.push(render);- return;- }- ModalCommands.pushWithKey(render, key);+ ModalCommands.pushWithKey(render, key ?? ACCOUNT_SWITCHER_MODAL_KEY);}).catch((error: unknown) => logger.error('Failed to load the account switcher', error));}++export function isAccountSwitcherModalOpen(): boolean {+ return Modal.hasModal(ACCOUNT_SWITCHER_MODAL_KEY);+}++export function toggleAccountSwitcherModal(options: AccountSwitcherOpenOptions = {}): void {+ if (ModalCommands.getTopModalKey() === ACCOUNT_SWITCHER_MODAL_KEY) {+ ModalCommands.popWithKey(ACCOUNT_SWITCHER_MODAL_KEY);+ return;+ }+ openAccountSwitcherModal(options);+}diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountsView.tsx b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountsView.tsxnew file mode 100644index 000000000..f848c6c04--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherAccountsView.tsx@@ -0,0 +1,271 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import Accessibility from '@app/features/accessibility/state/Accessibility';+import {DragItemType} from '@app/features/app/components/layout/types/DndTypes';+import {AccountSwitcherGrid} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherGrid';+import {+ MANAGE_HINT_DESCRIPTOR,+ OPEN_SHORTCUT_HINT_DESCRIPTOR,+ SLOT_KEYS_HINT_DESCRIPTOR,+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherMessages';+import styles from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherOverlay.module.css';+import {remFromPx} from '@app/features/theme/layout/RemFromPx';+import {Button} from '@app/features/ui/button/Button';+import {Scroller} from '@app/features/ui/components/Scroller';+import FocusRing from '@app/features/ui/focus_ring/FocusRing';+import {useDragAutoScroll} from '@app/features/ui/hooks/useDragAutoScroll';+import {KeybindHint} from '@app/features/ui/keybind_hint/KeybindHint';+import {useLingui} from '@lingui/react/macro';+import {MagnifyingGlassIcon} from '@phosphor-icons/react';+import clsx from 'clsx';+import {makeAutoObservable, observableRef} from 'mobx';+import {observer} from 'mobx-react-lite';+import type React from 'react';+import {type SetStateAction, useCallback} from 'react';+import {useDragLayer} from 'react-dnd';++interface FocusRequest {+ readonly key: string;+ readonly serial: number;+}+interface InteractionInitialState {+ readonly isManaging: boolean;+ readonly activeKey: string;+}+export class AccountSwitcherInteraction {+ isManaging: boolean;+ activeKey: string | null;+ menuKey: string | null = null;+ dragOrder: ReadonlyArray<string> | null = null;+ announcement = '';+ query = '';+ focusRequest: FocusRequest | null = null;+ private focusSerial = 0;+ private menuOwner: string | null = null;+ constructor({isManaging, activeKey}: InteractionInitialState) {+ this.isManaging = isManaging;+ this.activeKey = activeKey;+ makeAutoObservable<this, 'focusSerial' | 'menuOwner'>(+ this,+ {+ dragOrder: observableRef,+ focusRequest: observableRef,+ focusSerial: false,+ menuOwner: false,+ },+ {autoBind: true},+ );+ }+ setIsManaging(value: SetStateAction<boolean>): void {+ this.isManaging = typeof value === 'function' ? value(this.isManaging) : value;+ }+ setActiveKey(value: string | null): void {+ this.activeKey = value;+ }+ setDragOrder(value: SetStateAction<ReadonlyArray<string> | null>): void {+ this.dragOrder = typeof value === 'function' ? value(this.dragOrder) : value;+ }+ setAnnouncement(value: string): void {+ this.announcement = value;+ }+ setQuery(value: string): void {+ this.query = value;+ }+ setFocusRequest(value: SetStateAction<FocusRequest | null>): void {+ this.focusRequest = typeof value === 'function' ? value(this.focusRequest) : value;+ }+ requestFocus(key: string): void {+ this.focusSerial += 1;+ this.setActiveKey(key);+ this.setFocusRequest({key, serial: this.focusSerial});+ }+ openMenu(key: string): void {+ this.menuOwner = key;+ this.menuKey = key;+ }+ closeMenu(key: string): void {+ if (this.menuOwner !== key) {+ return;+ }+ this.menuOwner = null;+ this.menuKey = null;+ this.requestFocus(key);+ }+}+interface AccountsViewProps {+ readonly headingId: string;+ readonly heading: string;+ readonly isManaging: boolean;+ readonly showSlotHint: boolean;+ readonly showSearch: boolean;+ readonly searchRef: React.RefObject<HTMLInputElement | null>;+ readonly searchId: string;+ readonly query: string;+ readonly searchPlaceholder: string | undefined;+ readonly searchLabel: string | undefined;+ readonly setQuery: (query: string) => void;+ readonly emptyMessage: string | null;+ readonly gridProps: React.ComponentProps<typeof AccountSwitcherGrid>;+ readonly gridNode: HTMLUListElement | null;+ readonly announcement: string;+ readonly signOutExpiredLabel: string | null;+ readonly signOutExpiredPending: boolean;+ readonly onSignOutExpired: () => void;+ readonly isBusy: boolean;+ readonly toggleManaging: () => void;+ readonly manageLabel: string;+}+export function AccountSwitcherAccountsView({+ headingId,+ heading,+ isManaging,+ showSlotHint,+ showSearch,+ searchRef,+ searchId,+ query,+ searchPlaceholder,+ searchLabel,+ setQuery,+ emptyMessage,+ gridProps,+ gridNode,+ announcement,+ signOutExpiredLabel,+ signOutExpiredPending,+ onSignOutExpired,+ isBusy,+ toggleManaging,+ manageLabel,+}: AccountsViewProps): React.ReactElement {+ return (+ <div className={styles.stage} data-flx="auth.accounts.account-switcher-modal.stage">+ <div className={styles.header} data-flx="auth.accounts.account-switcher-modal.header">+ <h2 id={headingId} className={styles.heading} data-flx="auth.accounts.account-switcher-modal.heading">+ {heading}+ </h2>+ <SwitcherSubline+ isManaging={isManaging}+ showSlotHint={showSlotHint}+ data-flx="auth.accounts.account-switcher-modal.switcher-subline"+ />+ </div>+ {showSearch ? (+ <FocusRing within offset={-2} data-flx="auth.accounts.account-switcher-modal.search-focus-ring">+ <div className={styles.search} data-flx="auth.accounts.account-switcher-modal.search">+ <MagnifyingGlassIcon+ className={styles.searchIcon}+ size={remFromPx(16)}+ weight="bold"+ aria-hidden="true"+ data-flx="auth.accounts.account-switcher-modal.search-glass"+ />+ <input+ ref={searchRef}+ id={searchId}+ type="search"+ className={styles.searchInput}+ value={query}+ placeholder={searchPlaceholder}+ aria-label={searchLabel}+ autoComplete="off"+ spellCheck={false}+ onChange={(event) => setQuery(event.target.value)}+ data-flx="auth.accounts.account-switcher-modal.search-input"+ />+ </div>+ </FocusRing>+ ) : null}+ <Scroller+ className={styles.scroller}+ contentClassName={styles.scrollerContent}+ fade={false}+ data-flx="auth.accounts.account-switcher-modal.scroller"+ >+ {emptyMessage !== null ? (+ <p className={styles.empty} role="status" data-flx="auth.accounts.account-switcher-modal.empty">+ {emptyMessage}+ </p>+ ) : null}+ <AccountSwitcherGrid {...gridProps} data-flx="auth.accounts.account-switcher-modal.grid" />+ </Scroller>+ <AccountDragAutoScroll gridNode={gridNode} data-flx="auth.accounts.account-switcher-modal.drag-auto-scroll" />+ <span+ className={styles.srOnly}+ role="status"+ aria-live="polite"+ data-flx="auth.accounts.account-switcher-modal.announcement"+ >+ {announcement}+ </span>+ <div className={styles.actions} data-flx="auth.accounts.account-switcher-modal.actions">+ {signOutExpiredLabel !== null ? (+ <Button+ variant="secondary"+ disabled={isBusy}+ submitting={signOutExpiredPending}+ onClick={onSignOutExpired}+ data-flx="auth.accounts.account-switcher-modal.button.sign-out-expired"+ >+ {signOutExpiredLabel}+ </Button>+ ) : null}+ <Button+ variant={isManaging ? 'primary' : 'secondary'}+ disabled={isBusy}+ aria-pressed={isManaging}+ onClick={toggleManaging}+ data-flx="auth.accounts.account-switcher-modal.button.manage"+ >+ {manageLabel}+ </Button>+ </div>+ </div>+ );+}++function AccountDragAutoScroll({gridNode}: {readonly gridNode: HTMLElement | null}): null {+ const isDraggingAccount = useDragLayer(+ (monitor) => monitor.isDragging() && monitor.getItemType() === DragItemType.ACCOUNT_TILE,+ );+ const getScrollElement = useCallback(+ () => gridNode?.closest<HTMLElement>('[data-fluxer-scroll-container="true"]') ?? null,+ [gridNode],+ );+ useDragAutoScroll({active: isDraggingAccount, getScrollElement});+ return null;+}++const SwitcherSubline = observer(function SwitcherSubline({+ isManaging,+ showSlotHint,+}: {+ readonly isManaging: boolean;+ readonly showSlotHint: boolean;+}): React.ReactElement | null {+ const {i18n} = useLingui();+ if (isManaging) {+ return (+ <p className={styles.subline} data-flx="auth.accounts.account-switcher-modal.subline">+ {i18n._(MANAGE_HINT_DESCRIPTOR)}+ </p>+ );+ }+ if (Accessibility.hideKeyboardHints) {+ return null;+ }+ return (+ <p className={clsx(styles.subline, styles.sublineKeys)} data-flx="auth.accounts.account-switcher-modal.subline">+ {showSlotHint ? (+ <span data-flx="auth.accounts.account-switcher-modal.slot-hint">{i18n._(SLOT_KEYS_HINT_DESCRIPTOR)}</span>+ ) : null}+ <span className={styles.sublineShortcut} data-flx="auth.accounts.account-switcher-modal.shortcut-hint">+ {i18n._(OPEN_SHORTCUT_HINT_DESCRIPTOR)}+ <KeybindHint+ action="system_open_account_switcher"+ data-flx="auth.accounts.account-switcher-modal.keybind-hint"+ />+ </span>+ </p>+ );+});diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherOverlay.tsx b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherOverlay.tsxnew file mode 100644index 000000000..31cf76021--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherOverlay.tsx@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {useModalBackHandler} from '@app/features/app/hooks/useModalBackHandler';+import styles from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherOverlay.module.css';+import {+ captureSwitcherReturnTarget,+ restoreFocusAfterSwitcher,+} from '@app/features/auth/components/accounts/account_switcher/AccountSwitcherReturnFocus';+import * as PopoutCommands from '@app/features/ui/commands/PopoutCommands';+import FocusRingScope from '@app/features/ui/focus_ring/FocusRingScope';+import {usePrefersReducedMotion} from '@app/features/ui/hooks/usePrefersReducedMotion';+import {usePortalHost} from '@app/features/ui/overlay/PortalHostContext';+import LayerManager, {LayerType} from '@app/features/ui/state/LayerManager';+import OverlayStack from '@app/features/ui/state/OverlayStack';+import {ModalStackContext} from '@app/features/ui/utils/ModalStackContext';+import {FloatingFocusManager, FloatingPortal, useFloating} from '@floating-ui/react';+import {AnimatePresence, motion, useIsPresent} from 'framer-motion';+import type React from 'react';+import {useCallback, useContext, useEffect, useId, useRef, useState} from 'react';++const STAGE_FADE_SECONDS = 0.16;+const INTERACTIVE_SELECTOR = 'button, a, input, textarea, select, label, [data-switcher-card]';++function isEmptyAreaTarget(target: EventTarget | null): boolean {+ return target instanceof Element && target.closest(INTERACTIVE_SELECTOR) == null;+}+const VIEW_FADE_SECONDS = 0.18;+const VIEW_RISE_PX = 12;++interface AccountSwitcherOverlayProps {+ readonly viewKey: string;+ readonly labelledBy: string;+ readonly isBusy: boolean;+ readonly hasSwitchedAccount: () => boolean;+ readonly onEmptyAreaClick: () => void;+ readonly onEscape: () => void;+ readonly onKeyDown: (event: React.KeyboardEvent<HTMLDivElement>) => void;+ readonly children: React.ReactNode;+}++export function AccountSwitcherOverlay({+ viewKey,+ labelledBy,+ isBusy,+ hasSwitchedAccount,+ onEmptyAreaClick,+ onEscape,+ onKeyDown,+ children,+}: AccountSwitcherOverlayProps): React.ReactElement {+ const reducedMotion = usePrefersReducedMotion();+ const portalHost = usePortalHost();+ const ownerDocument = portalHost?.ownerDocument ?? document;+ const {isVisible, isTopmost} = useContext(ModalStackContext);+ const isInteractive = isVisible && isTopmost;+ const pointerDownOnEmptyRef = useRef(false);+ const handlePointerDownCapture = (event: React.PointerEvent<HTMLDivElement>) => {+ pointerDownOnEmptyRef.current = isEmptyAreaTarget(event.target);+ };+ const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {+ const startedOnEmpty = pointerDownOnEmptyRef.current;+ pointerDownOnEmptyRef.current = false;+ if (event.button !== 0 || !startedOnEmpty || !isEmptyAreaTarget(event.target)) {+ return;+ }+ onEmptyAreaClick();+ };+ const rootRef = useRef<HTMLDivElement | null>(null);+ const dialogRef = useRef<HTMLDivElement | null>(null);+ const [returnTarget] = useState(() => captureSwitcherReturnTarget(ownerDocument));+ const hasSwitchedAccountRef = useRef(hasSwitchedAccount);+ hasSwitchedAccountRef.current = hasSwitchedAccount;+ const focusRestoredRef = useRef(false);+ const restoreFocus = useCallback(() => {+ if (focusRestoredRef.current) return;+ focusRestoredRef.current = true;+ restoreFocusAfterSwitcher(ownerDocument, {+ overlay: rootRef.current,+ returnTarget,+ switchedAccount: hasSwitchedAccountRef.current(),+ });+ }, [ownerDocument, returnTarget]);+ const isPresent = useIsPresent();+ useEffect(() => {+ if (!isPresent) restoreFocus();+ }, [isPresent, restoreFocus]);+ useEffect(() => restoreFocus, [restoreFocus]);+ const {refs, context} = useFloating({open: true});+ const setDialogRef = useCallback(+ (node: HTMLDivElement | null) => {+ dialogRef.current = node;+ refs.setFloating(node);+ },+ [refs],+ );+ const [zIndex, setZIndex] = useState<number | null>(null);+ useEffect(() => {+ setZIndex(OverlayStack.acquire());+ return () => OverlayStack.release();+ }, []);+ useEffect(() => {+ PopoutCommands.closeAllForDocument(ownerDocument);+ }, [ownerDocument]);+ const escapeRef = useRef(onEscape);+ escapeRef.current = onEscape;+ const layerKey = useId();+ useEffect(() => {+ LayerManager.addLayer(LayerType.MODAL, layerKey, () => escapeRef.current());+ return () => LayerManager.removeLayer(LayerType.MODAL, layerKey);+ }, [layerKey]);+ useModalBackHandler(onEscape);+ const fade = reducedMotion ? {duration: 0} : {duration: STAGE_FADE_SECONDS, ease: 'easeOut' as const};+ const viewInitial = reducedMotion ? {opacity: 0} : {opacity: 0, y: VIEW_RISE_PX};+ const viewExit = reducedMotion ? {opacity: 0} : {opacity: 0, y: -VIEW_RISE_PX};+ return (+ <FloatingPortal root={portalHost ?? undefined} data-flx="auth.accounts.account-switcher.overlay.portal">+ <motion.div+ ref={rootRef}+ className={styles.root}+ style={{+ zIndex: zIndex ?? OverlayStack.peek(),+ pointerEvents: isInteractive ? 'auto' : 'none',+ visibility: isVisible ? 'visible' : 'hidden',+ }}+ data-reduced-motion={reducedMotion ? 'true' : 'false'}+ initial={{opacity: 0}}+ animate={{opacity: 1}}+ exit={{opacity: 0}}+ transition={fade}+ onPointerDownCapture={handlePointerDownCapture}+ onClick={handleClick}+ data-flx="auth.accounts.account-switcher.overlay.root"+ >+ <div+ className={styles.backdrop}+ aria-hidden="true"+ data-flx="auth.accounts.account-switcher.overlay.backdrop"+ />+ <FloatingFocusManager+ context={context}+ initialFocus={-1}+ disabled={!isInteractive}+ returnFocus={false}+ getInsideElements={() => {+ const inside: Array<Element> = [];+ const popoutsRoot = ownerDocument.querySelector('[data-popouts-root]');+ if (popoutsRoot != null) inside.push(popoutsRoot);+ ownerDocument.querySelectorAll('[data-floating-ui-portal]').forEach((element) => inside.push(element));+ return inside;+ }}+ data-flx="auth.accounts.account-switcher.overlay.focus-manager"+ >+ <div+ ref={setDialogRef}+ className={styles.dialog}+ role="dialog"+ aria-modal="true"+ aria-labelledby={labelledBy}+ aria-busy={isBusy}+ tabIndex={-1}+ onKeyDown={onKeyDown}+ data-account-switcher-overlay="true"+ data-flx="auth.accounts.account-switcher.overlay.dialog"+ >+ <FocusRingScope containerRef={dialogRef} data-flx="auth.accounts.account-switcher.overlay.focus-ring-scope">+ <AnimatePresence mode="wait" initial={false} data-flx="auth.accounts.account-switcher.overlay.views">+ <motion.div+ key={viewKey}+ className={styles.view}+ initial={viewInitial}+ animate={{opacity: 1, y: 0}}+ exit={viewExit}+ transition={+ reducedMotion ? {duration: VIEW_FADE_SECONDS} : {duration: VIEW_FADE_SECONDS, ease: 'easeOut'}+ }+ data-flx="auth.accounts.account-switcher.overlay.view"+ >+ {children}+ </motion.div>+ </AnimatePresence>+ </FocusRingScope>+ </div>+ </FloatingFocusManager>+ </motion.div>+ </FloatingPortal>+ );+}diff --git a/fluxer_app/src/features/auth/utils/AccountSwitcherModalUtils.tsx b/fluxer_app/src/features/auth/utils/AccountSwitcherModalUtils.tsxindex acbc71f83..5e1502dc8 100644--- a/fluxer_app/src/features/auth/utils/AccountSwitcherModalUtils.tsx+++ b/fluxer_app/src/features/auth/utils/AccountSwitcherModalUtils.tsx@@ -1,10 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport i18n from '@app/app/I18n';+import {Routes} from '@app/app/Routes';import {showGenericErrorModal} from '@app/features/app/components/alerts/GenericErrorModalCommands';import {Endpoints} from '@app/features/app/constants/Endpoints';import {resolveAccountInstanceLabel} from '@app/features/auth/AccountDisplayUtils';import {INSTANCE_UNAVAILABLE_DESCRIPTOR} from '@app/features/auth/AuthMessageDescriptors';+import {openAccountSwitcherModal} from '@app/features/auth/commands/AccountSwitcherModalCommands';import {AccountInstanceUnavailableError} from '@app/features/auth/state/AccountAccess';import {getAccountKey} from '@app/features/auth/state/AccountStorageKey';import {switcherAccounts} from '@app/features/auth/state/AccountSwitcherAccounts';@@ -45,7 +47,21 @@ const INSTANCE_UNAVAILABLE_UNNAMED_BODY_DESCRIPTOR = msg({const logger = new Logger('AccountSwitcherModalUtils');const STORED_ACCOUNT_LOGOUT_TIMEOUT_MS = 5000;-function showAccountSwitcherErrorModal(message: MessageDescriptor): void {+export type AccountSwitcherErrorHandler = (message: string) => void;++function instanceUnavailableMessage(account: Account): string {+ const instanceLabel = resolveAccountInstanceLabel(account);+ if (instanceLabel != null && instanceLabel.length > 0) {+ return i18n._(INSTANCE_UNAVAILABLE_NAMED_BODY_DESCRIPTOR, {instanceLabel});+ }+ return i18n._(INSTANCE_UNAVAILABLE_UNNAMED_BODY_DESCRIPTOR);+}++function reportAccountSwitcherError(message: MessageDescriptor, onError: AccountSwitcherErrorHandler | null): void {+ if (onError != null) {+ onError(i18n._(message));+ return;+ }showGenericErrorModal({title: () => i18n._(SOMETHING_WENT_WRONG_DESCRIPTOR),message: () => i18n._(message),@@ -54,16 +70,14 @@ function showAccountSwitcherErrorModal(message: MessageDescriptor): void {});}-function showAccountInstanceUnavailableModal(account: Account): void {- const instanceLabel = resolveAccountInstanceLabel(account);+function reportAccountInstanceUnavailable(account: Account, onError: AccountSwitcherErrorHandler | null): void {+ if (onError != null) {+ onError(instanceUnavailableMessage(account));+ return;+ }showGenericErrorModal({title: () => i18n._(INSTANCE_UNAVAILABLE_DESCRIPTOR),- message: () => {- if (instanceLabel != null && instanceLabel.length > 0) {- return i18n._(INSTANCE_UNAVAILABLE_NAMED_BODY_DESCRIPTOR, {instanceLabel});- }- return i18n._(INSTANCE_UNAVAILABLE_UNNAMED_BODY_DESCRIPTOR);- },+ message: () => instanceUnavailableMessage(account),dataFlx: 'auth.account-switcher-modal-utils.instance-unavailable-modal',defer: true,});@@ -74,31 +88,37 @@ export interface AccountSwitcherLogic {readonly currentAccount: Account | null;readonly currentAccountKey: string | null;readonly isBusy: boolean;- readonly handleSelectAccount: (account: Account) => void;readonly handleSwitchAccount: (accountKey: string) => Promise<void>;readonly handleLogout: () => Promise<void>;readonly handleLogoutStoredAccount: (account: Account) => Promise<void>;}export interface AccountSwitcherLogicOptions {- readonly onSelectCurrent?: (() => void) | null;readonly onSessionExpired: ((account: Account) => void) | null;- readonly redirectAfterSwitch: string | null;readonly switchAccount: ((accountKey: string) => Promise<void>) | null;}-export interface SwitchStoredAccountRequest extends AccountSwitcherLogicOptions {+export interface SwitchStoredAccountRequest {readonly accountKey: string;- readonly onSuccess: (() => void) | null;+ readonly redirectAfterSwitch: string | null;+ readonly onSessionExpired?: ((account: Account) => void) | null;+ readonly switchAccount?: ((accountKey: string) => Promise<void>) | null;+ readonly onSuccess?: (() => void) | null;+ readonly onError?: AccountSwitcherErrorHandler | null;+}++function openReloginInSwitcher(account: Account): void {+ openAccountSwitcherModal({initialReloginAccount: account});}interface ExpiredStoredAccountRequest {readonly account: Account | null;readonly error: unknown;readonly onSessionExpired: ((account: Account) => void) | null;+ readonly onError: AccountSwitcherErrorHandler | null;}-function handleExpiredStoredAccount({account, error, onSessionExpired}: ExpiredStoredAccountRequest): boolean {+function handleExpiredStoredAccount({account, error, onSessionExpired, onError}: ExpiredStoredAccountRequest): boolean {if (!(error instanceof SessionExpiredError) || account == null) {return false;}@@ -107,16 +127,17 @@ function handleExpiredStoredAccount({account, error, onSessionExpired}: ExpiredSreturn true;}logger.warn('Stored account session expired while switching', error);- showAccountSwitcherErrorModal(WE_COULDN_T_SWITCH_ACCOUNTS_PLEASE_TRY_AGAIN_DESCRIPTOR);+ reportAccountSwitcherError(WE_COULDN_T_SWITCH_ACCOUNTS_PLEASE_TRY_AGAIN_DESCRIPTOR, onError);return true;}export async function switchStoredAccountFromSwitcher({accountKey,- onSessionExpired,- onSuccess,+ onSessionExpired = openReloginInSwitcher,+ onSuccess = null,+ onError = null,redirectAfterSwitch,- switchAccount,+ switchAccount = null,}: SwitchStoredAccountRequest): Promise<void> {if (Accounts.isSwitching || Accounts.isLoading) {return;@@ -133,19 +154,60 @@ export async function switchStoredAccountFromSwitcher({}} catch (error) {const preparedAccount = Accounts.getAccount(accountKey) ?? account;- if (handleExpiredStoredAccount({account: preparedAccount, error, onSessionExpired})) {+ if (handleExpiredStoredAccount({account: preparedAccount, error, onSessionExpired, onError})) {return;}logger.error('Failed to switch account', error);if (error instanceof AccountInstanceUnavailableError && preparedAccount != null) {- showAccountInstanceUnavailableModal(preparedAccount);+ reportAccountInstanceUnavailable(preparedAccount, onError);return;}- showAccountSwitcherErrorModal(WE_COULDN_T_SWITCH_ACCOUNTS_PLEASE_TRY_AGAIN_DESCRIPTOR);+ reportAccountSwitcherError(WE_COULDN_T_SWITCH_ACCOUNTS_PLEASE_TRY_AGAIN_DESCRIPTOR, onError);+ }+}++export interface SavedAccountSwitchRequest {+ readonly accountKey: string;+ readonly redirectAfterSwitch?: string;+ readonly onSessionExpired?: ((account: Account) => void) | null;+ readonly onSelectCurrent?: (() => void) | null;+ readonly onSuccess?: (() => void) | null;+ readonly switchAccount?: ((accountKey: string) => Promise<void>) | null;+}++export async function switchToSavedAccount({+ accountKey,+ redirectAfterSwitch = Routes.ME,+ onSessionExpired = openReloginInSwitcher,+ onSelectCurrent = null,+ onSuccess = null,+ switchAccount = null,+}: SavedAccountSwitchRequest): Promise<void> {+ const account = Accounts.getAccount(accountKey);+ if (account === null) {+ return;+ }+ if (account.isValid === false) {+ onSessionExpired?.(account);+ return;}+ if (account.storageKey === Accounts.currentAccountKey) {+ onSelectCurrent?.();+ return;+ }+ await switchStoredAccountFromSwitcher({+ accountKey,+ onSessionExpired,+ onSuccess,+ redirectAfterSwitch,+ switchAccount,+ });}-async function removeStoredAccountFromSwitcher(accountKey: string): Promise<void> {+async function removeStoredAccountFromSwitcher(+ accountKey: string,+ onError: AccountSwitcherErrorHandler | null,+): Promise<void> {if (Accounts.isSwitching || Accounts.isLoading) {return;}@@ -153,17 +215,20 @@ async function removeStoredAccountFromSwitcher(accountKey: string): Promise<voidawait Accounts.removeStoredAccount(accountKey);} catch (error) {logger.error('Failed to remove account', error);- showAccountSwitcherErrorModal(WE_COULDN_T_REMOVE_THIS_ACCOUNT_PLEASE_TRY_DESCRIPTOR);+ reportAccountSwitcherError(WE_COULDN_T_REMOVE_THIS_ACCOUNT_PLEASE_TRY_DESCRIPTOR, onError);}}-export async function logoutStoredAccountFromSwitcher(account: Account): Promise<void> {+export async function logoutStoredAccountFromSwitcher(+ account: Account,+ onError: AccountSwitcherErrorHandler | null = null,+): Promise<void> {if (Accounts.isSwitching || Accounts.isLoading) {return;}if (account.instance == null) {logger.warn(`Stored account ${getAccountKey(account)} has no instance runtime, removing it locally`);- await removeStoredAccountFromSwitcher(getAccountKey(account));+ await removeStoredAccountFromSwitcher(getAccountKey(account), onError);return;}const target = instanceTargetFromSnapshot(account.instance);@@ -180,13 +245,28 @@ export async function logoutStoredAccountFromSwitcher(account: Account): Promise} catch (error) {logger.warn('Failed to log out stored account', error);}- await removeStoredAccountFromSwitcher(getAccountKey(account));+ await removeStoredAccountFromSwitcher(getAccountKey(account), onError);+}++export async function logoutCurrentAccountFromSwitcher(+ redirectPath: string,+ onError: AccountSwitcherErrorHandler | null,+): Promise<boolean> {+ if (Accounts.isSwitching || Accounts.isLoading) {+ return false;+ }+ try {+ await Accounts.logout({redirectPath});+ return true;+ } catch (error) {+ logger.error('Logout failed', error);+ reportAccountSwitcherError(SIGNING_OUT_FAILED_TRY_AGAIN_IN_A_MOMENT_DESCRIPTOR, onError);+ return false;+ }}export function useAccountSwitcherLogic({- onSelectCurrent,onSessionExpired,- redirectAfterSwitch,switchAccount,}: AccountSwitcherLogicOptions): AccountSwitcherLogic {const accounts = switcherAccounts();@@ -195,44 +275,18 @@ export function useAccountSwitcherLogic({const isBusy = Accounts.isSwitching || Accounts.isLoading;const handleSwitchAccount = useCallback(async (accountKey: string): Promise<void> => {- await switchStoredAccountFromSwitcher({+ await switchToSavedAccount({accountKey,onSessionExpired,onSuccess: ModalCommands.pop,- redirectAfterSwitch,switchAccount,});},- [onSessionExpired, redirectAfterSwitch, switchAccount],- );- const handleSelectAccount = useCallback(- (account: Account): void => {- if (isBusy) {- return;- }- if (account.isValid === false) {- onSessionExpired?.(account);- return;- }- const accountKey = getAccountKey(account);- if (accountKey === currentAccountKey) {- onSelectCurrent?.();- return;- }- void handleSwitchAccount(accountKey);- },- [currentAccountKey, handleSwitchAccount, isBusy, onSelectCurrent, onSessionExpired],+ [onSessionExpired, switchAccount],);const handleLogout = useCallback(async (): Promise<void> => {- if (Accounts.isSwitching || Accounts.isLoading) {- return;- }- try {- await Accounts.logout();+ if (await logoutCurrentAccountFromSwitcher(Routes.LOGIN, null)) {ModalCommands.pop();- } catch (error) {- logger.error('Logout failed', error);- showAccountSwitcherErrorModal(SIGNING_OUT_FAILED_TRY_AGAIN_IN_A_MOMENT_DESCRIPTOR);}}, []);return {@@ -240,7 +294,6 @@ export function useAccountSwitcherLogic({currentAccount,currentAccountKey,isBusy,- handleSelectAccount,handleSwitchAccount,handleLogout,handleLogoutStoredAccount: logoutStoredAccountFromSwitcher,