A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): add account switcher navigation and saved order
Hampuse89f36284fb2
diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherActivity.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherActivity.tsnew file mode 100644index 000000000..18c7bf1c9--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherActivity.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import AccountEngine from '@app/features/account_engine/state/AccountEngine';+import GuildReadState from '@app/features/guild/state/GuildReadState';+import {AccountEngineConnectionState} from '@fluxer/desktop_ipc/src/AccountEngineContract';++export const AccountTileConnection = Object.freeze({+ LIVE: 'live',+ RECONNECTING: 'reconnecting',+ OFFLINE: 'offline',+} as const);++export type AccountTileConnection = (typeof AccountTileConnection)[keyof typeof AccountTileConnection];++export interface AccountTileActivity {+ readonly mentionCount: number;+ readonly hasUnread: boolean;+ readonly connection: AccountTileConnection;+}++function engineConnection(accountKey: string): AccountTileConnection {+ switch (AccountEngine.getSummary(accountKey)?.state) {+ case AccountEngineConnectionState.BACKOFF:+ return AccountTileConnection.RECONNECTING;+ case AccountEngineConnectionState.OFFLINE:+ return AccountTileConnection.OFFLINE;+ default:+ return AccountTileConnection.LIVE;+ }+}++export function getAccountTileActivity(accountKey: string, isCurrent: boolean): AccountTileActivity {+ if (isCurrent) {+ return {+ mentionCount: GuildReadState.mentionCountAcrossGuilds(),+ hasUnread: GuildReadState.anyGuildUnread,+ connection: AccountTileConnection.LIVE,+ };+ }+ return {+ mentionCount: AccountEngine.getMentionCount(accountKey),+ hasUnread: AccountEngine.hasUnread(accountKey),+ connection: engineConnection(accountKey),+ };+}diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherMessages.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherMessages.tsnew file mode 100644index 000000000..5b71dff26--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherMessages.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {msg} from '@lingui/core/macro';++export const CHOOSE_AN_ACCOUNT_DESCRIPTOR = msg({+ message: 'Choose an account',+ comment: 'Heading of the full-screen account switcher, above the grid of saved accounts.',+});+export const MANAGE_ACCOUNTS_DESCRIPTOR = msg({+ message: 'Manage accounts',+ comment:+ 'Button under the account grid in the account switcher that turns on manage mode, and the heading shown while manage mode is on.',+});+export const SLOT_KEYS_HINT_DESCRIPTOR = msg({+ message: 'Press 1 to 9 to switch directly.',+ comment:+ 'Hint under the account switcher heading. Pressing a number key from 1 to 9 switches to the account in that position.',+});+export const OPEN_SHORTCUT_HINT_DESCRIPTOR = msg({+ message: 'Open this anytime with',+ comment:+ 'Hint under the account switcher heading, followed by the keyboard shortcut that opens the account switcher.',+});+export const MANAGE_HINT_DESCRIPTOR = msg({+ message: 'Choose an account to manage it, or drag accounts to reorder them.',+ comment:+ 'Hint under the account switcher heading while manage mode is on. The order of accounts also sets which number key switches to each one.',+});+export const MOVE_LEFT_DESCRIPTOR = msg({+ message: 'Move left',+ comment:+ 'Menu item for one account in the account switcher. It moves the account one place to the left in the grid, which also changes its number key.',+});+export const MOVE_RIGHT_DESCRIPTOR = msg({+ message: 'Move right',+ comment:+ 'Menu item for one account in the account switcher. It moves the account one place to the right in the grid, which also changes its number key.',+});+export const ACCOUNT_MOVED_DESCRIPTOR = msg({+ message: 'Moved {displayName} to position {position} of {count}',+ comment:+ 'Screen reader announcement after an account is moved in the account switcher, by dragging, by the Move left or Move right menu items, or with Alt and an arrow key. displayName is the account name, position and count are numbers.',+});+export const SEARCH_ACCOUNTS_DESCRIPTOR = msg({+ message: 'Search accounts',+ comment:+ 'Placeholder and accessible label of the search field above the account grid in the account switcher. It matches account names, usernames and instance hosts.',+});+export const NO_ACCOUNTS_MATCH_DESCRIPTOR = msg({+ message: 'No accounts match "{query}".',+ comment: 'Shown in the account switcher when the account search finds nothing. query is what the user typed.',+});+export const CURRENT_ACCOUNT_DESCRIPTOR = msg({+ message: 'Current account',+ comment: 'Screen reader status for the account in use, read out on its tile in the account switcher.',+});+export const RECONNECTING_DESCRIPTOR = msg({+ message: 'Reconnecting',+ comment:+ 'Status under a saved account in the account switcher while the app tries to reconnect that account in the background.',+});+export const CONNECTION_OFFLINE_DESCRIPTOR = msg({+ message: 'Offline',+ comment:+ 'Status under a saved account in the account switcher when the app cannot reach its instance because the device is offline.',+});+export const HAS_UNREAD_MESSAGES_DESCRIPTOR = msg({+ message: 'Unread messages',+ comment:+ 'Screen reader status for a saved account that has unread messages but no mentions, in the account switcher.',+});+export const SLOT_POSITION_DESCRIPTOR = msg({+ message: 'Press {slot}',+ comment:+ 'Screen reader hint on an account tile in the account switcher. Pressing that number key switches to the account. slot is a number from 1 to 9.',+});+export const ON_INSTANCE_DESCRIPTOR = msg({+ message: 'on {instanceLabel}',+ comment:+ 'Screen reader part of an account tile in the account switcher, naming the instance the account is on. instanceLabel is an instance name or host.',+});diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherNavigation.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherNavigation.tsnew file mode 100644index 000000000..2134cc827--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherNavigation.ts@@ -0,0 +1,272 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++const ACCOUNT_SWITCHER_TYPE_AHEAD_RESET_MS = 700;+export const ACCOUNT_SWITCHER_SEARCH_THRESHOLD = 13;++type GridKey = 'ArrowLeft' | 'ArrowRight' | 'ArrowUp' | 'ArrowDown' | 'Home' | 'End';++const GRID_KEYS: ReadonlySet<string> = new Set<GridKey>([+ 'ArrowLeft',+ 'ArrowRight',+ 'ArrowUp',+ 'ArrowDown',+ 'Home',+ 'End',+]);++export function isGridKey(key: string): key is GridKey {+ return GRID_KEYS.has(key);+}++interface TileRect {+ readonly left: number;+ readonly top: number;+ readonly width: number;+}++const ROW_TOLERANCE_PX = 1;++function rowTops(rects: ReadonlyArray<TileRect>): Array<number> {+ const tops: Array<number> = [];+ for (const rect of rects) {+ if (!tops.some((top) => Math.abs(top - rect.top) <= ROW_TOLERANCE_PX)) {+ tops.push(rect.top);+ }+ }+ return tops.sort((a, b) => a - b);+}++function rowOf(tops: ReadonlyArray<number>, rect: TileRect): number {+ return tops.findIndex((top) => Math.abs(top - rect.top) <= ROW_TOLERANCE_PX);+}++export interface GridMove {+ readonly rects: ReadonlyArray<TileRect>;+ readonly index: number;+ readonly key: GridKey;+ readonly rtl: boolean;+}++export function gridTargetIndex({rects, index, key, rtl}: GridMove): number {+ const count = rects.length;+ if (count === 0) {+ return -1;+ }+ const last = count - 1;+ const from = Math.min(Math.max(index, 0), last);+ switch (key) {+ case 'Home':+ return 0;+ case 'End':+ return last;+ case 'ArrowLeft':+ return Math.max(0, Math.min(last, from + (rtl ? 1 : -1)));+ case 'ArrowRight':+ return Math.max(0, Math.min(last, from + (rtl ? -1 : 1)));+ case 'ArrowUp':+ case 'ArrowDown': {+ const tops = rowTops(rects);+ const targetRow = rowOf(tops, rects[from]) + (key === 'ArrowDown' ? 1 : -1);+ if (targetRow < 0 || targetRow >= tops.length) {+ return from;+ }+ const center = rects[from].left + rects[from].width / 2;+ let best = from;+ let bestDistance = Number.POSITIVE_INFINITY;+ rects.forEach((rect, candidate) => {+ if (Math.abs(rect.top - tops[targetRow]) > ROW_TOLERANCE_PX) {+ return;+ }+ const distance = Math.abs(rect.left + rect.width / 2 - center);+ if (distance < bestDistance) {+ best = candidate;+ bestDistance = distance;+ }+ });+ return best;+ }+ }+}++export interface SlotKeyEvent {+ readonly code: string;+ readonly altKey: boolean;+ readonly ctrlKey: boolean;+ readonly metaKey: boolean;+ readonly shiftKey: boolean;+}++const SLOT_CODE_PATTERN = /^(?:Digit|Numpad)([1-9])$/;++export function slotIndexFromKeyEvent(event: SlotKeyEvent): number | null {+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {+ return null;+ }+ const match = SLOT_CODE_PATTERN.exec(event.code);+ if (match == null) {+ return null;+ }+ return Number(match[1]) - 1;+}++export interface TypeAheadState {+ readonly buffer: string;+ readonly lastAt: number;+}++export const EMPTY_TYPE_AHEAD: TypeAheadState = Object.freeze({buffer: '', lastAt: 0});++export function advanceTypeAhead(state: TypeAheadState, character: string, now: number): TypeAheadState {+ const expired = now - state.lastAt > ACCOUNT_SWITCHER_TYPE_AHEAD_RESET_MS;+ const buffer = (expired ? '' : state.buffer) + character.toLocaleLowerCase();+ return {buffer, lastAt: now};+}++export function typeAheadIsActive(state: TypeAheadState, now: number): boolean {+ return state.buffer.length > 0 && now - state.lastAt <= ACCOUNT_SWITCHER_TYPE_AHEAD_RESET_MS;+}++function isRepeatedCharacter(buffer: string): boolean {+ return buffer.length > 1 && [...buffer].every((character) => character === buffer[0]);+}++export function typeAheadMatch(+ labels: ReadonlyArray<ReadonlyArray<string>>,+ buffer: string,+ fromIndex: number,+): number | null {+ if (buffer.length === 0 || labels.length === 0) {+ return null;+ }+ const repeated = isRepeatedCharacter(buffer);+ const query = repeated ? buffer[0] : buffer;+ const start = repeated || buffer.length === 1 ? fromIndex + 1 : fromIndex;+ for (let offset = 0; offset < labels.length; offset++) {+ const index = (((start + offset) % labels.length) + labels.length) % labels.length;+ if (labels[index].some((label) => label.toLocaleLowerCase().startsWith(query))) {+ return index;+ }+ }+ return null;+}++export function isTypeAheadCharacter(event: {+ readonly key: string;+ readonly altKey: boolean;+ readonly ctrlKey: boolean;+ readonly metaKey: boolean;+}): boolean {+ if (event.altKey || event.ctrlKey || event.metaKey) {+ return false;+ }+ return [...event.key].length === 1 && event.key.trim().length === 1;+}++export function accountMatchesSearch(labels: ReadonlyArray<string>, query: string): boolean {+ const needle = query.trim().toLocaleLowerCase();+ if (needle.length === 0) {+ return true;+ }+ return labels.some((label) => label.toLocaleLowerCase().includes(needle));+}++export const SwitcherEscapeAction = Object.freeze({+ CLEAR_SEARCH: 'clear_search',+ LEAVE_MANAGE: 'leave_manage',+ LEAVE_AUTH: 'leave_auth',+ CLOSE: 'close',+} as const);++export type SwitcherEscapeAction = (typeof SwitcherEscapeAction)[keyof typeof SwitcherEscapeAction];++export interface SwitcherEscapeState {+ readonly hasSearchText: boolean;+ readonly manage: boolean;+ readonly auth: boolean;+}++export function switcherEscapeAction(state: SwitcherEscapeState): SwitcherEscapeAction {+ if (state.auth) {+ return SwitcherEscapeAction.LEAVE_AUTH;+ }+ if (state.hasSearchText) {+ return SwitcherEscapeAction.CLEAR_SEARCH;+ }+ if (state.manage) {+ return SwitcherEscapeAction.LEAVE_MANAGE;+ }+ return SwitcherEscapeAction.CLOSE;+}++export function focusKeyAfterRemoval(+ previousKeys: ReadonlyArray<string>,+ removedKey: string,+ nextKeys: ReadonlyArray<string>,+): string | null {+ if (nextKeys.length === 0) {+ return null;+ }+ const removedIndex = previousKeys.indexOf(removedKey);+ if (removedIndex < 0) {+ return nextKeys[0];+ }+ for (let index = removedIndex + 1; index < previousKeys.length; index++) {+ if (nextKeys.includes(previousKeys[index])) {+ return previousKeys[index];+ }+ }+ for (let index = removedIndex - 1; index >= 0; index--) {+ if (nextKeys.includes(previousKeys[index])) {+ return previousKeys[index];+ }+ }+ return nextKeys[0];+}++export interface InitialFocusInput {+ readonly accountKeys: ReadonlyArray<string>;+ readonly requestedKey: string | null;+ readonly mostRecentOtherKey: string | null;+ readonly currentKey: string | null;+}++export function initialFocusKey({+ accountKeys,+ requestedKey,+ mostRecentOtherKey,+ currentKey,+}: InitialFocusInput): string | null {+ for (const candidate of [requestedKey, mostRecentOtherKey, currentKey]) {+ if (candidate != null && accountKeys.includes(candidate)) {+ return candidate;+ }+ }+ return accountKeys[0] ?? null;+}++const AVATAR_MEDIA_SIZES = [160, 240, 320, 480] as const;+export type SwitcherAvatarMediaSize = (typeof AVATAR_MEDIA_SIZES)[number];++const ROOT_FONT_SIZE_PX = 16;+const PHONE_BREAKPOINT_PX = 42 * ROOT_FONT_SIZE_PX;++function clamp(min: number, value: number, max: number): number {+ return Math.min(max, Math.max(min, value));+}++export function switcherTileSizePx(viewportWidth: number): number {+ if (viewportWidth < PHONE_BREAKPOINT_PX) {+ return clamp(5.75 * ROOT_FONT_SIZE_PX, viewportWidth * 0.26, 7.5 * ROOT_FONT_SIZE_PX);+ }+ return clamp(6.5 * ROOT_FONT_SIZE_PX, 4.75 * ROOT_FONT_SIZE_PX + viewportWidth * 0.05, 9.75 * ROOT_FONT_SIZE_PX);+}++export function switcherAvatarMediaSize(tileSizePx: number, devicePixelRatio: number): SwitcherAvatarMediaSize {+ const target = tileSizePx * clamp(1, devicePixelRatio, 3);+ for (const size of AVATAR_MEDIA_SIZES) {+ if (size >= target) {+ return size;+ }+ }+ return AVATAR_MEDIA_SIZES[AVATAR_MEDIA_SIZES.length - 1];+}diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherReturnFocus.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherReturnFocus.tsnew file mode 100644index 000000000..df655975a--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/AccountSwitcherReturnFocus.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import Accounts from '@app/features/auth/state/Accounts';+import {ComponentBus} from '@app/features/platform/utils/ComponentBus';+import {when} from 'mobx';++const MAIN_CONTENT_ID = 'main-content';+const NEW_ACCOUNT_VIEW_TIMEOUT_MS = 5000;+const COMPOSER_RETRY_DELAY_MS = 300;++interface SwitcherReturnFocusRequest {+ readonly overlay: HTMLElement | null;+ readonly returnTarget: HTMLElement | null;+ readonly switchedAccount: boolean;+}++function asHTMLElement(node: Element | null, ownerDocument: Document): HTMLElement | null {+ const view = ownerDocument.defaultView;+ if (node == null || view == null || !(node instanceof view.HTMLElement)) return null;+ return node;+}++export function captureSwitcherReturnTarget(ownerDocument: Document): HTMLElement | null {+ const active = asHTMLElement(ownerDocument.activeElement, ownerDocument);+ return active === ownerDocument.body ? null : active;+}++function focusIfPossible(element: HTMLElement | null): boolean {+ if (element == null || !element.isConnected || element.closest('[inert]') != null) return false;+ element.focus({preventScroll: true});+ return element.ownerDocument.activeElement === element;+}++function focusNewAccountView(ownerDocument: Document): void {+ const mainContent = asHTMLElement(ownerDocument.getElementById(MAIN_CONTENT_ID), ownerDocument);+ const active = ownerDocument.activeElement;+ if (active != null && active !== ownerDocument.body && active !== mainContent && active.isConnected) return;+ focusIfPossible(mainContent);+ ComponentBus.dispatch('FOCUS_TEXTAREA');+}++function focusNewAccountViewOnceLive(ownerDocument: Document): void {+ const view = ownerDocument.defaultView;+ if (view == null) return;+ void when(() => Accounts.isViewLive, {timeout: NEW_ACCOUNT_VIEW_TIMEOUT_MS})+ .catch(() => {})+ .then(() => {+ view.requestAnimationFrame(() => focusNewAccountView(ownerDocument));+ view.setTimeout(() => focusNewAccountView(ownerDocument), COMPOSER_RETRY_DELAY_MS);+ });+}++export function focusNewAccountViewAfterSwitch(ownerDocument: Document): void {+ focusIfPossible(asHTMLElement(ownerDocument.getElementById(MAIN_CONTENT_ID), ownerDocument));+ focusNewAccountViewOnceLive(ownerDocument);+}++export function restoreFocusAfterSwitcher(+ ownerDocument: Document,+ {overlay, returnTarget, switchedAccount}: SwitcherReturnFocusRequest,+): void {+ const active = asHTMLElement(ownerDocument.activeElement, ownerDocument);+ const focusIsOutside =+ active != null && active !== ownerDocument.body && active.isConnected && overlay?.contains(active) !== true;+ if (focusIsOutside && active.closest('[aria-modal="true"]') != null) return;+ if (switchedAccount) {+ focusNewAccountViewAfterSwitch(ownerDocument);+ return;+ }+ if (focusIsOutside || focusIfPossible(returnTarget)) return;+ focusIfPossible(asHTMLElement(ownerDocument.getElementById(MAIN_CONTENT_ID), ownerDocument));+}diff --git a/fluxer_app/src/features/auth/components/accounts/account_switcher/useSavedAccountCheck.ts b/fluxer_app/src/features/auth/components/accounts/account_switcher/useSavedAccountCheck.tsnew file mode 100644index 000000000..fafe34412--- /dev/null+++ b/fluxer_app/src/features/auth/components/accounts/account_switcher/useSavedAccountCheck.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import AccountAccess from '@app/features/auth/state/AccountAccess';+import {getAccountKey} from '@app/features/auth/state/AccountStorageKey';+import type {Account} from '@app/features/platform/state/AuthSession';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {useEffect, useRef} from 'react';++const logger = new Logger('SavedAccountCheck');+const SAVED_ACCOUNT_RECHECK_INTERVAL_MS = 5 * 60_000;++function checkSignature(accounts: ReadonlyArray<Account>): string {+ return accounts.map((account) => `${getAccountKey(account)}:${account.isValid ? 1 : 0}`).join('|');+}++export function useSavedAccountCheck(accounts: ReadonlyArray<Account>, currentAccountKey: string | null): void {+ const accountsRef = useRef(accounts);+ accountsRef.current = accounts;+ const signature = checkSignature(accounts);+ useEffect(() => {+ if (signature.length === 0) {+ return;+ }+ const checkSavedAccounts = () => {+ for (const account of accountsRef.current) {+ const accountKey = getAccountKey(account);+ if (account.isValid === false || accountKey === currentAccountKey) {+ continue;+ }+ void AccountAccess.ensureAccountChecked(accountKey, {maxAgeMs: SAVED_ACCOUNT_RECHECK_INTERVAL_MS}).catch(+ (error: unknown) => {+ logger.warn(`Could not check saved account ${accountKey}`, error);+ },+ );+ }+ };+ checkSavedAccounts();+ window.addEventListener('focus', checkSavedAccounts);+ return () => window.removeEventListener('focus', checkSavedAccounts);+ }, [signature, currentAccountKey]);+}diff --git a/fluxer_app/src/features/auth/state/AccountStorageContract.ts b/fluxer_app/src/features/auth/state/AccountStorageContract.tsindex dc76f9d96..1b3e53d0c 100644--- a/fluxer_app/src/features/auth/state/AccountStorageContract.ts+++ b/fluxer_app/src/features/auth/state/AccountStorageContract.ts@@ -39,6 +39,7 @@ export interface StoredAccountData {managedStorageData?: Record<string, string>;lastActive: number;isValid?: boolean;+ switcherPosition?: number;}export interface StoredAccount extends StoredAccountData {@@ -127,7 +128,7 @@ export class BrowserAccountStorageTimeoutError extends BrowserAccountStorageUnav}}-export class InvalidAccountStorageSnapshotError extends Error {+class InvalidAccountStorageSnapshotError extends Error {constructor(message: string) {super(message);this.name = 'InvalidAccountStorageSnapshotError';diff --git a/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts b/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.tsindex 0edef3dec..2de03523e 100644--- a/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts+++ b/fluxer_app/src/features/auth/state/AccountSwitcherAccounts.ts@@ -5,7 +5,9 @@ import RuntimeConfig, {runtimeConfigSnapshotsAreSameInstance,runtimeInstanceKey,} from '@app/features/app/state/RuntimeConfig';-import {parseAccountStorageKey} from '@app/features/auth/state/AccountStorageKey';+import {resolveAccountInstanceKey} from '@app/features/auth/AccountDisplayUtils';+import {getAccountKey, parseAccountStorageKey} from '@app/features/auth/state/AccountStorageKey';+import {compareSwitcherOrder, mergeSwitcherOrder} from '@app/features/auth/state/AccountSwitcherOrder';import Accounts from '@app/features/auth/state/Accounts';import type {Account} from '@app/features/platform/state/AuthSession';import {isDesktop} from '@app/features/ui/utils/NativeUtils';@@ -21,20 +23,67 @@ function accountIsSelectableOnCurrentInstance(return parseAccountStorageKey(account.storageKey)?.instanceKey === currentInstanceKey;}-export function switcherAccounts(): Array<Account> {+export function currentInstanceAccounts(): Array<Account> {const accounts = Accounts.getAllAccounts();- if (isDesktop()) {- return accounts;- }const currentInstance = RuntimeConfig.getSnapshotOrNull();if (currentInstance === null) {- return accounts;+ return [...accounts].sort(compareSwitcherOrder);}const currentInstanceKey = runtimeInstanceKey(currentInstance);if (currentInstanceKey === null) {throw new Error('Current runtime snapshot has no instance identity');}- return accounts.filter((account) =>- accountIsSelectableOnCurrentInstance(account, currentInstance, currentInstanceKey),- );+ return accounts+ .filter((account) => accountIsSelectableOnCurrentInstance(account, currentInstance, currentInstanceKey))+ .sort(compareSwitcherOrder);+}++export function switcherAccounts(): Array<Account> {+ if (isDesktop()) {+ return [...Accounts.getAllAccounts()].sort(compareSwitcherOrder);+ }+ return currentInstanceAccounts();+}++export async function saveSwitcherOrder(orderedAccountKeys: ReadonlyArray<string>): Promise<void> {+ const allKeys = [...Accounts.getAllAccounts()].sort(compareSwitcherOrder).map(getAccountKey);+ await Accounts.reorderAccounts(mergeSwitcherOrder(allKeys, orderedAccountKeys));+}++export function adjacentSwitcherAccount(direction: 1 | -1): Account | null {+ const accounts = switcherAccounts();+ if (accounts.length < 2) {+ return null;+ }+ const currentAccountKey = Accounts.currentAccountKey;+ const currentIndex = accounts.findIndex((account) => getAccountKey(account) === currentAccountKey);+ if (currentIndex < 0) {+ return direction === 1 ? accounts[0] : accounts[accounts.length - 1];+ }+ return accounts[(currentIndex + direction + accounts.length) % accounts.length];+}++export function mostRecentOtherAccount(): Account | null {+ const currentAccountKey = Accounts.currentAccountKey;+ let mostRecent: Account | null = null;+ for (const account of switcherAccounts()) {+ if (getAccountKey(account) === currentAccountKey) {+ continue;+ }+ if (mostRecent == null || account.lastActive > mostRecent.lastActive) {+ mostRecent = account;+ }+ }+ return mostRecent;+}++export function accountsSpanSeveralInstances(accounts: ReadonlyArray<Account>): boolean {+ const instanceKeys = new Set<string | null>();+ for (const account of accounts) {+ instanceKeys.add(resolveAccountInstanceKey(account));+ if (instanceKeys.size > 1) {+ return true;+ }+ }+ return false;}diff --git a/fluxer_app/src/features/auth/state/AccountSwitcherOrder.ts b/fluxer_app/src/features/auth/state/AccountSwitcherOrder.tsnew file mode 100644index 000000000..3d26bad3d--- /dev/null+++ b/fluxer_app/src/features/auth/state/AccountSwitcherOrder.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {compareStrings} from '@app/lib/list/CompareStrings';+import {compare} from '@fluxer/snowflake/src/SnowflakeUtils';++interface OrderedAccount {+ readonly storageKey: string;+ readonly userId: string;+ readonly switcherPosition?: number;+}++function compareAccountAge(a: OrderedAccount, b: OrderedAccount): number {+ const ageDifference = compare(a.userId, b.userId);+ if (ageDifference !== 0) {+ return ageDifference;+ }+ return compareStrings(a.storageKey, b.storageKey);+}++export function compareSwitcherOrder(a: OrderedAccount, b: OrderedAccount): number {+ const aPosition = a.switcherPosition;+ const bPosition = b.switcherPosition;+ if (aPosition !== undefined && bPosition !== undefined) {+ return aPosition !== bPosition ? aPosition - bPosition : compareAccountAge(a, b);+ }+ if (aPosition !== undefined) {+ return -1;+ }+ if (bPosition !== undefined) {+ return 1;+ }+ return compareAccountAge(a, b);+}++export function mergeSwitcherOrder(+ allKeys: ReadonlyArray<string>,+ reorderedKeys: ReadonlyArray<string>,+): Array<string> {+ const reordered = new Set(reorderedKeys);+ const queue = reorderedKeys.filter((key) => allKeys.includes(key));+ return allKeys.map((key) => (reordered.has(key) ? (queue.shift() ?? key) : key));+}++export function moveKey(keys: ReadonlyArray<string>, key: string, targetIndex: number): Array<string> {+ const from = keys.indexOf(key);+ if (from < 0) {+ return [...keys];+ }+ const to = Math.max(0, Math.min(keys.length - 1, targetIndex));+ const next = keys.filter((candidate) => candidate !== key);+ next.splice(to, 0, key);+ return next;+}diff --git a/fluxer_app/src/features/auth/state/Accounts.ts b/fluxer_app/src/features/auth/state/Accounts.tsindex dd63775af..90b4008e5 100644--- a/fluxer_app/src/features/auth/state/Accounts.ts+++ b/fluxer_app/src/features/auth/state/Accounts.ts@@ -55,14 +55,14 @@ export class AccountReplacementOperationCapacityExceededError extends Error {}}-export class AccountSwitchTargetNotFoundError extends Error {+class AccountSwitchTargetNotFoundError extends Error {constructor(accountKey: string) {super(`No stored account found for ${accountKey}`);this.name = 'AccountSwitchTargetNotFoundError';}}-export class AccountSwitchUnavailableError extends Error {+class AccountSwitchUnavailableError extends Error {constructor(state: string) {super(`Cannot switch from state: ${state}`);this.name = 'AccountSwitchUnavailableError';@@ -76,7 +76,7 @@ export class AccountReplacementRecoveryFailedError extends AggregateError {}}-export interface SwitchToNewAccountRequest {+interface SwitchToNewAccountRequest {readonly userId: string;readonly token: string;readonly userData?: UserData;@@ -208,6 +208,10 @@ class Accounts {await SessionManager.initialize();}+ async reorderAccounts(orderedAccountKeys: ReadonlyArray<string>): Promise<void> {+ await SessionManager.reorderAccounts(orderedAccountKeys);+ }+markAccountInvalid(accountKey: string, expectedToken?: string): void {SessionManager.markAccountInvalid(accountKey, expectedToken);}@@ -292,7 +296,7 @@ class Accounts {}await this.runAccountReplacementActivation({activate: (suspension) => SessionManager.loginWithinAccountActivation(loginRequest, suspension),- redirectPath,+ redirectPath: redirectPath ?? Routes.ME,targetAccountKey,});});@@ -309,17 +313,23 @@ class Accounts {});}- async logout(): Promise<void> {+ async logout({+ redirectPath = Routes.LOGIN,+ ...options+ }: {+ notifyServer?: boolean;+ redirectPath?: string;+ } = {}): Promise<void> {await this.runAccountReplacementExclusive(async () => {const currentAccountKey = this.currentAccountKey;await this.leaveActiveVoiceChannel(VoiceAccountExitReason.LOGOUT);- await SessionManager.logout();+ await SessionManager.logout(options);ResettableStates.prepareForAccountTransition('logout');ExperimentAssignments.reset();if (currentAccountKey !== null) {AccountAccess.forgetAccount(currentAccountKey);}- RouterUtils.replaceWith('/login');+ RouterUtils.replaceWith(redirectPath);});}diff --git a/fluxer_app/src/features/auth/state/StoredAccountRecord.ts b/fluxer_app/src/features/auth/state/StoredAccountRecord.tsindex 16215057b..8e76f673a 100644--- a/fluxer_app/src/features/auth/state/StoredAccountRecord.ts+++ b/fluxer_app/src/features/auth/state/StoredAccountRecord.ts@@ -175,6 +175,13 @@ function readStoredAccountData(source: Record<string, unknown>): StoredAccountDaif (isValid !== undefined && typeof isValid !== 'boolean') {throw new StoredAccountRuntimeRecoveryError('Stored account validity must be a boolean or absent');}+ const switcherPosition = source.switcherPosition;+ if (+ switcherPosition !== undefined &&+ (typeof switcherPosition !== 'number' || !Number.isSafeInteger(switcherPosition) || switcherPosition < 0)+ ) {+ throw new StoredAccountRuntimeRecoveryError('Stored account switcher position must be a whole number or absent');+ }const data: StoredAccountData = {userId,token,@@ -196,6 +203,9 @@ function readStoredAccountData(source: Record<string, unknown>): StoredAccountDaif (Object.hasOwn(source, 'isValid')) {data.isValid = isValid;}+ if (switcherPosition !== undefined) {+ data.switcherPosition = switcherPosition;+ }return data;}