waybetter/packages/shell/src/frame/AccountSwitcher.tsx
CRT 60faed66be shell: the shell frame, createShell(site) (moved from wayBetter for X)
packages/shell/src/frame (waybetter/shell/frame): the whole shell of an app. An app describes its
site (ShellSite: names and pages, account rules, search, address chips and completions, its panel
tab, the new-tab page, palette items, deck column kinds and flags and an optional compose dock, the
media panel's composer rule, a theme store, overlays, the native features it serves) and passes
its Tauri API and i18n instance; createShell returns the root component.

- Shell.tsx: dockview host (tabs in the titlebar row, splits, drag-link drops, shortcuts, context
  menu, deck back-and-forth, session restore, workspace on start, overlay raise); state.ts (pane
  placeholders, tabs_sync one-in-flight via syncGate, shell_raise layer, profiles, layout).
- WebPanel (address bar), NewTabPage, CommandPalette + paletteModel (frame groups; site items),
  DeckView + AddColumnDialog + deckStore (site column kinds), PaneTheme + themeStore
  (createThemeStore over the app's ThemeAdapter) + chromeTheme (ChromeTheme input) + themeScopes,
  Titlebar + TitlebarExtras + icons + brand (wB mark data URI), AccountSwitcher + accountModel,
  workspaces + workspaceModel, backupModel, syncHost, devHost + devModel, pluginCommandStore,
  MediaPanel + mediaModel, searchInput, hooks, bridge (installPreviewMocks), i18n, boot.ts
  (bootScript: the first-frame boot.js), CSS themed with --wb-* tokens.
- paneModel: paneVisibility, raiseSupported, cssRgb; deckModel: isSourcePage.
- Includes the live-QA titlebar fix (dock ResizeObserver + rAF titlebar marks, dock sized by its
  insets).
- tests/frame.test.ts: every frame key has English and is used, palette order with a site,
  address fallback, layout gate, boot script, chrome variables, switcher rules, workspaces,
  deck settings with site flags.
- npm package 0.4.0: exports ./shell/frame, ./shell/frame/*, ./shell/frame/*.css (copied by the
  build); dockview and acorn optional peers; root devDependencies dockview, acorn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:10 +07:00

275 lines
17 KiB
TypeScript

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<void> {
if (!isTauri) { setProfiles(next); return; }
setProfiles(await invoke<ProfileSettings>('profiles_set', { settings: next }));
}
export const ProfileDot = ({ color, title }: { color: string; title?: string }) =>
<span className="bt-profile-dot" style={{ background: color }} title={title} aria-hidden={title ? undefined : true}/>;
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<void> {
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<void> {
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 }) =>
<Avatar name={accountLabel(profile).title} color={profile.color} size={size} src={profile.account?.avatar}/>;
/** "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<RowMenu | null>(null);
const [error, setError] = useState('');
const [anchor, setAnchor] = useState<{ top: number; right: number }>({ top: 44, right: 12 });
const button = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(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<HTMLElement>('.bt-acct-row.is-focused .bt-acct-main')
?? menu.current?.querySelector<HTMLElement>('.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<string | null>(null);
useEffect(() => {
if (!open) return;
if (rowMenu) {
lastRow.current = rowMenu.id;
requestAnimationFrame(() => menu.current?.querySelector<HTMLElement>(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<HTMLElement>(`.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<unknown>) {
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<HTMLDivElement>) {
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<HTMLElement>(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<HTMLElement>('.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 <>
<button ref={button} className="bt-profile-switcher" aria-label={buttonLabel}
title={multi ? t('wb.acct.buttonTitle', { pane: accountName(focused), tabs: accountName(tabProfile(settings, settings.active)) }) : accountName(focused)}
aria-haspopup="menu" aria-expanded={open} onClick={toggle}>
<AccountAvatar profile={focused} size={22}/><span className="bt-profile-switcher-name">{focused.account ? handle(focused) : accountLabel(focused).title}</span>
<Icon name="chevron" className="bt-profile-switcher-chevron"/>
</button>
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={menu} className="bt-menu bt-acct-menu bt-pop bt-pop--right" role="menu" aria-label={t('wb.acct.title')} style={{ top: anchor.top, right: anchor.right }}
onMouseDown={event => event.stopPropagation()} onKeyDown={onMenuKey}>
<div className="bt-acct-head" role="presentation">
<strong>{t('wb.acct.title')}</strong>
<span>{t('wb.acct.headBefore')} <kbd className="bt-kbd">{t('wb.acct.shift')}</kbd> {t('wb.acct.headAfter')}</span>
</div>
{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 <div key={profile.id} className={`bt-acct-row${isFocused ? ' is-focused' : ''}${sub ? ' is-open' : ''}`} data-profile={profile.id} role="none"
onContextMenu={event => { event.preventDefault(); event.stopPropagation(); setRowMenu({ id: profile.id }); }}>
<div className="bt-acct-line">
<button role="menuitem" className="bt-acct-main" aria-current={isFocused ? 'true' : undefined}
aria-label={label.state === 'signed-in' ? t('wb.acct.rowLabel', { name: accountName(profile), hint }) : label.state === 'new' ? t('wb.acct.rowLabelNew', { name: accountName(profile), hint }) : t('wb.acct.rowLabelOut', { name: accountName(profile), hint })}
onClick={onMainClick(profile.id)}>
<span className={`bt-acct-avatar is-${label.state}`}><AccountAvatar profile={profile} size={32}/></span>
<span className="bt-acct-text">
<span className="bt-acct-name">{label.title}{isDefault && multi && <span className="bt-acct-badge" title={t('wb.acct.newTabsTitle')}>{t('wb.acct.newTabs')}</span>}</span>
<span className={`bt-acct-meta is-${label.state}`}>{status}{count > 0 && <span className="bt-acct-count"> · {t('wb.ws.tabs', { count })}</span>}</span>
</span>
<span className="bt-acct-hint" aria-hidden="true">{hint}{action.type === 'open' && <Icon name="split"/>}</span>
</button>
<button className="bt-acct-more" tabIndex={-1} aria-haspopup="menu" aria-expanded={!!sub} aria-label={t('wb.acct.moreFor', { name: accountName(profile) })} title={t('wb.acct.more')}
onClick={() => setRowMenu(sub ? null : { id: profile.id })}>
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="6" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="18" cy="12" r="1.6"/></svg>
</button>
</div>
{sub && !sub.confirm && <div className="bt-acct-sub" role="menu" aria-label={t('wb.acct.actions', { name: accountName(profile) })}>
<button role="menuitem" data-action="tab" onClick={() => pick(profile.id, true)}>
<Icon name="plus"/><span className="bt-menu-label">{t('wb.acct.openNewTab')}</span><span className="bt-menu-keys">{t('wb.acct.shiftClick')}</span></button>
<button role="menuitemcheckbox" aria-checked={isDefault} data-action="default" disabled={isDefault}
onClick={() => void run(() => saveProfiles(setDefaultAccount(settings, profile.id))).then(ok => ok && setRowMenu(null))}>
<Icon name={isDefault ? 'check' : 'sparkle'}/><span className="bt-menu-label">{isDefault ? t('wb.acct.newTabsOpenHere') : t('wb.acct.useForNewTabs')}</span></button>
{label.state === 'signed-in'
? <button role="menuitem" data-action="signout" title={t('wb.acct.signOutTitle', { site: siteName })} onClick={() => { close(); shell.openAccount(profile.id, { url: logoutUrl }); }}>
<Icon name="external"/><span className="bt-menu-label">{t('wb.acct.signOut', { site: siteName })}</span></button>
: <button role="menuitem" data-action="signin" onClick={() => { close(); signIn(profile.id); }}>
<Icon name="user"/><span className="bt-menu-label">{t('wb.acct.signIn', { site: siteName })}</span></button>}
{profile.id !== DEFAULT_PROFILE && <button role="menuitem" data-action="remove" className="bt-acct-danger" onClick={() => setRowMenu({ id: profile.id, confirm: true })}>
<Icon name="trash"/><span className="bt-menu-label">{t('wb.acct.remove')}</span></button>}
</div>}
{sub?.confirm && <div className="bt-acct-confirm" role="alertdialog" aria-label={t('wb.common.removeItem', { item: label.title })}>
<span>{t('wb.acct.removeConfirm', { name: accountName(profile), tabs: count })}</span>
<div>
<button className="bt-acct-remove" onClick={() => void run(() => removeAccount(settings, profile.id)).then(ok => ok && setRowMenu(null))}>{t('wb.common.remove')}</button>
<button className="bt-acct-cancel" onClick={() => setRowMenu(null)}>{t('wb.common.cancel')}</button>
</div>
</div>}
</div>;
})}
<hr/>
<button role="menuitem" className="bt-acct-add" onClick={() => void run(() => addAccount(settings)).then(ok => ok && close())}>
<span className="bt-acct-add-icon"><Icon name="plus"/></span>
<span className="bt-acct-text"><span className="bt-acct-name">{t('wb.acct.add')}</span><span className="bt-acct-meta">{t('wb.acct.addHint', { site: siteName })}</span></span>
</button>
{error && <div className="bt-acct-error" role="alert">{error}</div>}
</div>
</div>, document.body)}
</>;
}