waybetter/packages/shell/src/panel/Panel.tsx
CRT ad2a3ad375 shell: the panel, createPanel(site) (moved from wayBetter for X)
packages/shell/src/panel (waybetter/shell/panel): an app's own tab. An app describes itself
(PanelSite: brand and the home page's words, its own sections and their order, its theme store,
catalog and the preview component a theme document is drawn in, Make's examples and docs, the
install controller, its languages, what its native side serves) and createPanel returns the
component for ShellSite.panel. It is in the shell package because it is drawn in the frame and
shares its stores, native bridge and language.

- Panel.tsx (header, settings search over every settings section, navigation, toasts; Accounts
  and Updates), nav.ts (which built-in sections an app gets: each shows only when the app serves
  what it needs; the app's sections in its order), Home.tsx (hero, highlights, About from the
  app's data), controls.tsx + panel.css.
- Appearance.tsx, ThemeBuilder.tsx + builderModel.ts + builder.css, fonts/ (FontBrowser, FontRoles,
  catalog, the offline Google Fonts list; scripts/google-fonts-catalog.mjs regenerates it):
  the theme documents are the runtime's, the store, catalog, accents, draft palette, file suffix
  and preview are the app's (PanelSite.themes).
- Plugins.tsx (the plugins list and custom CSS over the host's plugins_*/custom_css_*),
  StoreSection.tsx, MakePanel.tsx + makeModel.ts + MarkdownDoc.tsx + markdown.ts + make.css (the
  examples, the theme file and the docs are the app's), Settings.tsx (links and session over
  settings_get/set with `siteLinks`, keyword alerts, the media panel), FeatureToggles.tsx
  (useFeatures + FeatureGroups over features_get/set: the app names its flags and groups),
  PowerSettings.tsx (deck defaults from site.deck: its flags and presets; DeckPreset gets `name`
  and `hint`), BackupPanel.tsx + backup.css, DeveloperPanel.tsx, LanguageSettings.tsx, compare.ts.
- frame: language.ts (createLanguage: follow the site / the system / one language, i18n_set;
  moved from the app), appI18n.ts (createAppI18n: the app's typed i18n instance, useT, dates and
  numbers; the app passes React's useSyncExternalStore), formatDate in i18n.ts (ShellI18n.date).
- tests/panel.test.ts: every panel key has English and is used, sections per app, the builder
  model, the font catalog, plugin header rules, the UI kit demos, Markdown, compare.
- npm package: exports ./shell/panel, ./shell/panel/*, ./shell/panel/*.css; the build is
  scripts/build.mjs (the shell is compiled with the runtime sources it imports under one root and
  its imports are pointed at dist/runtime; stylesheets and the font list are copied).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:03:40 +07:00

209 lines
12 KiB
TypeScript

// The app's panel: a dockview tab in the shell, laid out for a narrow split pane beside the site
// first (tab strip) and a side rail from 720px. Night Ink, like the shell chrome. Every control
// changes the site live through native commands. A settings search filters every settings section
// at once. The framework brings the sections every app has; the app adds its own (`PanelSite`).
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { DEFAULT_PROFILE } from '../profileModel.ts';
import { setDefaultAccount } from '../frame/accountModel.ts';
import { AccountAvatar, accountLabel, addAccount, openTabs, removeAccount, saveProfiles, signIn, useProfiles } from '../frame/AccountSwitcher.tsx';
import { invoke } from '../frame/bridge.ts';
import { useT, useUpdateStatus } from '../frame/hooks.ts';
import { site } from '../frame/site.ts';
import { shell } from '../frame/state.ts';
import { Appearance } from './Appearance.tsx';
import { BackupPanel } from './BackupPanel.tsx';
import { Button, EmptyState, SearchField, SearchProvider } from './controls.tsx';
import { DeveloperPanel } from './DeveloperPanel.tsx';
import { Home } from './Home.tsx';
import { LanguageSettings } from './LanguageSettings.tsx';
import { MakePanel } from './MakePanel.tsx';
import { navEntries } from './nav.ts';
import { NavIcon } from './NavIcon.tsx';
import { ScriptPlugins } from './Plugins.tsx';
import { PowerSettings } from './PowerSettings.tsx';
import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx';
import { panelSite, type Notify, type SectionProps } from './site.ts';
import { StoreSection } from './StoreSection.tsx';
import { ThemeBuilder } from './ThemeBuilder.tsx';
import './panel.css';
const SEARCH_ICON = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="m15 15 5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>;
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
export default function Panel({ section: requested }: { section?: { name: string; nonce: number } }) {
const t = useT();
const panel = panelSite();
const entries = navEntries(panel);
const has = (id: string | undefined) => entries.some(entry => entry.id === id);
const [section, setSection] = useState<string>(has(requested?.name) ? requested!.name : 'home');
const [query, setQuery] = useState('');
const go = (id: string) => { if (has(id)) { setSection(id); setQuery(''); } };
useEffect(() => { if (requested) go(requested.name); }, [requested?.nonce]);
// Sections link to each other (Appearance → Theme Builder).
useEffect(() => {
const onSection = (event: Event) => go((event as CustomEvent<string>).detail);
window.addEventListener('bt-panel-section', onSection);
return () => window.removeEventListener('bt-panel-section', onSection);
}, []);
const [notice, setNotice] = useState<{ id: number; text: string; error: boolean } | null>(null);
const notify: Notify = (text, error = false) => setNotice({ id: Date.now(), text, error });
useEffect(() => {
if (!notice) return;
const timer = setTimeout(() => setNotice(null), notice.error ? 8000 : 3200);
return () => clearTimeout(timer);
}, [notice]);
const body = useRef<HTMLElement>(null);
useEffect(() => { body.current?.scrollTo({ top: 0 }); }, [section]);
const searching = query.trim().length > 0;
const entry = entries.find(item => item.id === section);
const Custom = entry?.component ?? null;
const props: SectionProps = { notify, openSection: go };
return <div className="btp-root"><div className={`btp ${searching ? 'is-searching' : ''}`}>
<header className="btp-head">
<div className="btp-brand"><img src={panel.brand.logo} alt="" width={22} height={22}/><strong>{panel.brand.name}</strong></div>
<SearchField label={t('wb.panel.search.label')} placeholder={t('wb.panel.search.label')} value={query} onChange={setQuery}/>
</header>
<nav className="btp-nav" aria-label={t('wb.panel.nav.label')}>
{entries.map(item => <button key={item.id} className={!searching && section === item.id ? 'is-on' : ''} aria-current={!searching && section === item.id ? 'page' : undefined}
onClick={() => go(item.id)}><NavIcon d={item.icon}/><span>{item.label(t)}</span></button>)}
</nav>
<main className="btp-body" ref={body}>
<div className="btp-page">
{searching ? <SearchResults query={query.trim()} {...props} onClear={() => setQuery('')}/> : <>
{section !== 'home' && <h1 className="btp-title">{entry?.label(t) ?? ''}</h1>}
{Custom && <Custom {...props}/>}
{!Custom && section === 'home' && <Home go={go}/>}
{!Custom && section === 'themes' && <Appearance notify={notify}/>}
{!Custom && section === 'builder' && <ThemeBuilder notify={notify}/>}
{!Custom && section === 'plugins' && <ScriptPlugins notify={notify}/>}
{!Custom && section === 'store' && <StoreSection notify={notify}/>}
{!Custom && section === 'make' && <MakePanel {...props}/>}
{!Custom && section === 'accounts' && <Accounts/>}
{!Custom && section === 'updates' && <Updates/>}
{!Custom && section === 'power' && <PowerSettings notify={notify}/>}
{!Custom && section === 'settings' && <SettingsSection {...props}/>}
{!Custom && section === 'backup' && <BackupPanel notify={notify}/>}
{!Custom && section === 'developer' && <DeveloperPanel notify={notify}/>}
</>}
</div>
</main>
{notice && <div key={notice.id} className={`btp-toast ${notice.error ? 'is-error' : ''}`} role={notice.error ? 'alert' : 'status'} onClick={() => setNotice(null)}>{notice.text}</div>}
</div></div>;
}
/** Settings: the language, links and session, then what the app serves (alerts, the media panel) and adds. */
function SettingsSection(props: SectionProps) {
const panel = panelSite();
return <>
{panel.languages && <LanguageSettings/>}
<BrowserSettings notify={props.notify}/>
{panel.settings?.alerts && <AlertSettings notify={props.notify}/>}
{site().media && <MediaSettingsRows notify={props.notify}/>}
{(panel.settings?.extra ?? []).map((Extra, index) => <Extra key={index} {...props}/>)}
</>;
}
/** Every settings section at once, each row filtered by the query; an empty state when nothing matches. */
function SearchResults({ query, notify, openSection, onClear }: SectionProps & { query: string; onClear(): void }) {
const t = useT();
const panel = panelSite();
const root = useRef<HTMLDivElement>(null);
const [count, setCount] = useState<number | null>(null);
useLayoutEffect(() => {
const measure = () => setCount(root.current?.querySelectorAll('.bt-row').length ?? 0);
measure();
// Sections load their values asynchronously; count again once they have rendered.
const timer = setTimeout(measure, 250);
return () => clearTimeout(timer);
});
const props: SectionProps = { notify, openSection };
return <SearchProvider value={query}>
<h1 className="btp-title">{t('wb.panel.search.results')} <span className="btp-title-sub">{t('wb.panel.search.for', { query })}</span></h1>
<div ref={root} className="btp-results">
{panel.languages && <LanguageSettings/>}
{panel.themes && <Appearance notify={notify}/>}
{(panel.sections ?? []).filter(section => section.searchable).map(section => <section.component key={section.id} {...props}/>)}
<ScriptPlugins notify={notify}/>
<BrowserSettings notify={notify}/>
{site().deck && <PowerSettings notify={notify}/>}
{panel.settings?.alerts && <AlertSettings notify={notify}/>}
{site().media && <MediaSettingsRows notify={notify}/>}
{(panel.settings?.extra ?? []).map((Extra, index) => <Extra key={index} {...props}/>)}
</div>
{count === 0 && <EmptyState icon={SEARCH_ICON} title={t('wb.panel.search.none')} action={<Button size="sm" onClick={onClear}>{t('wb.ui.search.clear')}</Button>}>
{t('wb.panel.search.noneHint')}
</EmptyState>}
</SearchProvider>;
}
// ---------------------------------------------------------------------------------------------
// Accounts
function Accounts() {
const t = useT();
const settings = useProfiles();
const [confirming, setConfirming] = useState<string | null>(null);
const [error, setError] = useState('');
async function run(action: () => Promise<unknown>) {
setError('');
try { await action(); return true; } catch (failure) { setError(getError(failure)); return false; }
}
return <section className="btp-group">
<div className="btp-group-head"><h2>{t('wb.panel.section.accounts')}</h2><p>{t('wb.panel.accounts.hint')}</p></div>
<div className="btp-list">
{settings.profiles.map(profile => {
const tabs = openTabs(profile.id);
const on = profile.id === settings.active;
const label = accountLabel(profile);
if (confirming === profile.id) return <div key={profile.id} className="btp-alert" role="alertdialog">
{t('wb.panel.accounts.removeConfirm', { name: label.title, tabs })}
<span className="btp-row-actions"><button className="btp-btn is-danger" onClick={() => void run(() => removeAccount(settings, profile.id)).then(ok => ok && setConfirming(null))}>{t('wb.common.remove')}</button><button className="btp-btn" onClick={() => setConfirming(null)}>{t('wb.common.cancel')}</button></span>
</div>;
return <div key={profile.id} className={`btp-account ${on ? 'is-on' : ''}`}>
<AccountAvatar profile={profile} size={32}/>
<button className="btp-account-name" title={label.state === 'signed-in' ? t('wb.panel.accounts.openFeed') : t('wb.panel.accounts.signInBeside')} onClick={() => shell.openAccount(profile.id)}>
<strong>{label.title}</strong><small>{label.detail}{on ? ` · ${t('wb.panel.accounts.newTabsBadge')}` : ''}{tabs ? ` · ${t('wb.panel.accounts.openCount', { count: tabs })}` : ''}</small>
</button>
{label.state !== 'signed-in' && <button className="btp-btn is-primary" onClick={() => signIn(profile.id)}>{t('wb.panel.accounts.signIn')}</button>}
<button className="btp-btn" aria-pressed={on} disabled={on} title={t('wb.panel.accounts.newTabsTitle')} onClick={() => void run(() => saveProfiles(setDefaultAccount(settings, profile.id)))}>{on ? t('wb.panel.accounts.newTabsHere') : t('wb.panel.accounts.useForNewTabs')}</button>
{profile.id !== DEFAULT_PROFILE && <button className="btp-btn" onClick={() => setConfirming(profile.id)}>{t('wb.common.remove')}</button>}
</div>;
})}
<button className="btp-link" onClick={() => void run(() => addAccount(settings))}>{t('wb.panel.accounts.add')}</button>
</div>
{error && <div className="btp-alert" role="alert">{error}</div>}
</section>;
}
// ---------------------------------------------------------------------------------------------
// Updates
const UPDATE_TEXT = {
idle: 'wb.panel.updates.idle',
checking: 'wb.panel.updates.checking',
upToDate: 'wb.panel.updates.upToDate',
downloading: 'wb.panel.updates.downloading',
installing: 'wb.panel.updates.installing',
ready: 'wb.panel.updates.ready',
error: 'wb.panel.updates.error',
problem: 'wb.panel.updates.problem',
} as const;
function Updates() {
const t = useT();
const [status, apply] = useUpdateStatus();
return <section className="btp-group">
<div className="btp-group-head"><h2>{t('wb.panel.section.updates')}</h2><p>{t('wb.panel.updates.hint')}</p></div>
<div className="btp-card">
<div><strong>{t(UPDATE_TEXT[status.state])}</strong>
{'version' in status && status.version && <small>{t('wb.panel.updates.version', { version: status.version })}</small>}
{status.state === 'error' && <small>{status.message}</small>}
{status.state === 'ready' && status.notes && <p className="btp-notes">{status.notes}</p>}
</div>
{status.state === 'ready' && <button className="btp-btn is-primary" onClick={apply}>{t('wb.panel.updates.restart')}</button>}
{status.state === 'problem' && <button className="btp-btn" onClick={() => invoke('open_external_url', { url: status.downloadUrl }).catch(() => {})}>{t('wb.panel.updates.download')}</button>}
</div>
</section>;
}