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.
This commit is contained in:
CRTkafa 2026-09-29 12:47:10 +07:00
parent 892de6cbf4
commit 068168469c
49 changed files with 6442 additions and 6 deletions

View file

@ -8,6 +8,8 @@
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"acorn": "^8.15.0",
"dockview": "^4",
"typescript": "^5.9.0", "typescript": "^5.9.0",
}, },
}, },
@ -28,11 +30,28 @@
}, },
"packages/waybetter": { "packages/waybetter": {
"name": "waybetter", "name": "waybetter",
"version": "0.2.0", "version": "0.3.0",
"bin": {
"waybetter": "bin/waybetter.mjs",
},
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"typescript": "^5.9.0", "typescript": "^5.9.0",
}, },
"peerDependencies": {
"acorn": ">=8.0.0",
"dockview": ">=4.0.0",
"esbuild": ">=0.20.0",
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
},
"optionalPeers": [
"acorn",
"dockview",
"esbuild",
"react",
"react-dom",
],
}, },
}, },
"packages": { "packages": {
@ -46,10 +65,18 @@
"@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"], "@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"],
"acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
"create-waybetter": ["create-waybetter@workspace:packages/create-waybetter"], "create-waybetter": ["create-waybetter@workspace:packages/create-waybetter"],
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"dockview": ["dockview@4.13.1", "", { "dependencies": { "dockview-core": "^4.13.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-K8xnYt3Rvkx8MYKHaEsb8aFaPyQclKRRkXS9JcpQPZUgqxumTLnSidgdd6uIfzEps6yJsXoZGQGJ9PtcaKyDcQ=="],
"dockview-core": ["dockview-core@4.13.1", "", {}, "sha512-+7vR0ZEoL8CNck6NqDVUMqBT22niwBu5CMMI137dZ3c8NDc7c5Si+3dGEqQgM4lNtHBLAtvypo1C4p21J2wkiQ=="],
"react": ["react@19.3.0", "", {}, "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],

View file

@ -26,6 +26,8 @@
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"@types/react": "^19.0.0", "@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0", "@types/react-dom": "^19.0.0",
"acorn": "^8.15.0",
"dockview": "^4",
"typescript": "^5.9.0" "typescript": "^5.9.0"
}, },
"engines": { "engines": {

View file

@ -1,3 +1,6 @@
# shell (internal) # shell (internal)
Sources of `waybetter/shell/*`. Published as part of the [`waybetter`](../waybetter/README.md) package; not published on its own. Sources of `waybetter/shell/*`: the shell models, the Store screens and the shell frame
(`src/frame`, `createShell`). Published as part of the [`waybetter`](../waybetter/README.md) package;
not published on its own. The repository README's "The shell frame" section describes what an app
supplies.

View file

@ -296,3 +296,19 @@ export function moveColumn<T extends { id: string }>(columns: readonly T[], id:
next.splice(target, 0, item!); next.splice(target, 0, item!);
return next; return next;
} }
/**
* A column still shows its source page (origin, path with the trailing slash ignored, and query);
* otherwise it navigated away (a post, a profile) and its header offers the way back. The page
* runtime uses the same rule (runtime/column.ts `isSourcePage`).
*/
export function isSourcePage(href: string, source: string): boolean {
try {
const a = new URL(href);
const b = new URL(source);
const path = (url: URL) => url.pathname.replace(/\/+$/, '') || '/';
return a.origin === b.origin && path(a) === path(b) && a.search === b.search;
} catch {
return false;
}
}

View file

@ -0,0 +1,275 @@
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)}
</>;
}

View file

@ -0,0 +1,118 @@
// "Add column": pick what the column shows (the site's column kinds: `site.deck.kinds`), which
// account it runs in and, for kinds that take one, the value. The shell rises above the tab
// webviews (or hides them) while it is open, so it draws above them.
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountLabel } from './AccountSwitcher.tsx';
import { decks, type Deck, type DeckColumn } from './deckStore.ts';
import { useProfiles, useT } from './hooks.ts';
import { Icon } from './icons.tsx';
import { site, type DeckSite } from './site.ts';
import { setOverlay } from './state.ts';
type Input = Pick<DeckColumn, 'profile' | 'source'>;
export function AddColumnDialog({ deck, onClose, onAdd }: { deck: Deck; onClose(): void; onAdd(input: Input): void }) {
const t = useT();
const profiles = useProfiles();
const spec = site().deck as DeckSite;
const types = spec.kinds;
const focused = deck.columns.find(c => c.id === decks.focus.get(deck.id));
const [kind, setKind] = useState<string>(types[0]?.kind ?? '');
const [profile, setProfile] = useState(tabProfile(profiles, focused?.profile ?? profiles.active).id);
const [value, setValue] = useState('');
const [caret, setCaret] = useState(0);
const field = useRef<HTMLInputElement>(null);
const dialog = useRef<HTMLDivElement>(null);
const type = types.find(item => item.kind === kind)!;
const parsed = type.value ? spec.parseValue(kind, value) : '';
const valid = parsed !== null && (!type.value || parsed !== '') && !!spec.urlFor({ kind, ...(parsed ? { value: parsed } : {}) });
const completer = spec.completer?.(kind) ?? null;
const chips = completer ? completer.suggest(value, caret, 6) : [];
const handlePrefix = site().accounts.handlePrefix;
useEffect(() => {
setOverlay(1);
const onBlur = () => onClose();
window.addEventListener('blur', onBlur);
(dialog.current?.querySelector('[aria-checked="true"]') as HTMLElement | null)?.focus();
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, []);
useEffect(() => { if (type.value) requestAnimationFrame(() => field.current?.focus()); }, [kind]);
const submit = () => {
if (!valid) { field.current?.focus(); return; }
onAdd({ profile, source: parsed ? { kind, value: parsed } : { kind } });
};
const onKey = (event: ReactKeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); onClose(); }
else if (event.key === 'Enter' && !(event.target as HTMLElement).matches('button')) { event.preventDefault(); submit(); }
else if (['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(event.key) && (event.target as HTMLElement).getAttribute('role') === 'radio'
&& (event.target as HTMLElement).closest('.bt-addcol-types')) {
event.preventDefault();
const index = types.findIndex(item => item.kind === kind);
const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowDown' ? 4 : -4;
const next = types[(index + step + types.length) % types.length]!;
setKind(next.kind);
requestAnimationFrame(() => (dialog.current?.querySelector(`[data-kind="${next.kind}"]`) as HTMLElement | null)?.focus());
}
};
const acceptChip = (insert: string) => {
if (!completer) return;
const next = completer.apply(value, caret, insert);
setValue(next.text);
setCaret(next.caret);
requestAnimationFrame(() => { field.current?.focus(); field.current?.setSelectionRange(next.caret, next.caret); });
};
return createPortal(<div className="bt-palette-backdrop bt-addcol-backdrop" onMouseDown={onClose}>
<div ref={dialog} className="bt-palette bt-addcol bt-pop" role="dialog" aria-modal="true" aria-labelledby="bt-addcol-title" onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
<header className="bt-addcol-head">
<h2 id="bt-addcol-title">{t('wb.deck.addColumn')}</h2>
<span>{t('wb.addcol.to', { deck: deck.name })}</span>
<button className="bt-icon" aria-label={t('wb.common.close')} onClick={onClose}><Icon name="close"/></button>
</header>
<div className="bt-addcol-types" role="radiogroup" aria-label={t('wb.addcol.type')}>
{types.map(item => <button key={item.kind} data-kind={item.kind} role="radio" aria-checked={item.kind === kind} tabIndex={item.kind === kind ? 0 : -1}
className={`bt-addcol-type${item.kind === kind ? ' is-on' : ''}`} onClick={() => setKind(item.kind)} onDoubleClick={() => { if (!item.value) onAdd({ profile, source: { kind: item.kind } }); }}>
<span className="bt-addcol-icon"><Icon name={item.icon}/></span>
<strong>{item.label}</strong>
<small>{item.hint}</small>
</button>)}
</div>
{type.value && <div className="bt-addcol-value">
<label htmlFor="bt-addcol-field">{type.value.label}</label>
<div className={`bt-addcol-field${value && parsed === null ? ' is-bad' : ''}`}>
<Icon name={type.icon}/>
<input id="bt-addcol-field" ref={field} spellCheck={false} autoComplete="off" placeholder={type.value.placeholder} value={value}
onChange={event => { setValue(event.target.value); setCaret(event.target.selectionStart ?? event.target.value.length); }}
onSelect={() => setCaret(field.current?.selectionStart ?? value.length)}
onKeyDown={event => { if (event.key === 'Tab' && !event.shiftKey && chips[0]) { event.preventDefault(); acceptChip(chips[0].insert); } }}/>
</div>
{chips.length > 0 && <div className="bt-addcol-chips" role="listbox" aria-label={completer?.label()}>
{chips.map((chip, index) => <button key={chip.insert} type="button" role="option" aria-selected={index === 0} title={`${chip.hint}${index === 0 ? ` (${t('wb.web.tabKey')})` : ''}`}
onMouseDown={event => event.preventDefault()} onClick={() => acceptChip(chip.insert)}>{chip.label}</button>)}
</div>}
{value && parsed === null && <p className="bt-addcol-error" role="alert">{spec.invalid(kind)}</p>}
</div>}
<div className="bt-addcol-accounts">
<span className="bt-addcol-label">{t('wb.addcol.account')}</span>
<div role="radiogroup" aria-label={t('wb.addcol.account')}>
{profiles.profiles.map(p => <button key={p.id} role="radio" aria-checked={p.id === profile} className={`bt-addcol-account${p.id === profile ? ' is-on' : ''}`} onClick={() => setProfile(p.id)}
style={{ ['--bt-col-account' as string]: p.color }}>
<AccountAvatar profile={p} size={22}/><span>{p.account ? `${handlePrefix}${p.account.handle}` : accountLabel(p).title}</span>
{p.account && !p.account.signedIn && <em>{t('wb.addcol.signedOut')}</em>}
</button>)}
</div>
</div>
<footer className="bt-addcol-foot">
<span><span className="bt-kbd">↵</span> {t('wb.addcol.add')}</span><span><span className="bt-kbd">Esc</span> {t('wb.addcol.close')}</span>
<span className="bt-palette-foot-end"/>
<button className="bt-deck-secondary" onClick={onClose}>{t('wb.common.cancel')}</button>
<button className="bt-deck-primary" disabled={!valid} onClick={submit}><Icon name="plus"/>{t('wb.addcol.submit')}</button>
</footer>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,116 @@
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Avatar, Icon } from './icons.tsx';
import { buildItems, moveSelection, type PaletteAction, type PaletteContext, type PaletteItem } from './paletteModel.ts';
import { hasFeature, site } from './site.ts';
import { setOverlay } from './state.ts';
/** Leading visual for a palette row: the tab's favicon, the account avatar or the item's glyph. */
function leading(item: PaletteItem, context: PaletteContext): ReactNode {
const [kind, ...rest] = item.id.split(':');
const key = rest.join(':');
if (kind === 'tab') {
const favicon = context.tabs.find(tab => `tab:${tab.id}` === item.id)?.favicon;
return favicon ? <img src={favicon} alt="" width={16} height={16}/> : <Icon name="globe"/>;
}
if (kind === 'profile') {
const profile = context.profiles.find(p => p.id === key);
return <Avatar name={profile?.name ?? '?'} color={profile?.color ?? '#8a90a6'} size={20}/>;
}
if (item.icon) return <Icon name={item.icon}/>;
if (kind === 'deck' || kind === 'deck-new') return <Icon name="grid"/>;
if (kind === 'deck-add') return <Icon name="plus"/>;
if (kind === 'deck-focus') return <Icon name="list"/>;
if (kind === 'ws') return <Icon name="grid"/>;
if (kind === 'ws-save') return <Icon name="plus"/>;
return <Icon name="search"/>;
}
const shortHint = (hint: string) => hint.replace(/^https?:\/\/(www\.)?/, '');
/** The frame's group names are translated; the site names its own groups; plugin groups are the plugins' names. */
const GROUPS: Record<string, string> = {
Tabs: 'wb.palette.group.tabs', Deck: 'wb.palette.group.deck', Workspaces: 'wb.palette.group.workspaces', Profiles: 'wb.palette.group.profiles',
};
const groupLabel = (group: string) => (GROUPS[group] ? t(GROUPS[group]!) : site().palette.groupLabel?.(group) ?? group);
/** Ctrl+K palette. The shell rises above the tab webviews (or hides them) while it is open. */
export function CommandPalette({ context, onRun, onClose }: { context: PaletteContext; onRun: (action: PaletteAction) => void; onClose: () => void }) {
const [query, setQuery] = useState('');
const [selected, setSelected] = useState(0);
const input = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const items = useMemo(() => {
const { palette, product, deck, media } = site();
return buildItems(context, query, { site: palette, product, decks: !!deck, media: !!media, workspaces: hasFeature('workspaces') });
}, [context, query]);
useEffect(() => {
setOverlay(1);
input.current?.focus();
const close = () => onClose();
window.addEventListener('blur', close);
return () => { setOverlay(-1); window.removeEventListener('blur', close); };
}, []);
useEffect(() => setSelected(0), [query]);
useEffect(() => { list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }); }, [selected]);
const run = (index: number) => {
const item = items[index];
if (!item) return;
if (item.action.type === 'complete') { setQuery(item.action.text); input.current?.focus(); return; }
onClose();
onRun(item.action);
};
const onKeyDown = (event: ReactKeyboardEvent) => {
if (event.nativeEvent.isComposing) return;
// Ctrl+K again closes, like the shortcut that opened it.
if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'k') { event.preventDefault(); event.stopPropagation(); onClose(); return; }
if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, 1, items.length)); }
else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, -1, items.length)); }
else if (event.key === 'Home' && event.ctrlKey) { event.preventDefault(); setSelected(0); }
else if (event.key === 'End' && event.ctrlKey) { event.preventDefault(); setSelected(Math.max(0, items.length - 1)); }
else if (event.key === 'Enter') { event.preventDefault(); run(selected); }
else if (event.key === 'Escape') { event.preventDefault(); onClose(); }
event.stopPropagation();
};
const tr = useT();
let lastGroup = '';
return createPortal(<div className="bt-palette-backdrop" onMouseDown={onClose}>
<div className="bt-palette bt-pop" role="dialog" aria-label={tr('wb.palette.title')} onMouseDown={event => event.stopPropagation()} onKeyDown={onKeyDown}>
<div className="bt-palette-field">
<Icon name="search"/>
<input ref={input} className="bt-palette-input" placeholder={site().palette.placeholder()} value={query}
onChange={event => setQuery(event.target.value)} role="combobox" aria-expanded="true" aria-controls="bt-palette-list"
aria-activedescendant={items[selected] ? `bt-pal-${selected}` : undefined} spellCheck={false}/>
<kbd className="bt-kbd">Esc</kbd>
</div>
<div className="bt-palette-list" id="bt-palette-list" role="listbox" ref={list}>
{items.length === 0 && <div className="bt-palette-empty">{tr('wb.palette.none')}</div>}
{items.map((item, index) => {
const heading = item.group !== lastGroup ? item.group : null;
lastGroup = item.group;
return <div key={item.id}>
{heading && <div className="bt-palette-group">{groupLabel(heading)}</div>}
<div id={`bt-pal-${index}`} role="option" aria-selected={index === selected} className="bt-palette-item"
onMouseMove={() => { if (selected !== index) setSelected(index); }} onClick={() => run(index)}>
<span className="bt-palette-icon">{leading(item, context)}</span>
<span className="bt-palette-label">{item.label}</span>
{item.hint && <span className={`bt-palette-hint ${item.hint === tr('wb.palette.active') ? 'bt-palette-hint--tag' : ''}`}>{shortHint(item.hint)}</span>}
<span className="bt-palette-enter" aria-hidden="true">↵</span>
</div>
</div>;
})}
</div>
<div className="bt-palette-foot">
<span><kbd className="bt-kbd">↑</kbd><kbd className="bt-kbd">↓</kbd> {tr('wb.palette.navigate')}</span>
<span><kbd className="bt-kbd">↵</kbd> {tr('wb.common.open')}</span>
<span><kbd className="bt-kbd">{tr('wb.web.tabKey')}</kbd> {tr('wb.palette.next')}</span>
<span className="bt-palette-foot-end"><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">K</kbd> {tr('wb.common.close')}</span>
</div>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,369 @@
// Decks: site columns side by side in one shell tab (dockview component `deck`). The shell draws
// the deck bar and a header per column; each column's body is a placeholder that a real site tab
// webview (its own account profile) covers, laid out by state.ts. Paging, not pixel scrolling: a
// page holds as many whole columns as fit; the others are parked off-page. Every request and every
// action in a column is the site's own; the shell only navigates, focuses and configures columns
// (native `column_configure`). The kinds of columns are the site's (`site.deck`).
import type { IDockviewPanelProps } from 'dockview';
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { COLUMN_GAP, COLUMN_WIDTHS, isSourcePage, layoutColumns, pageOf, unreadTotal } from '../deckModel.ts';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { AddColumnDialog } from './AddColumnDialog.tsx';
import { invoke } from './bridge.ts';
import {
addColumn, bump, columnSourceUrl, configureColumn, deckById, decks, patchColumn, removeColumn, shiftColumn,
type Deck, type DeckColumn,
} from './deckStore.ts';
import { useDecks, useProfiles, useT } from './hooks.ts';
import { Icon, type IconName } from './icons.tsx';
import { site } from './site.ts';
import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts';
import './deck.css';
const emitDecks = () => window.dispatchEvent(new CustomEvent('bt-decks'));
const unreadLabel = (count: number) => (count > 999 ? '999+' : String(count));
const deckSite = () => site().deck!;
/** Width of the columns row minus an open compose dock. */
function columnsWidth(total: number, deckId: string) {
const compose = deckSite().compose;
return compose && decks.compose.has(deckId) ? Math.max(0, total - compose.width - COLUMN_GAP) : total;
}
// ---------------------------------------------------------------------------------------------
// Deck commands (keys, palette, column menus)
export type DeckCommand =
| 'column-prev' | 'column-next' | 'column-page-prev' | 'column-page-next' | 'column-mark-read' | 'column-jump-unread' | 'deck-compose'
| `column-${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`;
/** The row width each deck was last laid out at (for paging from keys). */
const rowWidths = new Map<string, number>();
/** Focuses a column: it becomes the deck's focused column, its page is shown and its webview gets the keys. */
export function focusColumn(deckId: string, columnId: string, giveKeys = true) {
const deck = deckById(deckId);
const column = deck?.columns.find(c => c.id === columnId);
if (!deck || !column) return;
decks.focus.set(deckId, columnId);
const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId);
decks.page.set(deckId, pageOf(width, deck.columns, columnId, { maxVisible: decks.settings.maxVisible }, decks.page.get(deckId)));
emitDecks();
scheduleSync();
if (giveKeys) requestAnimationFrame(() => tabAction(column.tabId, 'focus'));
}
export function runDeckCommand(deckId: string, command: string) {
const deck = deckById(deckId);
if (!deck) return;
const focused = deck.columns.find(c => c.id === decks.focus.get(deckId)) ?? deck.columns[0];
const index = focused ? deck.columns.indexOf(focused) : -1;
const digit = /^column-([1-9])$/.exec(command);
if (digit) { const target = deck.columns[Number(digit[1]) - 1]; if (target) focusColumn(deckId, target.id); return; }
switch (command) {
case 'column-prev': case 'column-next': {
const target = deck.columns[Math.min(deck.columns.length - 1, Math.max(0, index + (command === 'column-next' ? 1 : -1)))];
if (target) focusColumn(deckId, target.id);
break;
}
case 'column-page-prev': case 'column-page-next': {
const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId);
const layout = layoutColumns(width, deck.columns, (decks.page.get(deckId) ?? 0) + (command === 'column-page-next' ? 1 : -1), { maxVisible: decks.settings.maxVisible });
decks.page.set(deckId, layout.page);
const first = layout.visible[0];
if (first) decks.focus.set(deckId, first.id);
emitDecks();
scheduleSync();
break;
}
case 'column-mark-read': if (focused) bump(focused, 'read'); break;
case 'column-jump-unread': if (focused) bump(focused, 'jump'); break;
case 'deck-compose': toggleCompose(deckId, focused?.profile); break;
}
}
export function toggleCompose(deckId: string, profile?: string) {
if (!deckSite().compose) return;
if (decks.compose.has(deckId)) decks.compose.delete(deckId);
else decks.compose.set(deckId, { profile: tabProfile(shell.profiles, profile ?? shell.profiles.active).id });
emitDecks();
scheduleSync();
}
// ---------------------------------------------------------------------------------------------
// Popovers (the shell rises above the tab webviews, or hides them, while one is open)
function Popover({ anchor, onClose, children, width = 260, label }: { anchor: DOMRect; onClose(): void; children: ReactNode; width?: number; label: string }) {
useEffect(() => {
setOverlay(1);
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation(); onClose(); } };
window.addEventListener('keydown', onKey, true);
window.addEventListener('blur', onClose);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey, true); window.removeEventListener('blur', onClose); };
}, []);
const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8));
const style: CSSProperties = { top: anchor.bottom + 6, left, width };
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-deck-pop bt-pop bt-pop--right" role="dialog" aria-label={label} style={style} onMouseDown={event => event.stopPropagation()}>{children}</div>
</div>, document.body);
}
function FilterPopover({ deckId, column, anchor, onClose }: { deckId: string; column: DeckColumn; anchor: DOMRect; onClose(): void }) {
const tr = useT();
const [text, setText] = useState('');
const input = useRef<HTMLInputElement>(null);
useEffect(() => { input.current?.focus(); }, []);
const filters = column.filters;
const set = (patch: Partial<DeckColumn['filters']>) => patchColumn(deckId, column.id, { filters: { ...filters, ...patch } });
const add = () => {
const terms = text.split(/\n|,(?![^/]*\/[a-z]*$)/).map(t => t.trim()).filter(Boolean).filter(t => t.length <= 200);
if (!terms.length) return;
set({ terms: [...filters.terms, ...terms.filter(t => !filters.terms.includes(t))].slice(0, 32) });
setText('');
};
const toggle = (key: 'hideReplies' | 'hideReposts' | 'mediaOnly', label: string, hint: string) =>
<label className="bt-deck-check"><input type="checkbox" checked={filters[key]} onChange={event => set({ [key]: event.target.checked })}/>
<span className="bt-deck-check-box" aria-hidden="true"><Icon name="check"/></span><span className="bt-deck-check-text"><strong>{label}</strong><small>{hint}</small></span></label>;
return <Popover anchor={anchor} onClose={onClose} width={300} label={tr('wb.deck.filters.label')}>
<div className="bt-deck-pop-head"><Icon name="filter"/><strong>{tr('wb.deck.filters')}</strong><span>{deckSite().title(column.source, column.title).title}</span></div>
<div className="bt-deck-terms">
<input ref={input} className="bt-deck-input" spellCheck={false} placeholder={tr('wb.deck.mutePlaceholder')} aria-label={tr('wb.deck.muteLabel')} value={text}
onChange={event => setText(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); add(); } }}/>
{filters.terms.length > 0 && <div className="bt-deck-chips">
{filters.terms.map(term => <span key={term} className={`bt-deck-chip ${/^\/.+\/[imsu]*$/.test(term) ? 'is-regex' : ''}`}>
<span>{term}</span><button type="button" aria-label={tr('wb.common.removeItem', { item: term })} onClick={() => set({ terms: filters.terms.filter(t => t !== term) })}><Icon name="close"/></button></span>)}
</div>}
</div>
<hr/>
{toggle('hideReplies', tr('wb.deck.hideReplies'), tr('wb.deck.hideRepliesHint'))}
{toggle('hideReposts', tr('wb.deck.hideReposts'), tr('wb.deck.hideRepostsHint'))}
{toggle('mediaOnly', tr('wb.deck.mediaOnly'), tr('wb.deck.mediaOnlyHint'))}
</Popover>;
}
function ColumnMenu({ deck, column, anchor, onClose, onRemove }: { deck: Deck; column: DeckColumn; anchor: DOMRect; onClose(): void; onRemove(): void }) {
const tr = useT();
const index = deck.columns.indexOf(column);
const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) =>
<button role="menuitem" disabled={disabled} onClick={() => { onClose(); action(); }}>
<Icon name={icon}/><span className="bt-menu-label">{label}</span>{keys && <span className="bt-menu-keys">{keys}</span>}</button>;
const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source) ?? '';
return <Popover anchor={anchor} onClose={onClose} width={236} label={tr('wb.deck.menu')}>
{item(tr('wb.deck.markRead'), 'check', () => bump(column, 'read'), false, 'Alt R')}
{item(tr('wb.deck.jumpUnread'), 'history', () => bump(column, 'jump'), false, 'Alt U')}
<hr/>
{item(tr('wb.deck.moveLeft'), 'back', () => shiftColumn(deck.id, column.id, -1), index <= 0)}
{item(tr('wb.deck.moveRight'), 'forward', () => shiftColumn(deck.id, column.id, 1), index >= deck.columns.length - 1)}
<div className="bt-deck-widths" role="group" aria-label={tr('wb.deck.widthLabel')}>
<span>{tr('wb.deck.width')}</span>
{COLUMN_WIDTHS.map(width => <button key={width} type="button" aria-pressed={column.width === width} className={column.width === width ? 'is-on' : ''}
onClick={() => { patchColumn(deck.id, column.id, { width }); scheduleSync(); }}>{width}</button>)}
</div>
<hr/>
{item(tr('wb.shell.menu.duplicate'), 'duplicate', () => addColumn(deck.id, { profile: column.profile, source: column.source, filters: column.filters, flags: column.flags, width: column.width }, column.id))}
{item(tr('wb.deck.openAsTab'), 'external', () => shell.openUrl(url, column.profile), !url)}
<hr/>
{item(tr('wb.deck.remove'), 'trash', onRemove)}
</Popover>;
}
// ---------------------------------------------------------------------------------------------
// One column: header strip + the placeholder its webview covers
function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; column: DeckColumn; x: number; width: number; focused: boolean; number: number }) {
const tr = useT();
const profiles = useProfiles();
const body = useRef<HTMLDivElement>(null);
const [menu, setMenu] = useState<null | { kind: 'filters' | 'menu'; anchor: DOMRect }>(null);
const [leaving, setLeaving] = useState(false);
const spec = deckSite();
const runtime = decks.runtime.get(column.tabId);
const account = tabProfile(profiles, column.profile);
const type = spec.kinds.find(kind => kind.kind === column.source.kind);
const { title, detail } = spec.title(column.source, column.title);
const source = columnSourceUrl(column.source);
const away = !!(runtime?.url && source && !isSourcePage(runtime.url, source));
const unread = runtime?.unread ?? 0;
const filtered = column.filters.terms.length > 0 || column.filters.hideReplies || column.filters.hideReposts || column.filters.mediaOnly;
const pageTitle = spec.pageTitle ?? ((text: string) => text);
useLayoutEffect(() => {
const el = body.current;
if (!el || leaving) return;
shell.placeholders.set(column.tabId, el);
const observer = new ResizeObserver(scheduleSync);
observer.observe(el);
scheduleSync();
return () => {
observer.disconnect();
if (shell.placeholders.get(column.tabId) === el) shell.placeholders.delete(column.tabId);
scheduleSync();
};
}, [column.tabId, leaving]);
// Position changes (paging, reordering, width) move the webview with the placeholder.
useEffect(() => { scheduleSync(); }, [x, width]);
const open = (kind: 'filters' | 'menu') => (event: ReactMouseEvent<HTMLButtonElement>) =>
setMenu(menu?.kind === kind ? null : { kind, anchor: event.currentTarget.getBoundingClientRect() });
const remove = () => {
setLeaving(true);
// The webview hides at once (no placeholder); the header slides out, then the column goes.
const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
setTimeout(() => removeColumn(deck.id, column.id), reduced ? 0 : 180);
};
return <section className={`bt-col${focused ? ' is-focused' : ''}${leaving ? ' is-leaving' : ''}`} style={{ left: x, width, ['--bt-col-account' as string]: account.color }}
aria-label={tr('wb.deck.columnLabel', { title })} onMouseDown={() => { if (!focused) focusColumn(deck.id, column.id, false); }}>
<header className="bt-col-head">
{away
? <button className="bt-col-glyph bt-col-back" title={tr('wb.deck.backTo', { title })} aria-label={tr('wb.deck.backTo', { title })}
onClick={() => { if (source) invoke('tab_navigate', { id: column.tabId, url: source }).catch(() => {}); }}><Icon name="back"/></button>
: <span className="bt-col-glyph" aria-hidden="true"><Icon name={type?.icon ?? 'globe'}/></span>}
<div className="bt-col-titles" title={detail ? `${title} · ${detail}` : title}>
<strong>{title}</strong>
<span>{away ? (pageTitle(runtime?.title ?? '') || tr('wb.deck.viewingPost')) : detail ?? `${site().accounts.handlePrefix}${account.account?.handle ?? account.name}`}</span>
</div>
{unread > 0 && <button className="bt-col-unread" title={tr('wb.deck.jumpUnreadTitle')} aria-label={tr('wb.deck.unreadLabel', { count: unread })} onClick={() => bump(column, 'jump')}>{unreadLabel(unread)}</button>}
<span className="bt-col-fill"/>
<span className="bt-col-account" title={tr('wb.shell.tab.account', { name: accountName(account) })}><AccountAvatar profile={account} size={20}/></span>
<button className={`bt-icon bt-col-btn${filtered ? ' is-active' : ''}`} title={tr('wb.deck.filters')} aria-label={tr('wb.deck.filters')} aria-haspopup="dialog" aria-expanded={menu?.kind === 'filters'} onClick={open('filters')}><Icon name="filter"/></button>
<button className="bt-icon bt-col-btn" title={tr('wb.deck.menu')} aria-label={tr('wb.deck.menu')} aria-haspopup="menu" aria-expanded={menu?.kind === 'menu'} onClick={open('menu')}>
<svg className="bt-glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 12h.01M12 12h.01M18 12h.01" strokeWidth="3"/></svg></button>
{number <= 9 && <span className="bt-col-key" aria-hidden="true">{number}</span>}
{runtime?.loading && <span className="bt-col-progress" aria-label={tr('wb.common.loading')}/>}
</header>
<div className="bt-col-body" ref={body}>
<div className="bt-col-hint"><span className="bt-spinner" aria-hidden="true"/><span>{title}</span></div>
</div>
{menu?.kind === 'filters' && <FilterPopover deckId={deck.id} column={column} anchor={menu.anchor} onClose={() => setMenu(null)}/>}
{menu?.kind === 'menu' && <ColumnMenu deck={deck} column={column} anchor={menu.anchor} onClose={() => setMenu(null)} onRemove={remove}/>}
</section>;
}
// ---------------------------------------------------------------------------------------------
function EmptyDeck({ deck, onAdd }: { deck: Deck; onAdd(): void }) {
const tr = useT();
const profiles = useProfiles();
const ids = profiles.profiles.map(p => p.id);
const ordered = [profiles.active, ...ids.filter(id => id !== profiles.active)];
return <div className="bt-deck-empty bt-rise">
<div className="bt-deck-empty-art" aria-hidden="true">{[0, 1, 2, 3].map(i => <span key={i} style={{ animationDelay: `${i * 70}ms` }}/>)}</div>
<h2>{tr('wb.deck.title')}</h2>
<p>{tr('wb.deck.emptyHint', { site: site().name })}</p>
<div className="bt-deck-empty-actions">
<button className="bt-deck-primary" onClick={onAdd}><Icon name="plus"/>{tr('wb.deck.addColumn')}</button>
{(deckSite().presets ?? []).map(preset => {
const needs = preset.needsTwoAccounts && ids.length < 2 ? preset.needsTwoAccounts() : undefined;
return <button key={preset.id} className="bt-deck-secondary" disabled={!!needs} title={needs}
onClick={() => { for (const column of preset.columns(ordered)) addColumn(deck.id, column); }}>{preset.label()}</button>;
})}
</div>
<p className="bt-deck-empty-keys">
<span><span className="bt-kbd">[</span><span className="bt-kbd">]</span> {tr('wb.deck.key.columns')}</span>
<span><span className="bt-kbd">Alt</span><span className="bt-kbd">1–9</span> {tr('wb.deck.key.jump')}</span>
<span><span className="bt-kbd">Alt</span><span className="bt-kbd">R</span> {tr('wb.deck.key.read')}</span>
{deckSite().compose && <span><span className="bt-kbd">Ctrl</span><span className="bt-kbd">Alt</span><span className="bt-kbd">N</span> {tr('wb.deck.key.post')}</span>}
</p>
</div>;
}
export function DeckView(props: IDockviewPanelProps<DeckParams>) {
const tr = useT();
useDecks();
const deckId = props.params.deckId;
const row = useRef<HTMLDivElement>(null);
const [rowWidth, setRowWidth] = useState(0);
const [adding, setAdding] = useState(false);
const deck = deckById(deckId);
const compose = deckSite().compose;
useLayoutEffect(() => {
const el = row.current;
if (!el) return;
const measure = () => { const w = Math.floor(el.getBoundingClientRect().width); rowWidths.set(deckId, w); setRowWidth(w); };
const observer = new ResizeObserver(measure);
observer.observe(el);
measure();
return () => observer.disconnect();
}, [deckId, !!deck]);
useEffect(() => {
const visibility = props.api.onDidVisibilityChange(scheduleSync);
// The palette's "Add column…" opens this deck's dialog.
const add = (event: Event) => { if ((event as CustomEvent<string>).detail === deckId) setAdding(true); };
window.addEventListener('bt-deck-add', add);
return () => { visibility.dispose(); window.removeEventListener('bt-deck-add', add); };
}, [props.api, deckId]);
// Every column gets its config before its webview exists (no flash of the site's chrome);
// unmounting the deck forgets what was sent, so reopening it configures again.
useEffect(() => {
if (!deck) return;
for (const column of deck.columns) {
if (decks.sent.has(column.tabId)) continue;
void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); scheduleSync(); });
}
});
useEffect(() => () => {
for (const column of deckById(deckId)?.columns ?? []) { decks.sent.delete(column.tabId); decks.ready.delete(column.tabId); }
}, [deckId]);
if (!deck) {
return <div className="bt-deck"><div className="bt-deck-empty"><h2>{tr('wb.deck.gone')}</h2><p>{tr('wb.deck.goneHint')}</p>
<button className="bt-deck-secondary" onClick={() => props.api.close()}>{tr('wb.shell.menu.close')}</button></div></div>;
}
const settings = decks.settings;
const width = columnsWidth(rowWidth, deck.id);
const layout = layoutColumns(width, deck.columns, decks.page.get(deck.id) ?? 0, { maxVisible: settings.maxVisible });
const focusedId = decks.focus.get(deck.id) ?? layout.visible[0]?.id;
const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns);
const setPage = (page: number) => { decks.page.set(deck.id, page); emitDecks(); scheduleSync(); };
const composing = compose && decks.compose.get(deck.id);
const overLimit = deck.columns.length > settings.maxVisible;
return <div className="bt-deck">
<div className="bt-deck-bar">
<span className="bt-deck-mark" aria-hidden="true"><Icon name="grid"/></span>
<strong className="bt-deck-name">{deck.name}</strong>
<span className="bt-deck-count">{tr('wb.deck.columnCount', { count: deck.columns.length })}</span>
{total > 0 && <span className="bt-deck-total" title={tr('wb.deck.unreadTitle')}>{tr('wb.deck.newCount', { count: unreadLabel(total) })}</span>}
<span className="bt-deck-fill"/>
{layout.pages > 1 && <div className="bt-deck-pager" role="group" aria-label={tr('wb.deck.pages')}>
<button className="bt-icon" title={tr('wb.deck.prevTitle')} aria-label={tr('wb.deck.prev')} disabled={layout.page === 0} onClick={() => setPage(layout.page - 1)}><Icon name="back"/></button>
{Array.from({ length: layout.pages }, (_, i) => <button key={i} className={`bt-deck-dot${i === layout.page ? ' is-on' : ''}`} aria-label={tr('wb.deck.page', { n: i + 1 })} aria-current={i === layout.page ? 'page' : undefined} onClick={() => setPage(i)}/>)}
<button className="bt-icon" title={tr('wb.deck.nextTitle')} aria-label={tr('wb.deck.next')} disabled={layout.page >= layout.pages - 1} onClick={() => setPage(layout.page + 1)}><Icon name="forward"/></button>
</div>}
{overLimit && <span className="bt-deck-memory" title={tr('wb.deck.memoryTitle', { count: decks.settings.maxVisible, site: site().name })}>{tr('wb.deck.onScreen', { visible: layout.visible.length, total: deck.columns.length })}</span>}
<button className="bt-deck-action" onClick={() => setAdding(true)} title={tr('wb.deck.addColumn')}><Icon name="plus"/><span>{tr('wb.deck.column')}</span></button>
{compose && <button className={`bt-deck-action${composing ? ' is-on' : ''}`} onClick={() => toggleCompose(deck.id, deck.columns.find(c => c.id === focusedId)?.profile)} title={tr('wb.deck.postTitle')} aria-pressed={!!composing}>
<Icon name="edit"/><span>{tr('wb.deck.post')}</span></button>}
<button className="bt-icon bt-deck-settings" title={tr('wb.deck.settings')} aria-label={tr('wb.deck.settings')} onClick={() => shell.openPanelSection('power')}><Icon name="settings"/></button>
</div>
<div className="bt-deck-row" ref={row}>
{deck.columns.length === 0
? <EmptyDeck deck={deck} onAdd={() => setAdding(true)}/>
: layout.visible.map(place => {
const column = deck.columns.find(c => c.id === place.id)!;
return <ColumnView key={column.id} deck={deck} column={column} x={place.x} width={place.width} focused={column.id === focusedId}
number={deck.columns.indexOf(column) + 1}/>;
})}
{compose && composing && <compose.Dock deckId={deck.id} left={width + COLUMN_GAP}/>}
</div>
{adding && <AddColumnDialog deck={deck} onClose={() => setAdding(false)} onAdd={input => {
const column = addColumn(deck.id, input);
void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); focusColumn(deck.id, column.id, false); });
setAdding(false);
}}/>}
</div>;
}
/** Unread total of a deck on its dockview tab. */
export function DeckTabBadge({ deckId }: { deckId: string }) {
useDecks();
const deck = deckById(deckId);
if (!deck) return null;
const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns);
return total > 0 ? <span className="bt-tab-unread" aria-label={`${total} unread`}>{unreadLabel(total)}</span> : null;
}

View file

@ -0,0 +1,113 @@
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { invoke, listen } from './bridge.ts';
import { useT } from './hooks.ts';
import { attachTarget, clipPreview, folderLabel, relativeTime, type ClipItem, type GalleryImage, type MediaSettings } from './mediaModel.ts';
import { site } from './site.ts';
import { isWeb, setOverlay, shell, type WebParams } from './state.ts';
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
function targetTab() {
const api = shell.api;
const media = site().media;
if (!api || !media) return null;
const tabs = api.panels.filter(isWeb).map(panel => ({ id: panel.id, url: (panel.params as WebParams).url }));
return attachTarget(tabs, api.activePanel?.id, media.canAttach);
}
/** Lazily loads one preview (a data URL read natively, only from inside a gallery folder). */
function Thumb({ command, args, alt }: { command: string; args: Record<string, unknown>; alt: string }) {
const [src, setSrc] = useState<string | null>(null);
useEffect(() => {
let live = true;
invoke<string>(command, args).then(url => { if (live) setSrc(url); }).catch(() => {});
return () => { live = false; };
}, [command, JSON.stringify(args)]);
return src ? <img src={src} alt={alt} loading="lazy" draggable={false}/> : <span className="bt-media-thumb-empty"/>;
}
/**
* Media side panel: recent images from the owner's gallery folders and the local clipboard
* history. Choosing an item attaches the image to (or inserts the text into) the composer of the
* active site tab (`site.media.canAttach`). Nothing is posted; the user reviews and sends it themselves.
*/
export function MediaPanel({ onClose }: { onClose: () => void }) {
const t = useT();
const siteName = site().name;
const [tab, setTab] = useState<'gallery' | 'clipboard'>('gallery');
const [settings, setSettings] = useState<MediaSettings | null>(null);
const [images, setImages] = useState<GalleryImage[] | null>(null);
const [clips, setClips] = useState<ClipItem[] | null>(null);
const [error, setError] = useState('');
const refresh = () => {
invoke<MediaSettings>('media_get').then(setSettings).catch(err => setError(getError(err)));
invoke<GalleryImage[]>('gallery_list', { limit: 60 }).then(setImages).catch(err => setError(getError(err)));
invoke<ClipItem[]>('clip_list').then(setClips).catch(err => setError(getError(err)));
};
useEffect(() => {
setOverlay(1);
invoke('shell_focus').catch(() => {});
refresh();
const unlisten = listen('clipboard-changed', () => { invoke<ClipItem[]>('clip_list').then(setClips).catch(() => {}); });
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey); unlisten.then(dispose => dispose()).catch(() => {}); };
}, []);
const deliver = (command: 'tab_attach_image' | 'tab_insert_text', args: Record<string, unknown>) => {
const target = targetTab();
if (!target) { setError(t('wb.media.noComposer', { site: siteName })); return; }
onClose();
shell.api?.getPanel(target.id)?.api.setActive();
// Wait until the tab webview is shown again (the overlay hid it), then attach. Never posts.
setTimeout(() => {
invoke(command, { id: target.id, ...args }).catch(err => console.warn('[shell] media attach failed', err));
}, 150);
};
const addFolder = () => invoke<MediaSettings>('gallery_add_folder').then(next => { setSettings(next); refresh(); }).catch(err => setError(getError(err)));
const removeClip = (id: string) => invoke<ClipItem[]>('clip_remove', { id }).then(setClips).catch(err => setError(getError(err)));
return createPortal(<div className="bt-palette-backdrop bt-media-backdrop" onMouseDown={onClose}>
<aside className="bt-media" role="dialog" aria-label={t('wb.media.title')} onMouseDown={event => event.stopPropagation()}>
<header className="bt-media-head">
<div className="bt-media-tabs" role="tablist">
<button role="tab" aria-selected={tab === 'gallery'} className={tab === 'gallery' ? 'active' : ''} onClick={() => setTab('gallery')}>{t('wb.media.gallery')}</button>
<button role="tab" aria-selected={tab === 'clipboard'} className={tab === 'clipboard' ? 'active' : ''} onClick={() => setTab('clipboard')}>{t('wb.media.clipboard')}</button>
</div>
<button className="bt-icon bt-media-close" aria-label={t('wb.common.close')} title={t('wb.media.closeTitle')} onClick={onClose}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
</header>
{error && <div className="bt-media-error" role="alert">{error}</div>}
{tab === 'gallery' && <div className="bt-media-body">
{settings && settings.folders.length === 0 && <div className="bt-media-empty"><p>{t('wb.media.pickFolders')}</p><button className="button small" onClick={() => void addFolder()}>{t('wb.media.addFolder')}</button></div>}
{settings && settings.folders.length > 0 && <div className="bt-media-folders">{settings.folders.map(folder => <span key={folder} className="pill" title={folder}>{folderLabel(folder)}</span>)}<button className="bt-media-link" onClick={() => void addFolder()}>{t('wb.media.add')}</button></div>}
{images && images.length > 0 && <div className="bt-media-grid">
{images.map(image => <button key={image.path} className="bt-media-tile" title={t('wb.media.attachTitle', { name: image.name })} onClick={() => deliver('tab_attach_image', { source: { kind: 'gallery', path: image.path } })}>
<Thumb command="gallery_thumb" args={{ path: image.path }} alt={image.name}/>
<span className="bt-media-caption">{relativeTime(image.modifiedMs)}</span>
</button>)}
</div>}
{settings && settings.folders.length > 0 && images?.length === 0 && <div className="bt-media-empty"><p>{t('wb.media.noImages')}</p></div>}
</div>}
{tab === 'clipboard' && <div className="bt-media-body">
{settings && !settings.clipboardEnabled && <div className="bt-media-empty"><p>{t('wb.media.clipOff', { count: settings.clipboardMax })}</p></div>}
{clips && clips.length === 0 && settings?.clipboardEnabled && <div className="bt-media-empty"><p>{t('wb.media.clipEmpty')}</p></div>}
{clips && clips.length > 0 && <ul className="bt-media-clips">
{clips.map(item => <li key={item.id} className="bt-media-clip">
<button className="bt-media-clip-main" title={t('wb.media.putIn')} onClick={() => item.kind === 'image'
? deliver('tab_attach_image', { source: { kind: 'clip', id: item.id } })
: deliver('tab_insert_text', { text: item.text ?? '' })}>
{item.kind === 'image' ? <span className="bt-media-clip-thumb"><Thumb command="clip_thumb" args={{ id: item.id }} alt={t('wb.media.copiedImage')}/></span> : <span className="bt-media-clip-text">{clipPreview(item)}</span>}
<small>{relativeTime(item.at)}</small>
</button>
<button className="bt-icon" aria-label={t('wb.media.removeFromHistory')} title={t('wb.common.remove')} onClick={() => void removeClip(item.id)}><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
</li>)}
</ul>}
</div>}
<footer className="bt-palette-foot"><span>{t('wb.media.clickToAttach', { site: siteName })}</span><span>{t('wb.media.youPost')}</span></footer>
</aside>
</div>, document.body);
}

View file

@ -0,0 +1,112 @@
import { useEffect, useRef, useState } from 'react';
import { tabProfile } from '../profileModel.ts';
import { invoke } from './bridge.ts';
import { useProfiles, useSiteText, useT } from './hooks.ts';
import { Avatar, Icon } from './icons.tsx';
import { toUrl } from './searchInput.ts';
import { site } from './site.ts';
import { shell } from './state.ts';
const hostOf = (url: string) => { try { return new URL(url).host.replace(/^www\./, ''); } catch { return url; } };
/** Human label for a closed tab without a stored title: the address bar's own reading of the URL. */
function labelFor(url: string, title: string | undefined): string {
if (title) return title;
const model = site().address(url);
if (!model) return url;
return [model.site.label, ...model.segments.map(segment => segment.label)].join(' / ');
}
/**
* The new-tab page (and the empty-dock state): one search/address field, the site's quick links,
* recently closed tabs and the account the links open in. Drawn by the shell; it never has a webview.
*/
export function NewTabPage({ panelId, profile: initialProfile, onProfile }: { panelId?: string; profile?: string; onProfile?: (id: string) => void }) {
const profiles = useProfiles();
useSiteText();
const [profile, setProfile] = useState(() => tabProfile(profiles, initialProfile ?? profiles.active).id);
const [query, setQuery] = useState('');
const [, refresh] = useState(0);
const input = useRef<HTMLInputElement>(null);
const multi = profiles.profiles.length > 1;
const recent = shell.closed.map((tab, index) => ({ ...tab, index })).reverse().slice(0, 6);
const { logo, newTab, isSiteUrl } = site();
useEffect(() => {
const focus = (event: Event) => {
if ((event as CustomEvent<string>).detail !== panelId) return;
input.current?.focus();
input.current?.select();
};
window.addEventListener('bt-focus-address', focus);
return () => window.removeEventListener('bt-focus-address', focus);
}, [panelId]);
const open = (url: string) => shell.openFromStart(url, profile, panelId);
const pick = (id: string) => { setProfile(id); onProfile?.(id); };
const reopen = (index: number) => {
const [tab] = shell.closed.splice(index, 1);
refresh(value => value + 1);
if (tab) shell.openFromStart(tab.url, tabProfile(profiles, tab.profile).id, panelId);
};
const t = useT();
const search = newTab.search();
return <div className="bt-start">
<div className="bt-start-inner">
<div className="bt-start-mark bt-rise" aria-hidden="true"><img src={logo} alt="" width={40} height={40} draggable={false}/></div>
<form className="bt-start-search bt-rise" style={{ animationDelay: '30ms' }} role="search"
onSubmit={event => { event.preventDefault(); if (query.trim()) open(toUrl(query, site().searchUrl)); }}>
<Icon name="search"/>
<input ref={input} value={query} onChange={event => setQuery(event.target.value)} spellCheck={false} autoComplete="off"
aria-label={search} placeholder={search}
onFocus={() => invoke('shell_focus').catch(() => {})}
onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); setQuery(''); } }}/>
<kbd className="bt-kbd">{t('wb.newtab.enter')}</kbd>
</form>
{multi && <div className="bt-start-accounts bt-rise" style={{ animationDelay: '60ms' }} role="radiogroup" aria-label={t('wb.newtab.openLinksAs')}>
<span className="bt-start-label">{t('wb.newtab.openAs')}</span>
{profiles.profiles.map(item => <button key={item.id} type="button" role="radio" aria-checked={item.id === profile}
className="bt-start-account" onClick={() => pick(item.id)}>
<Avatar name={item.name} color={item.color} size={20}/><span>{item.name}</span>
</button>)}
</div>}
{newTab.links.length > 0 && <section className="bt-start-section bt-rise" style={{ animationDelay: '90ms' }} aria-label={t('wb.newtab.goTo')}>
<div className="bt-start-links">
{newTab.links.map(link => {
const url = link.url(shell.homeUrl);
return <button key={link.id} type="button" className="bt-start-link" title={url} onClick={() => open(url)}>
<span className="bt-start-link-icon"><Icon name={link.icon}/></span>
<span className="bt-start-link-label">{link.label()}</span>
</button>;
})}
</div>
</section>}
{recent.length > 0 && <section className="bt-start-section bt-rise" style={{ animationDelay: '120ms' }} aria-labelledby="bt-start-recent">
<h2 className="bt-start-label" id="bt-start-recent">{t('wb.newtab.recent')}</h2>
<ul className="bt-start-recent">
{recent.map(tab => {
const account = tabProfile(profiles, tab.profile);
return <li key={`${tab.index}:${tab.url}`}>
<button type="button" className="bt-start-row" title={tab.url} onClick={() => reopen(tab.index)}>
{isSiteUrl(tab.url) ? <img className="bt-start-row-icon" src={logo} alt="" width={16} height={16}/> : <span className="bt-start-row-icon"><Icon name="globe"/></span>}
<span className="bt-start-row-title">{labelFor(tab.url, tab.title)}</span>
<span className="bt-start-row-host">{hostOf(tab.url)}</span>
{multi && <Avatar name={account.name} color={account.color} size={16}/>}
</button>
</li>;
})}
</ul>
</section>}
<footer className="bt-start-foot bt-rise" style={{ animationDelay: '150ms' }}>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">K</kbd> {t('wb.newtab.commands')}</span>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">⇧</kbd><kbd className="bt-kbd">T</kbd> {t('wb.newtab.reopen')}</span>
<span><kbd className="bt-kbd">Ctrl</kbd><kbd className="bt-kbd">\</kbd> {t('wb.newtab.split')}</span>
</footer>
</div>
</div>;
}

View file

@ -0,0 +1,82 @@
// "Theme for this pane": a menu (tab context menu, the address bar's ⋯ menu) that gives one pane its
// own theme or lets it follow its account's / the global theme again. Pane themes are stored with
// the other scopes (themeStore.ts → native `theme_scopes_set`), which re-themes that tab natively.
// Only with themes (`site.themes`).
import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { useT, useThemeState } from './hooks.ts';
import { Icon } from './icons.tsx';
import { site } from './site.ts';
import { setOverlay, shell } from './state.ts';
import { assign, themeIdFor } from './themeScopes.ts';
import type { ThemeDoc, ThemeStore } from './themeStore.ts';
import './paneTheme.css';
type Request = { id: string; profile: string; x: number; y: number };
let open: (request: Request | null) => void = () => {};
export const openPaneTheme = (request: Request) => open(request);
/** Three dots of a theme's page, text and accent. */
export function ThemeDots<Spec extends ThemeDoc>({ theme, store }: { theme: Spec; store?: ThemeStore<unknown, Spec> }) {
const themes = (store ?? site().themes) as ThemeStore<unknown, Spec> | undefined;
if (!themes) return null;
const c = themes.adapter.dots(theme);
return <span className="wb-dots" aria-hidden="true" style={{ background: c.page }}>
<i style={{ background: c.bg, boxShadow: `inset 0 0 0 1px ${c.border}` }}/><i style={{ background: c.text }}/><i style={{ background: c.accent }}/>
</span>;
}
export function PaneThemeHost() {
const [request, setRequest] = useState<Request | null>(null);
open = setRequest;
const themes = site().themes;
return request && themes ? <PaneThemeMenu request={request} store={themes} onClose={() => setRequest(null)}/> : null;
}
function PaneThemeMenu({ request, store, onClose }: { request: Request; store: ThemeStore<unknown, ThemeDoc>; onClose(): void }) {
const { scopes, choice } = useThemeState(store);
const list = useRef<HTMLDivElement>(null);
useEffect(() => {
setOverlay(1);
const onBlur = () => onClose();
window.addEventListener('blur', onBlur);
requestAnimationFrame(() => list.current?.querySelector<HTMLButtonElement>('[aria-checked=true]')?.focus());
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, []);
const own = scopes.panes[request.id];
const inherited = themeIdFor({ ...scopes, panes: {} }, { profile: request.profile }, store.adapter.preset(choice), id => store.knownTheme(id));
const pick = (theme: string | null) => {
onClose();
void store.setScopes(assign(store.themeState().scopes, 'panes', request.id, theme)).catch(() => {});
};
const onKey = (event: ReactKeyboardEvent) => {
const items = [...(list.current?.querySelectorAll<HTMLButtonElement>('button') ?? [])];
const index = items.indexOf(document.activeElement as HTMLButtonElement);
if (event.key === 'Escape') { event.preventDefault(); onClose(); }
else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
items[(index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus();
} else if (event.key === 'Home' || event.key === 'End') { event.preventDefault(); items[event.key === 'Home' ? 0 : items.length - 1]?.focus(); }
};
const t = useT();
const left = Math.max(8, Math.min(request.x, window.innerWidth - 280));
const top = Math.max(8, Math.min(request.y, window.innerHeight - 440));
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-pop wb-pane-menu" role="menu" aria-label={t('wb.pane.theme')} style={{ left, top }} onMouseDown={event => event.stopPropagation()} onKeyDown={onKey} ref={list}>
<div className="wb-pane-menu-head"><Icon name="palette"/><span>{t('wb.pane.theme')}</span></div>
<button role="menuitemradio" aria-checked={!own} onClick={() => pick(null)}>
<span className="bt-menu-label">{inherited.source === 'account' ? t('wb.pane.followAccount') : t('wb.pane.followApp')} <small>· {store.themeName(inherited.id)}</small></span>
{!own && <Icon name="check"/>}
</button>
<hr/>
<div className="wb-pane-menu-list">
{store.allThemes(choice).map(theme => <button key={theme.id} role="menuitemradio" aria-checked={own === theme.id} onClick={() => pick(theme.id)}>
<ThemeDots theme={theme} store={store}/><span className="bt-menu-label">{theme.name}</span>{own === theme.id && <Icon name="check"/>}
</button>)}
</div>
<hr/>
<button role="menuitem" onClick={() => { onClose(); shell.openPanelSection('themes'); }}><Icon name="settings"/><span className="bt-menu-label">{t('wb.pane.themesLink')}</span></button>
</div>
</div>, document.body);
}

View file

@ -0,0 +1,807 @@
// The shell: a trusted local page that fills the window and hosts the dock (dockview): tabs in the
// titlebar row, splits, the new-tab page, decks, the app's panel tab, link drags into the dock,
// keyboard shortcuts, overlays (menus, palette, dialogs) and session layout persistence. Each web
// tab is a native child webview that native code places over its pane (`tabs_sync`, state.ts).
import {
DockviewReact, themeDark,
type DockviewApi, type DockviewGroupPanel, type DockviewReadyEvent, type IDockviewHeaderActionsProps, type IDockviewPanel,
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
} from 'dockview';
import 'dockview/dist/styles/dockview.css';
import { useEffect, useState, type MouseEvent as ReactMouseEvent } from 'react';
import { createPortal } from 'react-dom';
import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts';
import { besideGroup } from '../paneModel.ts';
import { tabProfile } from '../profileModel.ts';
import { accountAction } from './accountModel.ts';
import { accountLabel } from './AccountSwitcher.tsx';
import { invoke, listen } from './bridge.ts';
import { CommandPalette } from './CommandPalette.tsx';
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx';
import { createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts';
import { installDevHost } from './devHost.ts';
import { useProfiles, useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import { MediaPanel } from './MediaPanel.tsx';
import { NewTabPage } from './NewTabPage.tsx';
import type { PaletteAction, PaletteContext } from './paletteModel.ts';
import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx';
import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts';
import { hasFeature, site } from './site.ts';
import {
isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
} from './state.ts';
import { installSyncHost } from './syncHost.ts';
import { ResizeGrips, Titlebar, titlebarContextMenu } from './Titlebar.tsx';
import { openWorkspaceSave } from './TitlebarExtras.tsx';
import { WebPanel } from './WebPanel.tsx';
import { frameless, isTauri, onMaximizedChange, os } from './windowBinding.ts';
import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
import './shell.css';
type Placement = { referencePanel: string; direction: 'within' | 'right' | 'below' };
/** A development build (createShell's `dev`): the shell keeps the devtools shortcut. */
let devBuild = false;
export function setDevBuild(value: boolean) {
devBuild = value;
}
/** Opens a web tab. `profile` defaults to the switcher's active account. */
const originOf = (url: string) => { try { return new URL(url).origin; } catch { return ''; } };
function addWeb(url: string, placement?: Placement | DropPlacement, activate = true, profile = shell.profiles.active, besideOf?: string): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const valid = placement && ('referencePanel' in placement ? !!api.getPanel(placement.referencePanel)
: 'referenceGroup' in placement ? !!api.getGroup(placement.referenceGroup) : true);
const reference = valid ? placement : undefined;
return api.addPanel<WebParams>({
id: newTabId(),
component: 'web',
title: t('wb.shell.tab.new'),
params: { kind: 'web', url, profile: tabProfile(shell.profiles, profile).id, ...(besideOf ? { besideOf } : {}) },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
inactive: !activate,
});
}
/**
* The "pane" link setting: opens `url` in the side pane right of `source`'s group: split once, then
* reused. A link clicked inside a side pane stays in that pane instead of splitting again.
*/
function openBeside(url: string, source: IDockviewPanel, activate: boolean, profile?: string) {
const api = shell.api;
if (!api) return;
const origin = isWeb(source) ? (source.params as WebParams).besideOf : undefined;
if (origin) { addWeb(url, { referenceGroup: source.group.id, direction: 'within' }, activate, profile, origin); return; }
const box = (group: DockviewGroupPanel) => {
const rect = group.element.getBoundingClientRect();
const besideOf = group.panels.map(panel => (panel.params as Partial<WebParams> | undefined)?.besideOf).filter((id): id is string => !!id);
return { id: group.id, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, besideOf };
};
const target = besideGroup(box(source.group), api.groups.map(box));
addWeb(url, target ? { referenceGroup: target, direction: 'within' } : { referencePanel: source.id, direction: 'right' }, activate, profile, source.group.id);
}
/** Opens the new-tab page (shell-drawn, no webview) in the active group; links from it keep `profile`. */
function addStart(profile = shell.profiles.active, placement?: Placement): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const reference = placement && api.getPanel(placement.referencePanel) ? placement : undefined;
const panel = api.addPanel<StartParams>({
id: newTabId(),
component: 'start',
title: t('wb.shell.tab.new'),
params: { kind: 'start', profile: tabProfile(shell.profiles, profile).id },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
});
focusAddress(panel.id);
return panel;
}
/** A link chosen on a new-tab page opens in that page's place; the page itself goes away. */
function openFromStart(url: string, profile: string, startId?: string) {
const start = startId ? shell.api?.getPanel(startId) : undefined;
if (!start) { addWeb(url, undefined, true, profile); return; }
const group = start.group;
addWeb(url, { referenceGroup: group.id, direction: 'within', index: group.panels.indexOf(start) }, true, profile);
start.api.close();
}
/**
* Account switcher click: a visible pane of that account gets focus; otherwise its home feed (or the
* site's sign-in) opens in a new pane right of the focused one. `force` opens a tab in the focused
* group instead; `url` opens that page of the account (e.g. the site's sign-out) beside.
*/
function openAccount(profile: string, options: { force?: boolean; url?: string } = {}) {
const api = shell.api;
if (!api) return;
const active = api.activePanel;
const { homeUrl, loginUrl, isSiteUrl } = site();
const action = options.url
? { type: 'open' as const, url: options.url, profile: tabProfile(shell.profiles, profile).id, where: 'beside' as const }
: accountAction(shell.profiles, paneInfos(), active?.id, profile, { force: options.force, homeUrl, loginUrl, isSiteUrl });
if (action.type === 'focus') {
const panel = api.getPanel(action.paneId);
panel?.api.setActive();
if (panel) tabAction(panel.id, 'focus');
return;
}
const placement = active ? { referencePanel: active.id, direction: action.where === 'tab' ? 'within' as const : 'right' as const } : undefined;
addWeb(action.url, placement, true, action.profile);
}
// ---------------------------------------------------------------------------------------------
// Decks of site columns (DeckView.tsx; only with `site.deck`)
const deckPanelId = (deckId: string) => `deck-${deckId}`;
/** The last focused tab that is not a deck, for Ctrl+Shift+D back and forth. */
let lastNonDeck: string | null = null;
/** Opens (or focuses) a deck tab; with no deck yet, creates one. */
function openDeck(deckId?: string) {
const api = shell.api;
if (!api || !site().deck) return;
const deck = (deckId && deckById(deckId)) || decks.list[0] || createDeck(t('wb.shell.deck.default'));
const existing = api.getPanel(deckPanelId(deck.id));
if (existing) { existing.api.setActive(); return; }
api.addPanel<DeckParams>({
id: deckPanelId(deck.id), component: 'deck', title: deck.name, params: { kind: 'deck', deckId: deck.id },
position: api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined,
});
}
/** Ctrl+Shift+D: to the deck, and from the deck back to the tab you came from. */
function toggleDeck() {
const api = shell.api;
const active = api?.activePanel;
if (active && (active.params as TabParams).kind === 'deck') {
const back = lastNonDeck ? api?.getPanel(lastNonDeck) : undefined;
back?.api.setActive();
if (back && isWeb(back)) tabAction(back.id, 'focus');
return;
}
openDeck();
}
/** The deck a shortcut is about: the column's deck (keys pressed in a column), else the active deck tab. */
function deckFor(id?: string): string | null {
const found = id ? findColumnTab(id) : null;
if (found) return found.deck.id;
const params = shell.api?.activePanel?.params as TabParams | undefined;
return params?.kind === 'deck' ? params.deckId : null;
}
function openPanel(section?: string, from?: string) {
const api = shell.api;
if (!api) return;
const existing = api.getPanel(panelId());
const nonce = Date.now();
if (existing) {
if (section) existing.api.updateParameters({ section, nonce });
existing.api.setActive();
return;
}
// Open beside the site so both stay visible; a second group means split view.
const reference = from && api.getPanel(from) ? { referencePanel: from, direction: 'right' as const } : undefined;
api.addPanel<PanelParams>({ id: panelId(), component: 'panel', title: site().panel.title, params: { kind: 'panel', section, nonce }, position: reference });
}
function closeTab(panel: IDockviewPanel) {
if ((panel.params as TabParams).pinned) return;
if (isWeb(panel)) { const { url, profile } = panel.params as WebParams; shell.closed.push({ url, profile, title: panel.api.title || undefined }); }
panel.api.close();
}
export function splitTab(panel: IDockviewPanel, direction: 'right' | 'below') {
// A lone tab cannot be moved out of its group, so split opens a copy of it instead.
if (panel.group.panels.length > 1) {
panel.api.moveTo({ group: panel.group, position: direction === 'right' ? 'right' : 'bottom' });
} else if (isWeb(panel)) {
const { url, profile } = panel.params as WebParams;
addWeb(url, { referencePanel: panel.id, direction }, true, profile);
}
}
function cycleTabs(step: number) {
const group = shell.api?.activeGroup;
if (!group || group.panels.length < 2) return;
const index = group.panels.findIndex(panel => panel.id === group.activePanel?.id);
group.panels[(index + step + group.panels.length) % group.panels.length]?.api.setActive();
}
function focusAddress(id: string) {
invoke('shell_focus').catch(() => {});
requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-focus-address', { detail: id })));
}
let togglePalette: () => void = () => {};
let toggleMedia: () => void = () => {};
function paletteContext(): PaletteContext {
const panels = shell.api?.panels.filter(isWeb) ?? [];
const deck = site().deck;
return {
tabs: panels.map(panel => ({ id: panel.id, title: panel.api.title ?? '', url: (panel.params as WebParams).url, favicon: (panel.params as WebParams).favicon })),
profiles: shell.profiles.profiles.map(({ id, name, color }) => ({ id, name, color })),
activeProfile: shell.profiles.active,
decks: deck ? decks.list.map(item => ({
id: item.id, name: item.name,
columns: item.columns.map(column => ({ id: column.id, title: deck.title(column.source, column.title).title, profile: column.profile })),
})) : undefined,
activeDeck: (() => { const params = shell.api?.activePanel?.params as TabParams | undefined; return params?.kind === 'deck' ? params.deckId : undefined; })(),
workspaces: hasFeature('workspaces') ? workspaceList() : undefined,
activeWorkspace: workspaces.active ?? undefined,
// Plugin commands of the focused site tab (they run there).
commands: focusedCommands(),
};
}
/** Palette actions only navigate; account changes are completed by the user on the site's own pages. */
function runPalette(action: PaletteAction) {
const api = shell.api;
if (!api) return;
switch (action.type) {
case 'focus-tab': api.getPanel(action.id)?.api.setActive(); break;
case 'new-tab': shell.newTab(action.profile); break;
case 'panel': openPanel(action.section, api.activePanel?.id); break;
case 'open': addWeb(action.url); break;
case 'media': toggleMedia(); break;
case 'deck': openDeck(action.deckId); break;
case 'deck-new': openDeck(createDeck(`Deck ${decks.list.length + 1}`).id); break;
case 'deck-add': openDeck(action.deckId); requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-deck-add', { detail: action.deckId }))); break;
case 'deck-focus': openDeck(action.deckId); requestAnimationFrame(() => focusColumn(action.deckId, action.columnId)); break;
case 'plugin-command': runPluginCommand(action.tab, action.command); break;
case 'workspace': void restoreWorkspace(action.id); break;
case 'workspace-save': openWorkspaceSave(); break;
}
}
function runShortcut(shortcut: string, id?: string) {
const api = shell.api;
if (!api) return;
if (shortcut === 'command-palette') { togglePalette(); return; }
if (shortcut === 'deck-toggle') { toggleDeck(); return; }
if (shortcut.startsWith('column-') || shortcut === 'deck-compose') {
const deckId = deckFor(id);
if (deckId) runDeckCommand(deckId, shortcut);
return;
}
// A browser shortcut pressed inside a deck column acts on its deck tab.
if (id && !api.getPanel(id) && findColumnTab(id)) id = deckPanelId(findColumnTab(id)!.deck.id);
const panel = (id && api.getPanel(id)) || api.activePanel;
switch (shortcut) {
case 'new-tab': addStart(); break;
case 'close-tab': if (panel) closeTab(panel); break;
case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; }
case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break;
case 'next-tab': cycleTabs(1); break;
case 'prev-tab': cycleTabs(-1); break;
case 'reload': case 'hard-reload': if (panel && isWeb(panel)) tabAction(panel.id, 'reload'); break;
case 'back': if (panel && isWeb(panel)) tabAction(panel.id, 'back'); break;
case 'forward': if (panel && isWeb(panel)) tabAction(panel.id, 'forward'); break;
case 'split-right': if (panel) splitTab(panel, 'right'); break;
case 'split-down': if (panel) splitTab(panel, 'below'); break;
case 'open-panel': openPanel(undefined, panel?.id); break;
case 'media-panel': toggleMedia(); break;
}
}
const editable = (target: EventTarget | null) => {
const el = target as HTMLElement | null;
return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName));
};
/** Deck keys pressed in the shell itself (a column header, the deck bar) while a deck tab is active. */
function deckShortcutFor(event: KeyboardEvent): string | null {
const mod = event.ctrlKey || event.metaKey;
if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle';
if ((shell.api?.activePanel?.params as TabParams | undefined)?.kind !== 'deck' || editable(event.target)) return null;
if (event.ctrlKey && event.altKey && !event.shiftKey && event.code === 'KeyN') return 'deck-compose';
if (event.altKey && !mod && !event.shiftKey) {
const digit = /^Digit([1-9])$/.exec(event.code);
if (digit) return `column-${digit[1]}`;
if (event.key === 'PageUp') return 'column-page-prev';
if (event.key === 'PageDown') return 'column-page-next';
if (event.code === 'KeyR') return 'column-mark-read';
if (event.code === 'KeyU') return 'column-jump-unread';
}
if (!mod && !event.altKey && event.key === '[') return 'column-prev';
if (!mod && !event.altKey && event.key === ']') return 'column-next';
return null;
}
function shortcutFor(event: KeyboardEvent): string | null {
const deck = site().deck ? deckShortcutFor(event) : null;
if (deck) return deck;
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (mod && !event.altKey) {
if (key === 't') return event.shiftKey ? 'reopen-tab' : 'new-tab';
if (key === 'w') return event.shiftKey ? 'open-panel' : 'close-tab';
if (key === 'l') return 'focus-address';
if (key === 'g' && event.shiftKey) return 'media-panel';
if (key === 'k' && !event.shiftKey) return 'command-palette';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return 'reload';
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
}
if (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;
}
// ---------------------------------------------------------------------------------------------
// Link drags: a link dragged out of a tab (or in from another app) drops as a new tab or split.
/**
* While active, the native tab webviews are hidden so the OS drag reaches the shell and dockview's
* drop zones. `internal`: a drag that started in the shell itself (tab moves, list reordering).
*/
const linkDrag = {
active: false, internal: false, url: null as string | null, from: undefined as string | undefined,
lastOver: 0, sawOver: false, blockedUntil: 0, timer: undefined as ReturnType<typeof setInterval> | undefined,
};
function beginLinkDrag(from?: string, url?: string) {
if (linkDrag.internal) return;
if (!linkDrag.active) {
// A tab that keeps announcing drags that never reach the shell cannot keep the panes hidden.
if (Date.now() < linkDrag.blockedUntil) return;
Object.assign(linkDrag, { active: true, sawOver: false, lastOver: Date.now(), url: null, from: undefined });
setOverlay(1);
document.querySelector('.bt-shell')?.classList.add('bt-shell--link-drag');
// Esc or a drop outside the window may end the drag without any event here.
linkDrag.timer = setInterval(() => { if (Date.now() - linkDrag.lastOver > 1500) endLinkDrag(true); }, 250);
}
if (url) { linkDrag.url = url; linkDrag.from = from; }
}
function endLinkDrag(timedOut = false) {
if (!linkDrag.active) return;
clearInterval(linkDrag.timer);
if (timedOut && !linkDrag.sawOver) linkDrag.blockedUntil = Date.now() + 5000;
Object.assign(linkDrag, { active: false, url: null, from: undefined, timer: undefined });
document.querySelector('.bt-shell')?.classList.remove('bt-shell--link-drag');
setOverlay(-1);
}
/** Opens the dropped link where it was dropped, in the source tab's account (else the active one). */
function dropLink(event: DragEvent, placement: DropPlacement | undefined) {
const url = dropUrl(type => event.dataTransfer?.getData(type) ?? '', linkDrag.url);
const source = linkDrag.from ? shell.api?.getPanel(linkDrag.from) : undefined;
const profile = source && isWeb(source) ? (source.params as WebParams).profile : shell.profiles.active;
endLinkDrag();
if (url) addWeb(url, placement, true, profile);
}
const dragTypes = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []);
// ---------------------------------------------------------------------------------------------
type Menu = { x: number; y: number; panel: IDockviewPanel };
let openMenu: (menu: Menu) => void = () => {};
function ContextMenu({ menu, onClose }: { menu: Menu; onClose: () => void }) {
const t = useT();
const { panel } = menu;
const params = panel.params as TabParams;
const web = params.kind === 'web' ? params : null;
const group = panel.group;
useEffect(() => {
setOverlay(1);
const close = () => onClose();
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
window.addEventListener('blur', close);
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('blur', close); window.removeEventListener('keydown', onKey); };
}, []);
const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) =>
<button role="menuitem" disabled={disabled} onClick={() => { onClose(); action(); }}>
<Icon name={icon}/><span className="bt-menu-label">{label}</span>{keys && <span className="bt-menu-keys">{keys}</span>}
</button>;
const others = group.panels.filter(other => other.id !== panel.id && !(other.params as TabParams).pinned);
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-pop" role="menu" style={{ left: Math.max(8, Math.min(menu.x, window.innerWidth - 248)), top: Math.max(8, Math.min(menu.y, window.innerHeight - 360)) }} onMouseDown={event => event.stopPropagation()}>
{item(params.pinned ? t('wb.shell.menu.unpin') : t('wb.shell.menu.pin'), params.pinned ? 'unpin' : 'pin', () => {
panel.api.updateParameters({ pinned: !params.pinned });
if (!params.pinned) panel.api.moveTo({ group, index: 0 });
saveLayoutSoon();
})}
{web && item(t('wb.shell.menu.duplicate'), 'duplicate', () => addWeb(web.url, { referencePanel: panel.id, direction: 'within' }, true, web.profile))}
{web && item(t('wb.shell.menu.reload'), 'reload', () => tabAction(panel.id, 'reload'), false, 'Ctrl R')}
<hr/>
{item(t('wb.shell.menu.splitRight'), 'split', () => splitTab(panel, 'right'), !web && group.panels.length < 2, 'Ctrl \\')}
{item(t('wb.shell.menu.splitDown'), 'splitDown', () => splitTab(panel, 'below'), !web && group.panels.length < 2, 'Ctrl ⇧ \\')}
{web && <>
<hr/>
{site().themes && item(t('wb.shell.menu.paneTheme'), 'palette', () => openPaneTheme({ id: panel.id, profile: tabProfile(shell.profiles, web.profile).id, x: menu.x, y: menu.y }))}
{item(t('wb.shell.menu.copyLink'), 'copy', () => void navigator.clipboard?.writeText(web.url))}
{item(t('wb.shell.menu.openBrowser'), 'external', () => invoke('open_external_url', { url: web.url }).catch(() => {}))}
</>}
<hr/>
{item(t('wb.shell.menu.close'), 'close', () => closeTab(panel), !!params.pinned, 'Ctrl W')}
{item(t('wb.shell.menu.closeOthers'), 'closeOthers', () => others.forEach(closeTab), others.length === 0)}
</div>
</div>, document.body);
}
function Favicon({ params }: { params: TabParams }) {
const t = useT();
const [broken, setBroken] = useState(false);
useEffect(() => setBroken(false), [params.kind === 'web' ? params.favicon : '']);
if (params.kind === 'panel') return <img className="bt-favicon" src={site().logo} alt=""/>;
if (params.kind === 'start') return <Icon name="sparkle" className="bt-favicon bt-favicon--glyph"/>;
if (params.kind === 'deck') return <Icon name="grid" className="bt-favicon bt-favicon--glyph bt-favicon--deck"/>;
if (params.loading) return <span className="bt-favicon bt-spinner" role="img" aria-label={t('wb.common.loading')}/>;
if (params.favicon && !broken) return <img key={params.favicon} className="bt-favicon bt-favicon--img" src={params.favicon} alt="" onError={() => setBroken(true)}/>;
return <Icon name="globe" className="bt-favicon bt-favicon--glyph"/>;
}
function Tab(props: IDockviewPanelHeaderProps<TabParams>) {
const t = useT();
const profiles = useProfiles();
const [title, setTitle] = useState(props.api.title ?? '');
useEffect(() => { const sub = props.api.onDidTitleChange(event => setTitle(event.title)); return () => sub.dispose(); }, [props.api]);
const params = props.params;
const panel = shell.api?.getPanel(props.api.id);
const onContextMenu = (event: ReactMouseEvent) => { event.preventDefault(); if (panel) openMenu({ x: event.clientX, y: event.clientY, panel }); };
const account = params.kind !== 'panel' && params.kind !== 'deck' && profiles.profiles.length > 1 ? tabProfile(profiles, params.profile) : null;
const accountName = account ? `${accountLabel(account).title}${account.account ? ` (${site().accounts.handlePrefix}${account.account.handle})` : ''}` : '';
const loading = params.kind === 'web' && !!params.loading;
// Titles saved by older sessions (or before the page reports one) said "New tab" in English.
const shown = params.kind === 'start' || !title || title === 'New tab' ? t('wb.shell.tab.new') : title;
return <div className={`bt-tab${params.pinned ? ' pinned bt-tab--pinned' : ''}${loading ? ' bt-tab--loading' : ''}`}
title={account ? `${shown} · ${accountName}` : shown} onContextMenu={onContextMenu}
onAuxClick={event => { if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}>
<span className="bt-tab-icon">
<Favicon params={params}/>
{account && <span className="bt-tab-account" style={{ background: account.color }} aria-label={t('wb.shell.tab.account', { name: accountName })}/>}
</span>
{!params.pinned && <span className="bt-tab-title">{shown}</span>}
{params.kind === 'deck' && <DeckTabBadge deckId={params.deckId}/>}
{!params.pinned && <button className="bt-tab-close" title={t('wb.shell.tab.closeTitle')} aria-label={t('wb.shell.menu.close')} onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); if (panel) closeTab(panel); }}>
<Icon name="close"/></button>}
</div>;
}
function GroupActions(props: IDockviewHeaderActionsProps) {
const t = useT();
return <div className="bt-group-actions">
<button className="bt-icon bt-newtab" title={t('wb.shell.tab.newTitle')} aria-label={t('wb.shell.tab.new')} onClick={() => addStart(undefined, { referencePanel: props.group.activePanel?.id ?? '', direction: 'within' })}>
<Icon name="plus"/></button>
</div>;
}
function AppPanel(props: IDockviewPanelProps<PanelParams>) {
const section = props.params.section ? { name: props.params.section, nonce: props.params.nonce ?? 0 } : undefined;
const Panel = site().panel.component;
return <div className="bt-panel"><Panel section={section}/></div>;
}
function StartPanel(props: IDockviewPanelProps<StartParams>) {
return <NewTabPage panelId={props.api.id} profile={props.params.profile}
onProfile={profile => { props.api.updateParameters({ profile }); saveLayoutSoon(); }}/>;
}
/** Every tab closed: the dock shows the new-tab page itself. */
function Watermark() {
return <NewTabPage/>;
}
const components = { web: WebPanel, panel: AppPanel, start: StartPanel, deck: DeckView };
/**
* Groups whose top edge touches the dock top host their tabs in the titlebar row: their header is
* TITLEBAR_H tall and transparent, the empty part drags the window. The leftmost one leaves room
* for the logo, the rightmost one for the caption buttons.
*/
function markTitlebarGroups() {
const api = shell.api;
const dock = document.querySelector('.bt-dock');
if (!api || !dock) return;
const bounds = dock.getBoundingClientRect();
document.querySelector('.bt-shell')?.classList.toggle('bt-shell--empty', api.groups.length === 0);
for (const group of api.groups) {
const el = group.element;
const rect = el.getBoundingClientRect();
const top = group.api.location.type === 'grid' && Math.abs(rect.top - bounds.top) < 1;
el.classList.toggle('bt-group--in-titlebar', top);
el.classList.toggle('bt-group--tb-left', top && Math.abs(rect.left - bounds.left) < 1);
el.classList.toggle('bt-group--tb-right', top && Math.abs(rect.right - bounds.right) < 1);
const voidContainer = el.querySelector('.dv-void-container');
if (voidContainer) {
if (top) voidContainer.setAttribute('data-tauri-drag-region', '');
else voidContainer.removeAttribute('data-tauri-drag-region');
}
}
}
export default function Shell() {
const [menu, setMenu] = useState<Menu | null>(null);
const [maximized, setMaximized] = useState(false);
const [palette, setPalette] = useState<PaletteContext | null>(null);
const [media, setMedia] = useState(false);
const { overlays = [] } = site();
openMenu = setMenu;
togglePalette = () => { invoke('shell_focus').catch(() => {}); void refreshPluginNames(); setPalette(open => open ? null : paletteContext()); };
toggleMedia = () => { if (isTauri && site().media) setMedia(open => !open); };
shell.split = (id, direction) => { const panel = shell.api?.getPanel(id); if (panel) splitTab(panel, direction); };
shell.openPanel = from => openPanel(undefined, from);
shell.newTab = profile => { addStart(profile); };
shell.openFromStart = openFromStart;
shell.openAccount = openAccount;
shell.openUrl = (url, profile) => { addWeb(url, undefined, true, profile); };
shell.openPanelSection = section => openPanel(section, shell.api?.activePanel?.id);
useEffect(() => {
document.documentElement.dataset.os = os;
if (!isTauri) return;
const unlisten = onMaximizedChange(value => setMaximized(value));
return () => { unlisten.then(dispose => dispose()).catch(() => {}); };
}, []);
// Maximize/restore changes the resize-band inset: re-send the tab rectangles once laid out.
useEffect(() => { requestAnimationFrame(() => { markTitlebarGroups(); scheduleSync(); }); }, [maximized]);
// Plugin palette commands, developer mode (live reload) and encrypted folder sync.
useEffect(() => {
if (!isTauri) return;
const off = [
hasFeature('pluginCommands') ? installPluginCommands() : null,
hasFeature('developer') ? installDevHost() : null,
hasFeature('sync') ? installSyncHost() : null,
].filter((dispose): dispose is () => void => !!dispose);
return () => off.forEach(dispose => dispose());
}, []);
// The site's own settings and events (e.g. X's Twitter/X wording).
useEffect(() => site().start?.(), []);
useEffect(() => {
const unlisten = [
// A tab saw its account sign in or out (native code already saved it): refresh the switcher.
listen<unknown>('profiles-changed', ({ payload }) => setProfiles(payload)),
listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number }>('tab-state', ({ payload }) => {
const panel = shell.api?.getPanel(payload.id);
if (!panel) {
// A deck column (or a deck's compose dock) reports about its own webview.
const found = findColumnTab(payload.id);
if (!found) return;
setRuntime(payload.id, { url: payload.url, title: payload.title, loading: payload.loading, unread: payload.unread });
if (found.compose) site().deck?.compose?.navigated?.(payload.id, payload.url, payload.loading);
if (payload.focused && found.column && decks.focus.get(found.deck.id) !== found.column.id) {
decks.focus.set(found.deck.id, found.column.id);
window.dispatchEvent(new CustomEvent('bt-decks'));
}
return;
}
// Another site must not keep the previous one's icon until (or unless) it reports its own.
const previous = (panel.params as WebParams).url;
const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf(previous) ? '' : undefined);
patchParams(panel, { url: payload.url, loading: payload.loading, favicon, title: payload.title });
if (payload.title !== undefined) panel.api.setTitle(payload.title || (panel.params as WebParams).url);
// A click into a visible pane makes it the active tab. A tab that is no longer shown (a link it
// opened just took its place in the group) reports a late focus too: it must not jump back.
if (payload.focused && !panel.api.isActive && panel.api.isVisible) panel.api.setActive();
saveLayoutSoon();
}),
listen<{ url: string; from?: string; background: boolean; beside?: boolean }>('tab-open', ({ payload }) => {
// Links opened from a tab stay in that tab's account; they never jump to another login.
const source = payload.from ? shell.api?.getPanel(payload.from) : undefined;
const column = payload.from && !source ? findColumnTab(payload.from) : null;
const profile = source && isWeb(source) ? (source.params as WebParams).profile
: column ? (column.column?.profile ?? decks.compose.get(column.deck.id)?.profile ?? shell.profiles.active) : shell.profiles.active;
if (column) { addWeb(payload.url, undefined, !payload.background, profile); return; }
if (payload.beside && source) { openBeside(payload.url, source, !payload.background, profile); return; }
addWeb(payload.url, payload.from ? { referencePanel: payload.from, direction: 'within' } : undefined, !payload.background, profile);
}),
listen<{ id: string; shortcut: string }>('tab-shortcut', ({ payload }) => runShortcut(payload.shortcut, payload.id)),
listen<{ from: string; section?: string }>('open-panel', ({ payload }) => openPanel(payload.section, payload.from)),
// A tab's link drag: `start` carries the natively validated link, `enter` is an external drag.
listen<{ id: string; phase: 'start' | 'enter' | 'end'; url?: string }>('link-drag', ({ payload }) => {
if (payload.phase === 'end') endLinkDrag();
else if (shell.api?.getPanel(payload.id)) beginLinkDrag(payload.id, payload.url);
}),
];
const onKey = (event: KeyboardEvent) => {
const shortcut = shortcutFor(event);
if (shortcut) {
// Leave text editing shortcuts (e.g. Ctrl+L/T in inputs) alone except tab management.
event.preventDefault();
runShortcut(shortcut);
return;
}
if (!isTauri) return;
// Browser-engine keys that make no sense in the shell itself (the tab webviews handle their own).
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (event.key === 'F5') { event.preventDefault(); runShortcut('reload'); return; }
if (mod && !event.altKey && (key === 'p' || key === 'f')) { event.preventDefault(); return; }
if (mod && event.shiftKey && key === 'i' && !devBuild) event.preventDefault();
};
const onContextMenu = (event: MouseEvent) => {
const target = event.target as Element | null;
if (target?.closest?.('input, textarea')) return;
if (frameless && target?.closest?.('.bt-group--in-titlebar .dv-void-container')) { titlebarContextMenu(event); return; }
event.preventDefault();
};
const onMouseUp = (event: MouseEvent) => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
runShortcut(event.button === 3 ? 'back' : 'forward');
};
// The app's settings ask for a deck tab.
const onDeckOpen = (event: Event) => openDeck((event as CustomEvent<string | undefined>).detail);
window.addEventListener('bt-deck-open', onDeckOpen);
if (isTauri) {
window.addEventListener('contextmenu', onContextMenu);
window.addEventListener('mouseup', onMouseUp);
}
const relayout = () => { markTitlebarGroups(); scheduleSync(); };
// Native webviews cover drop zones; hide them for the duration of a tab drag.
let dragging = false;
const dragStart = () => { linkDrag.internal = true; endLinkDrag(); if (!dragging) { dragging = true; setOverlay(1); } };
const dragEnd = () => { linkDrag.internal = false; if (dragging) { dragging = false; setOverlay(-1); } };
// A link dragged in from another app straight onto the shell chrome.
const dragEnter = (event: DragEvent) => { if (!linkDrag.internal && carriesLink(dragTypes(event))) beginLinkDrag(); };
const dragOver = (event: DragEvent) => {
if (!linkDrag.active) return;
linkDrag.lastOver = Date.now();
linkDrag.sawOver = true;
// Anywhere outside dockview's zones (e.g. the titlebar of an empty dock) still accepts: new tab.
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
};
// Dockview stops propagation of drops it handled; this only sees drops outside its zones.
const drop = (event: DragEvent) => { if (linkDrag.active) { event.preventDefault(); dropLink(event, undefined); } };
window.addEventListener('keydown', onKey);
window.addEventListener('resize', relayout);
// `resize` fires before dockview has laid its groups out at the new size (its own
// ResizeObserver does that), so the titlebar marks read stale rects there: the group at the
// right edge lost `bt-group--tb-right` and its tabs ran under the titlebar buttons. The dock's
// size changes are marked again one frame later, once dockview's own observer has laid out
// (measured live: marking inside the same observer pass still read the old rects).
const dockElement = document.querySelector('.bt-dock');
let markFrame = 0;
const dockResize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {
cancelAnimationFrame(markFrame);
markFrame = requestAnimationFrame(markTitlebarGroups);
});
if (dockElement) dockResize?.observe(dockElement);
document.addEventListener('dragstart', dragStart, true);
document.addEventListener('dragend', dragEnd, true);
document.addEventListener('drop', dragEnd, true);
document.addEventListener('dragenter', dragEnter, true);
document.addEventListener('dragover', dragOver);
document.addEventListener('drop', drop);
return () => {
endLinkDrag();
unlisten.forEach(promise => promise.then(dispose => dispose(), () => {}));
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', relayout);
dockResize?.disconnect();
cancelAnimationFrame(markFrame);
window.removeEventListener('bt-deck-open', onDeckOpen);
window.removeEventListener('contextmenu', onContextMenu);
window.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('dragstart', dragStart, true);
document.removeEventListener('dragend', dragEnd, true);
document.removeEventListener('drop', dragEnd, true);
document.removeEventListener('dragenter', dragEnter, true);
document.removeEventListener('dragover', dragOver);
document.removeEventListener('drop', drop);
};
}, []);
const onReady = async (event: DockviewReadyEvent) => {
const api: DockviewApi = event.api;
shell.api = api;
// Chrome colors and fonts follow the theme; panes with their own theme follow theirs.
site().themes?.attachDock(api);
let restoreTabs = true;
try {
const settings = await invoke<{ homeUrl: string; restoreTabs: boolean }>('settings_get');
shell.homeUrl = settings.homeUrl;
restoreTabs = settings.restoreTabs;
} catch { /* Defaults. */ }
// Profiles before the first tabs_sync, so restored tabs open in their own account right away.
try { setProfiles(await invoke('profiles_get')); } catch { /* Default profile only. */ }
loadDecks(shell.profiles.profiles.map(profile => profile.id), shell.profiles.active);
// A workspace chosen to open on start replaces the previous session's layout.
const startWorkspace = isTauri && hasFeature('workspaces') ? (await loadWorkspaces()).default : null;
const saved = startWorkspace ? null : loadLayout() as SerializedDockview | null;
if (startWorkspace) await restoreWorkspace(startWorkspace);
shell.restoring = true;
try {
if (saved) {
api.fromJSON(saved);
// Layouts saved before a rename still carry the old panel title.
api.getPanel(panelId())?.api.setTitle(site().panel.title);
for (const panel of [...api.panels]) {
const params = panel.params as TabParams;
if (params.kind === 'web') patchParams(panel, { loading: false });
// Without session restore only pinned tabs come back.
if (!restoreTabs && !params.pinned) panel.api.close();
}
}
} catch (error) {
console.warn('[shell] layout restore failed', error);
api.clear();
} finally {
shell.restoring = false;
}
// A restored deck tab counts: deck sessions come back to their deck, not a new Home tab.
if (!api.panels.some(panel => isWeb(panel) || (panel.params as TabParams | undefined)?.kind === 'deck')) addWeb(shell.homeUrl);
api.onDidLayoutChange(() => { markTitlebarGroups(); scheduleSync(); saveLayoutSoon(); });
api.onDidAddGroup(() => requestAnimationFrame(markTitlebarGroups));
api.onDidRemoveGroup(() => requestAnimationFrame(markTitlebarGroups));
// The titlebar switcher highlights the focused pane's account.
const paneChanged = () => window.dispatchEvent(new CustomEvent('bt-active-pane'));
api.onDidActivePanelChange(event => {
if (event && (event.params as TabParams | undefined)?.kind !== 'deck') lastNonDeck = event.id;
notePanelActive(event?.id);
scheduleSync();
paneChanged();
});
// A renamed deck renames its tab.
window.addEventListener('bt-decks', () => {
for (const panel of api.panels) {
const params = panel.params as TabParams;
if (params.kind !== 'deck') continue;
const name = deckById(params.deckId)?.name;
if (name && panel.api.title !== name) panel.api.setTitle(name);
}
});
api.onDidLayoutChange(paneChanged);
paneChanged();
api.onDidRemovePanel(scheduleSync);
api.onDidAddPanel(scheduleSync);
// Dockview's overflow list (the "N more tabs" button) is a shell popover: hide the tab webviews while it is open.
const popover = document.querySelector('.bt-dock .dv-popover-anchor');
if (popover) {
let shown = false;
new MutationObserver(() => {
const open = popover.childElementCount > 0;
if (open !== shown) { shown = open; setOverlay(open ? 1 : -1); }
}).observe(popover, { childList: true });
}
// External (non-panel) drags that carry a link get dockview's split/tab drop zones.
api.onUnhandledDragOverEvent(event => {
if (!linkDrag.internal && (linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) event.accept();
});
api.onDidDrop(event => {
if (linkDrag.internal || !(linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) return;
const tabIndex = event.panel && event.group ? event.group.panels.indexOf(event.panel) : -1;
dropLink(event.nativeEvent, placementFor({ position: event.position, groupId: event.group?.id, tabIndex: tabIndex >= 0 ? tabIndex : undefined }));
});
markTitlebarGroups();
scheduleSync();
};
const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native';
return <div className="bt-shell" data-chrome={chrome}>
<Titlebar maximized={maximized}/>
<DockviewReact
className="bt-dock"
theme={themeDark}
components={components}
defaultTabComponent={Tab}
rightHeaderActionsComponent={GroupActions}
watermarkComponent={Watermark}
onReady={event => void onReady(event)}
/>
{palette && <CommandPalette context={palette} onRun={runPalette} onClose={() => setPalette(null)}/>}
{overlays.map((Overlay, index) => <Overlay key={index}/>)}
{media && <MediaPanel onClose={() => setMedia(false)}/>}
{menu && <ContextMenu menu={menu} onClose={() => setMenu(null)}/>}
<PaneThemeHost/>
{frameless && !maximized && <ResizeGrips/>}
</div>;
}

View file

@ -0,0 +1,96 @@
import { useEffect, type CSSProperties, type MouseEvent as ReactMouseEvent } from 'react';
import { RESIZE_BORDER } from '../chrome.ts';
import { chipFor } from '../updateModel.ts';
import { AccountSwitcher } from './AccountSwitcher.tsx';
import { invoke } from './bridge.ts';
import { useT, useUpdateStatus } from './hooks.ts';
import { tx } from './i18n.ts';
import { site } from './site.ts';
import { TitlebarExtras } from './TitlebarExtras.tsx';
import { close, minimize, os, startResize, systemMenu, toggleMaximize, type ResizeDirection } from './windowBinding.ts';
const isInteractive = (target: EventTarget | null) =>
target instanceof Element && !!target.closest('button, input, textarea, a, .dv-tab, [role="button"]');
/** Right-click on empty titlebar space: the native system menu (Restore, Move, Size, ...). */
export function titlebarContextMenu(event: ReactMouseEvent | MouseEvent) {
if (isInteractive(event.target)) return;
event.preventDefault();
const scale = window.devicePixelRatio || 1;
systemMenu(Math.round(event.screenX * scale), Math.round(event.screenY * scale));
}
/**
* The 44px titlebar row. It sits under the dockview root: the top groups' tab headers are
* transparent and let clicks through to the drag layer, the logo and the caption buttons.
*/
export function Titlebar({ maximized }: { maximized: boolean }) {
return <header className="bt-titlebar" onContextMenu={titlebarContextMenu}>
<div className="bt-titlebar-drag" data-tauri-drag-region/>
<img className="bt-titlebar-logo" src={site().logo} alt="" draggable={false} data-tauri-drag-region/>
<div className="bt-titlebar-spacer" data-tauri-drag-region/>
<TitlebarExtras/>
<AccountSwitcher/>
<UpdateChip/>
{os !== 'macos' && <WindowControls maximized={maximized}/>}
</header>;
}
/** "Update ready · restart": appears only when a verified update is downloaded (or failed to start). */
function UpdateChip() {
const [status, apply] = useUpdateStatus();
const chip = chipFor(status, site().product, key => tx(key, undefined, '') || undefined);
// Widen the tab strip's right reserve while the chip is shown so tabs never sit under it.
useEffect(() => {
const root = document.documentElement;
if (chip) root.dataset.update = chip.kind; else delete root.dataset.update;
return () => { delete root.dataset.update; };
}, [chip?.kind]);
if (!chip) return null;
if (chip.kind === 'problem') {
return <button className="bt-update-chip bt-update-chip--problem" title={chip.title}
onClick={() => invoke('open_external_url', { url: chip.href }).catch(() => {})}>{chip.label}</button>;
}
return <button className={`bt-update-chip bt-update-chip--${chip.kind}`} title={chip.title} disabled={chip.kind === 'installing'} onClick={apply}>
<span className="bt-update-chip-dot" aria-hidden="true"/>{chip.label}
</button>;
}
function WindowControls({ maximized }: { maximized: boolean }) {
const t = useT();
return <div className="bt-captions">
<button className="bt-caption" aria-label={t('wb.shell.window.minimize')} title={t('wb.shell.window.minimize')} onClick={minimize}>
<svg viewBox="0 0 10 10" aria-hidden="true"><path d="M0 5.5h10"/></svg>
</button>
<button className="bt-caption" aria-label={maximized ? t('wb.shell.window.restore') : t('wb.shell.window.maximize')} title={maximized ? t('wb.shell.window.restore') : t('wb.shell.window.maximize')} onClick={toggleMaximize}>
{maximized
? <svg viewBox="0 0 10 10" aria-hidden="true"><path d="M.5 2.5h7v7h-7z"/><path d="M2.5 2.5v-2h7v7h-2"/></svg>
: <svg viewBox="0 0 10 10" aria-hidden="true"><path d="M.5.5h9v9h-9z"/></svg>}
</button>
<button className="bt-caption bt-caption--close" aria-label={t('wb.common.close')} title={t('wb.common.close')} onClick={close}>
<svg viewBox="0 0 10 10" aria-hidden="true"><path d="M0 0l10 10M10 0L0 10"/></svg>
</button>
</div>;
}
const CORNER = RESIZE_BORDER * 2;
const GRIPS: Array<[ResizeDirection, CSSProperties]> = [
['North', { top: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }],
['South', { bottom: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }],
['West', { left: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }],
['East', { right: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }],
['NorthWest', { top: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }],
['SouthEast', { bottom: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }],
['NorthEast', { top: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }],
['SouthWest', { bottom: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }],
];
/**
* The shell webview covers the whole frameless window, so the OS never sees its edges:
* these grips start native resize drags. Tab webviews are inset by the same band (Rust clamps too).
*/
export function ResizeGrips() {
return <>{GRIPS.map(([direction, style]) =>
<div key={direction} className="bt-grip" style={style} aria-hidden="true"
onPointerDown={event => { if (event.button === 0) { event.preventDefault(); startResize(direction); } }}/>)}</>;
}

View file

@ -0,0 +1,214 @@
// Titlebar extras left of the account switcher: the workspace menu (save the layout, switch with
// one click, choose the one opened on start) and two quiet chips that appear only when needed
// (developer mode errors / last reload, newer synced settings from another computer). The tab strip
// reserves their measured width (`--bt-tb-extra`, shell.css).
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { ago } from './backupModel.ts';
import { useDev, useSync, useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Icon } from './icons.tsx';
import { hasFeature } from './site.ts';
import { setOverlay, shell } from './state.ts';
import { WORKSPACE_LIMITS } from './workspaceModel.ts';
import {
deleteWorkspace, loadWorkspaces, renameSavedWorkspace, restoreWorkspace, saveCurrentWorkspace, setStartWorkspace, workspaceList, workspaces,
} from './workspaces.ts';
import './workspaces.css';
function useWorkspaces() {
const [, setTick] = useState(0);
useEffect(() => {
const update = () => setTick(tick => tick + 1);
window.addEventListener('bt-workspaces', update);
if (!workspaces.loaded) void loadWorkspaces();
return () => window.removeEventListener('bt-workspaces', update);
}, []);
return workspaces;
}
/** Opens the workspace menu with the "save as" field focused (Ctrl+K → "Save layout as workspace…"). */
export const openWorkspaceSave = () => window.dispatchEvent(new CustomEvent('bt-workspace-menu', { detail: 'save' }));
export function TitlebarExtras() {
const root = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const el = root.current;
if (!el) return;
const measure = () => document.documentElement.style.setProperty('--bt-tb-extra', `${Math.ceil(el.getBoundingClientRect().width)}px`);
measure();
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => { observer.disconnect(); document.documentElement.style.removeProperty('--bt-tb-extra'); };
}, []);
return <div className="bt-tb-extras" ref={root}>
{hasFeature('sync') && <SyncChip/>}
{hasFeature('developer') && <DevChip/>}
{hasFeature('workspaces') && <WorkspaceMenu/>}
</div>;
}
function DevChip() {
const t = useT();
const dev = useDev();
const [now, setNow] = useState(Date.now());
useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(timer); }, []);
if (!dev.enabled) return null;
const errors = dev.errors.length;
const recent = dev.last && now - dev.last.at < 4000 ? dev.last.text : null;
const first = dev.errors[0];
const title = errors
? dev.errors.slice(0, 5).map(error => `${error.file}${error.line ? `:${error.line}${error.column ? `:${error.column}` : ''}` : ''} — ${error.message}`).join('\n')
: t('wb.chip.dev.title');
return <button className={`bt-tb-chip bt-dev-chip${errors ? ' is-error' : ''}${recent ? ' is-fresh' : ''}`} title={title}
onClick={() => shell.openPanelSection('developer')}>
<span className="bt-tb-chip-dot" aria-hidden="true"/>
<span className="bt-tb-chip-text">{errors ? `${t('wb.chip.dev.errors', { count: errors })}${first ? ` · ${first.file}${first.line ? `:${first.line}` : ''}` : ''}` : recent ?? t('wb.chip.dev.label')}</span>
</button>;
}
function SyncChip() {
const t = useT();
const sync = useSync();
if (!sync.newer) return null;
return <button className="bt-tb-chip bt-sync-chip" title={t('wb.chip.sync.title', { device: sync.newer.deviceName, when: ago(sync.newer.createdAt) })}
onClick={() => { shell.openPanelSection('backup'); requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-sync-review', { detail: sync.newer?.name }))); }}>
<Icon name="reload"/><span className="bt-tb-chip-text">{t('wb.backup.fromDevice', { device: sync.newer.deviceName })}</span>
</button>;
}
type Mode = { kind: 'list' } | { kind: 'save' } | { kind: 'rename'; id: string } | { kind: 'confirm'; id: string };
function WorkspaceMenu() {
const t = useT();
const store = useWorkspaces();
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<Mode>({ kind: 'list' });
const [name, setName] = useState('');
const [error, setError] = useState('');
const [anchor, setAnchor] = useState({ top: 50, right: 8 });
const button = useRef<HTMLButtonElement>(null);
const menu = useRef<HTMLDivElement>(null);
const active = store.store.items.find(item => item.id === store.active);
const list = workspaceList();
const show = (next: Mode = { kind: 'list' }) => {
const rect = button.current?.getBoundingClientRect();
if (rect) setAnchor({ top: Math.round(rect.bottom + 6), right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
setMode(next); setError('');
setName(next.kind === 'save' ? (active ? '' : suggestName()) : '');
setOpen(true);
};
const close = (refocus = false) => { setOpen(false); setMode({ kind: 'list' }); setError(''); if (refocus) button.current?.focus(); };
useEffect(() => {
const onOpen = (event: Event) => show((event as CustomEvent<string>).detail === 'save' ? { kind: 'save' } : { kind: 'list' });
window.addEventListener('bt-workspace-menu', onOpen);
return () => window.removeEventListener('bt-workspace-menu', onOpen);
}, [active?.id]);
useEffect(() => {
if (!open) return;
setOverlay(1);
const onBlur = () => close();
window.addEventListener('blur', onBlur);
return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); };
}, [open]);
useEffect(() => {
if (!open) return;
requestAnimationFrame(() => menu.current?.querySelector<HTMLElement>('input, .bt-ws-main, button')?.focus());
}, [open, mode.kind]);
async function run(action: () => Promise<unknown>, done = true) {
setError('');
try { await action(); if (done) close(); return true; }
catch (failure) { setError(failure instanceof Error ? failure.message : String(failure)); return false; }
}
const onKey = (event: ReactKeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); if (mode.kind !== 'list') setMode({ kind: 'list' }); else close(true); return; }
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
const items = Array.from(menu.current?.querySelectorAll<HTMLElement>('.bt-ws-main, .bt-ws-save') ?? []);
if (!items.length) return;
event.preventDefault();
const at = items.indexOf(document.activeElement as HTMLElement);
items[(at + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus();
}
};
return <>
<button ref={button} className="bt-ws-button" aria-haspopup="menu" aria-expanded={open}
title={active ? `Workspace: ${active.name}` : 'Workspaces: save this layout, switch with one click'}
aria-label={active ? t('wb.ws.named', { name: active.name }) : t('wb.ws.title')} onClick={() => (open ? close() : show())}>
<WorkspaceGlyph/>
{active && <span className="bt-ws-button-name">{active.name}</span>}
</button>
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={menu} className="bt-menu bt-ws-menu bt-pop bt-pop--right" role="menu" aria-label={t('wb.ws.title')} style={{ top: anchor.top, right: anchor.right }}
onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
<div className="bt-ws-head" role="presentation">
<strong>{t('wb.ws.title')}</strong>
<span>{t('wb.ws.hint')}</span>
</div>
{list.length === 0 && mode.kind === 'list' && <div className="bt-ws-empty">{t('wb.ws.empty')}</div>}
{list.map(item => {
const isActive = item.id === store.active;
if (mode.kind === 'rename' && mode.id === item.id) {
return <form key={item.id} className="bt-ws-form" onSubmit={event => { event.preventDefault(); void run(() => renameSavedWorkspace(item.id, name), false).then(ok => ok && setMode({ kind: 'list' })); }}>
<input className="bt-ws-input" value={name} maxLength={WORKSPACE_LIMITS.name} onChange={event => setName(event.target.value)} aria-label={t('wb.ws.newName', { name: item.name })} spellCheck={false}/>
<button type="submit" className="bt-ws-primary" disabled={!name.trim()}>{t('wb.ws.rename')}</button>
</form>;
}
if (mode.kind === 'confirm' && mode.id === item.id) {
return <div key={item.id} className="bt-ws-confirm" role="alertdialog" aria-label={t('wb.ws.deleteNamed', { name: item.name })}>
<span>{t('wb.ws.deleteConfirm', { name: item.name })}</span>
<div>
<button className="bt-ws-danger" onClick={() => void run(() => deleteWorkspace(item.id), false).then(ok => ok && setMode({ kind: 'list' }))}>{t('kit.delete')}</button>
<button className="bt-ws-cancel" onClick={() => setMode({ kind: 'list' })}>{t('wb.common.cancel')}</button>
</div>
</div>;
}
return <div key={item.id} className={`bt-ws-row${isActive ? ' is-active' : ''}`} role="none">
<button role="menuitem" className="bt-ws-main" aria-current={isActive ? 'true' : undefined} onClick={() => void run(() => restoreWorkspace(item.id))}>
<span className="bt-ws-name">{item.name}{item.isDefault && <span className="bt-ws-badge" title={t('wb.ws.onStartTitle')}>{t('wb.ws.onStart')}</span>}</span>
<span className="bt-ws-meta">{t('wb.ws.tabs', { count: item.tabs })}{isActive ? ` · ${t('wb.ws.openNow')}` : ''}</span>
</button>
<span className="bt-ws-actions">
{isActive && <button className="bt-ws-icon" title={t('wb.ws.update')} aria-label={t('wb.ws.updateNamed', { name: item.name })}
onClick={() => void run(() => saveCurrentWorkspace(item.name, item.id))}><Icon name="check"/></button>}
<button className="bt-ws-icon" title={item.isDefault ? t('wb.ws.stopStart') : t('wb.ws.setStart')} aria-pressed={item.isDefault}
aria-label={item.isDefault ? t('wb.ws.stopStartNamed', { name: item.name }) : t('wb.ws.setStartNamed', { name: item.name })}
onClick={() => void run(() => setStartWorkspace(item.isDefault ? null : item.id), false)}><Icon name={item.isDefault ? 'pin' : 'unpin'}/></button>
<button className="bt-ws-icon" title={t('wb.ws.rename')} aria-label={t('wb.ws.renameNamed', { name: item.name })} onClick={() => { setName(item.name); setMode({ kind: 'rename', id: item.id }); }}><Icon name="edit"/></button>
<button className="bt-ws-icon" title={t('kit.delete')} aria-label={t('wb.ws.deleteNamed', { name: item.name })} onClick={() => setMode({ kind: 'confirm', id: item.id })}><Icon name="trash"/></button>
</span>
</div>;
})}
<hr/>
{mode.kind === 'save'
? <form className="bt-ws-form" onSubmit={event => { event.preventDefault(); void run(() => saveCurrentWorkspace(name)); }}>
<input className="bt-ws-input" value={name} placeholder={t('wb.ws.namePlaceholder')} maxLength={WORKSPACE_LIMITS.name} onChange={event => setName(event.target.value)} aria-label={t('wb.ws.name')} spellCheck={false}/>
<button type="submit" className="bt-ws-primary" disabled={!name.trim()}>{t('wb.common.save')}</button>
</form>
: <button role="menuitem" className="bt-ws-save" onClick={() => { setName(suggestName()); setMode({ kind: 'save' }); }}>
<span className="bt-ws-save-icon"><Icon name="plus"/></span>
<span className="bt-ws-text"><span className="bt-ws-name">{t('wb.ws.save')}</span><span className="bt-ws-meta">{t('wb.ws.saveMeta', { count: shell.api?.panels.length ?? 0 })}</span></span>
</button>}
{error && <div className="bt-ws-error" role="alert">{error}</div>}
</div>
</div>, document.body)}
</>;
}
function suggestName() {
const taken = new Set(workspaces.store.items.map(item => item.name));
for (let n = 1; ; n += 1) { const candidate = n === 1 ? t('wb.ws.default') : t('wb.ws.defaultN', { n }); if (!taken.has(candidate)) return candidate; }
}
/** Three stacked panes: a layout. */
function WorkspaceGlyph() {
return <svg className="bt-ws-glyph" viewBox="0 0 16 16" aria-hidden="true">
<rect x="1.75" y="2.25" width="12.5" height="11.5" rx="2.25"/>
<path d="M6.75 2.5v11M6.75 8h7.25"/>
</svg>;
}

View file

@ -0,0 +1,208 @@
import type { IDockviewPanelProps } from 'dockview';
import { Fragment, useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { WB_MARK } from './brand.ts';
import { invoke, listen } from './bridge.ts';
import { useProfiles, useSiteText, useT } from './hooks.ts';
import { Icon } from './icons.tsx';
import { openPaneTheme } from './PaneTheme.tsx';
import { toUrl } from './searchInput.ts';
import { site } from './site.ts';
import { scheduleSync, setOverlay, shell, tabAction, type WebParams } from './state.ts';
/** One browser tab: toolbar with the smart address bar over a placeholder the native webview covers. */
export function WebPanel(props: IDockviewPanelProps<WebParams>) {
const t = useT();
const { params, api } = props;
const viewport = useRef<HTMLDivElement>(null);
const input = useRef<HTMLInputElement>(null);
const omni = useRef<HTMLDivElement>(null);
const [draft, setDraft] = useState<string | null>(null);
const [caret, setCaret] = useState(0);
const [splitMenu, setSplitMenu] = useState(false);
// Windows: the page's last frame, shown while its webview is hidden (host `tab-still`).
const [still, setStill] = useState<string | null>(null);
useSiteText();
const profiles = useProfiles();
const { logo, product, addressCompleter, themes } = site();
// Same rule as the tab's account dot: shown once there is more than one account.
const account = profiles.profiles.length > 1 ? tabProfile(profiles, params.profile) : null;
const editing = draft !== null;
useEffect(() => {
const el = viewport.current;
if (!el) return;
shell.placeholders.set(api.id, el);
const observer = new ResizeObserver(scheduleSync);
observer.observe(el);
const visibility = api.onDidVisibilityChange(scheduleSync);
scheduleSync();
return () => {
observer.disconnect();
visibility.dispose();
if (shell.placeholders.get(api.id) === el) shell.placeholders.delete(api.id);
scheduleSync();
};
}, [api]);
useEffect(() => {
let off: (() => void) | undefined;
let gone = false;
listen<{ id: string; image: string }>('tab-still', ({ payload }) => { if (payload.id === api.id) setStill(payload.image); })
.then(dispose => { if (gone) dispose(); else off = dispose; }, () => { /* Browser preview: no native events. */ });
return () => { gone = true; off?.(); };
}, [api.id]);
// An overlay (the shell rises above the tab webviews, or hides them) while the menu is open; Esc closes it.
useEffect(() => {
if (!splitMenu) return;
setOverlay(1);
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); setSplitMenu(false); } };
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('keydown', onKey); };
}, [splitMenu]);
// Entering edit mode focuses the mono input; a seeded draft keeps the caret at the end.
const seeded = useRef(false);
useEffect(() => {
if (!editing) return;
const el = input.current;
if (!el) return;
el.focus();
if (seeded.current) { seeded.current = false; el.setSelectionRange(el.value.length, el.value.length); } else el.select();
}, [editing]);
const enterEdit = (seed?: string) => {
seeded.current = seed !== undefined;
setDraft(seed ?? params.url);
};
useEffect(() => {
const focusAddress = (event: Event) => {
if ((event as CustomEvent<string>).detail !== api.id) return;
if (draft === null) enterEdit();
else { input.current?.focus(); input.current?.select(); }
};
window.addEventListener('bt-focus-address', focusAddress);
return () => window.removeEventListener('bt-focus-address', focusAddress);
});
const navigate = (url: string) => {
invoke('tab_navigate', { id: api.id, url }).catch(() => {});
tabAction(api.id, 'focus');
};
const go = () => {
if (draft === null) return;
const url = toUrl(draft, site().searchUrl);
setDraft(null);
navigate(url);
};
// The site's completions for the token being typed (inline, so no overlay hides the page).
const chips = draft === null || !addressCompleter ? [] : addressCompleter.suggest(draft, caret, 5);
const trackCaret = () => setCaret(input.current?.selectionStart ?? draft?.length ?? 0);
const acceptChip = (insert: string) => {
if (draft === null || !addressCompleter) return;
const next = addressCompleter.apply(draft, caret, insert);
setDraft(next.text);
setCaret(next.caret);
requestAnimationFrame(() => { input.current?.focus(); input.current?.setSelectionRange(next.caret, next.caret); });
};
const onChipsKey = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.target !== event.currentTarget) return;
const mod = event.ctrlKey || event.metaKey || event.altKey;
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); enterEdit(); }
else if (!mod && event.key.length === 1) { event.preventDefault(); enterEdit(event.key); }
};
const model = site().address(params.url);
const segments = model?.segments ?? [];
return <div className="bt-web">
<div className="bt-addressbar">
<button className="bt-icon" title={t('wb.web.backTitle')} aria-label={t('wb.web.back')} onClick={() => tabAction(api.id, 'back')}><Icon name="back"/></button>
<button className="bt-icon" title={t('wb.web.forwardTitle')} aria-label={t('wb.web.forward')} onClick={() => tabAction(api.id, 'forward')}><Icon name="forward"/></button>
<button className="bt-icon" title={params.loading ? t('wb.web.stop') : t('wb.web.reloadTitle')} aria-label={params.loading ? t('wb.web.stop') : t('wb.shell.menu.reload')} onClick={() => tabAction(api.id, params.loading ? 'stop' : 'reload')}><Icon name={params.loading ? 'stop' : 'reload'}/></button>
{account && <span className="bt-pane-account" role="img" aria-label={t('wb.shell.tab.account', { name: accountName(account) })} title={t('wb.web.paneAccount', { name: accountName(account) })}
style={{ ['--bt-pane-account' as string]: account.color }}><AccountAvatar profile={account} size={20}/></span>}
{editing
? <div className="bt-omni bt-omni--edit" ref={omni}>
<Icon name="search" className="bt-omni-lead"/>
<input ref={input} spellCheck={false} aria-label={t('wb.web.address')} value={draft}
onChange={event => { setDraft(event.target.value); setCaret(event.target.selectionStart ?? event.target.value.length); }}
onSelect={trackCaret} onKeyUp={trackCaret}
onBlur={() => setDraft(null)}
onKeyDown={event => {
if (event.key === 'Tab' && !event.shiftKey && chips[0]) { event.preventDefault(); acceptChip(chips[0].insert); }
if (event.key === 'Enter') { event.preventDefault(); go(); }
if (event.key === 'Escape') { event.preventDefault(); setDraft(null); tabAction(api.id, 'focus'); }
}}/>
{chips.length > 0 && <span className="bt-omni-ops" role="listbox" aria-label={addressCompleter?.label()}>
{chips.map((chip, index) => <button key={chip.insert} type="button" role="option" aria-selected={index === 0} className="bt-omni-op" title={`${chip.hint}${index === 0 ? ` (${t('wb.web.tabKey')})` : ''}`}
onMouseDown={event => event.preventDefault()} onClick={() => acceptChip(chip.insert)}>{chip.label}</button>)}
</span>}
{params.loading && <span className="bt-omni-progress" aria-label={t('wb.common.loading')}/>}
</div>
: <div className="bt-omni" ref={omni} role="button" tabIndex={0} aria-label={t('wb.web.addressValue', { url: params.url })} title={params.url}
onClick={() => enterEdit()} onKeyDown={onChipsKey}>
{model?.insecure && <span className="bt-chip-insecure">{t('wb.web.insecure')}</span>}
{model
? <button className="bt-chip-site" title={model.site.href} onClick={event => { event.stopPropagation(); if (segments.length) navigate(model.site.href); else enterEdit(); }}>
{model.site.kind !== 'host'
? <img src={logo} alt="" width={14} height={14}/>
: params.favicon ? <img src={params.favicon} alt="" width={14} height={14}/> : null}
{model.site.label}
</button>
: <span className="bt-omni-raw">{params.url}</span>}
{segments.map((segment, index) => {
const last = index === segments.length - 1;
// The model already wraps search queries in straight quotes; show typographic ones.
const label = segment.quoted ? segment.label.replace(/^"/, '“').replace(/"$/, '”') : segment.label;
return <Fragment key={`${index}:${segment.href}`}>
<span className="bt-sep" aria-hidden="true">/</span>
{last
? <span className={`bt-seg ${segment.mono ? 'bt-seg--mono' : ''}`} aria-current="page">{label}</span>
: <button className={`bt-seg ${segment.mono ? 'bt-seg--mono' : ''}`} title={segment.href}
onClick={event => { event.stopPropagation(); navigate(segment.href); }}>{label}</button>}
</Fragment>;
})}
<span className="bt-omni-fill"/>
<button className="bt-omni-action" title={t('wb.shell.menu.openBrowser')} aria-label={t('wb.shell.menu.openBrowser')}
onClick={event => { event.stopPropagation(); invoke('open_external_url', { url: params.url }).catch(() => {}); }}><Icon name="external"/></button>
{params.loading && <span className="bt-omni-progress" aria-label={t('wb.common.loading')}/>}
</div>}
<div className="bt-split">
<button className="bt-icon bt-split-main" title={t('wb.web.splitTitle')} aria-label={t('wb.shell.menu.splitRight')} onClick={() => shell.split(api.id, 'right')}><Icon name="split"/></button>
<button className="bt-icon bt-split-more" title={t('wb.web.splitMore')} aria-label={t('wb.web.splitMore')} aria-haspopup="menu" aria-expanded={splitMenu}
onClick={() => setSplitMenu(open => !open)} onBlur={() => setTimeout(() => setSplitMenu(false), 150)}><Icon name="chevron"/></button>
{splitMenu && <div className="bt-menu bt-split-menu bt-pop" role="menu">
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={() => { setSplitMenu(false); shell.split(api.id, 'right'); }}>
<Icon name="split"/><span className="bt-menu-label">{t('wb.shell.menu.splitRight')}</span><span className="bt-menu-keys">{'Ctrl \\'}</span></button>
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={() => { setSplitMenu(false); shell.split(api.id, 'below'); }}>
<Icon name="splitDown"/><span className="bt-menu-label">{t('wb.shell.menu.splitDown')}</span><span className="bt-menu-keys">{'Ctrl \u21e7 \\'}</span></button>
{themes && <>
<hr/>
<button role="menuitem" onMouseDown={event => event.preventDefault()} onClick={event => {
setSplitMenu(false);
const box = (event.currentTarget.closest('.bt-split') as HTMLElement).getBoundingClientRect();
openPaneTheme({ id: api.id, profile: tabProfile(profiles, params.profile).id, x: box.right - 272, y: box.bottom + 6 });
}}><Icon name="palette"/><span className="bt-menu-label">{t('wb.shell.menu.paneTheme')}</span></button>
</>}
</div>}
</div>
<button className="bt-brand-button" title={`${product} (Ctrl+Shift+W)`} aria-label={product} onClick={() => shell.openPanel(api.id)}>
<img className="bt-wb" src={WB_MARK} alt="" width={30} height={17} draggable={false}/>
</button>
</div>
<div className="bt-viewport" ref={viewport}>
{/* Until the page's own webview is on screen: its last frame, else the site's shape (rail, timeline), not a blank pane. */}
{still
? <div className="bt-still" aria-hidden="true" style={{ backgroundImage: `url("${still}")` }}/>
: <div className="bt-skeleton" aria-hidden="true"><i/><b>{[0, 1, 2, 3].map(i => <span key={i}/>)}</b></div>}
{!still && <div className="bt-viewport-hint">{params.loading ? <span className="bt-spinner" aria-hidden="true"/> : null}<span>{params.title || model?.site.label || t('wb.common.loading')}</span></div>}
</div>
</div>;
}

View file

@ -0,0 +1,91 @@
// What a click in the titlebar account switcher does (pure; unit-tested under node).
//
// One click on an account shows that account: a visible pane of it is focused, otherwise its home
// feed (or the site's sign-in when it is not signed in) opens in a new pane beside the focused one.
// Only a modifier click or the row's "Open in new tab" forces a new tab. The default account
// (`ProfileSettings.active`, kept for profiles.json compatibility) is only where new tabs open.
import { addProfile, tabProfile, type Profile, type ProfileSettings } from '../profileModel.ts';
import { tx } from './i18n.ts';
/** A tab as the switcher sees it: its account and whether it is on screen right now. */
export type PaneInfo = {
id: string;
kind: 'web' | 'start' | 'panel';
/** Profile id as stored on the tab (missing or unknown = default). */
profile?: string;
url?: string;
/** Shown on screen (the visible tab of its group). */
visible: boolean;
};
export type AccountAction =
| { type: 'focus'; paneId: string }
| { type: 'open'; url: string; profile: string; where: 'beside' | 'tab' };
/** The site's pages an account click opens (`site.homeUrl`, `site.loginUrl`, `site.isSiteUrl`). */
export type AccountPages = { homeUrl: string; loginUrl: string; isSiteUrl?: (url: string) => boolean };
/** Where a click on this account lands: its feed once signed in, the site's sign-in otherwise. */
export function accountStartUrl(profile: Profile, pages: Pick<AccountPages, 'homeUrl' | 'loginUrl'>): string {
return profile.account?.signedIn ? pages.homeUrl : pages.loginUrl;
}
/** The account the focused tab runs in (the app's panel has none: the default account). */
export function focusedAccount(settings: ProfileSettings, panes: readonly PaneInfo[], activeId: string | null | undefined): Profile {
const pane = panes.find(item => item.id === activeId);
return tabProfile(settings, pane && pane.kind !== 'panel' ? pane.profile : settings.active);
}
/**
* The click's result. `force` (Shift/Ctrl-click, "Open in new tab") always opens a new tab in the
* focused group. Otherwise a visible web pane of the account is focused (the focused one first, then
* a pane on the site), and only when there is none does a new pane open beside the focused one.
*/
export function accountAction(
settings: ProfileSettings,
panes: readonly PaneInfo[],
activeId: string | null | undefined,
profileId: string,
options: { force?: boolean } & AccountPages,
): AccountAction {
const profile = tabProfile(settings, profileId);
const url = accountStartUrl(profile, options);
if (options.force) return { type: 'open', url, profile: profile.id, where: 'tab' };
const onSite = options.isSiteUrl ?? (() => false);
const mine = panes.filter(pane => pane.kind === 'web' && pane.visible && tabProfile(settings, pane.profile).id === profile.id);
const target = mine.find(pane => pane.id === activeId) ?? mine.find(pane => !!pane.url && onSite(pane.url)) ?? mine[0];
if (target) return { type: 'focus', paneId: target.id };
return { type: 'open', url, profile: profile.id, where: 'beside' };
}
/** "Use for new tabs": the only thing `active` means now. Unknown ids change nothing. */
export const setDefaultAccount = (settings: ProfileSettings, id: string): ProfileSettings =>
settings.profiles.some(profile => profile.id === id) && settings.active !== id ? { ...settings, active: id } : settings;
/** "Add account": a fresh profile for the site's sign-in. It does not become the default. */
export function addAccountProfile(settings: ProfileSettings, id?: string): { settings: ProfileSettings; profile: string } {
const next = addProfile(settings, '', id, key => tx(key, undefined, '') || undefined);
return { settings: { ...next, active: settings.active }, profile: next.active };
}
/** Open tabs per account id (for "N tabs" and for closing them before a remove). */
export function tabsByAccount(settings: ProfileSettings, panes: readonly PaneInfo[]): Map<string, string[]> {
const result = new Map<string, string[]>();
for (const pane of panes) {
if (pane.kind !== 'web') continue;
const id = tabProfile(settings, pane.profile).id;
result.set(id, [...(result.get(id) ?? []), pane.id]);
}
return result;
}
/** Roving focus in the menu: wraps around; Home/End jump to the ends. */
export function moveFocus(index: number, key: string, count: number): number {
if (count <= 0) return -1;
if (key === 'Home') return 0;
if (key === 'End') return count - 1;
if (key === 'ArrowDown') return index < 0 ? 0 : (index + 1) % count;
if (key === 'ArrowUp') return index < 0 ? count - 1 : (index - 1 + count) % count;
return index;
}

View file

@ -0,0 +1,91 @@
/* Titlebar account switcher menu and the per-pane account marker (AccountSwitcher.tsx, WebPanel.tsx).
Tokens come from shell.css (:root --bt-*). */
.bt-acct-menu { width: 340px; max-height: calc(100vh - 64px); overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--bt-line-strong) transparent; }
.bt-acct-head { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px 8px; }
.bt-acct-head strong { font: 600 13px/1.2 var(--bt-ui); color: var(--bt-text); }
.bt-acct-head span { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font: 400 12px/1.3 var(--bt-ui); color: var(--bt-muted); }
.bt-acct-head .bt-kbd { height: 16px; min-width: 0; font: 500 10.5px/1 var(--bt-ui); }
/* One account: the whole row is the main action; "…" sits at the right edge. */
.bt-acct-row { position: relative; display: flex; flex-direction: column; border-radius: 10px; }
.bt-acct-line { position: relative; display: flex; align-items: center; }
.bt-acct-row.is-focused { background: rgb(var(--bt-accent-rgb) / .08); box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .22); }
.bt-acct-row.is-focused::before {
content: ''; position: absolute; inset-inline-start: -5px; top: 12px; height: 24px; width: 3px; border-start-start-radius: 0; border-start-end-radius: 3px; border-end-end-radius: 3px; border-end-start-radius: 0; background: var(--bt-accent);
}
.bt-acct-row.is-open { background: rgb(var(--bt-text-rgb) / .035); }
.bt-menu .bt-acct-main { flex: 1; min-width: 0; height: auto; gap: 11px; padding-block: 8px; padding-inline: 8px 40px; border-radius: 10px; }
.bt-menu .bt-acct-main:focus-visible { box-shadow: var(--bt-ring); }
.bt-acct-avatar { position: relative; display: inline-grid; flex: none; }
.bt-acct-avatar.is-signed-out .bt-avatar, .bt-acct-avatar.is-new .bt-avatar { filter: saturate(.35); opacity: .7; }
.bt-acct-avatar.is-signed-out::after, .bt-acct-avatar.is-new::after {
content: ''; position: absolute; inset-inline-end: -1px; bottom: -1px; width: 9px; height: 9px; border-radius: 50%;
background: var(--bt-faint); box-shadow: 0 0 0 2px var(--bt-raised);
}
.bt-acct-text { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; }
.bt-acct-name { display: flex; align-items: center; gap: 6px; min-width: 0; font: 600 13.5px/1.15 var(--bt-ui); color: var(--bt-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-acct-meta { font: 400 12px/1.2 var(--bt-ui); color: var(--bt-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; }
.bt-acct-meta.is-signed-out, .bt-acct-meta.is-new { color: #f0b14a; }
.bt-acct-count { color: var(--bt-muted); }
.bt-acct-badge {
flex: none; padding: 2px 6px; border-radius: 999px; background: rgb(var(--bt-text-rgb) / .07); color: var(--bt-text-2);
font: 500 10.5px/1.2 var(--bt-ui); letter-spacing: .01em;
}
/* What the click will do, revealed on hover/focus so the row reads as one obvious action. */
/* Hidden until then, so a long @handle / status gets the full width. */
.bt-acct-hint { display: none; align-items: center; gap: 5px; flex: none; color: var(--bt-accent-ink); font: 500 11.5px/1 var(--bt-ui); animation: bt-acct-hint-in var(--bt-t1) var(--bt-ease-out); }
@keyframes bt-acct-hint-in { from { opacity: 0; transform: translateX(-3px); } }
.bt-acct-hint .bt-glyph { width: 13px; height: 13px; }
.bt-acct-row.is-focused .bt-acct-hint { display: inline-flex; color: var(--bt-accent-ink); }
.bt-acct-main:hover .bt-acct-hint, .bt-acct-main:focus-visible .bt-acct-hint { display: inline-flex; color: var(--bt-accent-ink); }
.bt-menu .bt-acct-more {
position: absolute; inset-inline-end: 6px; top: 50%; transform: translateY(-50%); width: 28px; height: 28px; padding: 0; justify-content: center;
color: var(--bt-muted); opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease);
}
.bt-acct-more svg { width: 16px; height: 16px; fill: currentColor; }
.bt-acct-row:hover .bt-acct-more, .bt-acct-row:focus-within .bt-acct-more, .bt-acct-more[aria-expanded=true] { opacity: 1; }
.bt-menu .bt-acct-more:hover, .bt-menu .bt-acct-more[aria-expanded=true] { color: var(--bt-text); background: var(--bt-press); }
/* Hover hint and "…" share the right edge: the hint moves left of it. */
.bt-acct-row:hover .bt-acct-hint { margin-inline-end: 2px; }
/* Row actions: inline under the row (no second floating layer over the native panes). */
.bt-acct-sub { display: flex; flex-direction: column; gap: 1px; margin-block: 0 6px; margin-inline: 49px 6px; padding-top: 2px; border-top: 1px solid var(--bt-line-soft); }
.bt-menu .bt-acct-sub button { height: 30px; font-size: 12.5px; }
.bt-acct-sub .bt-glyph { width: 15px; height: 15px; }
.bt-acct-sub .bt-menu-keys { font-size: 11px; }
.bt-menu .bt-acct-sub button[aria-checked=true]:disabled { color: var(--bt-text-2); }
.bt-menu .bt-acct-sub button[aria-checked=true]:disabled > .bt-glyph { color: var(--bt-accent); opacity: 1; }
.bt-menu .bt-acct-danger { color: #ff8a80; }
.bt-menu .bt-acct-danger > .bt-glyph { color: #ff8a80; }
.bt-acct-confirm {
display: flex; flex-direction: column; gap: 10px; margin: 2px 6px 6px; padding: 10px 12px; border-radius: 9px;
background: rgba(229, 72, 77, .08); box-shadow: inset 0 0 0 1px rgba(229, 72, 77, .25); color: var(--bt-text-2); font: 400 12.5px/1.45 var(--bt-ui);
}
.bt-acct-confirm strong { color: var(--bt-text); font-weight: 600; }
.bt-acct-confirm div { display: flex; gap: 6px; }
.bt-menu .bt-acct-confirm button { height: 28px; padding: 0 12px; font-weight: 600; font-size: 12.5px; }
.bt-menu .bt-acct-remove { background: var(--bt-danger); color: #fff; }
.bt-menu .bt-acct-remove:hover:not(:disabled), .bt-menu .bt-acct-remove:focus-visible { background: #d93d42; }
.bt-menu .bt-acct-cancel { background: var(--bt-hover); }
.bt-menu .bt-acct-add { height: auto; gap: 11px; padding: 8px; border-radius: 10px; }
.bt-menu .bt-acct-add:focus-visible { box-shadow: var(--bt-ring); }
.bt-acct-add .bt-acct-name { color: var(--bt-text-2); }
.bt-acct-add-icon { display: grid; place-items: center; width: 32px; height: 32px; flex: none; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--bt-line-strong); color: var(--bt-muted); }
.bt-acct-add-icon .bt-glyph { width: 15px; height: 15px; }
.bt-menu .bt-acct-add:hover .bt-acct-add-icon { box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .6); color: var(--bt-accent-ink); }
.bt-acct-error { padding: 6px 10px; color: #ff8a80; font: 12px/1.4 var(--bt-ui); }
/* Each pane's account, left of its address bar (same color as the tab's account dot). */
.bt-pane-account {
display: inline-grid; place-items: center; flex: none; width: 26px; height: 26px; margin-inline-start: 4px; border-radius: 50%;
box-shadow: 0 0 0 1.5px var(--bt-pane-account, var(--bt-line-strong));
}

View file

@ -0,0 +1,187 @@
// Settings backup / import preview (pure, unit-tested under node).
//
// A `.waybetter` file is JSON: `{ format: 'waybetter-backup', version: 1, createdAt, sections }`.
// Native code (waybetter-host `backup`) writes and reads the native sections (themes, plugins,
// customCss, features, settings, alerts, accounts, workspaces, drafts when asked); the shell adds
// its own storage (`decks`: the decks and deck settings). Import shows a preview:
// one row per section with what would change, each with a checkbox; nothing is applied until the
// owner confirms, and only the ticked sections are.
import { relativeTime, t, tx } from './i18n.ts';
export const BACKUP_FORMAT = 'waybetter-backup';
export const BACKUP_VERSION = 1;
/** Sections the shell applies itself (the rest go to native `backup_apply`). */
export const LOCAL_SECTIONS = ['decks'] as const;
/** Backup sections in display order; their names are `wb.backup.section.<id>` in the catalogs. */
export const SECTION_ORDER = ['themes', 'plugins', 'customCss', 'features', 'settings', 'alerts', 'accounts', 'workspaces', 'decks', 'drafts'];
export const sectionLabel = (section: string) => tx(`wb.backup.section.${section}`, undefined, section);
type Json = Record<string, unknown>;
const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value);
const list = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
const str = (value: unknown) => (typeof value === 'string' ? value : '');
/** Stable JSON (sorted keys) for equality. */
export function canonical(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (isObject(value)) return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`;
return JSON.stringify(value ?? null);
}
/** Secret-looking keys (same rule as native `strip_secrets`); never exported, never imported. */
export function isSecretKey(key: string): boolean {
const folded = key.replace(/[_-]/g, '').toLowerCase();
return ['cookie', 'cookies', 'setcookie', 'token', 'tokens', 'accesstoken', 'authtoken', 'refreshtoken', 'idtoken', 'ct0', 'password', 'passphrase', 'secret', 'clientsecret', 'session', 'sessionid', 'authorization', 'bearer', 'csrf', 'csrftoken', 'privatekey', 'signingkey'].includes(folded)
|| folded.endsWith('secret') || folded.endsWith('token') || folded.endsWith('password');
}
export function stripSecrets<T>(value: T): T {
if (Array.isArray(value)) return value.map(stripSecrets) as T;
if (!isObject(value)) return value;
const out: Json = {};
for (const [key, child] of Object.entries(value)) if (!isSecretKey(key)) out[key] = stripSecrets(child);
return out as T;
}
/** The shell's own sections: decks and deck settings (localStorage), never tab state. */
export function localSections(input: { decks: unknown[]; deckSettings: unknown }): Json {
return stripSecrets({ decks: { decks: input.decks, settings: input.deckSettings } });
}
export type SectionRow = {
section: string;
label: string;
/** `same`: nothing would change; `changed`: differs from this computer; `new`: nothing here yet. */
status: 'same' | 'changed' | 'new';
/** Short lines for the preview ("Nord → Paper", "+2 plugins", ...). */
details: string[];
/** Ticked by default: changed sections, except drafts (added only when asked). */
checked: boolean;
};
const names = (items: unknown[], key = 'name', max = 3) => {
const shown = items.map(item => (isObject(item) ? str(item[key]) || str(item.id) : '')).filter(Boolean);
return shown.length > max ? `${shown.slice(0, max).join(', ')} +${shown.length - max}` : shown.join(', ');
};
function themeDetails(current: Json, incoming: Json): string[] {
const out: string[] = [];
const now = isObject(current.theme) ? current.theme : {};
const next = isObject(incoming.theme) ? incoming.theme : {};
const presetNow = str(now.preset) || 'x';
const presetNext = str(next.preset) || 'x';
if (presetNow !== presetNext) out.push(t('wb.backup.detail.theme', { from: presetNow, to: presetNext }));
const ids = (theme: Json) => list(theme.themes).map(item => (isObject(item) ? str(item.id) : '')).filter(Boolean);
const added = ids(next).filter(id => !ids(now).includes(id));
if (added.length) out.push(t('wb.backup.detail.importedThemes', { count: added.length, names: added.slice(0, 3).join(', ') }));
if (canonical(now.accent) !== canonical(next.accent) || canonical(now.overrides) !== canonical(next.overrides)) out.push(t('wb.backup.detail.customizations'));
const scopes = isObject(incoming.scopes) ? incoming.scopes : {};
const accounts = isObject(scopes.profiles) ? Object.keys(scopes.profiles).length : 0;
if (canonical(current.scopes) !== canonical(incoming.scopes)) out.push(accounts ? t('wb.backup.detail.scopesAccounts', { count: accounts }) : t('wb.backup.detail.scopes'));
return out;
}
function pluginDetails(current: Json, incoming: Json): string[] {
const out: string[] = [];
const files = (section: Json) => new Map(list(section.files).filter(isObject).map(file => [str(file.file), str(file.source)]));
const now = files(current);
const next = files(incoming);
const added = [...next.keys()].filter(file => !now.has(file));
const changed = [...next.keys()].filter(file => now.has(file) && now.get(file) !== next.get(file));
if (added.length) out.push(t('wb.backup.detail.newPlugins', { count: added.length, names: added.slice(0, 3).join(', ') }));
if (changed.length) out.push(t('wb.backup.detail.changed', { count: changed.length, names: changed.slice(0, 3).join(', ') }));
const enabledNow = new Set(list(current.enabled).map(str));
const enabledNext = new Set(list(incoming.enabled).map(str));
const on = [...enabledNext].filter(file => !enabledNow.has(file));
const off = [...enabledNow].filter(file => !enabledNext.has(file));
const short = (files: string[]) => `${files.slice(0, 3).map(file => file.replace(/\.plugin\.js$/, '')).join(', ')}${files.length > 3 ? ` +${files.length - 3}` : ''}`;
if (on.length) out.push(t('wb.backup.detail.turnsOn', { names: short(on) }));
if (off.length) out.push(t('wb.backup.detail.turnsOff', { names: short(off) }));
return out;
}
function keyDetails(current: Json, incoming: Json, kind: 'tweak' | 'setting'): string[] {
const keys = [...new Set([...Object.keys(current), ...Object.keys(incoming)])].filter(key => canonical(current[key]) !== canonical(incoming[key]));
if (!keys.length) return [];
const names = `${keys.slice(0, 4).join(', ')}${keys.length > 4 ? ' …' : ''}`;
return [kind === 'tweak' ? t('wb.backup.detail.tweaksDiffer', { count: keys.length, names }) : t('wb.backup.detail.settingsDiffer', { count: keys.length, names })];
}
function details(section: string, current: Json, incoming: Json): string[] {
switch (section) {
case 'themes': return themeDetails(current, incoming);
case 'plugins': return pluginDetails(current, incoming);
case 'customCss': return [t('wb.backup.detail.css', { count: str(incoming.css).length, here: str(current.css).length })];
case 'features': return keyDetails(current, incoming, 'tweak');
case 'settings': return keyDetails(current, incoming, 'setting');
case 'alerts': {
const now = new Set(list(current.keywords).map(str));
const next = list(incoming.keywords).map(str);
const added = next.filter(word => !now.has(word));
const summary = incoming.enabled ? t('wb.backup.alertsOn', { count: next.length }) : `${t('wb.common.off')} · ${t('wb.backup.detail.keywords', { count: next.length })}`;
return [`${summary}${added.length ? ` (+${added.slice(0, 3).join(', ')})` : ''}`];
}
case 'accounts': {
const now = new Map(list(current.profiles).filter(isObject).map(profile => [str(profile.id), profile]));
const next = list(incoming.profiles).filter(isObject);
const added = next.filter(profile => !now.has(str(profile.id)));
const renamed = next.filter(profile => now.has(str(profile.id)) && canonical(now.get(str(profile.id))) !== canonical(profile));
const out: string[] = [];
if (added.length) out.push(t('wb.backup.detail.addsAccounts', { names: names(added) }));
if (renamed.length) out.push(t('wb.backup.detail.renames', { names: names(renamed) }));
out.push(t('wb.backup.detail.noneRemoved'));
return out;
}
case 'workspaces': {
const now = new Set(list(current.items).filter(isObject).map(item => str(item.id)));
const next = list(incoming.items).filter(isObject);
const added = next.filter(item => !now.has(str(item.id)));
return [added.length ? t('wb.backup.detail.workspacesNew', { count: next.length, names: names(added) }) : t('wb.backup.detail.workspaces', { count: next.length })];
}
case 'decks': {
const next = list(incoming.decks).filter(isObject);
return [t('wb.backup.detail.decks', { count: next.length, names: names(next) })];
}
case 'drafts': {
const count = list(incoming.drafts).length;
return [t('wb.backup.detail.drafts', { count })];
}
default: return [];
}
}
/** One preview row per section present in `incoming`, in display order. */
export function diffSections(current: Json, incoming: Json): SectionRow[] {
const rows: SectionRow[] = [];
for (const section of SECTION_ORDER) {
const next = incoming[section];
if (!isObject(next)) continue;
const now = isObject(current[section]) ? current[section] as Json : null;
const same = !!now && canonical(now) === canonical(next);
const status: SectionRow['status'] = same ? 'same' : now && Object.keys(now).length ? 'changed' : 'new';
const lines = same ? [t('wb.backup.detail.same')] : details(section, now ?? {}, next);
rows.push({ section, label: sectionLabel(section), status, details: lines.length ? lines : [t('wb.backup.detail.differs')], checked: !same && section !== 'drafts' });
}
return rows;
}
/** Splits the ticked sections into what native code applies and what the shell applies. */
export function pickSections(incoming: Json, chosen: Iterable<string>): { native: Json; local: Json } {
const native: Json = {};
const local: Json = {};
for (const section of chosen) {
const value = incoming[section];
if (!isObject(value) || !SECTION_ORDER.includes(section)) continue;
const clean = stripSecrets(value);
if ((LOCAL_SECTIONS as readonly string[]).includes(section)) local[section] = clean; else native[section] = clean;
}
return { native, local };
}
/** "3 minutes ago" / "yesterday" for sync snapshot times, in the active language. */
export function ago(ms: number, now = Date.now()): string {
return relativeTime(Math.min(ms, now), now);
}

View file

@ -0,0 +1,37 @@
// The first-frame script (`boot.js`, a classic script in the shell page's <head>): the chrome
// colors the global theme had last time (themeStore.ts writes them under BOOT_CACHE_KEY), so a light
// theme never starts on the dark default while the shell's modules and the persisted theme load.
// Shell webview only: other local webviews of the app (e.g. a popover) share the page and paint
// their own background. The app serves `bootScript()` as `/boot.js` (see the README: a Vite
// plugin or a build step writes it; nothing is copied by hand).
/** localStorage key of the last chrome variables (`--wb-*` name → value). */
export const BOOT_CACHE_KEY = 'bt.chrome.vars';
/** The page ground before any theme (Night Ink), as shell.css paints it. */
export const BOOT_GROUND = '#07080c';
/** The boot script's source. `label`: the shell webview's label (waybetter-host `policy::SHELL_LABEL`). */
export function bootScript(options: { label?: string } = {}): string {
const label = JSON.stringify(options.label ?? 'shell');
return `// Generated from waybetter/shell/frame/boot (bootScript): runs before the shell's first frame and
// paints the chrome colors the global theme had last time (${BOOT_CACHE_KEY}).
(() => {
try {
const label = window.__TAURI_INTERNALS__?.metadata?.currentWebview?.label;
if (label !== ${label}) return;
const vars = JSON.parse(localStorage.getItem(${JSON.stringify(BOOT_CACHE_KEY)}) || 'null');
if (!vars || typeof vars !== 'object') return;
const root = document.documentElement;
for (const [name, value] of Object.entries(vars)) {
if (/^--wb-[a-z]-[a-z0-9-]+$/.test(name) && typeof value === 'string' && value.length < 400) root.style.setProperty(name, value);
}
// shell.css (loaded with the shell's modules) paints the same ground; this rule only covers
// the frames before it, and \`html.bt-raised\` (more specific) still clears it.
const style = document.createElement('style');
style.textContent = 'html{background:var(--wb-c-ground,${BOOT_GROUND})}';
document.head.appendChild(style);
} catch { /* No cache yet or blocked storage: the default ground. */ }
})();
`;
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,76 @@
// The shell frame's line to native code. The app passes its own Tauri API (`@tauri-apps/api`
// `invoke`, `listen`, `getCurrentWindow`) through `createShell`, so the framework has no Tauri
// dependency and the app keeps its version. `call` normalizes errors; `installPreviewMocks` stands
// in for native code in a plain browser (the dev preview harnesses: every command answered from
// memory, events delivered with `emit`).
// No React; pure enough for node tests (nothing runs until a command is called).
import type { NativeWindow } from '../windowControls.ts';
export type Invoke = <T = unknown>(command: string, args?: Record<string, unknown>) => Promise<T>;
export type Listen = <T = unknown>(event: string, handler: (event: { payload: T }) => void) => Promise<() => void>;
/** The Tauri `Window` calls the frame makes (window controls, and the window's own background). */
export type ShellWindow = NativeWindow & { setBackgroundColor(color: [number, number, number, number]): Promise<void> };
export type NativeApi = { invoke: Invoke; listen: Listen; currentWindow: () => ShellWindow };
let api: NativeApi | null = null;
export function setNative(native: NativeApi) {
api = native;
}
function need(): NativeApi {
if (!api) throw new Error('wayBetter shell: createShell(site) first (no native API)');
return api;
}
/** A native command (rejects with an Error whose message is native code's `CODE: detail`). */
export const invoke: Invoke = async <T>(command: string, args?: Record<string, unknown>) => {
try { return await need().invoke<T>(command, args); }
catch (error) { throw error instanceof Error ? error : new Error(String(error)); }
};
/** A native event; resolves to its unlisten function (rejects outside Tauri without mocks). */
export const listen: Listen = (event, handler) => {
try { return need().listen(event, handler); }
catch (error) { return Promise.reject(error); }
};
export const currentWindow = () => need().currentWindow();
/** Tauri's IPC is present (the real app, or a preview with mocks installed). */
export const isNative = () => typeof globalThis === 'object' && '__TAURI_INTERNALS__' in globalThis;
export type MockHandler = (args: Record<string, unknown>) => unknown;
/**
* Development only: answers native commands from `handlers` (`window.__TAURI_INTERNALS__`, which
* `@tauri-apps/api` reads) so the real shell renders in a plain browser. Event listeners are
* mocked too; `emit(event, payload)` delivers an event to them. Unknown commands reject (and warn).
*/
export function installPreviewMocks(handlers: Record<string, MockHandler>, options: { label?: string; name?: string } = {}) {
const label = options.label ?? 'shell';
let callbackId = 0;
const callbacks = new Map<number, (message: unknown) => void>();
const listeners: Record<string, number[]> = {};
// Tauri's event plugin; `handlers` is read on every call, so commands can be added later.
const events: Record<string, MockHandler> = {
'plugin:event|listen': ({ event, handler }) => { (listeners[String(event)] ??= []).push(Number(handler)); return Number(handler); },
'plugin:event|unlisten': () => null,
};
const emit = (event: string, payload: unknown) =>
(listeners[event] ?? []).forEach(id => callbacks.get(id)?.({ event, id, payload }));
const target = window as unknown as Record<string, unknown>;
target.__TAURI_INTERNALS__ = {
invoke: async (cmd: string, args: Record<string, unknown> = {}) => {
const handler = handlers[cmd] ?? events[cmd];
if (!handler) { console.warn(`[${options.name ?? 'preview'}] ${cmd} is not mocked`); throw new Error(`Preview: ${cmd} is not mocked`); }
return structuredClone(await handler(args));
},
transformCallback: (callback: (message: unknown) => void) => { callbacks.set(++callbackId, callback); return callbackId; },
unregisterCallback: () => {},
metadata: { currentWindow: { label }, currentWebview: { label } },
};
target.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
return { handlers, emit };
}

View file

@ -0,0 +1,86 @@
// The app's own window in the active theme: the theme's palette and its chrome/mono fonts become
// the shell's `--wb-c-*` (tabs, address bar, titlebar, menus) and the panel's `--wb-p-*` tokens,
// which shell.css (and the app's panel CSS) read with Night Ink as the fallback. Pure (tests,
// shell, panel). The app turns its theme documents into a `ChromeTheme` (site.themes.chrome).
/** The shell's own interface font (what an inheriting chrome role falls back to outside the page). */
export const SHELL_UI_FONT = "'Geist Variable', system-ui, sans-serif";
export const SHELL_MONO_FONT = "'Geist Mono Variable', ui-monospace, monospace";
/** A theme as the chrome needs it: seven colors (none: the site's own colors) and two font stacks. */
export type ChromeTheme = {
colors?: { bg: string; surface: string; elevated: string; border: string; text: string; muted: string; accent: string } | null;
/** The chrome's font stack when the theme sets one other than SHELL_UI_FONT. */
chromeFont?: string | null;
/** The mono font stack when the theme sets one. */
monoFont?: string | null;
};
function hexToRgb(hex: string): [number, number, number] {
const n = parseInt(hex.slice(1), 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
const toHex = (rgb: number[]) => `#${rgb.map(v => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('')}`;
export function luminance(hex: string): number {
const [r, g, b] = hexToRgb(hex).map(v => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number];
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
export function contrast(a: string, b: string): number {
const [x, y] = [luminance(a), luminance(b)].sort((m, n) => n - m) as [number, number];
return (x + 0.05) / (y + 0.05);
}
export function mix(a: string, b: string, t: number): string {
const [x, y] = [hexToRgb(a), hexToRgb(b)];
return toHex(x.map((v, i) => v + (y[i]! - v) * t));
}
const channels = (hex: string) => hexToRgb(hex).join(' ');
/** Moves `color` toward `pole` until it reads at `ratio` on `surface`. */
function legible(color: string, surface: string, ratio: number): string {
if (contrast(color, surface) >= ratio) return color;
const pole = luminance(surface) > 0.18 ? '#000000' : '#ffffff';
for (let t = 0.1; t <= 1; t += 0.1) { const next = mix(color, pole, t); if (contrast(next, surface) >= ratio) return next; }
return pole;
}
/**
* CSS custom properties for the chrome in `theme`. A theme that keeps the site's colors changes
* only the fonts; `own` keeps wayBetter's own style entirely (empty result).
*/
export function chromeVars(theme: ChromeTheme, own = false): Record<string, string> {
if (own) return {};
const vars: Record<string, string> = {};
// The chrome inherits the theme's interface font (a web font of the site is not available here: then Geist).
if (theme.chromeFont) vars['--wb-f-chrome'] = theme.chromeFont;
if (theme.monoFont) vars['--wb-f-mono'] = theme.monoFont;
const colors = theme.colors;
if (!colors) return vars;
const { bg, surface, elevated, border, text, muted, accent } = colors;
const dark = luminance(bg) < luminance(text);
const ink = legible(mix(accent, text, 0.55), elevated, 4.5);
Object.assign(vars, {
// Shell chrome: the ground under the tabs is the theme's column background.
'--wb-c-ground': bg, '--wb-c-chrome': surface, '--wb-c-field': mix(surface, elevated, 0.45),
'--wb-c-raised': elevated, '--wb-c-raised-2': mix(elevated, border, 0.45),
'--wb-c-line': border, '--wb-c-line-soft': mix(border, bg, 0.45), '--wb-c-line-strong': mix(border, text, 0.14),
'--wb-c-text': text, '--wb-c-text-2': mix(text, muted, 0.4), '--wb-c-muted': muted, '--wb-c-faint': mix(muted, bg, 0.38),
'--wb-c-text-rgb': channels(text), '--wb-c-accent': accent, '--wb-c-accent-rgb': channels(accent), '--wb-c-accent-ink': ink,
'--wb-c-scheme': dark ? 'dark' : 'light',
...(dark ? {} : { '--wb-c-shadow-pop': `0 18px 44px -14px rgba(${hexToRgb(mix(text, bg, 0.2)).join(', ')}, .28), 0 3px 10px rgba(0, 0, 0, .08)` }),
// Panel.
'--wb-p-ground': bg, '--wb-p-chrome': mix(bg, surface, 0.5), '--wb-p-card': surface, '--wb-p-field': mix(surface, elevated, 0.5), '--wb-p-raise': elevated,
'--wb-p-line': border, '--wb-p-line-soft': mix(border, bg, 0.4), '--wb-p-line-strong': mix(border, text, 0.16),
'--wb-p-text': text, '--wb-p-text-2': mix(text, muted, 0.3), '--wb-p-muted': muted, '--wb-p-faint': mix(muted, bg, 0.35),
'--wb-p-accent': accent, '--wb-p-accent-rgb': channels(accent), '--wb-p-accent-ink': contrast(accent, '#ffffff') >= contrast(accent, bg) ? '#ffffff' : bg,
'--wb-p-text-rgb': channels(text), '--wb-p-popover': elevated, '--wb-p-thumb': `linear-gradient(180deg, ${mix(elevated, text, 0.08)}, ${elevated})`,
'--wb-p-track': mix(elevated, border, 0.5), '--wb-p-knob': mix(muted, text, 0.3),
});
return vars;
}
/** Every variable chromeVars may set (to clear them when a pane returns to the global theme). */
export const CHROME_VAR_NAMES = Object.keys(chromeVars({
colors: { bg: '#000000', surface: '#111111', elevated: '#222222', border: '#333333', text: '#ffffff', muted: '#999999', accent: '#1d9bf0' },
chromeFont: 'A', monoFont: 'B',
})).concat('--wb-c-shadow-pop');

View file

@ -0,0 +1,209 @@
/*
* Decks: the deck tab. A 40px deck bar, then a row of column cards. Each card is a 46px
* header over a body that a site tab webview covers exactly (so the body is square and flush with
* the window bottom; only the header is ours). Night Ink tokens from shell.css.
*/
.bt-deck { position: relative; height: 100%; display: flex; flex-direction: column; background: var(--bt-ground); color: var(--bt-text); overflow: hidden; }
/* The deck's dockview tab: unread total. */
.bt-tab-unread { flex: none; min-width: 16px; height: 16px; padding: 0 5px; box-sizing: border-box; border-radius: 999px; background: var(--bt-accent); color: #fff; font: 700 10px/16px var(--bt-mono); text-align: center; }
/* Deck bar ---------------------------------------------------------------------------------- */
.bt-deck-bar { flex: none; display: flex; align-items: center; gap: 10px; height: 40px; padding-block: 0; padding-inline: 14px 10px; }
.bt-deck-mark { display: grid; place-items: center; width: 22px; height: 22px; border-radius: 7px; background: linear-gradient(135deg, rgba(79, 107, 255, .28), rgba(34, 211, 238, .18)); box-shadow: inset 0 0 0 1px rgba(159, 211, 255, .18); color: #bfe0ff; }
.bt-deck-mark .bt-glyph { width: 13px; height: 13px; }
.bt-deck-name { font: 650 13.5px/1 var(--bt-ui); letter-spacing: -.01em; }
.bt-deck-count { color: var(--bt-faint); font: 500 11.5px/1 var(--bt-ui); }
.bt-deck-total { padding: 4px 8px; border-radius: 999px; background: var(--bt-accent-soft); color: var(--bt-accent-ink); font: 600 11px/1 var(--bt-mono); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .28); }
.bt-deck-fill { flex: 1; }
.bt-deck-pager { display: flex; align-items: center; gap: 2px; padding: 2px; border-radius: 999px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line-soft); }
.bt-deck-pager .bt-icon { width: 24px; height: 24px; border-radius: 999px; }
.bt-deck-pager .bt-glyph { width: 13px; height: 13px; }
.bt-deck-dot { width: 18px; height: 24px; padding: 0; border: 0; background: transparent; cursor: pointer; position: relative; }
.bt-deck-dot::after { content: ""; position: absolute; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px 0 0 -3px; border-radius: 999px; background: var(--bt-line-strong); transition: width var(--bt-t2) var(--bt-ease-out), margin var(--bt-t2) var(--bt-ease-out), background-color var(--bt-t1) var(--bt-ease); }
.bt-deck-dot:hover::after { background: var(--bt-muted); }
.bt-deck-dot.is-on::after { width: 14px; margin-left: -7px; background: var(--bt-accent); } /* rtl-ok: centred with left: 50% */
.bt-deck-memory { color: var(--bt-muted); font: 500 11px/1 var(--bt-mono); padding: 5px 8px; border-radius: 7px; background: rgba(238, 240, 247, .04); }
.bt-deck-action { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding-block: 0; padding-inline: 9px 11px; border: 0; border-radius: 8px; background: rgba(238, 240, 247, .05); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .06); color: var(--bt-text-2); font: 550 12.5px/1 var(--bt-ui); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-deck-action .bt-glyph { width: 14px; height: 14px; }
.bt-deck-action:hover { background: rgba(238, 240, 247, .09); color: var(--bt-text); }
.bt-deck-action.is-on { background: var(--bt-accent-soft); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .38); color: var(--bt-accent-ink); }
.bt-deck-settings { width: 28px; height: 28px; }
.bt-deck-settings .bt-glyph { width: 15px; height: 15px; }
/* Columns row ------------------------------------------------------------------------------- */
.bt-deck-row { position: relative; flex: 1; min-height: 0; margin: 0 8px; }
.bt-col, .bt-compose {
position: absolute; top: 0; bottom: 0; display: flex; flex-direction: column; box-sizing: border-box;
border-radius: 12px 12px 0 0; background: var(--bt-chrome); box-shadow: inset 0 0 0 1px var(--bt-line-soft);
--bt-col-account: var(--bt-accent);
}
/* Motion never transforms a column's body: the webview is placed on the body's rectangle, so only
opacity (the card) and the header move. */
.bt-col { animation: bt-fade-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-col > .bt-col-head { animation: bt-col-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-col.is-leaving { animation: bt-col-out 180ms var(--bt-ease) forwards; pointer-events: none; }
.bt-col.is-leaving > .bt-col-head { animation: bt-col-head-out 180ms var(--bt-ease) forwards; }
@keyframes bt-col-in { from { opacity: 0; transform: translateY(8px); } }
@keyframes bt-col-out { to { opacity: 0; } }
@keyframes bt-col-head-out { to { transform: translateY(-6px); } }
.bt-col-head, .bt-compose-head {
position: relative; flex: none; display: flex; align-items: center; gap: 8px; height: 46px; padding-block: 0; padding-inline: 8px 6px;
border-radius: 12px 12px 0 0; border-bottom: 1px solid var(--bt-line-soft);
background: linear-gradient(180deg, rgba(238, 240, 247, .025), transparent);
}
/* The focused column: an accent line on top and a lifted header. */
.bt-col-head::before, .bt-compose-head::before {
content: ""; position: absolute; left: 12px; right: 12px; top: 0; height: 2px; border-radius: 0 0 2px 2px;
background: var(--bt-brush); opacity: 0; transform: scaleX(.6); transition: opacity var(--bt-t2) var(--bt-ease), transform var(--bt-t3) var(--bt-ease-out);
}
.bt-col.is-focused .bt-col-head::before, .bt-compose-head::before { opacity: 1; transform: none; }
.bt-col.is-focused { box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .32); }
.bt-col.is-focused .bt-col-head { background: linear-gradient(180deg, rgba(29, 155, 240, .08), rgba(29, 155, 240, 0)); }
.bt-col-glyph {
display: grid; place-items: center; flex: none; width: 28px; height: 28px; border-radius: 8px; padding: 0; border: 0;
background: color-mix(in srgb, var(--bt-col-account) 16%, transparent); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--bt-col-account) 30%, transparent);
color: color-mix(in srgb, var(--bt-col-account) 55%, #ffffff);
}
.bt-col-glyph .bt-glyph { width: 15px; height: 15px; }
.bt-col-back { cursor: pointer; background: rgba(238, 240, 247, .07); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .1); color: var(--bt-text); transition: background-color var(--bt-t1) var(--bt-ease); }
.bt-col-back:hover { background: rgba(238, 240, 247, .12); }
.bt-col-titles { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.bt-col-titles strong { font: 650 13.5px/1.1 var(--bt-ui); letter-spacing: -.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-col-titles span { color: var(--bt-muted); font: 450 11.5px/1.1 var(--bt-ui); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-col-fill { flex: 1; min-width: 4px; }
.bt-col-unread {
flex: none; min-width: 22px; height: 20px; padding: 0 7px; box-sizing: border-box; border: 0; border-radius: 999px; cursor: pointer;
background: var(--bt-accent); color: #fff; font: 700 11px/20px var(--bt-mono); letter-spacing: -.02em;
box-shadow: 0 0 0 3px rgba(29, 155, 240, .16), 0 4px 12px -4px rgba(29, 155, 240, .8);
animation: bt-unread-in var(--bt-t3) var(--bt-ease-out);
}
.bt-col-unread:hover { filter: brightness(1.12); }
@keyframes bt-unread-in { from { transform: scale(.6); opacity: 0; } }
.bt-col-account { display: grid; place-items: center; flex: none; padding: 2px; border-radius: 999px; box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--bt-col-account) 70%, transparent); }
.bt-col-btn { width: 28px; height: 28px; border-radius: 8px; color: var(--bt-muted); }
.bt-col-btn .bt-glyph { width: 15px; height: 15px; }
.bt-col-btn:hover { color: var(--bt-text); }
.bt-col-btn.is-active { color: var(--bt-accent-ink); background: var(--bt-accent-soft); }
.bt-col-key { position: absolute; inset-inline-end: 6px; top: 4px; color: var(--bt-faint); font: 600 9px/1 var(--bt-mono); opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease); pointer-events: none; }
.bt-col-head:hover .bt-col-key { opacity: .8; }
.bt-col-progress { position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; overflow: hidden; }
.bt-col-progress::after { content: ""; position: absolute; top: 0; bottom: 0; width: 40%; background: linear-gradient(90deg, transparent, var(--bt-accent), transparent); animation: bt-col-load 1.1s var(--bt-ease) infinite; }
@keyframes bt-col-load { from { left: -40%; } to { left: 100%; } }
.bt-col-body { position: relative; flex: 1; min-height: 0; background: #000; }
.bt-col-hint { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; color: var(--bt-faint); font: 500 12px/1 var(--bt-ui); }
/* Compose dock ------------------------------------------------------------------------------ */
.bt-compose { right: 0; animation: bt-fade-in var(--bt-t3) var(--bt-ease-out) both; box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .28), -18px 0 40px -24px rgba(0, 0, 0, .8); }
.bt-compose > .bt-compose-head { animation: bt-slide-in var(--bt-t3) var(--bt-ease-out) both; }
.bt-compose-glyph { --bt-col-account: var(--bt-accent); }
.bt-compose-accounts { display: flex; gap: 2px; padding: 2px; border-radius: 999px; background: var(--bt-field); }
.bt-compose-accounts button { display: grid; place-items: center; padding: 2px; border: 0; border-radius: 999px; background: transparent; cursor: pointer; opacity: .55; transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-compose-accounts button:hover { opacity: .9; }
.bt-compose-accounts button.is-on { opacity: 1; box-shadow: 0 0 0 1.5px var(--bt-accent); }
/* Popovers (filters, column menu) --------------------------------------------------------------- */
.bt-deck-pop { gap: 2px; }
.bt-deck-pop-head { display: flex; align-items: center; gap: 8px; padding: 8px 8px 10px; }
.bt-deck-pop-head .bt-glyph { width: 15px; height: 15px; color: var(--bt-accent); }
.bt-deck-pop-head strong { font: 650 13px/1 var(--bt-ui); }
.bt-deck-pop-head span { margin-inline-start: auto; color: var(--bt-faint); font: 500 11.5px/1 var(--bt-ui); max-width: 55%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-deck-terms { display: flex; flex-direction: column; gap: 8px; padding: 0 4px 6px; }
.bt-deck-input { height: 32px; padding: 0 10px; border: 0; border-radius: 8px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line); color: var(--bt-text); font: 450 12.5px/1 var(--bt-mono); outline: none; user-select: text; }
.bt-deck-input:focus { box-shadow: var(--bt-ring); }
.bt-deck-chips { display: flex; flex-wrap: wrap; gap: 5px; max-height: 120px; overflow-y: auto; scrollbar-width: thin; }
.bt-deck-chip { display: inline-flex; align-items: center; gap: 2px; max-width: 100%; height: 24px; padding-block: 0; padding-inline: 9px 2px; border-radius: 999px; background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .07); font: 500 12px/1 var(--bt-ui); }
.bt-deck-chip > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-deck-chip.is-regex { font-family: var(--bt-mono); color: #d7c6ff; background: rgba(168, 85, 247, .12); box-shadow: inset 0 0 0 1px rgba(168, 85, 247, .25); }
.bt-menu .bt-deck-chip button { width: 20px; height: 20px; padding: 0; justify-content: center; border-radius: 999px; }
.bt-deck-chip .bt-glyph { width: 11px; height: 11px; }
.bt-deck-check { display: flex; align-items: flex-start; gap: 10px; padding: 7px 8px; border-radius: 8px; cursor: pointer; }
.bt-deck-check:hover { background: var(--bt-hover); }
.bt-deck-check input { position: absolute; opacity: 0; pointer-events: none; }
.bt-deck-check-box { display: grid; place-items: center; flex: none; width: 16px; height: 16px; margin-top: 1px; border-radius: 5px; box-shadow: inset 0 0 0 1.5px var(--bt-line-strong); color: transparent; transition: background-color var(--bt-t1) var(--bt-ease); }
.bt-deck-check-box .bt-glyph { width: 11px; height: 11px; stroke-width: 2.4; }
.bt-deck-check input:checked + .bt-deck-check-box { background: var(--bt-accent); box-shadow: none; color: #fff; }
.bt-deck-check input:focus-visible + .bt-deck-check-box { box-shadow: var(--bt-ring); }
.bt-deck-check-text { display: flex; flex-direction: column; gap: 3px; }
.bt-deck-check-text strong { font: 550 12.5px/1.1 var(--bt-ui); }
.bt-deck-check-text small { color: var(--bt-muted); font: 400 11.5px/1.2 var(--bt-ui); }
.bt-deck-widths { display: flex; align-items: center; gap: 2px; padding-block: 4px; padding-inline: 10px 6px; color: var(--bt-muted); font: 500 12px/1 var(--bt-ui); }
.bt-deck-widths > span { margin-inline-end: auto; }
.bt-menu .bt-deck-widths button { height: 24px; padding: 0 6px; border-radius: 6px; color: var(--bt-muted); font: 500 11px/1 var(--bt-mono); }
.bt-menu .bt-deck-widths button.is-on { background: var(--bt-accent-soft); color: var(--bt-accent-ink); }
/* Buttons ----------------------------------------------------------------------------------- */
.bt-deck-primary, .bt-deck-secondary {
display: inline-flex; align-items: center; justify-content: center; gap: 7px; height: 34px; padding: 0 14px; border: 0; border-radius: 9px; cursor: pointer;
font: 600 13px/1 var(--bt-ui); transition: filter var(--bt-t1) var(--bt-ease), background-color var(--bt-t1) var(--bt-ease);
}
.bt-deck-primary { background: var(--bt-accent); color: #fff; box-shadow: 0 6px 18px -8px rgba(29, 155, 240, .9), inset 0 1px 0 rgba(255, 255, 255, .18); }
.bt-deck-primary:hover:not(:disabled) { filter: brightness(1.08); }
.bt-deck-primary:disabled { opacity: .45; cursor: default; }
.bt-deck-primary .bt-glyph { width: 15px; height: 15px; stroke-width: 2.2; }
.bt-deck-secondary { background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .08); color: var(--bt-text-2); }
.bt-deck-secondary:hover:not(:disabled) { background: rgba(238, 240, 247, .1); color: var(--bt-text); }
.bt-deck-secondary:disabled { opacity: .45; cursor: default; }
/* Empty deck -------------------------------------------------------------------------------- */
.bt-deck-empty { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; text-align: center; }
.bt-deck-empty h2 { margin: 6px 0 0; font: 700 22px/1.1 var(--bt-ui); letter-spacing: -.02em; }
.bt-deck-empty p { margin: 0; max-width: 420px; color: var(--bt-muted); font: 400 13.5px/1.5 var(--bt-ui); }
.bt-deck-empty-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 8px; }
.bt-deck-empty-keys { display: flex; align-items: center; gap: 6px 18px; flex-wrap: wrap; justify-content: center; margin-top: 10px !important; font-size: 12px !important; color: var(--bt-faint) !important; }
.bt-deck-empty-keys > span { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.bt-deck-empty-art { display: flex; gap: 6px; height: 64px; align-items: flex-end; }
.bt-deck-empty-art span { width: 30px; border-radius: 7px 7px 2px 2px; background: linear-gradient(180deg, rgba(79, 107, 255, .5), rgba(34, 211, 238, .12)); box-shadow: inset 0 0 0 1px rgba(159, 211, 255, .2); animation: bt-rise var(--bt-t3) var(--bt-ease-out) both; }
.bt-deck-empty-art span:nth-child(1) { height: 64px; }
.bt-deck-empty-art span:nth-child(2) { height: 52px; }
.bt-deck-empty-art span:nth-child(3) { height: 58px; }
.bt-deck-empty-art span:nth-child(4) { height: 44px; background: linear-gradient(180deg, rgba(168, 85, 247, .5), rgba(168, 85, 247, .1)); }
/* Add column dialog ------------------------------------------------------------------------- */
.bt-addcol { width: min(680px, 100%); max-height: min(84vh, 640px); overflow-y: auto; }
.bt-addcol-head { display: flex; align-items: baseline; gap: 8px; padding-block: 18px 6px; padding-inline: 20px 16px; }
.bt-addcol-head h2 { margin: 0; font: 700 17px/1.1 var(--bt-ui); letter-spacing: -.015em; }
.bt-addcol-head > span { color: var(--bt-muted); font-size: 12.5px; }
.bt-addcol-head .bt-icon { margin-inline-start: auto; align-self: center; }
.bt-addcol-types { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; padding: 10px 16px 6px; }
.bt-addcol-type {
display: flex; flex-direction: column; align-items: flex-start; gap: 6px; min-height: 96px; padding: 12px; border: 0; border-radius: 11px; cursor: pointer; text-align: start;
background: rgba(238, 240, 247, .035); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .06); color: var(--bt-text-2);
transition: background-color var(--bt-t1) var(--bt-ease), box-shadow var(--bt-t1) var(--bt-ease), transform var(--bt-t2) var(--bt-ease-out);
}
.bt-addcol-type:hover { background: rgba(238, 240, 247, .06); }
.bt-addcol-type:active { transform: scale(.985); }
.bt-addcol-type.is-on { background: var(--bt-accent-soft); box-shadow: inset 0 0 0 1.5px rgba(29, 155, 240, .6); color: var(--bt-text); }
.bt-addcol-type strong { font: 650 13.5px/1.1 var(--bt-ui); color: var(--bt-text); }
.bt-addcol-type small { color: var(--bt-muted); font: 400 11.5px/1.35 var(--bt-ui); }
.bt-addcol-icon { display: grid; place-items: center; width: 28px; height: 28px; border-radius: 8px; background: rgba(238, 240, 247, .06); color: var(--bt-muted); }
.bt-addcol-type.is-on .bt-addcol-icon { background: rgba(29, 155, 240, .22); color: #bfe0ff; }
.bt-addcol-icon .bt-glyph { width: 15px; height: 15px; }
.bt-addcol-value { display: flex; flex-direction: column; gap: 8px; padding: 10px 16px 4px; }
.bt-addcol-value label, .bt-addcol-label { color: var(--bt-faint); font: 600 10.5px/1 var(--bt-ui); letter-spacing: .08em; text-transform: uppercase; }
.bt-addcol-field { display: flex; align-items: center; gap: 10px; height: 42px; padding: 0 12px; border-radius: 10px; background: var(--bt-field); box-shadow: inset 0 0 0 1px var(--bt-line); }
.bt-addcol-field:focus-within { box-shadow: var(--bt-ring); }
.bt-addcol-field.is-bad { box-shadow: 0 0 0 1px rgba(229, 72, 77, .7); }
.bt-addcol-field .bt-glyph { color: var(--bt-muted); }
.bt-addcol-field input { flex: 1; min-width: 0; border: 0; background: transparent; color: var(--bt-text); font: 500 14px/1 var(--bt-mono); outline: none; user-select: text; }
.bt-addcol-field input::placeholder { color: var(--bt-faint); }
.bt-addcol-chips { display: flex; flex-wrap: wrap; gap: 6px; }
.bt-addcol-chips button { height: 26px; padding: 0 10px; border: 0; border-radius: 999px; background: rgba(238, 240, 247, .06); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .08); color: var(--bt-text-2); font: 500 12px/1 var(--bt-mono); cursor: pointer; }
.bt-addcol-chips button[aria-selected=true] { background: var(--bt-accent-soft); color: var(--bt-accent-ink); box-shadow: inset 0 0 0 1px rgba(29, 155, 240, .35); }
.bt-addcol-error { margin: 0; color: #ff9a9e; font-size: 12px; }
.bt-addcol-accounts { display: flex; flex-direction: column; gap: 8px; padding: 12px 16px 8px; }
.bt-addcol-accounts > div { display: flex; flex-wrap: wrap; gap: 6px; }
.bt-addcol-account { display: inline-flex; align-items: center; gap: 8px; height: 34px; padding-block: 0; padding-inline: 6px 12px; border: 0; border-radius: 999px; cursor: pointer; background: rgba(238, 240, 247, .04); box-shadow: inset 0 0 0 1px rgba(238, 240, 247, .07); color: var(--bt-text-2); font: 550 12.5px/1 var(--bt-ui); }
.bt-addcol-account:hover { background: rgba(238, 240, 247, .08); }
.bt-addcol-account.is-on { box-shadow: inset 0 0 0 1.5px var(--bt-col-account); color: var(--bt-text); background: color-mix(in srgb, var(--bt-col-account) 12%, transparent); }
.bt-addcol-account em { color: var(--bt-faint); font: italic 400 11px/1 var(--bt-ui); }
.bt-addcol-foot { display: flex; align-items: center; gap: 14px; padding: 12px 16px 16px; color: var(--bt-muted); font-size: 11.5px; }
.bt-addcol-foot > span { display: inline-flex; align-items: center; gap: 6px; }
@media (max-width: 620px) { .bt-addcol-types { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (prefers-reduced-motion: reduce) {
.bt-col, .bt-col > .bt-col-head, .bt-col.is-leaving, .bt-compose, .bt-compose > .bt-compose-head, .bt-col-unread, .bt-deck-empty-art span { animation: none !important; }
.bt-col.is-leaving { opacity: 0; }
}

View file

@ -0,0 +1,264 @@
// Decks in the shell: the decks (localStorage `bt.shell.decks.v1`), the deck settings
// (`bt.shell.deck-settings.v1`), and what each column's webview last reported (unread, address,
// loading). Columns are real site tab webviews: state.ts lays them out through `columnBoxes()`,
// and each column's config reaches its page through the shell-only `column_configure` command
// (validated natively: waybetter-host `tabs::ColumnConfig`). The kinds of columns, their pages and
// flags are the site's (`site.deck`). Nothing here talks to the site.
import {
DEFAULT_COLUMN_WIDTH, DEFAULT_MAX_VISIBLE, clampWidth, columnUrl, emptyFilters, moveColumn, normalizeDecks,
type ColumnFilters, type ColumnSource, type Deck, type DeckColumn,
} from '../deckModel.ts';
import { invoke } from './bridge.ts';
import { site, type DeckSite } from './site.ts';
export type { Deck, DeckColumn, ColumnFilters, ColumnSource };
const DECKS_KEY = 'bt.shell.decks.v1';
const SETTINGS_KEY = 'bt.shell.deck-settings.v1';
/** The site's deck, or an empty one (no kinds, no flags) for an app without decks. */
const deckSite = (): DeckSite => site().deck ?? { kinds: [], urlFor: () => null, title: () => ({ title: '' }), parseValue: () => null, invalid: () => '', flags: [], defaultFlags: {} };
/** Flags a column may carry: the listed ones and the site's unlisted ones (native code checks them again). */
export const columnFlagKeys = () => [...deckSite().flags.map(option => option.key), ...(deckSite().extraFlags ?? [])];
const columnKinds = () => deckSite().kinds.map(kind => kind.kind);
export type DeckSettings = {
width: number;
density: 'compact' | 'comfortable';
/** Default flags for new columns (and every column that does not override them). */
flags: Record<string, boolean>;
/** Visible columns per page; the memory guard warns above DEFAULT_MAX_VISIBLE. */
maxVisible: number;
/** Columns on other pages drop to WebView2's low memory target. */
parkOffPage: boolean;
};
export const defaultDeckSettings = (): DeckSettings => ({
width: DEFAULT_COLUMN_WIDTH,
density: 'compact',
flags: { ...deckSite().defaultFlags },
maxVisible: DEFAULT_MAX_VISIBLE,
parkOffPage: true,
});
function read<T>(key: string): T | null {
try { return JSON.parse(localStorage.getItem(key) || 'null') as T; } catch { return null; }
}
function write(key: string, value: unknown) {
try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* best effort */ }
}
export function normalizeDeckSettings(value: unknown): DeckSettings {
const defaults = defaultDeckSettings();
const raw = (value && typeof value === 'object' ? value : {}) as Partial<DeckSettings>;
const allowed = columnFlagKeys();
const flags: Record<string, boolean> = {};
for (const [key, flag] of Object.entries(raw.flags && typeof raw.flags === 'object' ? raw.flags : defaults.flags)) {
if (allowed.includes(key) && typeof flag === 'boolean') flags[key] = flag;
}
const maxVisible = typeof raw.maxVisible === 'number' && Number.isFinite(raw.maxVisible) ? Math.round(Math.min(12, Math.max(1, raw.maxVisible))) : defaults.maxVisible;
return {
width: raw.width === undefined ? defaults.width : clampWidth(raw.width),
density: raw.density === 'comfortable' ? 'comfortable' : 'compact',
flags,
maxVisible,
parkOffPage: raw.parkOffPage !== false,
};
}
type ColumnRuntime = { url?: string; title?: string; loading?: boolean; unread: number };
export const decks = {
list: [] as Deck[],
/** `defaultDeckSettings()` once the site is set (createShell), then the saved ones (loadDecks). */
settings: { width: DEFAULT_COLUMN_WIDTH, density: 'compact', flags: {}, maxVisible: DEFAULT_MAX_VISIBLE, parkOffPage: true } as DeckSettings,
/** Per column tab: what its webview last reported. */
runtime: new Map<string, ColumnRuntime>(),
/** Focused column per deck. */
focus: new Map<string, string>(),
page: new Map<string, number>(),
/** Mark-read / jump requests per column tab (the page acts when the number changes). */
seq: new Map<string, { read: number; jump: number }>(),
/** Compose dock per deck: open and in which profile. */
compose: new Map<string, { profile: string }>(),
/** Last config sent per column tab (JSON), so unchanged configs are not re-sent. */
sent: new Map<string, string>(),
/** Column tabs whose config native code has: only these are laid out (their webview then starts
* with the site's chrome already hidden). */
ready: new Set<string>(),
loaded: false,
};
const emit = () => window.dispatchEvent(new CustomEvent('bt-decks'));
export function loadDecks(profiles?: readonly string[], fallbackProfile = 'default') {
decks.settings = normalizeDeckSettings(read(SETTINGS_KEY));
decks.list = normalizeDecks(read(DECKS_KEY), { kinds: columnKinds(), profiles, fallbackProfile, flags: columnFlagKeys() });
decks.loaded = true;
}
export function saveDecks() {
write(DECKS_KEY, decks.list);
emit();
}
export function setDeckSettings(next: DeckSettings) {
decks.settings = normalizeDeckSettings(next);
write(SETTINGS_KEY, decks.settings);
// Density and default flags are part of every column's config.
for (const deck of decks.list) for (const column of deck.columns) configureColumn(column);
emit();
}
export const deckById = (id: string) => decks.list.find(deck => deck.id === id);
export const newId = (prefix: string) => `${prefix}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 7)}`;
export function updateDeck(id: string, change: (deck: Deck) => Deck) {
decks.list = decks.list.map(deck => (deck.id === id ? change(deck) : deck));
saveDecks();
}
export function createDeck(name: string, columns: Array<Pick<DeckColumn, 'profile' | 'source'> & Partial<DeckColumn>> = []): Deck {
const deck: Deck = { id: newId('d'), name, columns: columns.map(column => makeColumn(column)) };
decks.list = [...decks.list, deck];
saveDecks();
return deck;
}
export function makeColumn(input: Pick<DeckColumn, 'profile' | 'source'> & Partial<DeckColumn>): DeckColumn {
return {
id: newId('c'),
tabId: newId('k'),
width: decks.settings.width,
flags: {},
filters: emptyFilters(),
...input,
};
}
export function addColumn(deckId: string, input: Pick<DeckColumn, 'profile' | 'source'> & Partial<DeckColumn>, after?: string): DeckColumn {
const column = makeColumn(input);
updateDeck(deckId, deck => {
const index = after ? deck.columns.findIndex(c => c.id === after) : -1;
const columns = [...deck.columns];
columns.splice(index >= 0 ? index + 1 : columns.length, 0, column);
return { ...deck, columns };
});
decks.focus.set(deckId, column.id);
return column;
}
export function removeColumn(deckId: string, columnId: string) {
const deck = deckById(deckId);
const column = deck?.columns.find(c => c.id === columnId);
if (!deck || !column) return;
updateDeck(deckId, d => ({ ...d, columns: d.columns.filter(c => c.id !== columnId) }));
forgetColumn(column.tabId);
}
export function patchColumn(deckId: string, columnId: string, patch: Partial<DeckColumn>) {
updateDeck(deckId, deck => ({ ...deck, columns: deck.columns.map(c => (c.id === columnId ? { ...c, ...patch } : c)) }));
const column = deckById(deckId)?.columns.find(c => c.id === columnId);
if (column) configureColumn(column);
}
export function shiftColumn(deckId: string, columnId: string, delta: number) {
updateDeck(deckId, deck => ({ ...deck, columns: moveColumn(deck.columns, columnId, delta) }));
}
export function forgetColumn(tabId: string) {
decks.runtime.delete(tabId);
decks.seq.delete(tabId);
decks.sent.delete(tabId);
decks.ready.delete(tabId);
invoke('column_configure', { id: tabId, config: null }).catch(() => {});
}
export const columnSourceUrl = (source: ColumnSource) => columnUrl(source, deckSite().urlFor);
/** The config a column's page gets (validated natively). */
export function columnConfig(column: DeckColumn) {
const url = columnSourceUrl(column.source);
if (!url) return null;
const seq = decks.seq.get(column.tabId) ?? { read: 0, jump: 0 };
const flags: Record<string, boolean> = { ...decks.settings.flags, ...column.flags, ...deckSite().kindFlags?.(column.source) };
return {
url,
kind: column.source.kind,
density: decks.settings.density,
filters: column.filters,
flags,
unread: true,
readSeq: seq.read,
jumpSeq: seq.jump,
};
}
/** Sends a column its config when it changed (or always with `force`, e.g. on mount). */
export function configureColumn(column: DeckColumn, force = false): Promise<void> {
const config = columnConfig(column);
const json = JSON.stringify(config);
if (!force && decks.sent.get(column.tabId) === json) return Promise.resolve();
decks.sent.set(column.tabId, json);
return invoke('column_configure', { id: column.tabId, config }).then(() => { decks.ready.add(column.tabId); }, error => {
decks.sent.delete(column.tabId);
console.error('[deck] column_configure', error);
});
}
/** The compose dock (`site.deck.compose`) is a column-like webview on the site's compose page. */
export const composeTabId = (deckId: string) => `${deckId}-compose`;
export function configureCompose(deckId: string): Promise<void> {
const url = deckSite().compose?.url;
if (!url) return Promise.resolve();
const id = composeTabId(deckId);
const config = { url, kind: 'compose', density: decks.settings.density, filters: emptyFilters(), flags: {}, unread: false, readSeq: 0, jumpSeq: 0 };
const json = JSON.stringify(config);
if (decks.sent.get(id) === json) return Promise.resolve();
decks.sent.set(id, json);
return invoke('column_configure', { id, config }).then(() => { decks.ready.add(id); }, () => { decks.sent.delete(id); });
}
export function bump(column: DeckColumn, which: 'read' | 'jump') {
const seq = decks.seq.get(column.tabId) ?? { read: 0, jump: 0 };
decks.seq.set(column.tabId, { ...seq, [which]: seq[which] + 1 });
if (which === 'read') setRuntime(column.tabId, { unread: 0 });
void configureColumn(column);
}
export function setRuntime(tabId: string, patch: Partial<ColumnRuntime>) {
const current = decks.runtime.get(tabId) ?? { unread: 0 };
const next = { ...current, ...Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)) };
if (JSON.stringify(next) === JSON.stringify(current)) return false;
decks.runtime.set(tabId, next);
emit();
return true;
}
/** The deck and column a tab webview id belongs to (columns and compose docks), if any. */
export function findColumnTab(tabId: string): { deck: Deck; column?: DeckColumn; compose?: boolean } | null {
for (const deck of decks.list) {
if (composeTabId(deck.id) === tabId) return { deck, compose: true };
const column = deck.columns.find(c => c.tabId === tabId);
if (column) return { deck, column };
}
return null;
}
/** Workspaces: decks a restored workspace shows that are no longer here come back (by id). */
export function ensureDecks(list: unknown[]) {
const incoming = normalizeDecks(list, { kinds: columnKinds(), fallbackProfile: 'default', flags: columnFlagKeys() });
const missing = incoming.filter(deck => !deckById(deck.id));
if (!missing.length) return;
decks.list = normalizeDecks([...decks.list, ...missing], { kinds: columnKinds(), fallbackProfile: 'default', flags: columnFlagKeys() });
saveDecks();
}
/** Settings import: the backup's decks and deck settings replace the ones here. */
export function replaceDecks(list: unknown, settings: unknown) {
decks.list = normalizeDecks(list, { kinds: columnKinds(), fallbackProfile: 'default', flags: columnFlagKeys() });
saveDecks();
setDeckSettings(normalizeDeckSettings(settings));
}

View file

@ -0,0 +1,82 @@
// Developer mode in the shell: native code watches the plugins folder, custom.css and the chosen
// theme file (waybetter-host `devmode`) and sends `dev-event`s. A changed plugin arrives as
// `check` with its source: the shell parses it (devModel.ts, never evaluated) and either asks
// native code to reload it in every site tab (`dev_reload_plugin`: stop, then start the new
// version) or reports the syntax error with file, line and column (`dev_report_error`: a toast in
// the site tabs, the list in the app's developer settings, the titlebar chip). Runtime errors of
// the new version show in the page.
import { invoke, listen } from './bridge.ts';
import { checkPluginSyntax } from './devModel.ts';
import { t } from './i18n.ts';
export { checkPluginSyntax, type SyntaxProblem } from './devModel.ts';
export type DevErrorInfo = { file: string; line?: number | null; column?: number | null; message: string; at?: string };
export type DevEventPayload =
| { kind: 'check'; file: string; source: string }
| { kind: 'reloaded'; target: 'plugin' | 'css' | 'theme'; file?: string | null }
| { kind: 'error'; error: DevErrorInfo }
| { kind: 'changed' };
export const dev = {
enabled: false,
errors: [] as DevErrorInfo[],
/** The last thing reloaded, for the titlebar chip ("Reloaded focus-mode.plugin.js"). */
last: null as { text: string; at: number } | null,
};
const emit = () => window.dispatchEvent(new CustomEvent('bt-dev'));
async function onCheck(file: string, source: string) {
const problem = await checkPluginSyntax(source);
if (problem) {
await invoke('dev_report_error', { file, line: problem.line, column: problem.column, message: problem.message }).catch(() => {});
return;
}
await invoke('dev_reload_plugin', { file }).catch(error => {
dev.errors = [{ file, message: String(error) }, ...dev.errors].slice(0, 20);
emit();
});
}
export async function refreshDev(): Promise<void> {
try {
const status = await invoke<{ enabled: boolean; errors: DevErrorInfo[] }>('dev_get');
dev.enabled = status.enabled;
dev.errors = status.errors ?? [];
} catch { dev.enabled = false; }
emit();
}
export function installDevHost(): () => void {
void refreshDev();
const off = listen<DevEventPayload>('dev-event', ({ payload }) => {
if (!payload) return;
if (payload.kind === 'check') { void onCheck(payload.file, payload.source); return; }
// Turned on or off (from the panel or elsewhere): read the state again.
if (payload.kind === 'changed') { void refreshDev(); return; }
// Only a watching app sends these.
dev.enabled = true;
if (payload.kind === 'error') {
dev.errors = [{ ...payload.error, at: new Date().toISOString() }, ...dev.errors.filter(error => error.file !== payload.error.file)].slice(0, 20);
} else if (payload.kind === 'reloaded') {
if (payload.file) dev.errors = dev.errors.filter(error => error.file !== payload.file);
dev.last = { text: t('wb.dev.reloaded', { file: payload.file ?? payload.target ?? '' }), at: Date.now() };
}
emit();
window.dispatchEvent(new CustomEvent('bt-dev-event', { detail: payload }));
});
return () => { void off.then(dispose => dispose(), () => {}); };
}
export function setDevEnabled(enabled: boolean) {
dev.enabled = enabled;
if (!enabled) dev.errors = [];
emit();
}
export function setDevErrors(errors: DevErrorInfo[]) {
dev.errors = errors;
emit();
}

View file

@ -0,0 +1,18 @@
// Developer mode's syntax gate (pure; unit-tested under node): a changed plugin file is parsed the
// way the host evaluates it (the body of a CommonJS function), never run, before native code is
// asked to reload it. Uses acorn (an optional peer dependency of the shell frame).
export type SyntaxProblem = { line: number; column: number; message: string };
/** Null when `source` parses. Line and column are 1-based, in the file. */
export async function checkPluginSyntax(source: string): Promise<SyntaxProblem | null> {
const { parse } = await import('acorn');
try {
parse(source.replace(/^/, ''), { ecmaVersion: 'latest', sourceType: 'script', allowReturnOutsideFunction: true, allowHashBang: true, allowAwaitOutsideFunction: false });
return null;
} catch (error) {
const loc = (error as { loc?: { line: number; column: number } }).loc;
const message = (error instanceof Error ? error.message : String(error)).replace(/\s*\(\d+:\d+\)$/, '');
return { line: loc?.line ?? 1, column: (loc?.column ?? 0) + 1, message: `SyntaxError: ${message}` };
}
}

View file

@ -0,0 +1,103 @@
// React hooks over the frame's shared state (profiles, decks, the language, site text, developer
// mode, sync, themes, the update status). Each re-renders its component when that state changes.
import { useEffect, useReducer, useState, useSyncExternalStore } from 'react';
import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts';
import { isTauri } from '../windowControls.ts';
import { invoke, listen } from './bridge.ts';
import { dev } from './devHost.ts';
import { subscribeText, t, textLocale } from './i18n.ts';
import { shell } from './state.ts';
import { syncState } from './syncHost.ts';
import type { ThemeDoc, ThemeStore } from './themeStore.ts';
import type { ProfileSettings } from '../profileModel.ts';
/** Re-renders the calling component when the language changes; returns `t`. */
export function useT(): typeof t {
useSyncExternalStore(subscribeText, textLocale, textLocale);
return t;
}
/** Re-renders on every window event in `events`. */
function useEvents(...events: string[]) {
const [, tick] = useReducer((n: number) => n + 1, 0);
useEffect(() => {
for (const event of events) window.addEventListener(event, tick);
return () => { for (const event of events) window.removeEventListener(event, tick); };
}, []);
}
/** Current profile list; re-renders on every `setProfiles`. */
export function useProfiles(): ProfileSettings {
const [profiles, set] = useState(shell.profiles);
useEffect(() => {
const update = () => set(shell.profiles);
window.addEventListener('bt-profiles', update);
update();
return () => window.removeEventListener('bt-profiles', update);
}, []);
return profiles;
}
/** Re-renders when the focused pane (or the layout) changes. */
export function usePaneTick(): number {
const [tick, setTick] = useState(0);
useEffect(() => {
const bump = () => setTick(value => value + 1);
window.addEventListener('bt-active-pane', bump);
return () => window.removeEventListener('bt-active-pane', bump);
}, []);
return tick;
}
/** Re-renders when the site's runtime text changes (`siteChanged()`). */
export const useSiteText = () => useEvents('bt-site');
/** Re-renders on deck and profile changes. */
export const useDecks = () => useEvents('bt-decks', 'bt-profiles');
export function useDev() {
useEvents('bt-dev');
return dev;
}
export function useSync() {
useEvents('bt-sync');
return syncState;
}
/** The theme state of `store`; loads it once. */
export function useThemeState<Choice, Spec extends ThemeDoc>(store: ThemeStore<Choice, Spec>) {
const [value, setValue] = useState(store.current());
useEffect(() => {
const update = () => setValue(store.current());
const off = store.subscribe(update);
void store.loadThemes();
update();
return off;
}, [store]);
return value;
}
/**
* Native update status for the titlebar chip. Native code checks, downloads and verifies; the
* shell only reads the status, confirms it started (`app_ready`) and asks to apply a ready update.
*/
export function useUpdateStatus(): [UpdateStatus, () => void] {
const [status, setStatus] = useState<UpdateStatus>({ state: 'idle' });
useEffect(() => {
if (!isTauri) return;
let unlisten: (() => void) | undefined;
let disposed = false;
listen('update-status', event => setStatus(parseUpdateStatus(event.payload)))
.then(fn => { if (disposed) fn(); else unlisten = fn; })
.catch(() => {});
// Handshake: the shell rendered, so a just-installed update is confirmed working.
invoke('app_ready').then(value => setStatus(parseUpdateStatus(value))).catch(() => {});
return () => { disposed = true; unlisten?.(); };
}, []);
const apply = () => {
invoke('apply_update').catch(() => invoke('update_status').then(value => setStatus(parseUpdateStatus(value))).catch(() => {}));
};
return [status, apply];
}

View file

@ -0,0 +1,72 @@
// The shell frame's words. They live in the framework catalogs (`waybetter/locales/<bcp47>.json`,
// `wb.*`); the app hands the frame its i18n instance (`setShellI18n`, a `createI18n` from
// waybetter/i18n that has the framework catalogs merged in), so the frame speaks the app's language
// and re-renders when it changes (`useT`, hooks.ts). Without one (a unit test), a key reads as itself.
// Pure (no React, no Tauri), so the models that use it are unit-tested under node.
//
// Placeholders: `{site}` is the site's name ("X").
export type Params = Record<string, string | number | boolean | Date | null | undefined>;
/** The part of a waybetter/i18n instance the frame uses. */
export type ShellI18n = {
readonly locale: string;
tx(key: string, params?: Params, fallback?: string): string;
onChange(listener: (locale: string) => void): () => void;
number(value: number, options?: Intl.NumberFormatOptions): string;
relative(value: number, unit: Intl.RelativeTimeFormatUnit): string;
};
let current: ShellI18n | null = null;
/** Parameters every frame message gets (`{site}`: the site's name, set by createShell). */
let defaults: Params = {};
const listeners = new Set<() => void>();
let unbind: (() => void) | null = null;
/** Binds the frame to the app's i18n instance (once, before the shell renders). */
export function setShellI18n(i18n: ShellI18n) {
unbind?.();
current = i18n;
unbind = i18n.onChange(() => { for (const listener of [...listeners]) listener(); });
for (const listener of [...listeners]) listener();
}
/** Sets the parameters every frame message gets (createShell: `{ site }`). */
export function setTextDefaults(values: Params) {
defaults = { ...values };
}
/** The message for a framework key in the active language (the key itself when unbound or missing). */
export function t(key: string, params?: Params): string {
return current ? current.tx(key, { ...defaults, ...params }) : key;
}
/** Like `t` for keys assembled at runtime: `fallback` when the key is unknown. */
export function tx(key: string, params?: Params, fallback?: string): string {
return current ? current.tx(key, { ...defaults, ...params }, fallback) : fallback ?? key;
}
/** Language changes (for `useT`). */
export function subscribeText(listener: () => void): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export const textLocale = () => current?.locale ?? '';
/** A number in the active language ("5 min", "5 dk" with a unit style). */
export function formatNumber(value: number, options?: Intl.NumberFormatOptions): string {
return current ? current.number(value, options) : String(value);
}
/** "3 minutes ago" style text for a timestamp in the active language. */
export function relativeTime(then: number, now = Date.now()): string {
if (!current) return new Date(then).toISOString();
const seconds = Math.round((then - now) / 1000);
const abs = Math.abs(seconds);
if (abs < 45) return current.relative(0, 'second');
if (abs < 3600) return current.relative(Math.round(seconds / 60), 'minute');
if (abs < 86400) return current.relative(Math.round(seconds / 3600), 'hour');
if (abs < 86400 * 30) return current.relative(Math.round(seconds / 86400), 'day');
if (abs < 86400 * 365) return current.relative(Math.round(seconds / (86400 * 30)), 'month');
return current.relative(Math.round(seconds / (86400 * 365)), 'year');
}

View file

@ -0,0 +1,61 @@
// Shared 24px stroke glyphs for the shell chrome (1.75 stroke, round joins; sized by CSS).
export const ICONS = {
back: 'M15 5l-7 7 7 7',
forward: 'M9 5l7 7-7 7',
reload: 'M20 12a8 8 0 1 1-2.34-5.66M20 4v5h-5',
stop: 'M6 6l12 12M18 6L6 18',
close: 'M7 7l10 10M17 7L7 17',
plus: 'M12 5v14M5 12h14',
external: 'M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5',
split: 'M4 5h16v14H4zM12 5v14',
splitDown: 'M4 5h16v14H4zM4 12h16',
chevron: 'M7 10l5 5 5-5',
check: 'M5 12.5l4.5 4.5L19 7.5',
pin: 'M9 4h6l-1 6 3 3H7l3-3zM12 13v7',
unpin: 'M9 4h6l-1 6 3 3H7l3-3zM12 13v7M4 4l16 16',
copy: 'M9 9h10v11H9zM5 15V4h10',
duplicate: 'M8 8h11v11H8zM5 16V5h11',
closeOthers: 'M4 6h16M4 12h10M4 18h7M15 15l5 5M20 15l-5 5',
search: 'M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM20 20l-4-4',
home: 'M4 11l8-7 8 7M6 9.5V20h4.5v-5.5h3V20H18V9.5',
bell: 'M6 16V11a6 6 0 1 1 12 0v5l1.5 2h-15zM10 20.5h4',
bookmark: 'M7 4h10v16l-5-4-5 4z',
mail: 'M4 6h16v12H4zM4 7l8 6 8-6',
list: 'M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01',
explore: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM15.5 8.5l-2 5-5 2 2-5z',
globe: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18',
settings: 'M12 15a3 3 0 1 1 0-6 3 3 0 0 1 0 6zM19.4 13.5l1.6 1.2-2 3.4-1.9-.7a7 7 0 0 1-2 1.2L14.8 21h-4l-.3-2.4a7 7 0 0 1-2-1.2l-1.9.7-2-3.4 1.6-1.2a7 7 0 0 1 0-2.4L4.6 9.9l2-3.4 1.9.7a7 7 0 0 1 2-1.2L10.8 3.6h4l.3 2.4a7 7 0 0 1 2 1.2l1.9-.7 2 3.4-1.6 1.2a7 7 0 0 1 0 2.4z',
palette: 'M12 21a9 9 0 1 1 9-9c0 2-1.5 3-3.5 3H16a2 2 0 0 0-1.5 3.3A1.6 1.6 0 0 1 12 21zM7.5 11h.01M10 7.5h.01M14.5 7.5h.01',
image: 'M4 5h16v14H4zM4 16l5-5 4 4 2-2 5 5M15 9.5h.01',
draft: 'M5 20h4L20 9l-4-4L5 16zM14 7l4 4',
user: 'M12 12a4 4 0 1 1 0-8 4 4 0 0 1 0 8zM4.5 20a7.5 7.5 0 0 1 15 0',
sparkle: 'M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8zM19 16l.7 1.8 1.8.7-1.8.7L19 21l-.7-1.8-1.8-.7 1.8-.7z',
bolt: 'M13 3L5 14h6l-1 7 8-11h-6z',
filter: 'M4 5h16l-6 7v6l-4 2v-8z',
history: 'M4 12a8 8 0 1 0 2.3-5.6M4 4v4.5h4.5M12 8v4l3 2',
trash: 'M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13',
edit: 'M4 20h4L19 9l-4-4L4 16zM14 6l4 4',
grid: 'M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z',
} as const;
export type IconName = keyof typeof ICONS;
export const Icon = ({ name, className }: { name: IconName; className?: string }) =>
<svg className={className ? `bt-glyph ${className}` : 'bt-glyph'} viewBox="0 0 24 24" aria-hidden="true"><path d={ICONS[name]}/></svg>;
/** Readable initial on a profile color: dark ink on light colors, white on dark ones. */
export function inkOn(hex: string): string {
const value = Number.parseInt(hex.slice(1), 16);
const [r, g, b] = [(value >> 16) & 255, (value >> 8) & 255, value & 255];
return (0.299 * r + 0.587 * g + 0.114 * b) > 150 ? '#0b0d12' : '#ffffff';
}
export const initial = (name: string) => ([...name.trim()][0] ?? '?').toUpperCase();
/** Round account avatar: the profile's initial on its color. */
/** An account's X profile picture when known (`src`), else its initial on the profile color. */
export const Avatar = ({ name, color, size = 20, className = '', src }: { name: string; color: string; size?: number; className?: string; src?: string }) =>
<span className={`bt-avatar ${src ? 'bt-avatar--image' : ''} ${className}`} aria-hidden="true"
style={{ width: size, height: size, flexBasis: size, background: color, color: inkOn(color), fontSize: Math.round(size * 0.46) }}>
{src ? <img src={src} alt="" width={size} height={size} draggable={false} referrerPolicy="no-referrer"/> : initial(name)}</span>;

View file

@ -0,0 +1,55 @@
// The wayBetter shell frame: `createShell(site, options)` gives an app the whole shell (tabs in the
// titlebar row, splits, the smart address bar, the new-tab page, the command palette, the account
// switcher, decks of site columns, workspaces, developer mode and sync chips, the media panel,
// pane themes, overlays and the native layout sync). The app describes its site (`ShellSite`) and
// passes its Tauri API and i18n instance; styles come with the components (`--wb-*` tokens).
//
// const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n });
// createRoot(root).render(<Shell/>);
import type { ComponentType } from 'react';
import { setNative, type NativeApi } from './bridge.ts';
import { decks, defaultDeckSettings } from './deckStore.ts';
import { setShellI18n, setTextDefaults, type ShellI18n } from './i18n.ts';
import Shell, { setDevBuild } from './Shell.tsx';
import { configureSite, type ShellSite } from './site.ts';
import { probeLayer, shell } from './state.ts';
export type ShellOptions = {
/** The app's Tauri API: `invoke` and `listen` from @tauri-apps/api, and `getCurrentWindow`. */
native: NativeApi;
/** The app's i18n instance (waybetter/i18n `createI18n`, the framework catalogs merged in). */
i18n: ShellI18n;
/** A development build (keeps the devtools shortcut). */
dev?: boolean;
};
/**
* Sets the site and the app's native API and language for every frame module, and returns the
* shell's root component. Call once, before anything of the frame renders (the app's own panel
* may render the frame's pieces, e.g. in a preview, without the shell).
*/
export function createShell(site: ShellSite, options: ShellOptions): ComponentType {
setNative(options.native);
setShellI18n(options.i18n);
setTextDefaults({ site: site.name });
configureSite(site);
setDevBuild(!!options.dev);
shell.homeUrl = site.homeUrl;
decks.settings = defaultDeckSettings();
probeLayer();
return Shell;
}
export type { ShellSite, DeckSite, PaletteSite, ColumnKind, ColumnFlag, DeckPreset, Completer, Suggestion } from './site.ts';
export { site, siteChanged } from './site.ts';
export type { NativeApi, Invoke, Listen, ShellWindow, MockHandler } from './bridge.ts';
export { invoke, listen, isNative, installPreviewMocks } from './bridge.ts';
export type { ShellI18n } from './i18n.ts';
export { setShellI18n } from './i18n.ts';
export { bootScript, BOOT_CACHE_KEY } from './boot.ts';
export { createThemeStore, type ThemeAdapter, type ThemeStore, type ThemeDoc, type InstalledFont, type Weights } from './themeStore.ts';
export { chromeVars, CHROME_VAR_NAMES, SHELL_UI_FONT, SHELL_MONO_FONT, type ChromeTheme } from './chromeTheme.ts';
export { shell, setOverlay, scheduleSync, flushSync, isWeb, tabAction, setProfiles, type TabParams, type WebParams } from './state.ts';
export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.ts';
export { Icon, Avatar, ICONS, type IconName } from './icons.tsx';

View file

@ -0,0 +1,58 @@
// Pure model for the Media side panel (gallery folders + clipboard history). No Tauri/DOM
// imports, so it is unit-tested under node. The panel never posts: it only asks native code to
// attach an image to, or insert text into, one site tab's composer (`site.media.canAttach` says
// which pages have one).
import { formatNumber, t } from './i18n.ts';
export type GalleryImage = { path: string; name: string; folder: string; modifiedMs: number; size: number };
export type ClipItem = { id: string; kind: 'text' | 'image'; text?: string; file?: string; hash: string; at: number };
export type MediaSettings = { folders: string[]; clipboardEnabled: boolean; clipboardMax: number };
export type TabInfo = { id: string; url: string };
export const CLIP_MAX_LIMIT = 100;
/** The tab an attachment goes to: the active tab if it can take one, else the most recent one that can. */
export function attachTarget(tabs: TabInfo[], activeId: string | undefined, canAttach: (url: string) => boolean, recent: string[] = []): TabInfo | null {
const active = tabs.find(tab => tab.id === activeId);
if (active && canAttach(active.url)) return active;
for (const id of recent) {
const tab = tabs.find(candidate => candidate.id === id);
if (tab && canAttach(tab.url)) return tab;
}
return tabs.find(tab => canAttach(tab.url)) ?? null;
}
/** Gallery folders shown as their last path segment (Windows or POSIX separators). */
export function folderLabel(folder: string): string {
const parts = folder.split(/[\\/]+/).filter(Boolean);
return parts[parts.length - 1] ?? folder;
}
export function clampClipMax(value: number): number {
if (!Number.isFinite(value)) return 30;
return Math.min(CLIP_MAX_LIMIT, Math.max(1, Math.round(value)));
}
/** Removing a folder is the only folder change the shell can make; adding goes through the native dialog. */
export function withoutFolder(settings: MediaSettings, folder: string): MediaSettings {
return { ...settings, folders: settings.folders.filter(f => f !== folder) };
}
export function clipPreview(item: ClipItem, max = 80): string {
if (item.kind === 'image') return t('wb.media.image');
const flat = (item.text ?? '').replace(/\s+/g, ' ').trim();
return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
}
export function relativeTime(ms: number, now = Date.now()): string {
const seconds = Math.max(0, Math.round((now - ms) / 1000));
if (seconds < 60) return t('wb.media.now');
// Compact units in the active language ("5m", "5 dk", "5分").
const unit = (value: number, name: 'minute' | 'hour' | 'day') => formatNumber(value, { style: 'unit', unit: name, unitDisplay: 'narrow' });
const minutes = Math.round(seconds / 60);
if (minutes < 60) return unit(minutes, 'minute');
const hours = Math.round(minutes / 60);
if (hours < 24) return unit(hours, 'hour');
return unit(Math.round(hours / 24), 'day');
}

View file

@ -0,0 +1,162 @@
// Pure model for the command palette (no Tauri/DOM imports, so it is unit-tested under node).
// Every item is navigation only: tabs are focused, profiles open a tab, decks and workspaces open,
// the app's panel opens at a section, plugin commands run in their tab; the site adds its own
// pages and completions (`site.palette`). Nothing here performs an account action on the user's behalf.
import { rankItems } from '../palette.ts';
import { t } from './i18n.ts';
import type { IconName } from './icons.tsx';
import type { PaletteSite } from './site.ts';
export { fuzzyScore, moveSelection } from '../palette.ts';
export type PaletteAction =
| { type: 'focus-tab'; id: string }
| { type: 'new-tab'; profile: string }
| { type: 'panel'; section: string }
| { type: 'open'; url: string }
| { type: 'media' }
/** Decks (navigation only): open a deck, make a new one, add or focus a column. */
| { type: 'deck'; deckId?: string }
| { type: 'deck-new' }
| { type: 'deck-add'; deckId: string }
| { type: 'deck-focus'; deckId: string; columnId: string }
/** Replaces the palette query (a completion); never navigates. */
| { type: 'complete'; text: string }
/** A plugin's command: the shell asks tab `tab` to run it in its page (`tab_run_command`). */
| { type: 'plugin-command'; tab: string; command: string }
/** Workspaces: restore one, or save the current layout under a name. */
| { type: 'workspace'; id: string }
| { type: 'workspace-save' };
/** The frame's groups; the app's items are grouped under its product name, plugin commands under the plugin's. */
export type PaletteGroup = 'Tabs' | 'Deck' | 'Workspaces' | 'Profiles';
export type PaletteItem = {
id: string;
/** A fixed group, the site's group, or a plugin's name for its commands. */
group: PaletteGroup | (string & {});
label: string;
hint?: string;
keywords?: string;
/** The row's glyph (tabs show their favicon, profiles their avatar). */
icon?: IconName;
action: PaletteAction;
};
export type PaletteContext = {
/** `favicon` and `color` only decorate the list; matching ignores them. */
tabs: Array<{ id: string; title: string; url: string; favicon?: string }>;
profiles: Array<{ id: string; name: string; color?: string }>;
activeProfile: string;
/** Decks and their columns (titles only); absent when the app has no decks. */
decks?: Array<{ id: string; name: string; columns: Array<{ id: string; title: string; profile: string }> }>;
/** The deck tab in front, if any. */
activeDeck?: string;
/** Saved workspaces (names only) and the one opened last. */
workspaces?: Array<{ id: string; name: string; tabs: number; isDefault?: boolean }>;
activeWorkspace?: string;
/** Plugin commands of the focused site tab, already named by plugin (`pluginCommandItems`). */
commands?: { tab: string; items: PluginCommandItem[] };
};
/** What the palette knows about the app: its site items, its name and which frame features it has. */
export type PaletteSetup = { site: PaletteSite; product: string; decks: boolean; media: boolean; workspaces?: boolean };
/** A plugin command as the palette lists it: the tab's report plus the plugin's display name. */
export type PluginCommandItem = { id: string; title: string; keywords: string; plugin: string };
/** Commands at most listed from one tab (the runtime and native code cap them too). */
export const MAX_PLUGIN_COMMANDS = 48;
/**
* Names each reported command (`<file>:<id>`) after its plugin (`@name` from the Plugins list);
* commands registered outside a plugin's start are listed under "Plugins". Bounded.
*/
export function pluginCommandItems(reported: ReadonlyArray<{ id: string; title: string; keywords?: string }>, pluginNames: Readonly<Record<string, string>>): PluginCommandItem[] {
const out: PluginCommandItem[] = [];
for (const command of reported) {
if (out.length >= MAX_PLUGIN_COMMANDS) break;
if (typeof command?.id !== 'string' || typeof command.title !== 'string') continue;
const at = command.id.indexOf(':');
if (at <= 0) continue;
const owner = command.id.slice(0, at);
const plugin = (owner !== '_' && pluginNames[owner]) || (owner === '_' ? t('wb.palette.plugins') : owner.replace(/\.plugin\.js$/, ''));
out.push({ id: command.id, title: command.title.slice(0, 80), keywords: (command.keywords ?? '').slice(0, 160), plugin });
}
return out;
}
/** The "Workspaces" group: switch to a saved workspace, save the current layout. */
function workspaceItems(context: PaletteContext): PaletteItem[] {
const items: PaletteItem[] = [];
for (const workspace of context.workspaces ?? []) {
items.push({
id: `ws:${workspace.id}`, group: 'Workspaces', label: t('wb.palette.switchTo', { name: workspace.name }),
hint: workspace.id === context.activeWorkspace ? t('wb.palette.active') : `${t('wb.ws.tabs', { count: workspace.tabs })}${workspace.isDefault ? ` · ${t('wb.palette.onStart')}` : ''}`,
keywords: 'workspace layout restore session switch', action: { type: 'workspace', id: workspace.id },
});
}
items.push({ id: 'ws-save', group: 'Workspaces', label: t('wb.ws.save'), keywords: 'workspace layout save session tabs panes', action: { type: 'workspace-save' } });
return items;
}
/** The "Deck" group: open/switch decks, add a column, focus a column of the active deck. */
function deckItems(context: PaletteContext): PaletteItem[] {
const decks = context.decks ?? [];
const items: PaletteItem[] = [];
const active = decks.find(deck => deck.id === context.activeDeck);
if (!decks.length) {
items.push({ id: 'deck:open', group: 'Deck', label: t('wb.palette.openPower'), hint: 'Ctrl+Shift+D', keywords: 'deck tweetdeck columns power user', action: { type: 'deck' } });
return items;
}
for (const deck of decks) {
if (deck.id === active?.id) continue;
items.push({ id: `deck:${deck.id}`, group: 'Deck', label: t('wb.palette.switchTo', { name: deck.name }), hint: t('wb.deck.columnCount', { count: deck.columns.length }), keywords: 'deck tweetdeck columns power user switch', action: { type: 'deck', deckId: deck.id } });
}
const target = active ?? decks[0]!;
items.push({ id: `deck-add:${target.id}`, group: 'Deck', label: t('wb.palette.addColumn'), hint: target.name, keywords: 'deck column new tweetdeck', action: { type: 'deck-add', deckId: target.id } });
if (active) {
active.columns.forEach((column, index) => {
items.push({ id: `deck-focus:${column.id}`, group: 'Deck', label: t('wb.palette.focusColumn', { name: column.title }), hint: index < 9 ? `Alt+${index + 1}` : undefined, keywords: 'column deck', action: { type: 'deck-focus', deckId: active.id, columnId: column.id } });
});
}
items.push({ id: 'deck-new', group: 'Deck', label: t('wb.palette.newDeck'), keywords: 'deck columns power user create', action: { type: 'deck-new' } });
return items;
}
export function buildItems(context: PaletteContext, query: string, setup: PaletteSetup): PaletteItem[] {
const { site } = setup;
const items: PaletteItem[] = [];
const text = query.trim();
const search = text ? site.search?.(text) ?? null : null;
if (search) items.push(search);
for (const tab of context.tabs) {
items.push({ id: `tab:${tab.id}`, group: 'Tabs', label: tab.title || tab.url, hint: tab.url, keywords: tab.url, action: { type: 'focus-tab', id: tab.id } });
}
if (setup.decks) items.push(...deckItems(context));
if (setup.workspaces !== false) items.push(...workspaceItems(context));
for (const profile of context.profiles) {
items.push({ id: `profile:${profile.id}`, group: 'Profiles', label: t('wb.palette.newTabAs', { name: profile.name }), hint: profile.id === context.activeProfile ? t('wb.palette.active') : undefined, keywords: 'account switch', action: { type: 'new-tab', profile: profile.id } });
}
for (const section of site.sections) {
items.push({ id: `panel:${section.id}`, group: setup.product, label: section.label(), keywords: section.keywords, icon: section.icon, action: { type: 'panel', section: section.id } });
}
if (setup.media) items.push({ id: 'media', group: setup.product, label: t('wb.palette.media'), hint: 'Ctrl+Shift+G', keywords: 'photos images screenshots attach paste media', icon: 'image', action: { type: 'media' } });
// Plugin commands, grouped under each plugin's name; they run in the focused site tab.
if (context.commands) {
const { tab } = context.commands;
// One heading per plugin: stable sort keeps each plugin's own order.
const sorted = context.commands.items.slice(0, MAX_PLUGIN_COMMANDS).sort((a, b) => a.plugin.localeCompare(b.plugin));
for (const command of sorted) {
items.push({ id: `cmd:${command.id}`, group: command.plugin, label: command.title, keywords: `${command.plugin} plugin ${command.keywords}`, icon: 'bolt', action: { type: 'plugin-command', tab, command: command.id } });
}
}
items.push(...site.items?.() ?? []);
if (!text) return items;
const completions = site.completions?.(query.replace(/^\s+/, '')) ?? [];
const scored = rankItems(items, text, item => item === search);
// The literal search stays available as the last resort.
return search ? [...completions, ...scored, search] : [...completions, ...scored];
}

View file

@ -0,0 +1,9 @@
/* Theme swatches (page, text, accent) and the "Theme for this pane" menu. */
.wb-dots { display: inline-flex; align-items: center; gap: 3px; flex: none; height: 18px; padding: 0 5px; border-radius: 6px; box-shadow: inset 0 0 0 1px rgb(127 127 127 / .28); }
.wb-dots i { width: 7px; height: 7px; border-radius: 50%; }
.wb-pane-menu { width: 272px; }
.wb-pane-menu-head { display: flex; align-items: center; gap: 8px; padding: 7px 10px 6px; color: var(--bt-muted); font: 600 11px/1 var(--bt-ui); letter-spacing: .04em; text-transform: uppercase; }
.wb-pane-menu-head .bt-glyph { width: 14px; height: 14px; }
.wb-pane-menu-list { display: flex; flex-direction: column; gap: 1px; max-height: 300px; overflow-y: auto; scrollbar-width: thin; }
.wb-pane-menu small { color: var(--bt-muted); font-weight: 450; }
.wb-pane-menu button > .bt-glyph:last-child { margin-inline-start: auto; color: var(--bt-accent); }

View file

@ -0,0 +1,61 @@
// Plugin palette commands as the shell knows them: what each site tab last reported (native
// `tab-commands` event, validated natively: waybetter-host `plugins::commands`) and the plugins'
// display names (`plugins_list`). The palette lists the commands of the focused site tab and runs
// one there (`tab_run_command`).
import { invoke, listen } from './bridge.ts';
import { pluginCommandItems, type PluginCommandItem } from './paletteModel.ts';
import { isWeb, shell } from './state.ts';
type Reported = { id: string; title: string; keywords: string };
const byTab = new Map<string, Reported[]>();
let names: Record<string, string> = {};
/** The last web tab that was active (the palette may be opened from the app's panel). */
let lastWebTab: string | null = null;
export function installPluginCommands(): () => void {
const off = listen<{ id: string; commands: Reported[] }>('tab-commands', ({ payload }) => {
if (!payload || typeof payload.id !== 'string') return;
if (Array.isArray(payload.commands) && payload.commands.length) byTab.set(payload.id, payload.commands);
else byTab.delete(payload.id);
});
void refreshPluginNames();
return () => { void off.then(dispose => dispose(), () => {}); };
}
/** Called when the active tab changes. */
export function notePanelActive(id: string | undefined) {
const panel = id ? shell.api?.getPanel(id) : undefined;
if (panel && isWeb(panel)) lastWebTab = panel.id;
}
export async function refreshPluginNames(): Promise<void> {
try {
const list = await invoke<Array<{ file: string; name: string }>>('plugins_list');
names = Object.fromEntries(list.map(plugin => [plugin.file, plugin.name]));
} catch { /* browser preview: no plugins */ }
}
/** The focused site tab's commands for the palette, or undefined when it has none. */
export function focusedCommands(): { tab: string; items: PluginCommandItem[] } | undefined {
const api = shell.api;
const active = api?.activePanel;
const tab = active && isWeb(active) ? active.id : lastWebTab && api?.getPanel(lastWebTab) ? lastWebTab : null;
if (!tab) return undefined;
const reported = byTab.get(tab);
if (!reported?.length) return undefined;
return { tab, items: pluginCommandItems(reported, names) };
}
export function runPluginCommand(tab: string, command: string) {
const panel = shell.api?.getPanel(tab);
panel?.api.setActive();
invoke('tab_run_command', { id: tab, command }).catch(error => console.warn('[shell] plugin command', error));
}
/** Tests and the preview harness. */
export function setReportedCommands(tab: string, commands: Reported[], pluginNames?: Record<string, string>) {
byTab.set(tab, commands);
if (pluginNames) names = { ...names, ...pluginNames };
}

View file

@ -0,0 +1,9 @@
// Address-bar / palette text → URL. Pure, so it is unit-tested under node.
/** Full URLs as-is, bare domains over https, anything else searches the site (`search`). */
export function toUrl(input: string, search: (text: string) => string): string {
const text = input.trim();
if (/^https?:\/\//i.test(text)) return text;
if (/^(localhost|[\w-]+(\.[\w-]+)+)(:\d+)?([/?#].*)?$/i.test(text)) return `https://${text}`;
return search(text);
}

View file

@ -0,0 +1,625 @@
/*
* Shell chrome, Night Ink. Custom 44px titlebar hosting pill tabs, 48px toolbar with the structured
* address bar, shell-drawn overlays (menus, palette, pickers, new-tab page).
*
* Scale: space 4/8/12/16/24/32 · radius 6/8/10/12/14 · type 11/12/13/14/16 (Geist, Geist Mono for
* addresses, keys and counts) · motion 120/180/320ms, disabled under prefers-reduced-motion.
*/
/* Colors and fonts follow the active theme (`--wb-c-*` / `--wb-f-*`, set by frame/themeStore.ts on
<html>, and on a pane's dock group when that pane shows another theme); the literals are
wayBetter's own Night Ink, used when a theme keeps the site's colors and when "Keep wayBetter's
own style" is on. An app without themes gets Night Ink. */
:root, .wb-pane-theme {
--bt-ground: var(--wb-c-ground, #07080c); --bt-chrome: var(--wb-c-chrome, #0d1017); --bt-field: var(--wb-c-field, #11141c); --bt-raised: var(--wb-c-raised, #141823); --bt-raised-2: var(--wb-c-raised-2, #191e2b);
--bt-line: var(--wb-c-line, #1e2333); --bt-line-soft: var(--wb-c-line-soft, #161a26); --bt-line-strong: var(--wb-c-line-strong, #2a3044);
--bt-text: var(--wb-c-text, #eef0f7); --bt-text-2: var(--wb-c-text-2, #c3c7d4); --bt-muted: var(--wb-c-muted, #8a90a6); --bt-faint: var(--wb-c-faint, #5d6379);
/* Space-separated channels for translucent tints: rgb(var(--bt-text-rgb) / .06). */
--bt-text-rgb: var(--wb-c-text-rgb, 238 240 247); --bt-accent-rgb: var(--wb-c-accent-rgb, 29 155 240);
--bt-accent: var(--wb-c-accent, #1d9bf0); --bt-accent-ink: var(--wb-c-accent-ink, #cfe6ff); --bt-accent-soft: rgb(var(--bt-accent-rgb) / .14);
--bt-hover: rgb(var(--bt-text-rgb) / .055); --bt-press: rgb(var(--bt-text-rgb) / .09);
--bt-ring: 0 0 0 1px rgb(var(--bt-accent-rgb) / .55), 0 0 0 4px rgb(var(--bt-accent-rgb) / .16);
--bt-shadow-pop: var(--wb-c-shadow-pop, 0 18px 44px -14px rgba(0, 0, 0, .75), 0 3px 10px rgba(0, 0, 0, .35), inset 0 1px 0 rgba(255, 255, 255, .035));
--bt-ui: var(--wb-f-chrome, 'Geist Variable', system-ui, sans-serif); --bt-mono: var(--wb-f-mono, 'Geist Mono Variable', ui-monospace, monospace);
color-scheme: var(--wb-c-scheme, dark);
}
.wb-pane-theme { --bt-bg: var(--bt-ground); --bt-surface: var(--bt-chrome); --bt-surface-2: var(--bt-field); }
:root {
--bt-danger: #e5484d;
--bt-brush: linear-gradient(90deg, #4f6bff, #22d3ee 55%, #a855f7);
--bt-s1: 4px; --bt-s2: 8px; --bt-s3: 12px; --bt-s4: 16px; --bt-s5: 24px; --bt-s6: 32px;
--bt-r1: 6px; --bt-r2: 8px; --bt-r3: 10px; --bt-r4: 12px; --bt-r5: 14px;
--bt-ease: cubic-bezier(.2, .7, .2, 1); --bt-ease-out: cubic-bezier(.16, 1, .3, 1);
--bt-t1: 120ms; --bt-t2: 180ms; --bt-t3: 320ms;
--bt-titlebar-h: 44px; --bt-toolbar-h: 48px; --bt-resize-border: 5px;
/* Room the titlebar-hosted tab strip leaves for the logo (left) and caption buttons + drag spacer + account switcher (right). */
--bt-tb-left: 50px; --bt-tb-right: calc(138px + 48px + 184px + var(--bt-tb-extra, 0px));
}
html[data-os=macos] { --bt-tb-left: calc(78px + 50px); --bt-tb-right: calc(48px + 184px + var(--bt-tb-extra, 0px)); }
html, body, #root { height: 100%; margin: 0; overflow: hidden; background: var(--bt-ground); color: var(--bt-text); font: 400 13px/1.3 var(--bt-ui); -webkit-font-smoothing: antialiased; }
.bt-shell {
/* Legacy names used by the tab strip and menus. */
--bt-bg: var(--bt-ground);
--bt-surface: var(--bt-chrome);
--bt-surface-2: var(--bt-field);
position: relative;
height: 100vh;
overflow: hidden;
color: var(--bt-text);
background: var(--bt-ground);
font: 400 13px/1.3 var(--bt-ui);
user-select: none;
}
/* Base glyph style; zero specificity so every component can size its own icons. */
:where(.bt-shell svg:not(.dv-svg), .bt-glyph) { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; }
:where(.bt-shell, .bt-menu, .bt-palette, .bt-media) button { font-family: var(--bt-ui); }
:where(.bt-shell, .bt-menu, .bt-palette, .bt-media) :focus-visible { outline: 2px solid rgb(var(--bt-accent-rgb) / .8); outline-offset: 1px; }
:where(.bt-palette-list, .bt-profile-menu, .bt-start, .bt-media-body, .dv-tabs-overflow-container) { scrollbar-width: thin; scrollbar-color: var(--bt-line-strong) transparent; }
.bt-kbd { display: inline-grid; place-items: center; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box; border-radius: 5px; background: rgb(var(--bt-text-rgb) / .06); box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .07), inset 0 -1px 0 rgb(var(--bt-text-rgb) / .05); color: var(--bt-text-2); font: 500 10.5px/1 var(--bt-mono); }
.bt-kbd + .bt-kbd { margin-inline-start: 3px; }
.bt-avatar--image { overflow: hidden; position: relative; }
.bt-avatar--image img { width: 100%; height: 100%; object-fit: cover; display: block; border-radius: 50%; }
.bt-avatar--image::after { content: ""; position: absolute; inset: 0; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .14); }
.bt-profile-signin { margin-inline-start: auto; font: 600 12px/1 var(--bt-ui); color: var(--bt-accent); background: rgb(var(--bt-accent-rgb) / .12); border: 0; border-radius: 999px; padding: 6px 10px; cursor: pointer; }
.bt-profile-signin:hover { background: rgb(var(--bt-accent-rgb) / .2); }
.bt-avatar { display: inline-grid; place-items: center; flex: none; border-radius: 50%; font-family: var(--bt-ui); font-weight: 650; line-height: 1; letter-spacing: 0; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .16), inset 0 -6px 10px -6px rgba(0, 0, 0, .25); user-select: none; }
/* motion */
@keyframes bt-pop-in { from { opacity: 0; transform: translateY(-4px) scale(.98); } }
@keyframes bt-fade-in { from { opacity: 0; } }
@keyframes bt-rise { from { opacity: 0; transform: translateY(6px); } }
@keyframes bt-slide-in { from { transform: translateX(24px); opacity: 0; } }
@keyframes bt-slide-in-rtl { from { transform: translateX(-24px); opacity: 0; } }
@keyframes bt-spin { to { transform: rotate(360deg); } }
.bt-pop { animation: bt-pop-in var(--bt-t2) var(--bt-ease-out); transform-origin: top left; }
.bt-pop--right { transform-origin: top right; }
.bt-rise { animation: bt-rise var(--bt-t3) var(--bt-ease-out) both; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 1ms !important; animation-iteration-count: 1 !important; animation-delay: 0ms !important; transition-duration: 1ms !important; }
}
/* ------------------------------------------------------------------------------------------------
* Titlebar: under the dock; the top groups' headers are transparent above it. */
.bt-titlebar { position: absolute; top: 0; left: 0; right: 0; z-index: 0; height: var(--bt-titlebar-h); display: flex; align-items: stretch; background: var(--bt-ground); }
.bt-titlebar-drag { position: absolute; inset: 0; z-index: 0; }
.bt-titlebar > *:not(.bt-titlebar-drag) { position: relative; z-index: 1; }
/* The top tab strips live in the dock (z 1), whose group views span the titlebar row and swallowed
clicks on the account switcher and caption buttons. The titlebar sits above the dock and takes
pointer events only on its own controls; everything else falls through to the tabs and their
drag region. With no tabs the titlebar itself is the drag region again. */
.bt-titlebar { z-index: 2; pointer-events: none; }
.bt-titlebar > :not(.bt-titlebar-drag):not(.bt-titlebar-spacer):not(.bt-titlebar-logo) { pointer-events: auto; }
.bt-shell--empty .bt-titlebar > * { pointer-events: auto; }
/* Above the dock, so it must not paint: the tab strips hosted in the titlebar row show through it. */
.bt-shell:not(.bt-shell--empty) .bt-titlebar { background: transparent; }
html[data-os=macos] .bt-titlebar { padding-left: 78px; } /* rtl-ok: traffic lights; the titlebar stays LTR */
.bt-titlebar-logo { width: 20px; height: 20px; margin: 12px 14px 12px 16px; flex: 0 0 20px; -webkit-user-drag: none; }
.bt-titlebar-spacer { flex: 1; min-width: 48px; }
.bt-captions { display: flex; }
.bt-caption { width: 46px; height: 44px; display: grid; place-items: center; padding: 0; background: transparent; border: 0; color: var(--bt-text-2); cursor: default; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-caption:hover { background: var(--bt-hover); color: var(--bt-text); }
.bt-caption:active { background: rgb(var(--bt-text-rgb) / .035); }
.bt-caption--close:hover { background: #c42b1c; color: #fff; }
.bt-caption--close:active { background: #b22a1b; }
.bt-shell .bt-caption svg { width: 10px; height: 10px; stroke: currentColor; fill: none; stroke-width: 1; stroke-linecap: butt; stroke-linejoin: miter; }
.bt-grip { position: fixed; z-index: 50; }
/* Update chip: a quiet brush-edged pill left of the account switcher, only while an update is actionable. */
html[data-update] { --bt-tb-right: calc(138px + 48px + 184px + 184px + var(--bt-tb-extra, 0px)); }
html[data-os=macos][data-update] { --bt-tb-right: calc(48px + 184px + 184px + var(--bt-tb-extra, 0px)); }
.bt-update-chip {
align-self: center; display: inline-flex; align-items: center; gap: 8px; height: 28px; margin-right: 8px; padding: 0 12px 0 10px; /* rtl-ok: titlebar */
border: 1px solid transparent; border-radius: 14px; color: var(--bt-text); font: 500 12px/1 var(--bt-ui); white-space: nowrap; cursor: pointer;
background: linear-gradient(var(--bt-field), var(--bt-field)) padding-box, var(--bt-brush) border-box;
transition: background var(--bt-t1) var(--bt-ease);
}
.bt-update-chip:hover { background: linear-gradient(var(--bt-raised-2), var(--bt-raised-2)) padding-box, var(--bt-brush) border-box; }
.bt-update-chip:disabled { cursor: default; color: var(--bt-muted); }
.bt-update-chip-dot { position: relative; width: 7px; height: 7px; border-radius: 50%; background: #22d3ee; }
.bt-update-chip-dot::after { content: ''; position: absolute; inset: 0; border-radius: 50%; background: inherit; animation: bt-ping 2.4s var(--bt-ease-out) infinite; }
@keyframes bt-ping { 0% { transform: scale(1); opacity: .6; } 70%, 100% { transform: scale(2.8); opacity: 0; } }
.bt-update-chip--installing .bt-update-chip-dot { background: var(--bt-muted); }
.bt-update-chip--problem { background: rgba(245, 158, 11, .08); border-color: rgba(245, 158, 11, .32); color: #fbbf24; }
.bt-update-chip--problem:hover { background: rgba(245, 158, 11, .14); }
/* Account switcher (titlebar). Width is reserved in --bt-tb-right. */
.bt-profile-switcher {
align-self: center; display: inline-flex; align-items: center; gap: 8px; max-width: 176px; height: 30px; margin-right: 8px; padding: 0 9px 0 4px; box-sizing: border-box; /* rtl-ok: titlebar */
border: 1px solid var(--bt-line-soft); border-radius: 15px; background: rgb(var(--bt-text-rgb) / .035); color: var(--bt-text); font: 500 12.5px/1 var(--bt-ui); cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease);
}
.bt-profile-switcher:hover { background: var(--bt-hover); border-color: var(--bt-line-strong); }
.bt-profile-switcher[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); }
.bt-profile-switcher-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-shell .bt-profile-switcher-chevron { width: 13px; height: 13px; color: var(--bt-muted); transition: transform var(--bt-t2) var(--bt-ease); }
.bt-profile-switcher[aria-expanded=true] .bt-profile-switcher-chevron { transform: rotate(180deg); }
.bt-profile-dot { width: 8px; height: 8px; flex: 0 0 8px; border-radius: 50%; box-shadow: 0 0 0 1.5px var(--bt-ground); }
/* ------------------------------------------------------------------------------------------------
* Dock: over the titlebar; inset by the resize band while the frameless window is restored. */
/* DockviewReact puts width/height:100% inline on its root; the insets below size the dock
(restored: inside the resize border; empty: under the titlebar) or it overflowed them. */
.bt-dock { position: absolute; inset: 0; z-index: 1; width: auto !important; height: auto !important; }
.bt-shell[data-chrome=restored] .bt-dock { left: var(--bt-resize-border); right: var(--bt-resize-border); bottom: var(--bt-resize-border); }
.bt-shell--empty .bt-dock { top: var(--bt-titlebar-h); }
.bt-shell .dockview-theme-dark, .bt-dock.dockview-theme-dark, .bt-dock .wb-pane-theme {
--dv-background-color: transparent;
--dv-group-view-background-color: transparent;
--dv-tabs-and-actions-container-background-color: var(--bt-ground);
--dv-tabs-and-actions-container-height: 40px;
--dv-tabs-and-actions-container-font-size: 13px;
--dv-activegroup-visiblepanel-tab-background-color: var(--bt-raised);
--dv-activegroup-hiddenpanel-tab-background-color: transparent;
--dv-inactivegroup-visiblepanel-tab-background-color: var(--bt-raised);
--dv-inactivegroup-hiddenpanel-tab-background-color: transparent;
--dv-activegroup-visiblepanel-tab-color: var(--bt-text);
--dv-activegroup-hiddenpanel-tab-color: var(--bt-muted);
--dv-inactivegroup-visiblepanel-tab-color: var(--bt-text-2);
--dv-inactivegroup-hiddenpanel-tab-color: var(--bt-muted);
--dv-tab-divider-color: transparent;
--dv-separator-border: var(--bt-line-soft);
--dv-paneview-header-border-color: var(--bt-line-soft);
--dv-drag-over-background-color: rgb(var(--bt-accent-rgb) / 0.14);
--dv-drag-over-border-color: var(--bt-accent);
--dv-sash-color: transparent;
--dv-active-sash-color: rgb(var(--bt-accent-rgb) / .7);
--dv-icon-hover-background-color: var(--bt-field);
--dv-scrollbar-background-color: rgb(var(--bt-text-rgb) / .14);
}
.bt-shell .dv-groupview > .dv-content-container { background: var(--bt-ground); }
.bt-shell .dv-tabs-and-actions-container { border-bottom: 1px solid var(--bt-line-soft); padding-left: 6px; } /* rtl-ok: tab strips stay LTR */
/* The + (and the "N more" overflow button) follow the last tab; the rest of the strip stays empty/draggable. */
.bt-shell .dv-tabs-and-actions-container > .dv-right-actions-container { order: 2; }
.bt-shell .dv-tabs-and-actions-container > .dv-void-container { order: 3; flex: 1 1 0; }
.bt-shell .dv-split-view-container > .dv-sash-container > .dv-sash { background: transparent; }
/* titlebar-hosted tab strips (groups whose top edge is the window top) */
.bt-shell .bt-group--in-titlebar { --dv-tabs-and-actions-container-height: var(--bt-titlebar-h); }
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container { background: transparent; border-bottom: 0; pointer-events: none; }
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container .dv-tabs-container { pointer-events: none; }
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container .dv-tab,
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container .dv-void-container,
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container .bt-group-actions,
.bt-shell .bt-group--in-titlebar > .dv-tabs-and-actions-container .dv-tabs-overflow-dropdown-root { pointer-events: auto; }
.bt-shell .bt-group--tb-left > .dv-tabs-and-actions-container { padding-left: var(--bt-tb-left); } /* rtl-ok: window frame */
.bt-shell .bt-group--tb-right > .dv-tabs-and-actions-container { padding-right: var(--bt-tb-right); } /* rtl-ok: window frame */
/* ------------------------------------------------------------------------------------------------
* Tabs: floating pills. They shrink to 52px (favicon only), then the strip scrolls and dockview adds its "N more" list. */
.bt-shell .dv-tabs-container .dv-tab {
--bt-tab-bg: var(--bt-ground); --bt-tab-fg: var(--bt-muted);
height: 30px; margin: 5px 2px 0 0; padding: 0; border-radius: 9px; box-sizing: border-box;
width: 224px; min-width: 52px; flex: 0 1 auto;
/* Dockview colors tabs with higher-specificity rules; the pill states below only set these two variables. */
color: var(--bt-tab-fg) !important; background-color: var(--bt-tab-bg) !important; box-shadow: none;
transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease);
}
.bt-shell .bt-group--in-titlebar .dv-tabs-container .dv-tab { height: 32px; margin-top: 6px; }
.bt-shell .dv-tabs-container .dv-tab.dv-inactive-tab:hover { --bt-tab-bg: var(--bt-field); --bt-tab-fg: var(--bt-text-2); }
.bt-shell .dv-tabs-container .dv-tab.dv-active-tab {
--bt-tab-bg: var(--bt-raised); --bt-tab-fg: var(--bt-text);
box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .06), inset 0 1px 0 rgb(var(--bt-text-rgb) / .05), 0 1px 2px rgba(0, 0, 0, .5);
}
/* The brush marks the focused pane's tab; other panes keep a plain raised pill. */
.bt-shell .dv-tabs-container .dv-tab.dv-active-tab::after {
content: ''; position: absolute; left: 12px; right: 12px; bottom: 0; height: 2px; border-radius: 2px 2px 0 0;
background: var(--bt-brush); opacity: .95; pointer-events: none;
}
.bt-shell .dv-groupview.dv-inactive-group .dv-tabs-container .dv-tab.dv-active-tab { --bt-tab-bg: var(--bt-field); --bt-tab-fg: var(--bt-text-2); }
.bt-shell .dv-groupview.dv-inactive-group .dv-tabs-container .dv-tab.dv-active-tab::after { opacity: 0; }
.bt-shell .dv-tabs-container .dv-tab:focus-visible { box-shadow: inset 0 0 0 2px rgb(var(--bt-accent-rgb) / .7); }
.bt-shell .dv-tabs-container .dv-tab.dv-tab-dragging { --bt-tab-bg: var(--bt-raised-2); --bt-tab-fg: var(--bt-text); }
/* A hairline between the pinned tabs and the rest. */
.bt-shell .dv-tabs-container .dv-tab:has(.bt-tab--pinned) + .dv-tab:not(:has(.bt-tab--pinned)) { margin-left: 7px; } /* rtl-ok: tab strips stay LTR */
.bt-shell .dv-tabs-container .dv-tab:has(.bt-tab--pinned) + .dv-tab:not(:has(.bt-tab--pinned))::before {
content: ''; position: absolute; left: -6px; top: 9px; bottom: 9px; width: 1px; height: auto; background: var(--bt-line-strong); pointer-events: none;
}
.bt-shell .dv-tabs-container .dv-tab:has(.bt-tab--pinned) { width: 36px; min-width: 36px; flex: 0 0 36px; }
.bt-shell .dv-tabs-container .dv-tab:has(.bt-tab--pinned)::after { left: 10px; right: 10px; }
.bt-tab { container-type: inline-size; height: 100%; width: 100%; box-sizing: border-box; display: flex; align-items: center; gap: 8px; padding-block: 0; padding-inline: 10px 5px; min-width: 0; user-select: none; font: 500 12.5px/1 var(--bt-ui); letter-spacing: .005em; }
.bt-tab--pinned { justify-content: center; padding: 0; }
.bt-tab-icon { position: relative; display: grid; place-items: center; width: 16px; height: 16px; flex: 0 0 16px; }
.bt-favicon { width: 16px !important; height: 16px !important; flex: 0 0 16px; border-radius: 4px; color: var(--bt-muted); }
.bt-favicon--img { animation: bt-fade-in var(--bt-t2) var(--bt-ease); }
.bt-shell .bt-favicon--glyph { width: 15px !important; height: 15px !important; }
.bt-tab-account { position: absolute; inset-inline-end: -3px; bottom: -3px; width: 7px; height: 7px; border-radius: 50%; box-shadow: 0 0 0 2px var(--bt-tab-bg, var(--bt-raised)); transition: box-shadow var(--bt-t1) var(--bt-ease); }
.bt-tab-title { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; line-height: 16px; -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 18px), transparent); mask-image: linear-gradient(90deg, #000 calc(100% - 18px), transparent); }
.bt-tab--loading .bt-tab-title { color: var(--bt-text-2); }
.bt-tab-close { flex: 0 0 20px; width: 20px; height: 20px; display: grid; place-items: center; padding: 0; border: 0; border-radius: 6px; background: transparent; color: var(--bt-muted); cursor: pointer; opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease), background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-shell .bt-tab-close svg { width: 13px; height: 13px; stroke-width: 2; }
.dv-tab:hover .bt-tab-close, .dv-active-tab .bt-tab-close, .bt-tab-close:focus-visible { opacity: 1; }
.dv-inactive-tab .bt-tab-close { color: var(--bt-faint); }
.bt-tab-close:hover { background: var(--bt-press); color: var(--bt-text) !important; }
.bt-tab-close:active { background: rgb(var(--bt-text-rgb) / .13); }
/* Shrinking tabs: first the close button leaves inactive tabs (it returns on hover), then titles give way to the favicon. */
@container (max-width: 124px) {
.bt-tab { gap: 7px; padding-inline-start: 9px; }
.dv-inactive-tab .bt-tab-close { display: none; }
.dv-inactive-tab:hover .bt-tab-close { display: grid; }
}
@container (max-width: 76px) {
.bt-tab { justify-content: center; gap: 4px; padding: 0 4px; }
.bt-tab-title { display: none; }
.dv-inactive-tab .bt-tab-close, .dv-inactive-tab:hover .bt-tab-close { display: none; }
}
.bt-spinner { display: inline-block; width: 14px; height: 14px; border-radius: 50%; border: 1.75px solid rgb(var(--bt-text-rgb) / .12); border-top-color: var(--bt-accent); border-inline-end-color: #22d3ee; animation: bt-spin .75s linear infinite; box-sizing: border-box; }
.bt-favicon.bt-spinner { width: 14px !important; height: 14px !important; flex-basis: 14px; border-radius: 50%; }
@media (prefers-reduced-motion: reduce) { .bt-spinner { animation: none; border-color: rgb(var(--bt-accent-rgb) / .35); border-top-color: var(--bt-accent); } }
.bt-group-actions { height: 100%; display: flex; align-items: center; padding: 0 4px 0 2px; }
.bt-group--in-titlebar .bt-group-actions { padding-top: 0; }
.bt-group-actions .bt-icon { width: 28px; height: 28px; flex-basis: 28px; border-radius: 8px; }
.bt-group--in-titlebar .bt-group-actions .bt-icon { margin-top: 0; }
.bt-shell .bt-newtab svg { width: 15px; height: 15px; }
/* Dockview's overflow button ("N more tabs") and its list; an overflowing strip fades out instead of cutting a tab. */
.bt-shell .dv-tabs-and-actions-container:has(.dv-tabs-overflow-dropdown-root) > .dv-scrollable {
-webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent); mask-image: linear-gradient(90deg, #000 calc(100% - 28px), transparent);
}
.bt-shell .dv-tabs-overflow-dropdown-root { display: flex; align-items: center; height: 100%; }
.bt-shell .dv-tabs-overflow-dropdown-default {
height: 26px; margin: 0 2px 0 4px; padding: 0 8px 0 6px; gap: 2px; box-sizing: border-box; border-radius: 8px;
background: rgb(var(--bt-text-rgb) / .04); box-shadow: inset 0 0 0 1px var(--bt-line); color: var(--bt-text-2);
font: 500 11.5px/1 var(--bt-mono); font-variant-numeric: tabular-nums; transition: background-color var(--bt-t1) var(--bt-ease);
}
.bt-shell .dv-tabs-overflow-dropdown-default:hover { background: var(--bt-hover); color: var(--bt-text); }
.bt-shell .dv-tabs-overflow-dropdown-default > span { padding-left: 2px; } /* rtl-ok: tab strips stay LTR */
.bt-shell .dv-tabs-overflow-dropdown-default > span::before { content: '+'; }
.bt-shell .dv-tabs-overflow-dropdown-default .dv-svg { width: 9px; height: 9px; transform: rotate(90deg); opacity: .8; }
.bt-shell .dv-tabs-overflow-container {
display: flex; flex-direction: column; gap: 2px; width: 300px; max-height: min(60vh, 520px); padding: 6px; box-sizing: border-box;
border: 1px solid var(--bt-line) !important; border-radius: var(--bt-r4); background: var(--bt-raised) !important; box-shadow: var(--bt-shadow-pop);
animation: bt-pop-in var(--bt-t2) var(--bt-ease-out); transform-origin: top right;
}
.bt-shell .dv-tabs-overflow-container .dv-tab { --bt-tab-bg: var(--bt-raised); height: 34px; flex: none; margin: 0; padding: 0; border: 0 !important; border-radius: var(--bt-r2); color: var(--bt-text-2) !important; background-color: var(--bt-tab-bg) !important; cursor: pointer; }
.bt-shell .dv-tabs-overflow-container .dv-tab:hover { --bt-tab-bg: var(--bt-raised-2); color: var(--bt-text) !important; }
.bt-shell .dv-tabs-overflow-container .dv-tab.dv-active-tab { --bt-tab-bg: var(--bt-raised-2); color: var(--bt-text) !important; }
.bt-shell .dv-tabs-overflow-container .dv-tab::before, .bt-shell .dv-tabs-overflow-container .dv-tab::after { display: none; }
.bt-shell .dv-tabs-overflow-container .bt-tab--pinned { justify-content: flex-start; padding: 0 10px; }
.bt-shell .dv-tabs-overflow-container .bt-tab-close { display: none; }
/* ------------------------------------------------------------------------------------------------
* Toolbar and the structured address bar. */
.bt-web, .bt-panel { height: 100%; display: flex; flex-direction: column; background: var(--bt-ground); }
.bt-web { container: pane / inline-size; }
.bt-addressbar {
flex: 0 0 var(--bt-toolbar-h); height: var(--bt-toolbar-h); box-sizing: border-box; display: flex; align-items: center; gap: 2px; padding: 0 8px;
background: var(--bt-chrome); border-bottom: 1px solid var(--bt-line-soft); box-shadow: inset 0 1px 0 rgb(var(--bt-text-rgb) / .03);
}
.bt-icon { width: 32px; height: 32px; flex: 0 0 32px; display: grid; place-items: center; padding: 0; border-radius: var(--bt-r2); background: transparent; border: 0; color: var(--bt-muted); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-icon:hover { background: var(--bt-hover); color: var(--bt-text); }
.bt-icon:active { background: var(--bt-press); }
.bt-shell .bt-icon svg { width: 17px; height: 17px; }
.bt-omni {
position: relative; flex: 1; min-width: 0; height: 34px; margin: 0 6px; box-sizing: border-box; display: flex; align-items: center; gap: 2px; padding: 0 5px;
border-radius: var(--bt-r3); background: var(--bt-field); border: 1px solid rgb(var(--bt-text-rgb) / .045); cursor: text; overflow: hidden; outline: 0;
transition: border-color var(--bt-t1) var(--bt-ease), box-shadow var(--bt-t2) var(--bt-ease), background-color var(--bt-t1) var(--bt-ease);
}
.bt-omni:hover { border-color: var(--bt-line-strong); }
.bt-omni:focus-within, .bt-omni:focus-visible { border-color: transparent; box-shadow: var(--bt-ring); background: var(--bt-field); outline: 0; }
.bt-omni--edit { padding-inline-start: 10px; gap: 8px; }
.bt-shell .bt-omni-lead { width: 15px; height: 15px; color: var(--bt-muted); }
.bt-chip-site {
display: inline-flex; align-items: center; gap: 6px; height: 24px; padding-block: 0; padding-inline: 6px 8px; margin-inline-end: 2px; flex: 0 0 auto; border: 0; border-radius: 7px;
background: var(--bt-accent-soft); color: var(--bt-accent-ink); font: 600 12.5px/1 var(--bt-ui); letter-spacing: .005em; cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease);
}
.bt-chip-site:hover { background: rgb(var(--bt-accent-rgb) / .22); }
.bt-chip-site img { width: 14px; height: 14px; border-radius: 3px; }
.bt-chip-insecure { display: inline-flex; align-items: center; flex: 0 0 auto; height: 22px; margin-inline-end: 2px; padding: 0 8px; border-radius: 6px; background: rgba(245, 158, 11, .12); color: #fbbf24; font: 600 11.5px/1 var(--bt-ui); }
.bt-seg { display: inline-flex; align-items: center; height: 24px; padding: 0 6px; flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; border-radius: 6px; border: 0; background: transparent; color: var(--bt-text-2); font: 500 13px/1 var(--bt-ui); white-space: nowrap; cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-seg:hover { background: var(--bt-hover); color: var(--bt-text); }
.bt-seg[aria-current] { cursor: text; background: none; color: var(--bt-text); font-weight: 600; }
.bt-seg--mono { font: 500 12.5px/1 var(--bt-mono); color: var(--bt-text-2); }
.bt-seg--mono[aria-current] { font-weight: 500; }
.bt-sep { flex: 0 0 auto; color: var(--bt-faint); font: 400 14px/1 var(--bt-ui); padding: 0 1px; opacity: .8; }
.bt-omni-raw { flex: 1; min-width: 0; padding-inline-start: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 400 12.5px var(--bt-mono); color: var(--bt-muted); }
.bt-omni-fill { flex: 1; min-width: 8px; align-self: stretch; }
.bt-omni-action { width: 26px; height: 26px; flex: 0 0 26px; display: grid; place-items: center; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--bt-faint); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-omni:hover .bt-omni-action { color: var(--bt-muted); }
.bt-omni-action:hover { background: var(--bt-hover); color: var(--bt-text) !important; }
.bt-shell .bt-omni-action svg { width: 14px; height: 14px; }
.bt-omni input { flex: 1; min-width: 0; padding: 0; background: none; border: 0; outline: 0; color: var(--bt-text); font: 400 12.5px var(--bt-mono); user-select: text; }
.bt-omni input:focus-visible { outline: 0; }
.bt-omni input::selection { background: rgb(var(--bt-accent-rgb) / .35); }
.bt-omni-ops { display: flex; gap: 4px; flex: 0 1 auto; min-width: 0; overflow: hidden; }
.bt-omni-op { flex: 0 0 auto; height: 22px; padding: 0 8px; border: 1px solid var(--bt-line); border-radius: 6px; background: var(--bt-chrome); color: var(--bt-muted); font: 500 11.5px var(--bt-mono); cursor: pointer; }
.bt-omni-op[aria-selected=true] { color: var(--bt-accent-ink); border-color: rgb(var(--bt-accent-rgb) / .5); background: var(--bt-accent-soft); }
.bt-omni-op:hover { color: var(--bt-text); border-color: var(--bt-accent); }
.bt-omni-progress { position: absolute; left: 8px; right: 8px; bottom: 0; height: 2px; border-radius: 2px; background: var(--bt-brush); transform-origin: left; animation: bt-load 1.2s ease-in-out infinite; pointer-events: none; }
@keyframes bt-load { 0% { transform: scaleX(.05); } 60% { transform: scaleX(.7); } 100% { transform: scaleX(.95); opacity: .3; } }
@media (prefers-reduced-motion: reduce) { .bt-omni-progress { animation: none; transform: scaleX(.6); } }
/* split + wayBetter buttons */
.bt-split { position: relative; display: flex; align-items: center; }
.bt-split .bt-split-main { border-start-start-radius: 8px; border-start-end-radius: 0; border-end-end-radius: 0; border-end-start-radius: 8px; }
.bt-split .bt-split-more { width: 18px; flex-basis: 18px; border-start-start-radius: 0; border-start-end-radius: 8px; border-end-end-radius: 8px; border-end-start-radius: 0; }
.bt-shell .bt-split-more svg { width: 12px; height: 12px; }
.bt-menu.bt-split-menu { position: absolute; top: 40px; inset-inline-end: 0; z-index: 20; min-width: 200px; }
.bt-brand-button {
display: inline-flex; align-items: center; gap: 7px; height: 32px; margin-inline-start: 6px; padding-block: 0; padding-inline: 9px 12px; flex: 0 0 auto;
border: 1px solid var(--bt-line); border-radius: 9px; background: rgb(var(--bt-text-rgb) / .02); color: var(--bt-text); font: 600 12.5px/1 var(--bt-ui); cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease);
}
.bt-brand-button:hover { background: var(--bt-hover); border-color: var(--bt-line-strong); }
.bt-brand-button:active { background: var(--bt-press); }
/* The wayBetter mark: a brush-painted "w" leaning into a heavy "B", in the brush gradient (wb-mark.svg). */
.bt-brand-button { padding: 0 10px; min-width: 40px; justify-content: center; }
.bt-wb { display: block; width: auto; height: 17px; flex: 0 0 auto; pointer-events: none; transition: filter var(--bt-t1) var(--bt-ease), transform var(--bt-t2) var(--bt-ease); }
.bt-brand-button:hover .bt-wb { filter: brightness(1.18) saturate(1.1); transform: rotate(-3deg); }
.bt-brand-button:hover { border-color: rgba(79, 107, 255, .5); }
@container pane (max-width: 640px) {
.bt-brand-button { padding: 0; width: 36px; min-width: 36px; }
.bt-split .bt-split-more { display: none; }
.bt-split .bt-split-main { border-radius: 8px; }
}
@container pane (max-width: 420px) {
.bt-addressbar > .bt-icon[aria-label=Forward], .bt-split { display: none; }
.bt-omni { margin: 0 4px; }
}
.bt-viewport { flex: 1; min-height: 0; position: relative; background: var(--bt-ground); }
.bt-viewport-hint { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 0 24px; color: var(--bt-faint); font-size: 13px; text-align: center; }
/* A quiet outline of a feed behind the loading title: a rail of icons and a timeline of posts. */
.bt-skeleton { position: absolute; inset: 0; display: flex; justify-content: center; gap: 24px; padding: 20px 16px 0; overflow: hidden; opacity: .55; pointer-events: none; }
.bt-skeleton > i { flex: none; width: 36px; background: radial-gradient(circle at 18px 18px, rgb(var(--bt-text-rgb) / .07) 13px, transparent 14px) 0 0 / 36px 58px repeat-y; }
.bt-skeleton > b { flex: 0 1 600px; min-width: 0; display: flex; flex-direction: column; gap: 14px; border-inline-start: 1px solid var(--bt-line-soft); border-inline-end: 1px solid var(--bt-line-soft); padding: 0 16px; }
.bt-skeleton > b > span { height: 118px; border-bottom: 1px solid var(--bt-line-soft);
background: radial-gradient(circle at 20px 20px, rgb(var(--bt-text-rgb) / .07) 19px, transparent 20px) no-repeat,
linear-gradient(rgb(var(--bt-text-rgb) / .06), rgb(var(--bt-text-rgb) / .06)) 52px 8px / 34% 10px no-repeat,
linear-gradient(rgb(var(--bt-text-rgb) / .05), rgb(var(--bt-text-rgb) / .05)) 52px 32px / calc(100% - 52px) 9px no-repeat,
linear-gradient(rgb(var(--bt-text-rgb) / .05), rgb(var(--bt-text-rgb) / .05)) 52px 50px / 72% 9px no-repeat,
linear-gradient(rgb(var(--bt-text-rgb) / .04), rgb(var(--bt-text-rgb) / .04)) 52px 84px / 46% 8px no-repeat; }
@container pane (max-width: 520px) { .bt-skeleton > i { display: none; } }
/* Windows: the page's last frame, taken as its webview was hidden (host `tab-still`), over the outline. */
.bt-still { position: absolute; inset: 0; background: var(--bt-ground) no-repeat left top / cover; }
/* Raised over the tab webviews for an overlay (state.ts `shell_raise`): see-through wherever a
pane or deck column is, so the site stays on screen under menus, dialogs and drag zones. Chrome
keeps its own background; a few px of gutter show the window's, painted the theme's ground
(state.ts). Modal scrims are a flat tint (no backdrop blur, which cannot reach the tab webviews
under the shell and left the site undimmed): every pane dims the same. Menus do not dim. */
html.bt-raised, html.bt-raised body, html.bt-raised #root, html.bt-raised .bt-shell:not(.bt-shell--empty),
html.bt-raised .bt-shell .dv-groupview > .dv-content-container, html.bt-raised .bt-web, html.bt-raised .bt-viewport,
html.bt-raised .bt-deck:has(.bt-col-body), html.bt-raised .bt-col, html.bt-raised .bt-compose, html.bt-raised .bt-col-body { background: transparent; }
html.bt-raised :is(.bt-viewport-hint, .bt-col-hint, .bt-skeleton, .bt-still) { visibility: hidden; }
html.bt-raised .bt-deck:has(.bt-col-body) > .bt-deck-bar { background: var(--bt-ground); }
html.bt-raised .bt-deck :is(.bt-col-head, .bt-compose-head) { background-color: var(--bt-chrome); }
/* The app's panel tab (`site.panel`): the panel fills the pane. */
.bt-panel { position: relative; }
/* ------------------------------------------------------------------------------------------------
* Menus (tab context menu, split menu, account menu). */
.bt-menu-backdrop { position: fixed; inset: 0; z-index: 1000; }
.bt-menu {
position: fixed; min-width: 232px; padding: 5px; box-sizing: border-box; display: flex; flex-direction: column; gap: 1px;
border-radius: var(--bt-r4); background: var(--bt-raised); border: 1px solid var(--bt-line-strong); box-shadow: var(--bt-shadow-pop);
color: var(--bt-text); font: 500 13px/1.3 var(--bt-ui); user-select: none;
}
.bt-menu button { display: flex; align-items: center; gap: 10px; height: 32px; padding: 0 10px; border: 0; border-radius: 7px; background: transparent; color: var(--bt-text); font: inherit; text-align: start; cursor: pointer; transition: background-color 80ms var(--bt-ease); }
.bt-menu button:hover:not(:disabled), .bt-menu button:focus-visible { background: var(--bt-hover); outline: 0; }
.bt-menu button:active:not(:disabled) { background: var(--bt-press); }
.bt-menu button:disabled { color: var(--bt-faint); cursor: default; }
.bt-menu button > .bt-glyph { color: var(--bt-muted); }
.bt-menu button:hover:not(:disabled) > .bt-glyph { color: var(--bt-text); }
.bt-menu button:disabled > .bt-glyph { color: var(--bt-faint); opacity: .7; }
.bt-menu-label { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.bt-menu-keys { margin-inline-start: auto; padding-inline-start: 16px; color: var(--bt-faint); font: 500 11px/1 var(--bt-mono); letter-spacing: .02em; white-space: nowrap; }
.bt-menu hr { border: 0; border-top: 1px solid var(--bt-line); margin: 4px 6px; }
/* Account menu */
.bt-profile-menu { width: 320px; max-height: calc(100vh - 64px); overflow-y: auto; }
.bt-profile-menu-head { display: flex; flex-direction: column; gap: 3px; padding: 8px 10px 10px; }
.bt-profile-menu-head strong { font: 600 13px/1.2 var(--bt-ui); color: var(--bt-text); }
.bt-profile-menu-head span { font: 400 12px/1.3 var(--bt-ui); color: var(--bt-muted); }
.bt-profile-row { position: relative; display: flex; align-items: center; border-radius: 9px; }
.bt-profile-row.is-active { background: rgb(var(--bt-text-rgb) / .035); }
.bt-menu .bt-profile-pick { flex: 1; min-width: 0; height: auto; gap: 11px; padding: 7px 8px; border-radius: 9px; }
.bt-profile-text { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.bt-profile-name { font: 600 13.5px/1.15 var(--bt-ui); color: var(--bt-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-profile-meta { font: 400 12px/1.2 var(--bt-ui); color: var(--bt-muted); font-variant-numeric: tabular-nums; }
.bt-profile-active { margin-inline-start: auto; display: inline-flex; align-items: center; gap: 4px; padding: 0 2px; color: var(--bt-accent-ink); font: 500 11.5px/1 var(--bt-ui); transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-profile-active .bt-glyph { width: 13px; height: 13px; stroke-width: 2.2; }
.bt-profile-actions { position: absolute; inset-inline-end: 6px; top: 50%; transform: translateY(-50%); display: flex; gap: 2px; padding-inline-start: 12px; opacity: 0; pointer-events: none; background: linear-gradient(90deg, transparent, var(--bt-raised) 12px); transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-profile-row.is-active .bt-profile-actions { background: linear-gradient(90deg, transparent, var(--bt-raised) 12px); }
[dir="rtl"] .bt-profile-actions, [dir="rtl"] .bt-profile-row.is-active .bt-profile-actions { background: linear-gradient(270deg, transparent, var(--bt-raised) 12px); }
.bt-profile-row:hover .bt-profile-actions, .bt-profile-row:focus-within .bt-profile-actions { opacity: 1; pointer-events: auto; }
.bt-profile-row:hover .bt-profile-active, .bt-profile-row:focus-within .bt-profile-active { opacity: 0; }
.bt-menu .bt-profile-action { width: 28px; height: 28px; padding: 0; justify-content: center; color: var(--bt-muted); }
.bt-menu .bt-profile-action:hover:not(:disabled) { color: var(--bt-text); background: var(--bt-press); }
.bt-profile-action .bt-glyph { width: 15px; height: 15px; }
.bt-profile-edit { display: flex; flex-direction: column; gap: 10px; padding: 7px 8px 9px; border-radius: 9px; background: rgb(var(--bt-text-rgb) / .035); }
.bt-profile-edit-row { display: flex; align-items: center; gap: 11px; }
.bt-profile-name-input { flex: 1; min-width: 0; height: 32px; padding: 0 10px; box-sizing: border-box; border: 0; border-radius: 8px; background: var(--bt-field); box-shadow: var(--bt-ring); color: var(--bt-text); font: 500 13.5px/1 var(--bt-ui); outline: none; user-select: text; }
.bt-profile-swatches { display: flex; flex-wrap: wrap; gap: 8px; padding-inline-start: 41px; }
.bt-menu .bt-profile-swatch { width: 18px; height: 18px; padding: 0; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .18); transition: transform var(--bt-t1) var(--bt-ease); }
.bt-menu .bt-profile-swatch:hover { transform: scale(1.12); background-color: revert; }
.bt-menu .bt-profile-swatch[aria-checked=true] { outline: 2px solid var(--bt-text); outline-offset: 2px; }
.bt-menu .bt-profile-add { height: 44px; gap: 11px; padding: 0 8px; color: var(--bt-text-2); }
.bt-profile-add-icon { display: grid; place-items: center; width: 30px; height: 30px; flex: none; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--bt-line-strong); color: var(--bt-muted); }
.bt-profile-add-icon .bt-glyph { width: 14px; height: 14px; }
.bt-menu .bt-profile-add:hover .bt-profile-add-icon { box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .6); color: var(--bt-accent-ink); }
.bt-profile-foot { margin: 2px 10px 6px; color: var(--bt-faint); font: 400 11.5px/1.4 var(--bt-ui); }
.bt-profile-confirm { display: flex; flex-direction: column; gap: 10px; margin: 1px 0; padding: 10px 12px; border-radius: 9px; background: rgba(229, 72, 77, .08); box-shadow: inset 0 0 0 1px rgba(229, 72, 77, .25); color: var(--bt-text-2); font: 400 12.5px/1.45 var(--bt-ui); }
.bt-profile-confirm strong { color: var(--bt-text); font-weight: 600; }
.bt-profile-confirm div { display: flex; gap: 6px; }
.bt-menu .bt-profile-confirm button { height: 28px; padding: 0 12px; font-weight: 600; font-size: 12.5px; }
.bt-menu .bt-profile-danger { background: var(--bt-danger); color: #fff; }
.bt-menu .bt-profile-danger:hover:not(:disabled) { background: #d93d42; }
.bt-menu .bt-profile-cancel { background: var(--bt-hover); }
.bt-profile-error { padding: 6px 10px; color: #ff8a80; font: 12px/1.4 var(--bt-ui); }
/* ------------------------------------------------------------------------------------------------
* Command palette (Ctrl+K) and the composer drafts picker, which reuses it. */
.bt-palette-backdrop { position: fixed; inset: 0; z-index: 1100; display: flex; justify-content: center; align-items: flex-start; padding: 12vh 16px 0; background: rgba(3, 4, 7, .6); animation: bt-fade-in var(--bt-t1) var(--bt-ease); }
.bt-palette {
position: relative; width: min(640px, 100%); max-height: min(70vh, 580px); display: flex; flex-direction: column; overflow: hidden;
border-radius: var(--bt-r5); background: var(--bt-raised); border: 1px solid var(--bt-line-strong); box-shadow: 0 32px 80px -20px rgba(0, 0, 0, .8), var(--bt-shadow-pop);
font: 14px/1.3 var(--bt-ui); color: var(--bt-text); transform-origin: top center;
}
.bt-palette::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 1px; background: var(--bt-brush); opacity: .9; }
.bt-palette-field { flex: none; display: flex; align-items: center; gap: 12px; height: 54px; padding-block: 0; padding-inline: 17px 14px; border-bottom: 1px solid var(--bt-line); }
.bt-palette-field > .bt-glyph { width: 18px; height: 18px; color: var(--bt-muted); }
.bt-palette-input { flex: 1; min-width: 0; margin: 0; padding: 0; border: 0; background: transparent; color: var(--bt-text); font: 500 15.5px/1.2 var(--bt-ui); letter-spacing: -.005em; outline: none; user-select: text; }
.bt-palette-input:focus-visible { outline: none; }
.bt-palette-input::placeholder { color: var(--bt-faint); }
.bt-palette-list { flex: 1; overflow-y: auto; padding: 6px; }
.bt-palette-group { padding: 12px 10px 6px; color: var(--bt-faint); font: 600 10.5px/1 var(--bt-ui); letter-spacing: .08em; text-transform: uppercase; }
.bt-palette-group:first-child { padding-top: 6px; }
.bt-palette-item { display: flex; align-items: center; gap: 11px; min-height: 38px; padding: 0 10px; box-sizing: border-box; border-radius: 9px; cursor: pointer; color: var(--bt-text-2); }
.bt-palette-item[aria-selected=true] { background: rgb(var(--bt-text-rgb) / .055); color: var(--bt-text); }
.bt-palette-icon { display: grid; place-items: center; width: 26px; height: 26px; flex: none; border-radius: 7px; background: rgb(var(--bt-text-rgb) / .04); box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .05); color: var(--bt-muted); transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-palette-icon img { width: 16px; height: 16px; border-radius: 4px; }
.bt-palette-icon .bt-glyph { width: 15px; height: 15px; }
.bt-palette-item[aria-selected=true] .bt-palette-icon { background: var(--bt-accent-soft); box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .3); color: var(--bt-accent-ink); }
.bt-palette-label { font-weight: 500; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
.bt-palette-hint { margin-inline-start: auto; color: var(--bt-faint); font: 400 11.5px/1.2 var(--bt-mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 42%; flex-shrink: 0; }
.bt-palette-hint--tag { padding: 3px 7px; border-radius: 6px; background: rgb(var(--bt-text-rgb) / .06); color: var(--bt-muted); font: 500 11px/1.2 var(--bt-ui); }
.bt-palette-hint--tag.is-match { background: var(--bt-accent-soft); color: var(--bt-accent-ink); }
.bt-palette-enter { width: 14px; flex: none; color: var(--bt-muted); font: 500 12px/1 var(--bt-mono); opacity: 0; }
.bt-palette-item[aria-selected=true] .bt-palette-enter { opacity: .8; }
.bt-palette-empty { padding: 28px 18px; color: var(--bt-muted); text-align: center; font-size: 13px; }
.bt-palette-foot { flex: none; display: flex; align-items: center; gap: 16px; height: 38px; padding: 0 14px; border-top: 1px solid var(--bt-line); color: var(--bt-muted); font: 400 11.5px/1 var(--bt-ui); white-space: nowrap; overflow: hidden; }
.bt-palette-foot > span { display: inline-flex; align-items: center; gap: 6px; }
.bt-palette-foot-end { margin-inline-start: auto; }
@media (max-width: 560px) { .bt-palette-foot > span:nth-child(3) { display: none; } }
/* ------------------------------------------------------------------------------------------------
* New-tab page (also the empty dock). */
.bt-start {
height: 100%; overflow-y: auto; box-sizing: border-box; container: start / inline-size; user-select: none;
background:
radial-gradient(760px 360px at 50% -140px, rgba(79, 107, 255, .13), transparent 70%),
radial-gradient(520px 280px at 78% -60px, rgba(168, 85, 247, .07), transparent 70%),
var(--bt-ground);
}
.bt-start-inner { max-width: 660px; margin: 0 auto; padding: clamp(40px, 13vh, 132px) 20px 40px; display: flex; flex-direction: column; align-items: center; gap: 24px; }
.bt-start-mark { display: grid; place-items: center; width: 60px; height: 60px; border-radius: 18px; background: linear-gradient(180deg, var(--bt-raised-2), var(--bt-chrome)); box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .07), inset 0 1px 0 rgb(var(--bt-text-rgb) / .06), 0 24px 60px -24px rgba(79, 107, 255, .65); }
.bt-start-mark img { border-radius: 9px; -webkit-user-drag: none; }
.bt-start-search {
width: 100%; height: 52px; display: flex; align-items: center; gap: 12px; padding-block: 0; padding-inline: 17px 12px; box-sizing: border-box;
border-radius: 14px; background: var(--bt-chrome); border: 1px solid var(--bt-line); box-shadow: 0 10px 30px -18px rgba(0, 0, 0, .9);
transition: border-color var(--bt-t1) var(--bt-ease), box-shadow var(--bt-t2) var(--bt-ease);
}
.bt-start-search:hover { border-color: var(--bt-line-strong); }
.bt-start-search:focus-within { border-color: transparent; box-shadow: var(--bt-ring), 0 10px 30px -18px rgba(0, 0, 0, .9); }
.bt-start-search > .bt-glyph { width: 18px; height: 18px; color: var(--bt-muted); }
.bt-start-search input { flex: 1; min-width: 0; height: 100%; padding: 0; border: 0; background: transparent; color: var(--bt-text); font: 500 15.5px/1 var(--bt-ui); letter-spacing: -.005em; outline: 0; user-select: text; }
.bt-start-search input:focus-visible { outline: 0; }
.bt-start-search input::placeholder { color: var(--bt-faint); }
.bt-start-search .bt-kbd { opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-start-search:focus-within .bt-kbd { opacity: 1; }
.bt-start-label { margin: 0; color: var(--bt-faint); font: 600 10.5px/1 var(--bt-ui); letter-spacing: .08em; text-transform: uppercase; }
.bt-start-accounts { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; gap: 6px; margin-top: -8px; }
.bt-start-accounts .bt-start-label { margin-inline-end: 6px; }
.bt-start-account {
display: inline-flex; align-items: center; gap: 7px; height: 30px; padding-block: 0; padding-inline: 5px 12px; box-sizing: border-box;
border: 1px solid var(--bt-line-soft); border-radius: 15px; background: transparent; color: var(--bt-muted); font: 500 12.5px/1 var(--bt-ui); cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease);
}
.bt-start-account:hover { background: var(--bt-hover); color: var(--bt-text-2); }
.bt-start-account[aria-checked=true] { background: rgb(var(--bt-text-rgb) / .06); border-color: var(--bt-line-strong); color: var(--bt-text); }
.bt-start-account:not([aria-checked=true]) .bt-avatar { filter: saturate(.55) brightness(.85); }
.bt-start-section { width: 100%; display: flex; flex-direction: column; gap: 10px; }
.bt-start-section > .bt-start-label { padding-inline-start: 4px; }
.bt-start-links { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 8px; }
.bt-start-link {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; height: 88px; padding: 0 6px;
border: 1px solid var(--bt-line-soft); border-radius: var(--bt-r4); background: rgb(var(--bt-text-rgb) / .02); color: var(--bt-text-2); font: 500 12.5px/1 var(--bt-ui); cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease), transform var(--bt-t2) var(--bt-ease-out);
}
.bt-start-link-icon { display: grid; place-items: center; width: 36px; height: 36px; border-radius: 11px; background: var(--bt-field); box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .05); color: var(--bt-muted); transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-start-link-icon .bt-glyph { width: 18px; height: 18px; }
.bt-start-link-label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-start-link:hover { background: rgb(var(--bt-text-rgb) / .045); border-color: var(--bt-line); color: var(--bt-text); transform: translateY(-1px); }
.bt-start-link:hover .bt-start-link-icon { background: var(--bt-accent-soft); color: var(--bt-accent-ink); }
.bt-start-link:active { transform: translateY(0) scale(.985); }
.bt-start-recent { list-style: none; margin: 0; padding: 4px; border: 1px solid var(--bt-line-soft); border-radius: var(--bt-r4); background: rgb(var(--bt-text-rgb) / .015); }
.bt-start-row { display: flex; align-items: center; gap: 11px; width: 100%; height: 38px; padding: 0 10px; box-sizing: border-box; border: 0; border-radius: 8px; background: transparent; color: var(--bt-text-2); font: 500 13px/1 var(--bt-ui); text-align: start; cursor: pointer; transition: background-color 80ms var(--bt-ease), color 80ms var(--bt-ease); }
.bt-start-row:hover { background: var(--bt-hover); color: var(--bt-text); }
.bt-start-row-icon { display: grid; place-items: center; width: 16px; height: 16px; flex: none; border-radius: 4px; color: var(--bt-muted); }
.bt-start-row-icon .bt-glyph { width: 15px; height: 15px; }
.bt-start-row-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-start-row-host { flex: none; max-width: 40%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--bt-faint); font: 400 11.5px/1 var(--bt-mono); }
.bt-start-foot { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 20px; margin-top: 4px; color: var(--bt-faint); font: 400 12px/1 var(--bt-ui); }
.bt-start-foot > span { display: inline-flex; align-items: center; gap: 7px; }
@container start (max-width: 600px) { .bt-start-links { grid-template-columns: repeat(3, minmax(0, 1fr)); } .bt-start-row-host { display: none; } }
@container start (max-width: 340px) { .bt-start-links { grid-template-columns: repeat(2, minmax(0, 1fr)); } .bt-start-foot { display: none; } }
/* ------------------------------------------------------------------------------------------------
* Media panel (gallery + clipboard history), drawn over the right edge while tab webviews are hidden. */
.bt-media-backdrop { justify-content: flex-end; align-items: stretch; padding: 0; }
.bt-media { width: min(380px, 100%); height: 100%; display: flex; flex-direction: column; background: var(--bt-raised); border-inline-start: 1px solid var(--bt-line); box-shadow: -24px 0 60px rgba(0, 0, 0, .45); font: 14px/1.3 var(--bt-ui); color: var(--bt-text); animation: bt-slide-in var(--bt-t2) var(--bt-ease-out); }
[dir="rtl"] .bt-media { box-shadow: 24px 0 60px rgba(0, 0, 0, .45); animation-name: bt-slide-in-rtl; }
.bt-media-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; height: 52px; padding-block: 0; padding-inline: 12px 10px; box-sizing: border-box; border-bottom: 1px solid var(--bt-line); }
.bt-media-tabs { display: flex; gap: 2px; padding: 3px; border-radius: 10px; background: rgb(var(--bt-text-rgb) / .045); }
.bt-media-tabs button { height: 28px; padding: 0 12px; border: 0; border-radius: 7px; background: transparent; color: var(--bt-muted); font: 500 12.5px/1 var(--bt-ui); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
.bt-media-tabs button:hover { color: var(--bt-text-2); }
.bt-media-tabs button.active { color: var(--bt-text); background: var(--bt-raised-2); box-shadow: inset 0 0 0 1px rgb(var(--bt-text-rgb) / .07), 0 1px 2px rgba(0, 0, 0, .4); }
.bt-media .bt-icon svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; }
.bt-media-body { flex: 1; min-height: 0; overflow-y: auto; padding: 12px; }
.bt-media-error { margin: 8px 12px 0; color: #ff6b73; font-size: 12.5px; }
.bt-media-empty { color: var(--bt-muted); display: flex; flex-direction: column; gap: 10px; align-items: flex-start; padding: 12px 2px; }
.bt-media-empty p { margin: 0; }
.bt-media-folders { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 12px; }
.bt-media-link { border: 0; background: transparent; color: var(--bt-muted); cursor: pointer; font: 600 12px/1 var(--bt-ui); padding: 4px 6px; border-radius: 6px; }
.bt-media-link:hover { color: var(--bt-text); background: var(--bt-hover); }
.bt-media-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; }
.bt-media-tile { position: relative; aspect-ratio: 1; padding: 0; border: 1px solid var(--bt-line-soft); border-radius: var(--bt-r2); overflow: hidden; background: rgb(var(--bt-text-rgb) / .03); cursor: pointer; transition: border-color var(--bt-t1) var(--bt-ease), transform var(--bt-t2) var(--bt-ease-out); }
.bt-media-tile:hover, .bt-media-tile:focus-visible { border-color: rgb(var(--bt-text-rgb) / .5); outline: none; transform: scale(1.02); }
.bt-media-tile img, .bt-media-clip-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.bt-media-thumb-empty { display: block; width: 100%; height: 100%; }
.bt-media-caption { position: absolute; inset-inline-end: 4px; bottom: 4px; padding: 2px 5px; border-radius: 5px; background: rgba(0, 0, 0, .62); color: #fff; font: 500 10.5px/1.3 var(--bt-mono); }
.bt-media-clips { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
.bt-media-clip { display: flex; align-items: center; gap: 4px; }
.bt-media-clip-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; padding: 8px; border: 0; border-radius: var(--bt-r2); background: transparent; color: var(--bt-text); text-align: start; cursor: pointer; font: inherit; font-size: 13px; }
.bt-media-clip-main:hover, .bt-media-clip-main:focus-visible { background: var(--bt-hover); outline: none; }
.bt-media-clip-main small { margin-inline-start: auto; color: var(--bt-faint); font: 500 11px/1 var(--bt-mono); }
.bt-media-clip-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-media-clip-thumb { width: 48px; height: 48px; flex: none; border-radius: 7px; overflow: hidden; }
/* ------------------------------------------------------------------------------------------------
* Link drag (a link dragged out of a tab, or in from another app): drop zones with labels. */
.bt-shell--link-drag .dv-drop-target > .dv-drop-target-dropzone > .dv-drop-target-selection,
.bt-shell--link-drag .dv-drop-target-container .dv-drop-target-anchor {
display: grid; place-items: center; overflow: hidden; box-sizing: border-box;
background: rgb(var(--bt-accent-rgb) / .1); border: 1.5px solid rgb(var(--bt-accent-rgb) / .85); border-radius: 12px;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .04), inset 0 0 60px rgb(var(--bt-accent-rgb) / .12);
}
.bt-shell--link-drag .dv-drop-target-selection::after,
.bt-shell--link-drag .dv-drop-target-anchor::after {
content: 'Open as tab'; padding: 8px 13px; border-radius: 999px; background: var(--bt-raised); color: var(--bt-text);
font: 600 12px/1 var(--bt-ui); letter-spacing: .01em; white-space: nowrap;
box-shadow: inset 0 0 0 1px var(--bt-line-strong), 0 10px 30px -10px rgba(0, 0, 0, .8);
animation: bt-pop-in var(--bt-t2) var(--bt-ease-out);
}
.bt-shell--link-drag .dv-drop-target-selection.dv-drop-target-left::after, .bt-shell--link-drag .dv-drop-target-anchor.dv-drop-target-left::after { content: '\2190 Split left'; }
.bt-shell--link-drag .dv-drop-target-selection.dv-drop-target-right::after, .bt-shell--link-drag .dv-drop-target-anchor.dv-drop-target-right::after { content: 'Split right \2192'; }
.bt-shell--link-drag .dv-drop-target-selection.dv-drop-target-top::after, .bt-shell--link-drag .dv-drop-target-anchor.dv-drop-target-top::after { content: '\2191 Split up'; }
.bt-shell--link-drag .dv-drop-target-selection.dv-drop-target-bottom::after, .bt-shell--link-drag .dv-drop-target-anchor.dv-drop-target-bottom::after { content: '\2193 Split down'; }
/* Tab strip and the empty titlebar part of it: a new tab in that group. */
.bt-shell--link-drag .dv-tabs-and-actions-container .dv-drop-target-selection { border-radius: 8px; }
.bt-shell--link-drag .dv-tabs-and-actions-container .dv-drop-target-selection::after { content: '+ New tab'; padding: 4px 9px; font-size: 11px; }
.bt-shell--link-drag .dv-drop-target-small-vertical::after,
.bt-shell--link-drag .dv-drop-target-small-horizontal::after { content: none; }
/* Right-to-left languages (ar, fa, he, ur): the window frame keeps its physical layout. macOS traffic
lights and the caption buttons never move, --bt-tb-left/right reserve room by physical side, and
dockview measures its tab strips left to right; so the titlebar row and every tab strip stay LTR,
while the words in them run in their own direction. Everything below the strips mirrors. */
[dir="rtl"] .bt-titlebar,
[dir="rtl"] .bt-shell .dv-tabs-and-actions-container { direction: ltr; }
[dir="rtl"] .bt-shell .dv-tab .bt-tab-title,
[dir="rtl"] .bt-update-chip,
[dir="rtl"] .bt-tb-chip-text,
[dir="rtl"] .bt-ws-button-name,
/* Page titles and URLs in lists: each keeps its own direction ("Home / X" is not reordered). */
[dir="rtl"] .bt-palette-label,
[dir="rtl"] .bt-palette-hint,
/* A handle or an address starts with a Latin letter or @, so it keeps its own order ("@CRTkafa"). */
.bt-profile-switcher-name, .bt-omni-raw { unicode-bidi: plaintext; }

View file

@ -0,0 +1,170 @@
// What a wayBetter app tells the shell frame about its site: names, pages, the address bar chips,
// the new-tab page, the palette's site items, deck column kinds, the app's own panel and the
// overlays it adds. `createShell(site)` sets it; every frame module reads it through `site()`.
// Everything here is data or small functions; the frame owns the behavior (tabs, splits, the
// titlebar, overlays, layout sync, workspaces, sync, developer mode).
import type { ComponentType } from 'react';
import type { AddressModel } from '../addressModel.ts';
import type { ColumnSource, DeckColumn } from '../deckModel.ts';
import type { AccountRules } from '../profileModel.ts';
import type { IconName } from './icons.tsx';
import type { PaletteItem } from './paletteModel.ts';
import type { ThemeStore } from './themeStore.ts';
/** An inline completion for a text field (the address bar, a column's value). */
export type Suggestion = { label: string; insert: string; hint: string };
/** Completions for what is being typed and how accepting one rewrites the text. */
export type Completer = {
/** Up to `max` completions for the token at `caret`. */
suggest(text: string, caret: number, max: number): Suggestion[];
apply(text: string, caret: number, insert: string): { text: string; caret: number };
/** Accessible name of the chips ("X search operators"). */
label(): string;
};
/** One kind of deck column (Home, Notifications, a search, a profile, ...). */
export type ColumnKind = {
kind: string;
label: string;
icon: IconName;
hint: string;
/** What the value field asks for (none = no value). */
value?: { label: string; placeholder: string };
};
/** A deck column flag the page applies (a site tweak), with its label for settings. */
export type ColumnFlag = { key: string; label: string; hint: string };
/** A ready-made set of columns ("Monitor", "Two accounts"). */
export type DeckPreset = {
id: string;
label(): string;
/** Disabled (with this hint) when only one account exists. */
needsTwoAccounts?: () => string;
columns(profiles: readonly string[]): Array<Pick<DeckColumn, 'profile' | 'source'>>;
};
export type DeckSite = {
kinds: readonly ColumnKind[];
/** The page a column loads, or null when its value is not valid for its kind. */
urlFor(source: ColumnSource): string | null;
/** Header title and subtitle for a column. */
title(source: ColumnSource, custom?: string): { title: string; detail?: string };
/** The typed value → the stored value, or null when it is not valid for that kind. */
parseValue(kind: string, input: string): string | null;
/** Why a typed value is not valid for `kind` (shown under the field). */
invalid(kind: string): string;
/** Completions in a kind's value field (e.g. search operators for a search column). */
completer?(kind: string): Completer | null;
/** Flags a column may override (listed in settings), and flags the page accepts that are not listed. */
flags: readonly ColumnFlag[];
extraFlags?: readonly string[];
/** Flags every column starts with. */
defaultFlags: Record<string, boolean>;
/** Flags a column's kind always sets (e.g. X's Following column selects X's own Following tab). */
kindFlags?(source: ColumnSource): Record<string, boolean>;
presets?: readonly DeckPreset[];
/** A page docked at the right of a deck to write in (X: its composer). */
compose?: {
url: string;
width: number;
/** The docked page's chrome and placeholder (it registers its placeholder with the frame). */
Dock: ComponentType<{ deckId: string; left: number }>;
/** The dock's webview reported a page (e.g. load a fresh composer once one was sent). */
navigated?(tabId: string, url: string | undefined, loading: boolean | undefined): void;
};
/** A page title without the site's suffix (" / X"). */
pageTitle?(title: string): string;
};
export type PaletteSite = {
/** The field's placeholder. */
placeholder(): string;
/** The literal search for the query (listed first; kept as the last resort when ranking). */
search?(text: string): PaletteItem | null;
/** Completions ranked above everything else while typing (they rewrite the query). */
completions?(text: string): PaletteItem[];
/** Sections of the app's panel ("Themes", "Plugins", ...). */
sections: ReadonlyArray<{ id: string; label(): string; keywords: string; icon: IconName }>;
/** The site's own pages and actions (after the tabs, decks and the app's items). */
items?(): PaletteItem[];
/** Heading for a site group (`PaletteItem.group`); the frame names its own groups. */
groupLabel?(group: string): string | undefined;
};
export type ShellSite = {
/** The site's name in messages ("X"). */
name: string;
/** The app's name ("wayBetter for X"): the update chip, the brand button, the palette's group. */
product: string;
/** The app's logo (an image URL): titlebar, the panel tab, the new-tab page, the site chip. */
logo: string;
/** The site's home feed: the first tab, and what an account opens beside. */
homeUrl: string;
/** The site's own sign-in and sign-out pages (accounts are signed in and out on the site). */
loginUrl: string;
logoutUrl: string;
/** A page of the site itself (https, the site's hosts). */
isSiteUrl(url: string): boolean;
/** Account handle and avatar rules (as the native `AccountRules`). */
accounts: AccountRules;
/** Text typed in the address bar or the new-tab page that is not an address: the site's search. */
searchUrl(text: string): string;
/** Address bar chips for a URL (null: show the raw address). */
address(url: string): AddressModel | null;
/** Completions while the address is edited. */
addressCompleter?: Completer;
/** The app's own tab: its settings panel, opened at a section (`openPanelSection`). */
panel: {
/** Tab id (kept in saved layouts and workspaces). */
id: string;
title: string;
component: ComponentType<{ section?: { name: string; nonce: number } }>;
};
newTab: {
/** The search field's placeholder. */
search(): string;
/** Quick links (their `url` gets the `homeUrl` setting). */
links: ReadonlyArray<{ id: string; label(): string; icon: IconName; url(homeUrl: string): string }>;
};
palette: PaletteSite;
/** Decks of site columns (Power User Mode); omit for none. */
deck?: DeckSite;
/** Gallery and clipboard panel: which tabs have a composer to attach to; omit for none. */
media?: { canAttach(url: string): boolean };
/** The app's theme store (createThemeStore): chrome and pane themes; omit to keep the frame's own style. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
themes?: ThemeStore<any, any>;
/**
* Native features the app serves (waybetter-host modules it wires up): workspaces (`workspaces_*`),
* encrypted folder sync (`sync_*`), developer mode (`dev_*`) and plugin palette commands
* (`tab_run_command`). Each is on unless set to false; off, the frame shows nothing of it.
*/
features?: { workspaces?: boolean; sync?: boolean; developer?: boolean; pluginCommands?: boolean };
/** Components rendered on top of the shell (they listen to their own events). */
overlays?: ReadonlyArray<ComponentType>;
/** Called once the dock exists (read site settings, listen to site events). Returns a cleanup. */
start?(): (() => void) | undefined;
};
let current: ShellSite | null = null;
/** Sets the site (createShell). */
export function configureSite(value: ShellSite) {
current = value;
}
export function site(): ShellSite {
if (!current) throw new Error('wayBetter shell: createShell(site) first');
return current;
}
/** Whether the app serves a native feature (`site.features`, on by default). */
export const hasFeature = (name: keyof NonNullable<ShellSite['features']>) => site().features?.[name] !== false;
/** The site's runtime text changed (X: the Twitter/X wording): address bars and new-tab pages re-render. */
export function siteChanged() {
window.dispatchEvent(new CustomEvent('bt-site'));
}

View file

@ -0,0 +1,263 @@
// Shared, non-React shell state: the dock, pane placeholders and the native webview reconciliation
// (`tabs_sync`, one layout in flight at a time), shell overlays (the shell webview is raised above
// the tab webviews while a menu, dialog or drag is open), profiles and session layout persistence.
import type { DockviewApi, IDockviewPanel } from 'dockview';
import { cssRgb, paneVisibility, raiseSupported, withNavRedundant } from '../paneModel.ts';
import { defaultProfiles, normalizeProfiles, tabProfile, type ProfileSettings } from '../profileModel.ts';
import type { PaneInfo } from './accountModel.ts';
import { currentWindow, invoke } from './bridge.ts';
import { columnSourceUrl, composeTabId, deckById, decks } from './deckStore.ts';
import { site } from './site.ts';
import { latestOnly } from './syncGate.ts';
/** `profile`: the account profile (WebView data directory) the tab runs in; missing = default. */
/** `besideOf`: the group whose "beside" link opened this tab; its group is that group's side pane. */
export type WebParams = { kind: 'web'; url: string; profile?: string; title?: string; favicon?: string; loading?: boolean; pinned?: boolean; besideOf?: string };
/** The app's own tab (its settings panel, `site.panel`). */
export type PanelParams = { kind: 'panel'; section?: string; nonce?: number; pinned?: boolean };
/** The new-tab page: drawn by the shell itself (no webview); `profile` is the account it opens links in. */
export type StartParams = { kind: 'start'; profile?: string; pinned?: boolean };
/** A deck of site columns (DeckView.tsx); its columns are tab webviews of their own. */
export type DeckParams = { kind: 'deck'; deckId: string; pinned?: boolean };
export type TabParams = WebParams | PanelParams | StartParams | DeckParams;
const LAYOUT_KEY = 'bt.shell.layout.v1';
/** Shared, non-React shell state: pane placeholders and the native webview reconciliation. */
export const shell = {
api: null as DockviewApi | null,
placeholders: new Map<string, HTMLElement>(),
/**
* Open shell overlays (menus, dialogs, palette, drag zones). While > 0 the shell webview is raised
* above the tab webviews (panes stay visible under it), or, where it cannot be, they are hidden.
*/
overlay: 0,
/** Recently closed web tabs, newest last (Ctrl+Shift+T, new-tab page). */
closed: [] as Array<{ url: string; profile?: string; title?: string }>,
profiles: defaultProfiles() as ProfileSettings,
restoring: false,
/** Toolbar actions implemented by Shell.tsx (split view, the app's panel). */
split: (_id: string, _direction: 'right' | 'below') => {},
openPanel: (_from?: string) => {},
/** Opens the new-tab page in the given profile. */
newTab: (_profile: string) => {},
/** The `homeUrl` setting (new-tab page "Home" link, first tab); `site.homeUrl` until read. */
homeUrl: '',
/** Opens `url` from the new-tab page: replaces that page (`startId`) or, without one, adds a tab. */
openFromStart: (_url: string, _profile: string, _startId?: string) => {},
/** Account switcher click: focus a visible pane of that account or open its feed beside (Shell.tsx). */
openAccount: (_profile: string, _options?: { force?: boolean; url?: string }) => {},
/** Opens `url` as a web tab in `profile` (a deck column's "Open as tab"). */
openUrl: (_url: string, _profile: string) => {},
/** Opens the app's panel at a section (e.g. the deck's settings button). */
openPanelSection: (_section: string) => {},
};
/** The app's panel tab id (`site.panel.id`, kept in saved layouts). */
export const panelId = () => site().panel.id;
/** Replaces the profile list (after a native save) and tells mounted switchers and tabs. */
export function setProfiles(value: unknown) {
shell.profiles = normalizeProfiles(value, site().accounts);
window.dispatchEvent(new CustomEvent('bt-profiles'));
scheduleSync();
}
export const newTabId = () => `t${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
export const isWeb = (panel: IDockviewPanel) => (panel.params as TabParams | undefined)?.kind === 'web';
/** Every tab as the account switcher sees it. */
export function paneInfos(): PaneInfo[] {
return (shell.api?.panels ?? []).map(panel => {
const params = panel.params as TabParams | undefined;
return {
id: panel.id,
kind: !params || params.kind === 'deck' ? 'panel' : params.kind,
profile: params && params.kind !== 'panel' && params.kind !== 'deck' ? params.profile : undefined,
url: params?.kind === 'web' ? params.url : undefined,
visible: panel.api.isVisible,
};
});
}
/** Merge params without ever passing `undefined` (dockview deletes keys set to undefined). */
export function patchParams(panel: IDockviewPanel, patch: Partial<WebParams>) {
const clean = Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));
if (Object.keys(clean).length) panel.api.updateParameters(clean);
}
let frame = 0;
let lastPayload = '';
/** Last `navRedundant` per tab; a hidden tab keeps its value so it shows up without a flicker. */
const navRedundant = new Map<string, boolean>();
export function scheduleSync() {
if (frame) return;
frame = requestAnimationFrame(() => { frame = 0; void syncTabs(); });
}
/** Sends the tab rectangles now (e.g. so native code knows closed tabs are gone before a profile removal). */
export function flushSync(): Promise<void> {
if (frame) { cancelAnimationFrame(frame); frame = 0; }
return syncTabs();
}
function syncTabs(): Promise<void> {
const api = shell.api;
if (!api) return Promise.resolve();
const boxes = api.panels.filter(isWeb).map(panel => {
const params = panel.params as WebParams;
const el = shell.placeholders.get(panel.id);
const rect = el?.isConnected ? el.getBoundingClientRect() : null;
const shown = !!rect && rect.width > 1 && rect.height > 1 && panel.api.isVisible;
const { visible, parked } = paneVisibility({ shown, overlay: shell.overlay, raiseSupported: layer.supported });
return {
id: panel.id,
url: params.url,
profile: tabProfile(shell.profiles, params.profile).id,
x: Math.round(rect?.left ?? 0),
y: Math.round(rect?.top ?? 0),
width: Math.round(rect?.width ?? 1),
height: Math.round(rect?.height ?? 1),
visible,
// Not shown for a reason other than a shell overlay: only these drop to low memory.
parked,
};
});
// Only visible panes are judged (a shell overlay hides them all and so changes nothing).
const items = withNavRedundant([...boxes, ...columnBoxes()], site().isSiteUrl, navRedundant);
const payload = JSON.stringify(items);
if (payload === lastPayload) return Promise.resolve();
lastPayload = payload;
saveLayoutSoon();
// `viewport`: the window size this layout is for; native code re-bases it if the window was
// resized while it was in flight (it also follows resizes itself, before the shell re-lays out).
return sendLayout({ items, viewport: [window.innerWidth, window.innerHeight] });
}
/** One tabs_sync in flight at a time; during a drag only the newest layout waits (syncGate.ts). */
const sendLayout = latestOnly<{ items: unknown[]; viewport: [number, number] }>(args =>
invoke('tabs_sync', args).then(() => {}, error => console.error('[shell] tabs_sync', error)));
/**
* Deck columns (and each deck's compose dock) of every open deck tab. A column on another page of
* its deck has no placeholder: hidden, and parked (low memory) when the setting says so; a deck
* tab in the background parks all of its columns.
*/
function columnBoxes() {
const api = shell.api;
const composeUrl = site().deck?.compose?.url;
if (!api) return [];
const boxes = [];
for (const panel of api.panels) {
const params = panel.params as TabParams | undefined;
if (params?.kind !== 'deck') continue;
const deck = deckById(params.deckId);
if (!deck) continue;
const deckShown = panel.api.isVisible;
const entries = deck.columns.map(column => ({ id: column.tabId, profile: column.profile, url: columnSourceUrl(column.source) }));
const compose = decks.compose.get(deck.id);
if (compose && composeUrl) entries.push({ id: composeTabId(deck.id), profile: compose.profile, url: composeUrl });
for (const entry of entries) {
if (!entry.url || !decks.ready.has(entry.id)) continue;
const el = shell.placeholders.get(entry.id);
const rect = el?.isConnected ? el.getBoundingClientRect() : null;
const shown = !!rect && rect.width > 1 && rect.height > 1 && deckShown;
boxes.push({
id: entry.id,
url: entry.url,
profile: tabProfile(shell.profiles, entry.profile).id,
x: Math.round(rect?.left ?? 0),
y: Math.round(rect?.top ?? 0),
width: Math.round(rect?.width ?? 1),
height: Math.round(rect?.height ?? 1),
visible: paneVisibility({ shown, overlay: shell.overlay, raiseSupported: layer.supported }).visible,
parked: !shown && (decks.settings.parkOffPage || !deckShown),
role: 'column' as const,
});
}
}
return boxes;
}
export function setOverlay(delta: number) {
const before = shell.overlay;
shell.overlay = Math.max(0, before + delta);
if ((before === 0) !== (shell.overlay === 0)) syncLayer();
scheduleSync();
}
/**
* The shell webview's place relative to the tab webviews. `supported`: `shell_raise` works here
* (Windows, Linux, macOS; probed once at startup, which also lowers a shell left raised by a reload). While raised,
* `html.bt-raised` makes the page see-through where panes are (shell.css).
*/
const layer = { supported: false, raised: false, queue: Promise.resolve(), probed: false };
const frames = () => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
/** The startup probe (createShell): whether this platform can raise the shell above its tabs. */
export function probeLayer() {
if (layer.probed) return;
layer.probed = true;
// `localStorage['bt.dev.noRaise'] = '1'` (then reload): overlays hide the tabs as where raising
// is not supported, for before/after comparisons.
const off = (() => { try { return localStorage.getItem('bt.dev.noRaise') === '1'; } catch { return false; } })();
invoke<boolean>('shell_raise', { on: false }).then(ok => { layer.supported = raiseSupported(ok, off); syncLayer(); scheduleSync(); }, () => {});
}
/**
* While the shell is see-through, the few px of gutter between panes show the window's own
* background: paint it the theme's ground (read before `bt-raised` clears the page's).
*/
let windowGround = '';
function paintWindowGround() {
const ground = cssRgb(getComputedStyle(document.documentElement).backgroundColor);
if (!ground || ground.join() === windowGround) return;
windowGround = ground.join();
currentWindow().setBackgroundColor([...ground, 255]).catch(() => { windowGround = ''; });
}
function syncLayer() {
if (!layer.supported) return;
layer.queue = layer.queue.then(async () => {
const want = shell.overlay > 0;
if (want === layer.raised) return;
const root = document.documentElement;
if (want) {
// See-through first (still under the tabs, so nothing changes on screen), then on top.
paintWindowGround();
root.classList.add('bt-raised');
await frames();
layer.raised = true;
await invoke('shell_raise', { on: true });
} else {
// Under the tabs first, then opaque again: the panes never blink.
const refocus = document.hasFocus() && (!document.activeElement || document.activeElement === document.body);
layer.raised = false;
await invoke('shell_raise', { on: false });
await frames();
if (shell.overlay === 0) root.classList.remove('bt-raised');
// Closed from the keyboard or a click in the shell (not by the window losing focus) with
// nothing in the shell focused: typing goes back to the active pane.
const active = shell.api?.activePanel;
if (refocus && shell.overlay === 0 && active && isWeb(active)) void tabAction(active.id, 'focus');
}
}).catch(error => console.error('[shell] shell_raise', error));
}
let saveTimer: ReturnType<typeof setTimeout> | undefined;
export function saveLayoutSoon() {
clearTimeout(saveTimer);
saveTimer = setTimeout(() => {
if (!shell.api || shell.restoring) return;
try { localStorage.setItem(LAYOUT_KEY, JSON.stringify(shell.api.toJSON())); } catch { /* Session restore is best effort. */ }
}, 400);
}
export function loadLayout(): unknown {
try { return JSON.parse(localStorage.getItem(LAYOUT_KEY) || 'null'); } catch { return null; }
}
export const tabAction = (id: string, action: 'back' | 'forward' | 'reload' | 'stop' | 'focus') =>
invoke('tab_action', { id, action }).catch(() => {});

View file

@ -0,0 +1,26 @@
/**
* At most one send in flight; while one is, only the newest value waits and goes out right after
* it (older ones are dropped). The tab layout IPC uses it: during a divider drag or a window resize
* the shell lays out every frame, and queueing every frame's rectangles made native code replay
* stale layouts one after another (each a WebView2 re-layout) while falling further behind.
*
* The returned promise settles once this value, or a newer one that replaced it, was sent and
* acknowledged, so a caller that awaits it knows native code has seen at least its layout.
*/
export function latestOnly<T>(send: (value: T) => Promise<void>): (value: T) => Promise<void> {
let busy = false;
let next: { value: T; waiters: Array<() => void> } | null = null;
const run = async (value: T, waiters: Array<() => void>) => {
busy = true;
try { await send(value); } catch { /* The sender reports its own errors. */ }
for (const resolve of waiters) resolve();
const queued = next;
next = null;
if (queued) void run(queued.value, queued.waiters);
else busy = false;
};
return value => new Promise<void>(resolve => {
if (!busy) { void run(value, [resolve]); return; }
next = { value, waiters: [...(next?.waiters ?? []), resolve] };
});
}

View file

@ -0,0 +1,84 @@
// Encrypted folder sync in the shell: while a sync folder is unlocked, the settings are pushed as
// an encrypted snapshot when they change (native code skips unchanged ones), and a newer snapshot
// from another computer is offered (titlebar chip → the app's backup settings, with the same
// preview and per-section checkboxes as a file import). Crypto and files are native
// (waybetter-host `sync`).
import { localSections } from './backupModel.ts';
import { invoke } from './bridge.ts';
import { decks } from './deckStore.ts';
export type SnapshotInfo = { name: string; device: string; deviceName: string; createdAt: number; size: number };
export type SyncStatus = {
folder: string | null; device: string; deviceName: string; autoPush: boolean; initialized: boolean; unlocked: boolean;
remembered: boolean; lastPushedAt: number; lastPulled: number; snapshots: SnapshotInfo[]; error: string | null;
};
export const syncState = {
status: null as SyncStatus | null,
/** A newer snapshot from another computer, not pulled or dismissed yet. */
newer: null as SnapshotInfo | null,
};
const emit = () => window.dispatchEvent(new CustomEvent('bt-sync'));
const PUSH_MS = 30_000;
const CHECK_MS = 180_000;
/** The shell's own sections for backups and snapshots. */
export const shellSections = () => localSections({ decks: decks.list, deckSettings: decks.settings });
export async function refreshSync(): Promise<SyncStatus | null> {
try { syncState.status = await invoke<SyncStatus>('sync_status'); } catch { syncState.status = null; }
emit();
return syncState.status;
}
export function setSyncStatus(status: SyncStatus) {
syncState.status = status;
emit();
}
export async function pushNow(force = false): Promise<boolean> {
const status = syncState.status;
if (!status?.folder || !status.unlocked) return false;
const result = await invoke<{ pushed: boolean }>('sync_push', { extra: shellSections(), force });
if (result.pushed) await refreshSync();
return result.pushed;
}
export async function checkNewer(): Promise<SnapshotInfo | null> {
const status = syncState.status;
if (!status?.folder || !status.unlocked) return null;
try { syncState.newer = await invoke<SnapshotInfo | null>('sync_check', { extra: shellSections() }); } catch { syncState.newer = null; }
emit();
return syncState.newer;
}
export function clearNewer() {
syncState.newer = null;
emit();
}
export function installSyncHost(): () => void {
let alive = true;
void refreshSync().then(status => { if (alive && status?.unlocked) void checkNewer(); });
const push = setInterval(() => { if (syncState.status?.autoPush) pushNow().catch(() => {}); }, PUSH_MS);
const check = setInterval(() => void checkNewer(), CHECK_MS);
// Coming back to the window is when another computer's changes are most likely waiting.
const onFocus = () => void checkNewer();
// Settings changed through the panel: push soon (native code skips unchanged settings).
let soon: ReturnType<typeof setTimeout> | undefined;
const onChanged = () => { clearTimeout(soon); soon = setTimeout(() => { if (syncState.status?.autoPush) pushNow().catch(() => {}); }, 2500); };
window.addEventListener('focus', onFocus);
window.addEventListener('bt-settings-changed', onChanged);
window.addEventListener('bt-decks', onChanged);
return () => {
alive = false;
clearInterval(push);
clearInterval(check);
clearTimeout(soon);
window.removeEventListener('focus', onFocus);
window.removeEventListener('bt-settings-changed', onChanged);
window.removeEventListener('bt-decks', onChanged);
};
}

View file

@ -0,0 +1,71 @@
// Which theme each site tab gets. The global theme applies everywhere unless an account profile
// has a theme of its own, and any pane can override both (the pane's “…” menu, the app's theme
// settings). A pane or account theme is the theme document as it is (the global theme's
// customizations and accent belong to the global theme). Native code keeps the same rules and
// delivers each tab its theme; the shell uses them for pane chrome. Pure (tests, shell, panel).
export type ThemeScopes = {
/** wayBetter's window (tabs, address bar, titlebar, panel) follows the theme, or keeps its own style. */
chrome: 'theme' | 'own';
/** Account profile id -> theme id. */
profiles: Record<string, string>;
/** Pane (tab) id -> theme id. */
panes: Record<string, string>;
};
export const MAX_PROFILE_THEMES = 32;
export const MAX_PANE_THEMES = 64;
export const SCOPES_DEFAULT: ThemeScopes = { chrome: 'theme', profiles: {}, panes: {} };
const THEME_ID = /^[a-z0-9-]{1,40}$/;
const PROFILE_ID = /^(default|p[a-z0-9]{1,32})$/;
const TAB_ID = /^[A-Za-z0-9-]{1,40}$/;
function entries(value: unknown, key: RegExp, max: number): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
const out: Record<string, string> = {};
for (const [id, theme] of Object.entries(value)) {
if (Object.keys(out).length >= max) break;
if (key.test(id) && typeof theme === 'string' && THEME_ID.test(theme)) out[id] = theme;
}
return out;
}
/** Any JSON to valid scopes (bounded; unknown values dropped). */
export function normalizeScopes(input: unknown): ThemeScopes {
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
return {
chrome: source.chrome === 'own' ? 'own' : 'theme',
profiles: entries(source.profiles, PROFILE_ID, MAX_PROFILE_THEMES),
panes: entries(source.panes, TAB_ID, MAX_PANE_THEMES),
};
}
export type ScopeSource = 'pane' | 'account' | 'global';
/**
* The theme id a tab shows and where it comes from: the pane's own, else its account's, else the
* global one. An id that no longer exists (a removed imported theme) falls through.
*/
export function themeIdFor(scopes: ThemeScopes, tab: { id?: string; profile?: string }, globalPreset: string, known: (id: string) => boolean): { id: string; source: ScopeSource } {
const pane = tab.id ? scopes.panes[tab.id] : undefined;
if (pane && known(pane)) return { id: pane, source: 'pane' };
const account = tab.profile ? scopes.profiles[tab.profile] : undefined;
if (account && known(account)) return { id: account, source: 'account' };
return { id: globalPreset, source: 'global' };
}
/** Drops pane entries whose pane is gone (the shell calls this with its open tab ids). */
export function prunePanes(scopes: ThemeScopes, open: Iterable<string>): ThemeScopes {
const keep = new Set(open);
const panes = Object.fromEntries(Object.entries(scopes.panes).filter(([id]) => keep.has(id)));
return Object.keys(panes).length === Object.keys(scopes.panes).length ? scopes : { ...scopes, panes };
}
/** Sets (or with null clears) one pane's or account's theme. */
export function assign(scopes: ThemeScopes, kind: 'panes' | 'profiles', id: string, theme: string | null): ThemeScopes {
const next = { ...scopes[kind] };
if (theme) next[id] = theme; else delete next[id];
return normalizeScopes({ ...scopes, [kind]: next });
}

View file

@ -0,0 +1,257 @@
// The shell's view of theming: the global theme choice, account/pane themes (scopes), installed
// Google fonts and a theme editor's live preview. The app's settings, pane menus and the chrome
// share it (they all live in the shell webview). Native code persists everything and themes the
// site tabs; this module themes the app's own window with the same documents. What a theme
// document is belongs to the app (`ThemeAdapter`); `createThemeStore(adapter)` makes the store the
// app keeps and hands to the frame (`site.themes`).
import type { DockviewApi } from 'dockview';
import { BOOT_CACHE_KEY } from './boot.ts';
import { invoke } from './bridge.ts';
import { CHROME_VAR_NAMES, chromeVars, type ChromeTheme } from './chromeTheme.ts';
import { SCOPES_DEFAULT, normalizeScopes, prunePanes, themeIdFor, type ScopeSource, type ThemeScopes } from './themeScopes.ts';
import { shell, type TabParams } from './state.ts';
export type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] };
export type InstalledFont = { family: string; weights: Weights; bytes: number; faces: number; installedAt: string };
type FaceData = { weight: [number, number]; unicodeRange: string | null; data: string };
/** A theme document as the frame needs it: an id and a name (the rest is the app's). */
export type ThemeDoc = { id: string; name: string };
/** What the app's themes are and how native code stores them. */
export type ThemeAdapter<Choice = unknown, Spec extends ThemeDoc = ThemeDoc> = {
/** The choice before anything is read (and when reading fails). */
defaultChoice: Choice;
/** Reads the persisted global choice (normalized). */
load(): Promise<Choice>;
/** Persists `choice` and themes every site tab (throws native code's error). */
commit(choice: Choice): Promise<void>;
/** Shows `spec` (a draft) in every site tab until it is saved or closed; null ends it. */
preview(spec: Spec | null): Promise<void>;
/** The theme document a choice shows (its customizations applied). */
resolve(choice: Choice): Spec;
/** The chosen theme's id. */
preset(choice: Choice): string;
/** The choice a theme id stands for: the global choice itself, or that theme without customizations. */
choiceForId(choice: Choice, id: string): Choice;
/** Every theme that can be picked: built-in ones and the choice's imported ones. */
all(choice: Choice): Spec[];
/** Google font families a theme uses (in `roles` only, when given). */
googleFonts(spec: Spec, roles?: readonly string[]): string[];
/** The chrome's colors and fonts for a theme. */
chrome(spec: Spec): ChromeTheme;
/** Three swatch colors for menus (page, text, accent, on the theme's surface and border). */
dots(spec: Spec): { page: string; bg: string; border: string; text: string; accent: string };
};
export type ThemeState<Choice, Spec> = { ready: boolean; choice: Choice; scopes: ThemeScopes; fonts: InstalledFont[]; preview: Spec | null };
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
export type ThemeStore<Choice = unknown, Spec extends ThemeDoc = ThemeDoc> = ReturnType<typeof createThemeStore<Choice, Spec>>;
export function createThemeStore<Choice, Spec extends ThemeDoc>(adapter: ThemeAdapter<Choice, Spec>) {
const state: ThemeState<Choice, Spec> = { ready: false, choice: adapter.defaultChoice, scopes: SCOPES_DEFAULT, fonts: [], preview: null };
const listeners = new Set<() => void>();
let snapshot = { ...state };
const emit = () => { snapshot = { ...state }; for (const listener of [...listeners]) listener(); applyChrome(); };
let loading: Promise<void> | null = null;
/** Reads the persisted theme state once (every caller shares the same load). */
function loadThemes(): Promise<void> {
loading ??= Promise.all([
adapter.load().catch(() => adapter.defaultChoice),
invoke<unknown>('theme_scopes_get').then(normalizeScopes).catch(() => SCOPES_DEFAULT),
invoke<InstalledFont[]>('gfonts_installed').catch(() => [] as InstalledFont[]),
]).then(([choice, scopes, fonts]) => {
Object.assign(state, { ready: true, choice, scopes, fonts: Array.isArray(fonts) ? fonts : [] });
committed = choice;
emit();
});
return loading;
}
/** The last choice native code acknowledged (an error reverts to it). */
let committed: Choice | null = null;
/** Shows `next` right away; `commit` persists it and themes every site tab (reverted on error). */
async function setChoice(next: Choice, commit = true): Promise<void> {
const previous = state.choice;
state.choice = next;
emit();
if (!commit) return;
try { await adapter.commit(next); committed = next; }
catch (error) { state.choice = committed ?? previous; emit(); throw new Error(getError(error)); }
}
async function setScopes(next: ThemeScopes): Promise<void> {
const previous = state.scopes;
state.scopes = normalizeScopes(next);
emit();
try { await invoke('theme_scopes_set', { scopes: state.scopes }); }
catch (error) { state.scopes = previous; emit(); throw new Error(getError(error)); }
}
/** A theme editor's draft, shown in every site tab and the chrome until it is saved or closed. */
async function setPreview(theme: Spec | null): Promise<void> {
state.preview = theme;
emit();
try { await adapter.preview(theme); } catch { /* Preview is best effort (browser preview). */ }
}
const themeState = () => state;
const allThemes = (choice: Choice = state.choice) => adapter.all(choice);
const knownTheme = (id: string, choice: Choice = state.choice) => allThemes(choice).some(theme => theme.id === id);
const themeName = (id: string) => allThemes().find(theme => theme.id === id)?.name ?? id;
/** The theme a tab (or pane) shows, as the chrome and the theme lists describe it. */
function tabTheme(tab: { id?: string; profile?: string }): { id: string; source: ScopeSource; theme: Spec } {
const found = themeIdFor(state.scopes, tab, adapter.preset(state.choice), id => knownTheme(id));
return { ...found, theme: adapter.resolve(adapter.choiceForId(state.choice, found.id)) };
}
// -------------------------------------------------------------------------------------------
// Google fonts in the shell (chrome, previews): registered from bytes like in the site's page.
const shellFonts = new Map<string, Promise<boolean>>();
function register(family: string, faces: FaceData[]) {
for (const face of faces) {
const bytes = Uint8Array.from(atob(face.data), char => char.charCodeAt(0));
const [min, max] = face.weight;
const descriptors: FontFaceDescriptors = { weight: min === max ? String(min) : `${min} ${max}`, style: 'normal', display: 'swap' };
if (face.unicodeRange) descriptors.unicodeRange = face.unicodeRange;
const fontFace = new FontFace(family, bytes.buffer, descriptors);
document.fonts.add(fontFace);
void fontFace.load().catch(() => {});
}
}
/** Registers an installed Google font in the shell document once. */
function ensureShellFont(family: string): Promise<boolean> {
let pending = shellFonts.get(family);
if (!pending) {
pending = invoke<{ faces: FaceData[] }>('gfonts_faces', { family })
.then(result => { register(family, result.faces); return true; })
.catch(() => { shellFonts.delete(family); return false; });
shellFonts.set(family, pending);
}
return pending;
}
const previews = new Map<string, Promise<string | null>>();
let previewSeq = 0;
/**
* A text-subset preview of any Google font (a few KB, fetched natively): registers it under a
* private family name and resolves to that name, or null when it failed.
*/
function previewFont(family: string, weights: Weights, text: string): Promise<string | null> {
const key = `${family}|${JSON.stringify(weights)}|${text}`;
let pending = previews.get(key);
if (!pending) {
const alias = `wbp-${++previewSeq}`;
const attempt = (tries: number): Promise<string | null> => invoke<FaceData[]>('gfonts_preview', { family, weights, text })
.then(faces => { register(alias, faces); return alias; })
.catch(error => {
// Six previews at most are in flight natively; the list retries shortly.
if (tries > 0 && /busy/i.test(getError(error))) return new Promise<string | null>(done => setTimeout(() => done(attempt(tries - 1)), 250 + Math.random() * 400));
previews.delete(key);
return null;
});
pending = attempt(12);
previews.set(key, pending);
}
return pending;
}
async function installFont(family: string, weights: Weights): Promise<InstalledFont> {
const font = await invoke<InstalledFont>('gfonts_install', { family, weights });
state.fonts = [...state.fonts.filter(item => item.family !== family), font].sort((a, b) => a.family.localeCompare(b.family));
shellFonts.delete(family);
emit();
return font;
}
async function removeFont(family: string): Promise<void> {
await invoke('gfonts_remove', { family });
state.fonts = state.fonts.filter(item => item.family !== family);
emit();
}
const isInstalled = (family: string) => state.fonts.some(font => font.family === family);
/** Google families a theme needs that are not downloaded yet. */
const missingFonts = (theme: Spec) => adapter.googleFonts(theme).filter(family => !isInstalled(family));
// -------------------------------------------------------------------------------------------
// Chrome
function setVars(element: HTMLElement, vars: Record<string, string>) {
for (const name of CHROME_VAR_NAMES) if (!(name in vars)) element.style.removeProperty(name);
for (const [name, value] of Object.entries(vars)) element.style.setProperty(name, value);
}
function chromeFontsFor(theme: Spec) {
for (const family of adapter.googleFonts(theme, ['chrome', 'mono'])) if (isInstalled(family)) void ensureShellFont(family);
}
/** The chrome follows the global theme (or the editor's draft); panes with their own theme follow theirs. */
function applyChrome() {
if (typeof document === 'undefined' || !state.ready) return;
const own = state.scopes.chrome === 'own';
const global = state.preview ?? adapter.resolve(state.choice);
chromeFontsFor(global);
const vars = chromeVars(adapter.chrome(global), own);
setVars(document.documentElement, vars);
// The next start paints these from its first frame (boot.ts); an editor's draft is not kept.
if (!state.preview) { try { localStorage.setItem(BOOT_CACHE_KEY, JSON.stringify(vars)); } catch { /* Best effort. */ } }
syncGroups();
}
let dock: DockviewApi | null = null;
/** Pane chrome: a dock group whose active tab shows another theme than the global one gets that theme. */
function syncGroups() {
const api = dock ?? shell.api;
if (!api) return;
const own = state.scopes.chrome === 'own';
for (const group of api.groups) {
const params = group.activePanel?.params as TabParams | undefined;
const tab = params && (params.kind === 'web' || params.kind === 'start') ? { id: params.kind === 'web' ? group.activePanel!.id : undefined, profile: params.profile ?? 'default' } : null;
const scoped = !own && !state.preview && tab ? tabTheme(tab) : null;
const element = group.element;
if (scoped && scoped.source !== 'global') {
chromeFontsFor(scoped.theme);
element.classList.add('wb-pane-theme');
setVars(element, chromeVars(adapter.chrome(scoped.theme)));
element.dataset.wbTheme = scoped.id;
} else if (element.classList.contains('wb-pane-theme')) {
element.classList.remove('wb-pane-theme');
setVars(element, {});
delete element.dataset.wbTheme;
}
}
}
/** Shell.tsx hands over the dock once it exists: pane chrome follows focus and layout changes. */
function attachDock(api: DockviewApi) {
dock = api;
const sync = () => requestAnimationFrame(syncGroups);
api.onDidActivePanelChange(sync);
api.onDidLayoutChange(sync);
api.onDidAddPanel(sync);
api.onDidRemovePanel(() => {
sync();
// A closed pane's theme goes with it.
const open = api.panels.map(panel => panel.id);
const pruned = prunePanes(state.scopes, open);
if (pruned !== state.scopes && !shell.restoring) void setScopes(pruned).catch(() => {});
});
window.addEventListener('bt-profiles', sync);
void loadThemes().then(sync);
}
/** For `useThemeState` (hooks.ts): subscribe, and the current snapshot. */
const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
const current = () => snapshot;
return {
adapter, loadThemes, setChoice, setScopes, setPreview, themeState, allThemes, knownTheme, themeName, tabTheme,
ensureShellFont, previewFont, installFont, removeFont, isInstalled, missingFonts, attachDock, subscribe, current,
};
}

View file

@ -0,0 +1,10 @@
// The frame's window controls (custom titlebar, grips, caption buttons), bound to the app's Tauri
// API as handed to createShell.
import { createWindowControls } from '../windowControls.ts';
import { currentWindow, invoke } from './bridge.ts';
export { frameless, isTauri, os, type ResizeDirection } from '../windowControls.ts';
export const { minimize, toggleMaximize, close, startResize, onMaximizedChange, systemMenu } =
createWindowControls((command, args) => invoke(command, args), currentWindow);

View file

@ -0,0 +1,257 @@
// Workspaces: named snapshots of the tab/pane/deck layout (each tab's URL, account profile and pane
// theme), restored with one click, switched from Ctrl+K and the titlebar menu, one optionally
// opened on start. Pure (no Tauri/DOM imports) so it is unit-tested under node. Stored natively
// (`workspaces_get` / `workspaces_set`; waybetter-host `workspaces` re-checks the same bounds).
//
// A workspace keeps dockview's own serialized layout, reduced to what reopening needs: panels of
// the kinds the shell knows, their params without transient state (loading, nonces), http(s)
// URLs only. Restoring gives every web/new-tab page a fresh id (so it opens as a new webview and
// never inherits a live tab's state); deck tabs and the app's panel keep their fixed ids.
import { t } from './i18n.ts';
export const WORKSPACE_LIMITS = Object.freeze({
/** Saved workspaces. */
count: 20,
name: 60,
/** Tabs in one workspace. */
tabs: 64,
/** Serialized size of one workspace (JSON characters). */
bytes: 256 * 1024,
url: 4096,
title: 300,
});
export type WorkspaceTab = { kind: 'web' | 'panel' | 'start' | 'deck'; url?: string; profile?: string; title?: string };
export type Workspace = {
id: string;
name: string;
savedAt: string;
/** dockview's `SerializedDockview`, reduced (see `captureWorkspace`). */
layout: SerializedLayout;
/** Pane themes of this workspace's tabs: tab id (in `layout`) → theme id. */
paneThemes: Record<string, string>;
/** Decks the workspace shows (Power User Mode), so a deck deleted since can come back. */
decks?: unknown[];
};
export type WorkspaceStore = { version: 1; default: string | null; items: Workspace[] };
export const EMPTY_WORKSPACES: WorkspaceStore = { version: 1, default: null, items: [] };
type Json = Record<string, unknown>;
export type SerializedLayout = { grid: Json; panels: Record<string, Json>; activeGroup?: string; floatingGroups?: unknown[]; popoutGroups?: unknown[] };
const KINDS = new Set(['web', 'panel', 'start', 'deck']);
/** Params each kind keeps; everything else (loading, nonce, favicon, besideOf, ...) is dropped. */
const KEEP: Record<string, readonly string[]> = {
web: ['kind', 'url', 'profile', 'title', 'pinned'],
panel: ['kind', 'section', 'pinned'],
start: ['kind', 'profile', 'pinned'],
deck: ['kind', 'deckId', 'pinned'],
};
const ID = /^[A-Za-z0-9_-]{1,64}$/;
const THEME_ID = /^[a-z0-9-]{1,40}$/;
const WORKSPACE_ID = /^[a-z0-9-]{1,40}$/;
const isObject = (value: unknown): value is Json => !!value && typeof value === 'object' && !Array.isArray(value);
export function httpUrl(value: unknown): string | null {
if (typeof value !== 'string' || value.length > WORKSPACE_LIMITS.url) return null;
try {
const url = new URL(value);
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : null;
} catch { return null; }
}
export function cleanName(value: unknown): string {
// eslint-disable-next-line no-control-regex
return typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, WORKSPACE_LIMITS.name) : '';
}
/** A slug for a new workspace id, unique among `taken`. */
export function workspaceId(name: string, taken: Iterable<string>): string {
const used = new Set(taken);
const base = cleanName(name).toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'workspace';
let id = base;
for (let n = 2; used.has(id); n += 1) id = `${base}-${n}`;
return id;
}
/** A panel's params reduced to what reopening needs, or null when the panel cannot be kept. */
function cleanParams(params: unknown): Json | null {
if (!isObject(params) || typeof params.kind !== 'string' || !KINDS.has(params.kind)) return null;
const out: Json = {};
for (const key of KEEP[params.kind]!) {
const value = params[key];
if (value === undefined || value === null) continue;
if (key === 'url') {
const url = httpUrl(value);
if (!url) return null;
out.url = url;
} else if (key === 'pinned') {
if (value === true) out.pinned = true;
} else if (key === 'title') {
if (typeof value === 'string') out.title = value.slice(0, WORKSPACE_LIMITS.title);
} else if (typeof value === 'string' && value.length <= 64) {
out[key] = value;
}
}
if (params.kind === 'web' && !out.url) return null;
if (params.kind === 'deck' && typeof out.deckId !== 'string') return null;
return out;
}
/** Visits every group's `views`/`activeView` in the grid and in floating/popout groups. */
function mapGroups(value: unknown, fn: (group: Json) => void): void {
if (Array.isArray(value)) { for (const item of value) mapGroups(item, fn); return; }
if (!isObject(value)) return;
if (Array.isArray(value.views)) fn(value);
for (const [key, child] of Object.entries(value)) if (key !== 'views') mapGroups(child, fn);
}
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
/** Drops views whose panel is gone; returns the tab ids still referenced. */
function pruneViews(layout: SerializedLayout): Set<string> {
const referenced = new Set<string>();
mapGroups([layout.grid, layout.floatingGroups, layout.popoutGroups], group => {
const views = (group.views as unknown[]).filter((id): id is string => typeof id === 'string' && id in layout.panels);
group.views = views;
if (typeof group.activeView === 'string' && !views.includes(group.activeView)) group.activeView = views[0];
for (const id of views) referenced.add(id);
});
return referenced;
}
export type CaptureInput = {
id: string;
name: string;
layout: unknown;
/** The pane theme map (`ThemeScopes.panes`); only this layout's tabs are kept. */
paneThemes?: Record<string, string>;
decks?: Array<{ id: string }>;
now?: Date;
};
/** Makes a workspace from the live dockview layout. Throws when there is nothing to keep or it is too large. */
export function captureWorkspace(input: CaptureInput): Workspace {
const name = cleanName(input.name);
if (!name) throw new Error('A workspace needs a name.');
if (!WORKSPACE_ID.test(input.id)) throw new Error(t('wb.ws.err.id'));
const raw = input.layout as Partial<SerializedLayout> | null;
if (!isObject(raw) || !isObject(raw.grid) || !isObject(raw.panels)) throw new Error(t('wb.ws.err.noLayout'));
const layout = clone(raw) as SerializedLayout;
const panels: Record<string, Json> = {};
for (const [id, panel] of Object.entries(layout.panels)) {
if (!ID.test(id) || !isObject(panel)) continue;
const params = cleanParams(panel.params);
if (!params) continue;
const title = typeof panel.title === 'string' ? panel.title.slice(0, WORKSPACE_LIMITS.title) : undefined;
panels[id] = { id, contentComponent: panel.contentComponent, params, ...(title ? { title } : {}) };
}
layout.panels = panels;
const kept = pruneViews(layout);
for (const id of Object.keys(layout.panels)) if (!kept.has(id)) delete layout.panels[id];
const count = Object.keys(layout.panels).length;
if (!count) throw new Error(t('wb.ws.err.noTabs'));
if (count > WORKSPACE_LIMITS.tabs) throw new Error(`A workspace holds at most ${WORKSPACE_LIMITS.tabs} tabs.`);
const paneThemes: Record<string, string> = {};
for (const [tab, theme] of Object.entries(input.paneThemes ?? {})) {
if (tab in layout.panels && typeof theme === 'string' && THEME_ID.test(theme)) paneThemes[tab] = theme;
}
const deckIds = new Set(Object.values(layout.panels).map(panel => (panel.params as Json).deckId).filter((id): id is string => typeof id === 'string'));
const decks = (input.decks ?? []).filter(deck => deckIds.has(deck.id));
const workspace: Workspace = {
id: input.id,
name,
savedAt: (input.now ?? new Date()).toISOString(),
layout,
paneThemes,
...(decks.length ? { decks: clone(decks) } : {}),
};
if (JSON.stringify(workspace).length > WORKSPACE_LIMITS.bytes) throw new Error(t('wb.ws.err.tooLarge'));
return workspace;
}
/** Tabs of a workspace in layout order (for menus: "3 tabs · x.com/home, …"). */
export function workspaceTabs(workspace: Workspace): WorkspaceTab[] {
const order: string[] = [];
mapGroups([workspace.layout.grid, workspace.layout.floatingGroups], group => { for (const id of group.views as string[]) if (!order.includes(id)) order.push(id); });
return order.map(id => workspace.layout.panels[id]?.params as WorkspaceTab | undefined).filter((tab): tab is WorkspaceTab => !!tab);
}
export type RestorePlan = {
layout: SerializedLayout;
/** Pane themes for the restored tab ids. */
paneThemes: Record<string, string>;
/** Tab id in the workspace → id it gets now. */
ids: Record<string, string>;
};
/**
* The layout to hand dockview's `fromJSON`: web and new-tab pages get fresh ids from `newId`
* (a live tab never keeps its webview across a switch), deck and wayBetter tabs keep theirs.
* `profileKnown` drops accounts that no longer exist (the tab opens in the default account).
*/
export function planRestore(workspace: Workspace, newId: () => string, profileKnown: (id: string) => boolean = () => true): RestorePlan {
const layout = clone(workspace.layout);
const ids: Record<string, string> = {};
const panels: Record<string, Json> = {};
for (const [id, panel] of Object.entries(layout.panels)) {
const params = cleanParams(panel.params);
if (!params) continue;
if (typeof params.profile === 'string' && !profileKnown(params.profile)) delete params.profile;
const fresh = params.kind === 'web' || params.kind === 'start' ? newId() : id;
ids[id] = fresh;
panels[fresh] = { ...panel, id: fresh, params };
}
layout.panels = panels;
mapGroups([layout.grid, layout.floatingGroups, layout.popoutGroups], group => {
group.views = (group.views as unknown[]).map(id => (typeof id === 'string' ? ids[id] : undefined)).filter((id): id is string => !!id);
if (typeof group.activeView === 'string') group.activeView = ids[group.activeView] ?? (group.views as string[])[0];
});
pruneViews(layout);
const paneThemes: Record<string, string> = {};
for (const [tab, theme] of Object.entries(workspace.paneThemes ?? {})) if (ids[tab]) paneThemes[ids[tab]!] = theme;
return { layout, paneThemes, ids };
}
/** Parses what native code returned; anything malformed is dropped, never thrown. */
export function normalizeWorkspaces(value: unknown): WorkspaceStore {
if (!isObject(value) || !Array.isArray(value.items)) return { ...EMPTY_WORKSPACES, items: [] };
const items: Workspace[] = [];
for (const item of value.items) {
if (!isObject(item) || typeof item.id !== 'string' || !WORKSPACE_ID.test(item.id) || items.some(other => other.id === item.id)) continue;
const name = cleanName(item.name);
if (!name || !isObject(item.layout) || !isObject(item.layout.grid) || !isObject(item.layout.panels)) continue;
const paneThemes = isObject(item.paneThemes) ? Object.fromEntries(Object.entries(item.paneThemes).filter(([, theme]) => typeof theme === 'string' && THEME_ID.test(theme))) as Record<string, string> : {};
items.push({ id: item.id, name, savedAt: typeof item.savedAt === 'string' ? item.savedAt : '', layout: item.layout as SerializedLayout, paneThemes, ...(Array.isArray(item.decks) ? { decks: item.decks } : {}) });
if (items.length >= WORKSPACE_LIMITS.count) break;
}
const fallback = typeof value.default === 'string' && items.some(item => item.id === value.default) ? value.default : null;
return { version: 1, default: fallback, items };
}
/** Adds or replaces (same id) a workspace; the list stays bounded. */
export function upsertWorkspace(store: WorkspaceStore, workspace: Workspace): WorkspaceStore {
const exists = store.items.some(item => item.id === workspace.id);
if (!exists && store.items.length >= WORKSPACE_LIMITS.count) throw new Error(t('wb.ws.err.tooMany', { count: WORKSPACE_LIMITS.count }));
const items = exists ? store.items.map(item => (item.id === workspace.id ? workspace : item)) : [...store.items, workspace];
return { ...store, items };
}
export function removeWorkspace(store: WorkspaceStore, id: string): WorkspaceStore {
return { version: 1, default: store.default === id ? null : store.default, items: store.items.filter(item => item.id !== id) };
}
export function renameWorkspace(store: WorkspaceStore, id: string, name: string): WorkspaceStore {
const clean = cleanName(name);
if (!clean) throw new Error('A workspace needs a name.');
return { ...store, items: store.items.map(item => (item.id === id ? { ...item, name: clean } : item)) };
}
export function setDefaultWorkspace(store: WorkspaceStore, id: string | null): WorkspaceStore {
return { ...store, default: id && store.items.some(item => item.id === id) ? id : null };
}

View file

@ -0,0 +1,84 @@
/* Titlebar extras (TitlebarExtras.tsx): workspace menu and the dev/sync chips. Tokens from shell.css.
Their measured width is reserved in the tab strip through --bt-tb-extra. */
.bt-tb-extras { align-self: center; display: flex; align-items: center; gap: 6px; margin-inline-end: 8px; }
.bt-ws-button {
display: inline-flex; align-items: center; gap: 7px; height: 30px; max-width: 170px; padding-block: 0; padding-inline: 8px 10px; box-sizing: border-box;
border: 1px solid var(--bt-line-soft); border-radius: 15px; background: rgb(var(--bt-text-rgb) / .035); color: var(--bt-text-2);
font: 500 12.5px/1 var(--bt-ui); cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease);
}
.bt-ws-button:not(:has(.bt-ws-button-name)) { width: 30px; padding: 0; justify-content: center; }
.bt-ws-button:hover { background: var(--bt-hover); border-color: var(--bt-line-strong); color: var(--bt-text); }
.bt-ws-button[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); color: var(--bt-text); }
.bt-ws-button:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
.bt-ws-button-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--bt-text); }
.bt-ws-glyph { width: 15px; height: 15px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.35; stroke-linejoin: round; }
.bt-ws-menu { width: 330px; max-height: calc(100vh - 64px); overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--bt-line-strong) transparent; }
.bt-ws-head { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px; }
.bt-ws-head strong { font: 600 13px/1.2 var(--bt-ui); color: var(--bt-text); }
.bt-ws-head span { font: 400 12px/1.35 var(--bt-ui); color: var(--bt-muted); }
.bt-ws-empty { margin: 2px 6px 6px; padding: 10px 12px; border-radius: 9px; background: rgb(var(--bt-text-rgb) / .035); color: var(--bt-muted); font: 400 12.5px/1.45 var(--bt-ui); }
.bt-ws-row { position: relative; display: flex; align-items: center; border-radius: 10px; }
.bt-ws-row.is-active { background: rgb(var(--bt-accent-rgb) / .08); box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .22); }
.bt-ws-row.is-active::before { content: ''; position: absolute; inset-inline-start: -5px; top: 10px; height: 22px; width: 3px; border-start-start-radius: 0; border-start-end-radius: 3px; border-end-end-radius: 3px; border-end-start-radius: 0; background: var(--bt-accent); }
.bt-menu .bt-ws-main { flex: 1; min-width: 0; height: auto; flex-direction: column; align-items: flex-start; gap: 4px; padding: 8px 10px; border-radius: 10px; }
.bt-menu .bt-ws-main:focus-visible, .bt-menu .bt-ws-save:focus-visible { box-shadow: var(--bt-ring); }
.bt-ws-name { display: flex; align-items: center; gap: 6px; max-width: 100%; font: 600 13.5px/1.15 var(--bt-ui); color: var(--bt-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bt-ws-meta { font: 400 12px/1.2 var(--bt-ui); color: var(--bt-muted); font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
.bt-ws-badge { flex: none; padding: 2px 6px; border-radius: 999px; background: rgb(var(--bt-accent-rgb) / .14); color: var(--bt-accent-ink); font: 500 10.5px/1.2 var(--bt-ui); }
.bt-ws-actions { display: flex; gap: 1px; padding-inline-end: 4px; opacity: 0; transition: opacity var(--bt-t1) var(--bt-ease); }
.bt-ws-row:hover .bt-ws-actions, .bt-ws-row:focus-within .bt-ws-actions, .bt-ws-row.is-active .bt-ws-actions { opacity: 1; }
.bt-menu .bt-ws-icon { width: 26px; height: 26px; padding: 0; justify-content: center; color: var(--bt-muted); }
.bt-menu .bt-ws-icon .bt-glyph { width: 14px; height: 14px; }
.bt-menu .bt-ws-icon[aria-pressed=true] { color: var(--bt-accent-ink); }
.bt-menu .bt-ws-save { height: auto; gap: 11px; padding: 8px; border-radius: 10px; }
.bt-ws-save-icon { display: grid; place-items: center; width: 30px; height: 30px; flex: none; border-radius: 9px; box-shadow: inset 0 0 0 1px var(--bt-line-strong); color: var(--bt-muted); }
.bt-ws-save-icon .bt-glyph { width: 15px; height: 15px; }
.bt-menu .bt-ws-save:hover .bt-ws-save-icon { box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .6); color: var(--bt-accent-ink); }
.bt-ws-text { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.bt-ws-save .bt-ws-name { font-weight: 500; color: var(--bt-text-2); }
.bt-ws-form { display: flex; gap: 6px; padding: 6px; }
.bt-ws-input {
flex: 1; min-width: 0; height: 30px; padding: 0 10px; box-sizing: border-box; border: 1px solid var(--bt-line-strong); border-radius: 8px;
background: var(--bt-field); color: var(--bt-text); font: 500 13px/1 var(--bt-ui); outline: 0;
}
.bt-ws-input:focus { border-color: rgb(var(--bt-accent-rgb) / .6); box-shadow: 0 0 0 3px rgb(var(--bt-accent-rgb) / .14); }
.bt-menu .bt-ws-primary { height: 30px; padding: 0 12px; background: var(--bt-accent); color: var(--bt-on-accent, #fff); font-weight: 600; }
.bt-menu .bt-ws-primary:hover:not(:disabled) { background: var(--bt-accent); filter: brightness(1.08); }
.bt-menu .bt-ws-primary:disabled { background: var(--bt-hover); color: var(--bt-faint); }
.bt-ws-confirm {
display: flex; flex-direction: column; gap: 10px; margin: 2px 6px 6px; padding: 10px 12px; border-radius: 9px;
background: rgba(229, 72, 77, .08); box-shadow: inset 0 0 0 1px rgba(229, 72, 77, .25); color: var(--bt-text-2); font: 400 12.5px/1.45 var(--bt-ui);
}
.bt-ws-confirm strong { color: var(--bt-text); font-weight: 600; }
.bt-ws-confirm div { display: flex; gap: 6px; }
.bt-menu .bt-ws-confirm button { height: 28px; padding: 0 12px; font-weight: 600; font-size: 12.5px; }
.bt-menu .bt-ws-danger { background: var(--bt-danger); color: #fff; }
.bt-menu .bt-ws-danger:hover:not(:disabled) { background: #d93d42; }
.bt-menu .bt-ws-cancel { background: var(--bt-hover); }
.bt-ws-error { padding: 6px 10px; color: #ff8a80; font: 12px/1.4 var(--bt-ui); }
/* Quiet chips: only while there is something to say. */
.bt-tb-chip {
display: inline-flex; align-items: center; gap: 7px; height: 28px; max-width: 220px; padding-block: 0; padding-inline: 9px 11px; box-sizing: border-box;
border: 1px solid var(--bt-line-soft); border-radius: 14px; background: rgb(var(--bt-text-rgb) / .035); color: var(--bt-text-2);
font: 500 12px/1 var(--bt-ui); white-space: nowrap; cursor: pointer; transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease);
}
.bt-tb-chip:hover { background: var(--bt-hover); border-color: var(--bt-line-strong); color: var(--bt-text); }
.bt-tb-chip:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
.bt-tb-chip-text { overflow: hidden; text-overflow: ellipsis; }
.bt-tb-chip .bt-glyph { width: 14px; height: 14px; color: var(--bt-accent-ink); }
.bt-tb-chip-dot { width: 7px; height: 7px; flex: none; border-radius: 50%; background: #3dd68c; box-shadow: 0 0 0 3px rgba(61, 214, 140, .14); }
.bt-dev-chip { font-family: var(--bt-mono); font-size: 11.5px; }
.bt-dev-chip.is-fresh .bt-tb-chip-dot { animation: bt-dev-pulse 1s var(--bt-ease-out) 2; }
@keyframes bt-dev-pulse { 50% { box-shadow: 0 0 0 6px rgba(61, 214, 140, .22); } }
.bt-dev-chip.is-error { border-color: rgba(229, 72, 77, .38); background: rgba(229, 72, 77, .09); color: #ffb4ab; }
.bt-dev-chip.is-error .bt-tb-chip-dot { background: var(--bt-danger); box-shadow: 0 0 0 3px rgba(229, 72, 77, .18); }
.bt-sync-chip { border-color: rgb(var(--bt-accent-rgb) / .35); background: rgb(var(--bt-accent-rgb) / .08); color: var(--bt-text); }

View file

@ -0,0 +1,107 @@
// Workspaces in the shell: the saved list (native `workspaces_get` / `workspaces_set`), saving the
// live layout, restoring one with one click (Ctrl+K, the titlebar menu, the default on start).
// The pure part (capture, restore plan, bounds) is workspaceModel.ts.
import type { SerializedDockview } from 'dockview';
import { invoke } from './bridge.ts';
import { decks, ensureDecks } from './deckStore.ts';
import { t } from './i18n.ts';
import { site } from './site.ts';
import { newTabId, panelId, patchParams, saveLayoutSoon, scheduleSync, shell, type TabParams } from './state.ts';
import {
EMPTY_WORKSPACES, captureWorkspace, normalizeWorkspaces, planRestore, removeWorkspace, renameWorkspace, setDefaultWorkspace,
upsertWorkspace, workspaceId, workspaceTabs, type Workspace, type WorkspaceStore,
} from './workspaceModel.ts';
const ACTIVE_KEY = 'bt.shell.workspace.active';
export const workspaces = {
store: EMPTY_WORKSPACES as WorkspaceStore,
/** The workspace restored or saved last (the titlebar shows its name). */
active: (() => { try { return localStorage.getItem(ACTIVE_KEY); } catch { return null; } })() as string | null,
loaded: false,
};
const emit = () => window.dispatchEvent(new CustomEvent('bt-workspaces'));
const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^VALIDATION: /, '');
function setActive(id: string | null) {
workspaces.active = id;
try { if (id) localStorage.setItem(ACTIVE_KEY, id); else localStorage.removeItem(ACTIVE_KEY); } catch { /* best effort */ }
}
export async function loadWorkspaces(): Promise<WorkspaceStore> {
try { workspaces.store = normalizeWorkspaces(await invoke('workspaces_get')); } catch { workspaces.store = EMPTY_WORKSPACES; }
if (workspaces.active && !workspaces.store.items.some(item => item.id === workspaces.active)) setActive(null);
workspaces.loaded = true;
emit();
return workspaces.store;
}
async function persist(next: WorkspaceStore) {
try { workspaces.store = normalizeWorkspaces(await invoke('workspaces_set', { store: next })); }
catch (error) { throw new Error(errorText(error)); }
if (workspaces.active && !workspaces.store.items.some(item => item.id === workspaces.active)) setActive(null);
emit();
}
/** Pane themes of the open layout (none without themes). */
const paneThemes = () => site().themes?.themeState().scopes.panes ?? {};
/** Saves the live layout as `name` (a new workspace, or over `replaceId`). */
export async function saveCurrentWorkspace(name: string, replaceId?: string): Promise<Workspace> {
const api = shell.api;
if (!api) throw new Error(t('wb.ws.notReady'));
const id = replaceId ?? workspaceId(name, workspaces.store.items.map(item => item.id));
const workspace = captureWorkspace({
id, name, layout: api.toJSON(), paneThemes: paneThemes(),
decks: decks.list,
});
await persist(upsertWorkspace(workspaces.store, workspace));
setActive(id);
emit();
return workspace;
}
/** Replaces every tab with workspace `id`'s tabs, splits and pane themes. */
export async function restoreWorkspace(id: string): Promise<void> {
const api = shell.api;
const workspace = workspaces.store.items.find(item => item.id === id);
if (!api || !workspace) return;
if (workspace.decks?.length) ensureDecks(workspace.decks);
const known = new Set(shell.profiles.profiles.map(profile => profile.id));
const plan = planRestore(workspace, newTabId, profile => known.has(profile));
// The tabs of the layout being left can come back with Ctrl+Shift+T.
for (const panel of api.panels) {
const params = panel.params as TabParams | undefined;
if (params?.kind === 'web') shell.closed.push({ url: params.url, profile: params.profile, title: panel.api.title || undefined });
}
shell.restoring = true;
try {
api.fromJSON(plan.layout as unknown as SerializedDockview);
api.getPanel(panelId())?.api.setTitle(site().panel.title);
for (const panel of api.panels) if ((panel.params as TabParams).kind === 'web') patchParams(panel, { loading: false });
} finally {
shell.restoring = false;
}
setActive(id);
emit();
scheduleSync();
saveLayoutSoon();
// Pane themes follow the new tab ids; panes of the layout left behind are dropped.
const themes = site().themes;
if (!themes) return;
const open = new Set(api.panels.map(panel => panel.id));
const kept = Object.fromEntries(Object.entries(themes.themeState().scopes.panes).filter(([tab]) => open.has(tab)));
const panes = { ...kept, ...plan.paneThemes };
try { await themes.setScopes({ ...themes.themeState().scopes, panes }); } catch { /* the layout is restored either way */ }
}
export const renameSavedWorkspace = (id: string, name: string) => persist(renameWorkspace(workspaces.store, id, name));
export const deleteWorkspace = (id: string) => persist(removeWorkspace(workspaces.store, id));
export const setStartWorkspace = (id: string | null) => persist(setDefaultWorkspace(workspaces.store, id));
/** Palette/menu view: names and tab counts. */
export function workspaceList() {
return workspaces.store.items.map(item => ({ id: item.id, name: item.name, tabs: workspaceTabs(item).length, isDefault: workspaces.store.default === item.id }));
}

View file

@ -55,3 +55,27 @@ export function withNavRedundant<T extends PaneBox>(boxes: readonly T[], isSiteU
for (const id of memory.keys()) if (!boxes.some(box => box.id === id)) memory.delete(id); for (const id of memory.keys()) if (!boxes.some(box => box.id === id)) memory.delete(id);
return items; return items;
} }
/**
* A tab webview's `visible`/`parked` for `tabs_sync`. `shown`: its pane is on screen in the shell;
* `overlay`: shell overlays open (menus, dialogs, palette, drags); `raiseSupported`: the shell can
* be raised above the tab webviews for them (`shell_raise`), so panes stay visible under
* the overlay. Where it cannot, an overlay hides every tab (the shell would draw under them). An
* overlay never parks (drops to low memory) a tab: only a pane that is not shown is parked.
*/
export function paneVisibility(pane: { shown: boolean; overlay: number; raiseSupported: boolean }): { visible: boolean; parked: boolean } {
return { visible: pane.shown && (pane.raiseSupported || pane.overlay === 0), parked: !pane.shown };
}
/** `shell_raise`'s startup probe (`probe`: its answer) unless the developer switch turned raising off. */
export function raiseSupported(probe: unknown, devOff: boolean): boolean {
return probe === true && !devOff;
}
/** `[r, g, b]` of a computed CSS color (`rgb(...)`/`rgba(...)`), or null (unparsable or fully transparent). */
export function cssRgb(color: string): [number, number, number] | null {
const parts = /^rgba?\(([^)]+)\)$/.exec(color.trim())?.[1]?.split(/[\s,/]+/).filter(Boolean).map(Number);
if (!parts || parts.length < 3 || parts.slice(0, 3).some(n => !Number.isFinite(n))) return null;
if (parts.length > 3 && parts[3] === 0) return null;
return [0, 1, 2].map(i => Math.max(0, Math.min(255, Math.round(parts[i]!)))) as [number, number, number];
}

View file

@ -0,0 +1,148 @@
// The shell frame's pure parts: its words (every key it uses has English and every English key is
// used), the palette's ordering with a site's items, the address fallback, the one-in-flight layout
// sync, the first-frame script, the chrome variables, the account switcher's rules, workspaces and
// the deck settings with a site's flags.
import assert from 'node:assert/strict';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { accountAction, accountStartUrl, tabsByAccount, type PaneInfo } from '../src/frame/accountModel.ts';
import { BOOT_CACHE_KEY, bootScript } from '../src/frame/boot.ts';
import { CHROME_VAR_NAMES, chromeVars } from '../src/frame/chromeTheme.ts';
import { defaultDeckSettings, normalizeDeckSettings } from '../src/frame/deckStore.ts';
import { FRAME_MESSAGES } from '../src/frame/frameMessages.ts';
import { attachTarget } from '../src/frame/mediaModel.ts';
import { buildItems, type PaletteContext } from '../src/frame/paletteModel.ts';
import { toUrl } from '../src/frame/searchInput.ts';
import { configureSite, type ShellSite } from '../src/frame/site.ts';
import { latestOnly } from '../src/frame/syncGate.ts';
import { captureWorkspace, planRestore } from '../src/frame/workspaceModel.ts';
import { normalizeProfiles } from '../src/profileModel.ts';
const here = dirname(fileURLToPath(import.meta.url));
const FRAME = join(here, '../src/frame');
const files = (dir: string): string[] => readdirSync(dir).flatMap(name => {
const path = join(dir, name);
return statSync(path).isDirectory() ? files(path) : [path];
});
test('every key the frame uses has English, and every English key is used', () => {
const sources = files(FRAME).filter(file => /\.tsx?$/.test(file) && !file.endsWith('frameMessages.ts')).map(file => readFileSync(file, 'utf8')).join('\n');
const used = new Set([...sources.matchAll(/'(wb\.[A-Za-z0-9_.]+)'/g)].map(match => match[1]!));
const en = JSON.parse(readFileSync(join(here, '../../waybetter/locales/en.json'), 'utf8')).messages as Record<string, string>;
for (const key of used) assert.ok(key in en, `${key} is in the framework catalog`);
// `wb.backup.section.<id>` is built at runtime (backupModel.sectionLabel).
for (const key of Object.keys(FRAME_MESSAGES)) assert.ok(used.has(key) || key.startsWith('wb.backup.section.'), `${key} is used`);
});
const site = {
name: 'Example', product: 'wayBetter for Example', logo: '', homeUrl: 'https://example.com/home', loginUrl: 'https://example.com/login', logoutUrl: 'https://example.com/logout',
isSiteUrl: (url: string) => url.startsWith('https://example.com/'),
accounts: { handle: /^\w{1,15}$/, avatarPrefixes: [], handlePrefix: '@' },
searchUrl: (text: string) => `https://example.com/search?q=${encodeURIComponent(text)}`,
address: () => null,
panel: { id: 'app', title: 'App', component: () => null },
newTab: { search: () => 'Search', links: [] },
palette: {
placeholder: () => 'Search',
search: text => ({ id: 'search', group: 'Search', label: `Search for ${text}`, action: { type: 'open', url: `https://example.com/search?q=${text}` } }),
completions: text => (text.endsWith(':') ? [{ id: 'op:from:', group: 'Operators', label: 'from:', action: { type: 'complete', text: `${text}someone` } }] : []),
sections: [{ id: 'themes', label: () => 'Themes', keywords: 'colors', icon: 'palette' }],
items: () => [{ id: 'page:/home', group: 'Example', label: 'Home', keywords: 'feed', action: { type: 'open', url: 'https://example.com/home' } }],
},
deck: {
kinds: [{ kind: 'home', label: 'Home', icon: 'home', hint: '' }], urlFor: () => 'https://example.com/home', title: () => ({ title: 'Home' }),
parseValue: () => '', invalid: () => '', flags: [{ key: 'quiet', label: 'Quiet', hint: '' }], extraFlags: ['hidden'], defaultFlags: { quiet: true },
},
} satisfies ShellSite;
configureSite(site);
const context: PaletteContext = {
tabs: [{ id: 't1', title: 'Home', url: 'https://example.com/home' }],
profiles: [{ id: 'default', name: 'Main' }],
activeProfile: 'default',
decks: [],
};
const setup = { site: site.palette, product: site.product, decks: true, media: false };
test('palette: frame groups, then the app, plugins and the site; the literal search stays last', () => {
const empty = buildItems(context, '', setup);
assert.deepEqual([...new Set(empty.map(item => item.group))], ['Tabs', 'Deck', 'Workspaces', 'Profiles', 'wayBetter for Example', 'Example']);
assert.ok(!empty.some(item => item.id === 'media'), 'no media item without a media panel');
const typed = buildItems(context, 'hom', setup);
assert.equal(typed.at(-1)?.id, 'search');
assert.equal(typed.filter(item => item.id === 'search').length, 1);
assert.equal(buildItems(context, 'x from:', setup)[0]?.id, 'op:from:', 'completions come first');
assert.ok(!buildItems(context, '', { ...setup, decks: false }).some(item => item.group === 'Deck'));
});
test('address text: URLs, bare domains, else the site search', () => {
assert.equal(toUrl(' https://a.dev/x ', site.searchUrl), 'https://a.dev/x');
assert.equal(toUrl('a.dev/x', site.searchUrl), 'https://a.dev/x');
assert.equal(toUrl('two words', site.searchUrl), 'https://example.com/search?q=two%20words');
});
test('layout sync: one send in flight, only the newest waits', async () => {
const sent: number[] = [];
let release!: () => void;
const send = latestOnly<number>(async value => { sent.push(value); if (value === 1) await new Promise<void>(resolve => { release = resolve; }); });
const first = send(1);
void send(2);
const third = send(3);
release();
await Promise.all([first, third]);
assert.deepEqual(sent, [1, 3]);
});
test('boot script: paints only the shell webview, only --wb-* variables', () => {
const source = bootScript();
assert.doesNotThrow(() => new Function(source));
assert.ok(source.includes(JSON.stringify(BOOT_CACHE_KEY)));
assert.ok(source.includes("label !== \"shell\""));
assert.ok(bootScript({ label: 'main' }).includes("label !== \"main\""));
});
test('chrome variables: none for the own style, fonts only without colors, every name listed', () => {
assert.deepEqual(chromeVars({ colors: null }, true), {});
assert.deepEqual(chromeVars({ chromeFont: 'Inter', colors: null }), { '--wb-f-chrome': 'Inter' });
const vars = chromeVars({ colors: { bg: '#ffffff', surface: '#f4f4f4', elevated: '#eeeeee', border: '#dddddd', text: '#111111', muted: '#666666', accent: '#1d9bf0' } });
assert.equal(vars['--wb-c-scheme'], 'light');
for (const name of Object.keys(vars)) assert.ok(CHROME_VAR_NAMES.includes(name), name);
});
test('account switcher: a visible pane on the site first, else the feed or sign-in beside', () => {
const settings = normalizeProfiles({ active: 'default', profiles: [
{ id: 'default', name: 'Main', color: '#1d9bf0', account: { handle: 'me', name: 'Me', signedIn: true } },
{ id: 'pnew1', name: 'New', color: '#f91880' },
] }, site.accounts);
const panes: PaneInfo[] = [
{ id: 'a', kind: 'web', profile: 'default', url: 'https://other.dev/', visible: true },
{ id: 'b', kind: 'web', profile: 'default', url: 'https://example.com/home', visible: true },
];
const pages = { homeUrl: site.homeUrl, loginUrl: site.loginUrl, isSiteUrl: site.isSiteUrl };
assert.deepEqual(accountAction(settings, panes, null, 'default', pages), { type: 'focus', paneId: 'b' });
assert.deepEqual(accountAction(settings, panes, null, 'pnew1', pages), { type: 'open', url: site.loginUrl, profile: 'pnew1', where: 'beside' });
assert.equal(accountStartUrl(settings.profiles[0]!, pages), site.homeUrl);
assert.deepEqual([...tabsByAccount(settings, panes).keys()], ['default']);
assert.equal(attachTarget([{ id: 'a', url: 'https://other.dev/' }, { id: 'b', url: 'https://example.com/x' }], 'a', site.isSiteUrl)?.id, 'b');
});
test('workspaces: web tabs get fresh ids on restore, the app panel keeps its own', () => {
const layout = {
grid: { root: { type: 'branch', data: [{ type: 'leaf', data: { views: ['w1', 'app'], activeView: 'w1', id: '1' }, size: 100 }], size: 100 }, width: 100, height: 100, orientation: 'HORIZONTAL' },
panels: {
w1: { id: 'w1', contentComponent: 'web', params: { kind: 'web', url: 'https://example.com/home', loading: true } },
app: { id: 'app', contentComponent: 'panel', params: { kind: 'panel', section: 'themes', nonce: 4 } },
},
};
const workspace = captureWorkspace({ id: 'one', name: 'One', layout });
assert.deepEqual(workspace.layout.panels.w1?.params, { kind: 'web', url: 'https://example.com/home' });
const plan = planRestore(workspace, () => 'fresh');
assert.deepEqual(Object.keys(plan.layout.panels).sort(), ['app', 'fresh']);
});
test('deck settings: the site\'s default flags; unknown flags are dropped', () => {
assert.deepEqual(defaultDeckSettings().flags, { quiet: true });
assert.deepEqual(normalizeDeckSettings({ flags: { quiet: false, hidden: true, other: true } }).flags, { quiet: false, hidden: true });
});

View file

@ -1,9 +1,9 @@
{ {
"name": "waybetter", "name": "waybetter",
"version": "0.3.0", "version": "0.4.0",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"type": "module", "type": "module",
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command, `waybetter release windows|macos` (signed native releases and the update manifest, configured by waybetter.release.json) and `waybetter/build` (the page runtime bundle, with an optional esbuild peer). No dependencies.", "description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates), the shell frame (createShell: tabs, splits, address bar, titlebar, palette, account switcher, decks, workspaces, overlays; React + dockview peers) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command, `waybetter release windows|macos` (signed native releases and the update manifest, configured by waybetter.release.json) and `waybetter/build` (the page runtime bundle, with an optional esbuild peer). No dependencies.",
"keywords": [ "keywords": [
"waybetter", "waybetter",
"tauri", "tauri",
@ -160,6 +160,15 @@
"import": "./dist/shell/StoreView.js" "import": "./dist/shell/StoreView.js"
}, },
"./shell/store.css": "./dist/shell/store.css", "./shell/store.css": "./dist/shell/store.css",
"./shell/frame": {
"types": "./dist/shell/frame/index.d.ts",
"import": "./dist/shell/frame/index.js"
},
"./shell/frame/*.css": "./dist/shell/frame/*.css",
"./shell/frame/*": {
"types": "./dist/shell/frame/*.d.ts",
"import": "./dist/shell/frame/*.js"
},
"./shell/*": { "./shell/*": {
"types": "./dist/shell/*.d.ts", "types": "./dist/shell/*.d.ts",
"import": "./dist/shell/*.js" "import": "./dist/shell/*.js"
@ -190,7 +199,9 @@
"peerDependencies": { "peerDependencies": {
"esbuild": ">=0.20.0", "esbuild": ">=0.20.0",
"react": ">=18.0.0", "react": ">=18.0.0",
"react-dom": ">=18.0.0" "react-dom": ">=18.0.0",
"dockview": ">=4.0.0",
"acorn": ">=8.0.0"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"esbuild": { "esbuild": {
@ -201,13 +212,19 @@
}, },
"react-dom": { "react-dom": {
"optional": true "optional": true
},
"dockview": {
"optional": true
},
"acorn": {
"optional": true
} }
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
}, },
"scripts": { "scripts": {
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p ../runtime/tsconfig.build.json --outDir dist/runtime --inlineSources --declarationMap false && tsc -p ../shell/tsconfig.build.json --outDir dist/shell --inlineSources --declarationMap false && node -e \"require('fs').copyFileSync('../shell/src/store.css','dist/shell/store.css')\"", "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p ../runtime/tsconfig.build.json --outDir dist/runtime --inlineSources --declarationMap false && tsc -p ../shell/tsconfig.build.json --outDir dist/shell --inlineSources --declarationMap false && node -e \"const fs=require('fs');fs.copyFileSync('../shell/src/store.css','dist/shell/store.css');for(const f of fs.readdirSync('../shell/src/frame'))if(f.endsWith('.css'))fs.copyFileSync('../shell/src/frame/'+f,'dist/shell/frame/'+f)\"",
"test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts packages/waybetter/tests/*.test.mjs", "test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts packages/waybetter/tests/*.test.mjs",
"prepublishOnly": "npm run build && npm test" "prepublishOnly": "npm run build && npm test"
}, },