import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from 'react'; import { createPortal } from 'react-dom'; import { DEFAULT_PROFILE, accountLabel as accountLabelCore, removeProfile, tabProfile, type Profile, type ProfileSettings } from '../profileModel.ts'; import { accountAction, addAccountProfile, focusedAccount, moveFocus, setDefaultAccount, tabsByAccount } from './accountModel.ts'; import { invoke } from './bridge.ts'; import { decks, forgetColumn, saveDecks } from './deckStore.ts'; import { usePaneTick, useProfiles, useT } from './hooks.ts'; import { t, tx } from './i18n.ts'; import { Avatar, Icon } from './icons.tsx'; import { site } from './site.ts'; import { flushSync, paneInfos, setOverlay, setProfiles, shell } from './state.ts'; import { isTauri } from './windowBinding.ts'; import './accountSwitcher.css'; export { useProfiles } from './hooks.ts'; /** What the switcher shows for a profile: the site login once seen, the profile name before. */ export function accountLabel(profile: Profile) { return accountLabelCore(profile, site().accounts, key => tx(key, undefined, '') || undefined); } /** Saves natively (Rust validates and owns the data directories); the preview keeps it in memory. */ export async function saveProfiles(next: ProfileSettings): Promise { if (!isTauri) { setProfiles(next); return; } setProfiles(await invoke('profiles_set', { settings: next })); } export const ProfileDot = ({ color, title }: { color: string; title?: string }) => ; export function openTabs(profile: string) { return tabsByAccount(shell.profiles, paneInfos()).get(profile)?.length ?? 0; } /** The site's own sign-in page for that account, in a new pane beside the focused one. */ export function signIn(profile: string) { shell.openAccount(profile, { url: site().loginUrl }); } /** "Add account": a fresh login (its own cookies and storage) whose sign-in opens in a new pane. */ export async function addAccount(settings: ProfileSettings): Promise { const next = addAccountProfile(settings); await saveProfiles(next.settings); signIn(next.profile); } /** * Removes an account after the user confirmed: its tabs close first (native code refuses to delete * the data directory of a profile that still has a tab), then the list is saved and native code * deletes that login's data on this computer. Never called without the explicit confirm step. */ export async function removeAccount(settings: ProfileSettings, id: string): Promise { if (id === DEFAULT_PROFILE) return; const tabs = tabsByAccount(settings, paneInfos()).get(id) ?? []; for (const tab of tabs) shell.api?.getPanel(tab)?.api.close(); // Start pages of that account fall back to the default one. for (const panel of shell.api?.panels ?? []) { const params = panel.params as { kind?: string; profile?: string } | undefined; if (params?.kind === 'start' && params.profile === id) panel.api.updateParameters({ profile: DEFAULT_PROFILE }); } // Deck columns of that account go too (each is a webview in its profile); a compose dock in it closes. let deckChanged = false; decks.list = decks.list.map(deck => { const gone = deck.columns.filter(column => column.profile === id); if (!gone.length) return deck; deckChanged = true; for (const column of gone) forgetColumn(column.tabId); return { ...deck, columns: deck.columns.filter(column => column.profile !== id) }; }); for (const [deckId, compose] of decks.compose) if (compose.profile === id) { decks.compose.delete(deckId); deckChanged = true; } if (deckChanged) saveDecks(); // dockview drops closed panels from `api.panels` synchronously (checked in the harness, whose // profiles_set refuses like native code), so this sync no longer lists the account's tabs. await flushSync(); try { await saveProfiles(removeProfile(settings, id)); } catch (failure) { const message = String(failure); if (/PROFILE: close this profile's tabs/.test(message)) throw new Error(t('wb.acct.notRemoved')); throw failure; } } export const AccountAvatar = ({ profile, size }: { profile: Profile; size: number }) => ; /** "Name (@handle)" for titles and labels. */ export function accountName(profile: Profile): string { return `${accountLabel(profile).title}${profile.account ? ` (${site().accounts.handlePrefix}${profile.account.handle})` : ''}`; } type RowMenu = { id: string; confirm?: boolean }; /** * Titlebar account switcher. Every entry is a separate site login on this computer (its own * WebView data directory) that shows the account the site itself reports as signed in there. * * One click shows the account: a visible pane of it gets focus, otherwise its home feed (or the * site's sign-in) opens in a new pane beside the focused one. Shift/Ctrl-click opens a new tab * instead. Everything else ("Open in new tab", "Use for new tabs", sign out, remove) is in the * row's "…" menu. The button shows the focused pane's account. */ export function AccountSwitcher() { const t = useT(); const settings = useProfiles(); usePaneTick(); const [open, setOpen] = useState(false); const [rowMenu, setRowMenu] = useState(null); const [error, setError] = useState(''); const [anchor, setAnchor] = useState<{ top: number; right: number }>({ top: 44, right: 12 }); const button = useRef(null); const menu = useRef(null); const panes = paneInfos(); const activeId = shell.api?.activePanel?.id; const focused = focusedAccount(settings, panes, activeId); const tabs = tabsByAccount(settings, panes); const multi = settings.profiles.length > 1; const { name: siteName, homeUrl, loginUrl, logoutUrl, isSiteUrl, accounts: rules } = site(); const handle = (profile: Profile) => `${rules.handlePrefix}${profile.account!.handle}`; useEffect(() => { if (!open) return; // Native tab webviews would cover the menu. setOverlay(1); const onBlur = () => close(); // Escape while focus is outside the menu (a click on its padding); inside, onMenuKey handles it. const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && !menu.current?.contains(event.target as Node)) close(true); }; window.addEventListener('blur', onBlur); window.addEventListener('keydown', onKey); // Start on the focused pane's account. // Two lookups: a selector list matches in document order, so it would always pick the first row. requestAnimationFrame(() => (menu.current?.querySelector('.bt-acct-row.is-focused .bt-acct-main') ?? menu.current?.querySelector('.bt-acct-main'))?.focus()); return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); window.removeEventListener('keydown', onKey); }; }, [open]); // The row menu takes focus when it opens; closing it returns focus to its row. const lastRow = useRef(null); useEffect(() => { if (!open) return; if (rowMenu) { lastRow.current = rowMenu.id; requestAnimationFrame(() => menu.current?.querySelector(rowMenu.confirm ? '.bt-acct-confirm button' : '.bt-acct-sub button:not(:disabled)')?.focus()); } else if (lastRow.current) { const id = lastRow.current; lastRow.current = null; requestAnimationFrame(() => menu.current?.querySelector(`.bt-acct-row[data-profile="${id}"] .bt-acct-main`)?.focus()); } }, [rowMenu, open]); function close(refocus = false) { setOpen(false); setRowMenu(null); setError(''); if (refocus) button.current?.focus(); } function toggle() { const rect = button.current?.getBoundingClientRect(); if (rect) setAnchor({ top: Math.round(rect.bottom + 6), right: Math.max(8, Math.round(window.innerWidth - rect.right)) }); setRowMenu(null); setError(''); setOpen(value => !value); } async function run(action: () => Promise) { setError(''); try { await action(); return true; } catch (failure) { setError(String(failure).replace(/^Error: /, '')); return false; } } /** The main click: focus or open beside; Shift/Ctrl (or "Open in new tab") forces a tab. */ function pick(profile: string, force = false) { close(); shell.openAccount(profile, { force }); } const onMainClick = (profile: string) => (event: ReactMouseEvent) => pick(profile, event.shiftKey || event.ctrlKey || event.metaKey); function onMenuKey(event: ReactKeyboardEvent) { const target = event.target as HTMLElement; const inSub = !!target.closest('.bt-acct-sub, .bt-acct-confirm'); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); if (rowMenu) setRowMenu(null); else close(true); return; } if (event.key === 'Tab') { event.preventDefault(); close(true); return; } const scope = inSub ? target.closest('.bt-acct-sub, .bt-acct-confirm')! : menu.current!; const items = Array.from(scope.querySelectorAll(inSub ? 'button:not(:disabled)' : '.bt-acct-main, .bt-acct-add')); if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { event.preventDefault(); items[moveFocus(items.indexOf(target), event.key, items.length)]?.focus(); return; } const row = target.closest('.bt-acct-row')?.dataset.profile; if (!inSub && row && (event.key === 'ArrowRight' || event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey))) { event.preventDefault(); setRowMenu({ id: row }); return; } if (inSub && event.key === 'ArrowLeft') { event.preventDefault(); setRowMenu(null); return; } // Keyboard Enter/Space clicks carry no modifiers: Shift/Ctrl+Enter forces a new tab here. if (!inSub && row && event.key === 'Enter' && (event.shiftKey || event.ctrlKey || event.metaKey)) { event.preventDefault(); pick(row, true); } } const buttonLabel = t('wb.acct.buttonLabel', { name: accountName(focused) }); return <> {open && createPortal(
close()} onContextMenu={event => { event.preventDefault(); close(); }}>
event.stopPropagation()} onKeyDown={onMenuKey}>
{t('wb.acct.title')} {t('wb.acct.headBefore')} {t('wb.acct.shift')} {t('wb.acct.headAfter')}
{settings.profiles.map(profile => { const label = accountLabel(profile); const count = tabs.get(profile.id)?.length ?? 0; const isFocused = profile.id === focused.id; const isDefault = profile.id === settings.active; const action = accountAction(settings, panes, activeId, profile.id, { homeUrl, loginUrl, isSiteUrl }); const hint = action.type === 'focus' ? (action.paneId === activeId ? t('wb.acct.thisPane') : t('wb.acct.goToPane')) : label.state === 'signed-in' ? t('wb.acct.openBeside') : t('wb.acct.signInBeside'); const status = label.state === 'signed-in' ? handle(profile) : label.state === 'signed-out' ? t('wb.acct.signedOut', { handle: handle(profile) }) : label.detail; const sub = rowMenu?.id === profile.id ? rowMenu : null; return
{ event.preventDefault(); event.stopPropagation(); setRowMenu({ id: profile.id }); }}>
{sub && !sub.confirm &&
{label.state === 'signed-in' ? : } {profile.id !== DEFAULT_PROFILE && }
} {sub?.confirm &&
{t('wb.acct.removeConfirm', { name: accountName(profile), tabs: count })}
}
; })}
{error &&
{error}
}
, document.body)} ; }