waybetter/packages/shell/src/frame/TitlebarExtras.tsx
CRT a078202bd7 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.
2026-09-29 05:47:10 +00:00

214 lines
12 KiB
TypeScript

// 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>;
}