waybetter/packages/shell/src/StoreView.tsx
CRT 74e06e5e15 shell: the Store view and install screen as framework React components, strings in the framework catalogs
Moved from wayBetter for X so every wayBetter app gets the Store UI; the app passes its native
bridge, theme adapter, translator and (optionally) its own controls and button classes.

- storeModel.ts: wire types of the native store commands (InstallPreview, StoreCatalogView,
  LinkEvent, StoreItem with `apps`), permission badges in the site's words, categories, item state
  (install/installed/update/changed locally/built in), search, free theme ids, versions, previews.
- installController.ts: the install screen's state machine (links incl. those queued before the
  shell listened, dropped files, store items, cancel, confirm), generic over the app's theme format
  (`ThemeAdapter`: parse, ids, facts, save) and its bridge (`StoreBackend`: invoke/listen).
- InstallDialog.tsx (`InstallHost`): the screen (Install enabled after 1 s, Enter never installs,
  tabs hidden via setOverlay) and the window-wide drop target. StoreView.tsx: search, kinds,
  categories, cards, permission badges, install/update/remove; default controls or the app's.
- store.css: both, themed with framework `--wb-*` tokens (documented; dark defaults).
- storeMessages.ts + every framework catalog: 120 `wb.store.*`, `wb.install.*`, `wb.permission.*`
  messages moved from the app catalogs with all existing translations; the six that named X take
  `{site}`; generic words the components need copied with their translations.
- npm package: exports for the new modules and store.css, optional react/react-dom peers; @types
  for the typecheck. Tests: models, controller flows with a fake bridge, every looked-up key exists.
2026-09-29 04:08:04 +00:00

179 lines
13 KiB
TypeScript

// The wayBetter Store view, shared by every wayBetter app: themes and plugins from the signed
// catalog (native code verifies its Ed25519 signature, keeps this app's items, then checks each
// download's sha256). Search, kinds, categories, cards with previews and permission badges, and
// Install / Update / Remove. Installing always goes through the install screen (InstallHost), never
// straight from here. Styles: `store.css` (framework `--wb-*` tokens). The app may pass its own
// controls (buttons, search field, segmented control) so the view matches its settings.
import { useEffect, useMemo, useState, useSyncExternalStore, type ReactNode } from 'react';
import type { InstallController } from './installController.ts';
import type { StoreText } from './storeMessages.ts';
import { categoryLabel, errorText, filterItems, itemState, permissionBadges, type ItemState, type StoreCatalogView, type StoreItem } from './storeModel.ts';
type ButtonProps = { children: ReactNode; onClick?(): void; tone?: 'plain' | 'primary' | 'ghost' | 'danger'; size?: 'sm' | 'md'; disabled?: boolean; title?: string };
type Option<T extends string> = { value: T; label: string };
export type StoreControls = {
Button(props: ButtonProps): ReactNode;
SearchField(props: { value: string; onChange(next: string): void; placeholder: string; label: string }): ReactNode;
Segmented<T extends string>(props: { value: T; options: Array<Option<T>>; onChange(next: T): void; label: string; size?: 'sm' | 'md' }): ReactNode;
EmptyState(props: { icon?: ReactNode; title: string; children?: ReactNode; action?: ReactNode }): ReactNode;
Badge(props: { children: ReactNode }): ReactNode;
};
export const DEFAULT_CONTROLS: StoreControls = {
Button: ({ children, onClick, tone = 'plain', size = 'md', disabled, title }) =>
<button type="button" className={`wb-btn is-${tone} is-${size}`} disabled={disabled} title={title} onClick={onClick}>{children}</button>,
SearchField: ({ value, onChange, placeholder, label }) =>
<input className="wb-field" type="search" aria-label={label} placeholder={placeholder} value={value}
onChange={event => onChange(event.target.value)} onKeyDown={event => { if (event.key === 'Escape' && value) { event.stopPropagation(); onChange(''); } }}/>,
Segmented: ({ value, options, onChange, label }) =>
<div className="wb-segmented" role="radiogroup" aria-label={label}>
{options.map(option => <button key={option.value} type="button" role="radio" aria-checked={option.value === value} className={option.value === value ? 'is-on' : ''} onClick={() => onChange(option.value)}>{option.label}</button>)}
</div>,
EmptyState: ({ icon, title, children, action }) =>
<div className="wb-empty">{icon && <div aria-hidden="true">{icon}</div>}<strong>{title}</strong>{children && <p>{children}</p>}{action}</div>,
Badge: ({ children }) => <span className="wb-badge">{children}</span>,
};
export type StoreViewProps<Theme> = {
t: StoreText;
/** The site's name in messages ("X"). */
site: string;
/** `store_catalog` (the app passes `refresh => invoke('store_catalog', { refresh })`). */
load(refresh: boolean): Promise<StoreCatalogView>;
/** The install screen's controller: Install opens it; the list refreshes when it closes. */
controller: InstallController<Theme>;
/** Theme ids that ship with the app, and the owner's own theme ids now. */
builtinThemes: readonly string[];
userThemes: readonly string[];
/** Removes an installed item (plugin file, or the owner's copy of a store theme); false: nothing to remove. */
onRemove(item: StoreItem, view: StoreCatalogView): Promise<boolean>;
/** Makes a built-in theme the current one. */
onUse(item: StoreItem): Promise<void>;
notify(text: string, error?: boolean): void;
/** "3 minutes ago" for a timestamp (the app's relative-time formatter). */
relativeTime(at: number): string;
/** Window events after which the list reloads (e.g. the app's "plugins changed"). */
reloadOn?: readonly string[];
controls?: Partial<StoreControls>;
};
const STORE_ICON = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9l1.5-5h13L20 9M4 9h16v11H4zM4 9a2.7 2.7 0 0 0 5.3 0 2.7 2.7 0 0 0 5.4 0 2.7 2.7 0 0 0 5.3 0M10 20v-5h4v5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"/></svg>;
function Preview({ item }: { item: StoreItem }) {
const [broken, setBroken] = useState(false);
const c = item.colors;
if (item.preview && !broken) return <img className="wbs-img" src={item.preview} alt="" loading="lazy" onError={() => setBroken(true)}/>;
// Offline or not published yet: swatches from the signed catalog (themes) or a plain tile.
return <div className="wbs-img wbs-swatch" style={c ? { background: c.bg } : undefined} aria-hidden="true">
{c ? <><span style={{ background: c.surface ?? c.bg, borderColor: c.text }}/><i style={{ background: c.text }}/><b style={{ background: c.accent }}/></> : <strong>{item.name.slice(0, 1)}</strong>}
</div>;
}
function Action({ item, state, busy, t, ui, onInstall, onRemove, onUse }: { item: StoreItem; state: ItemState; busy: boolean; t: StoreText; ui: StoreControls; onInstall(): void; onRemove(): void; onUse(): void }) {
const { Button } = ui;
const [asking, setAsking] = useState(false);
if (state.state === 'builtin') return <div className="wbs-actions"><span className="wbs-state">{t('wb.store.builtIn')}</span><Button size="sm" onClick={onUse}>{t('wb.store.use')}</Button></div>;
if (state.state === 'install') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.install')}</Button></div>;
const remove = asking
? <><Button size="sm" tone="danger" onClick={() => { setAsking(false); onRemove(); }}>{t('wb.store.remove')}</Button><Button size="sm" tone="ghost" onClick={() => setAsking(false)}>{t('wb.store.keep')}</Button></>
: <Button size="sm" tone="ghost" onClick={() => setAsking(true)}>{t('wb.store.remove')}</Button>;
if (state.state === 'update') return <div className="wbs-actions"><Button size="sm" tone="primary" disabled={busy} onClick={onInstall}>{t('wb.store.updateTo', { version: item.version })}</Button>{remove}</div>;
if (state.state === 'modified') return <div className="wbs-actions"><span className="wbs-state" title={t('wb.store.modifiedTitle')}>{t('wb.store.modified')}</span><Button size="sm" disabled={busy} onClick={onInstall}>{t('wb.store.replace')}</Button>{remove}</div>;
return <div className="wbs-actions"><span className="wbs-state is-ok">{state.version ? t('wb.store.installedVersion', { version: state.version }) : t('wb.store.installed')}</span>{remove}</div>;
}
export function StoreView<Theme>(props: StoreViewProps<Theme>) {
const { t, site, controller, notify } = props;
const ui: StoreControls = { ...DEFAULT_CONTROLS, ...props.controls };
const { Button, SearchField, Segmented, EmptyState, Badge } = ui;
const [view, setView] = useState<StoreCatalogView | null>(null);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState('');
const [kind, setKind] = useState<'all' | 'theme' | 'plugin'>('all');
const [category, setCategory] = useState<string>('all');
const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current);
const load = (refresh: boolean) => {
setLoading(true);
return props.load(refresh).then(setView).catch(error => notify(errorText(error), true)).finally(() => setLoading(false));
};
useEffect(() => { void load(false); }, []);
// Installs finish in the install screen; refresh what is installed afterwards.
useEffect(() => {
const again = () => void load(false);
const events = props.reloadOn ?? [];
for (const name of events) window.addEventListener(name, again);
return () => { for (const name of events) window.removeEventListener(name, again); };
}, [(props.reloadOn ?? []).join(' ')]);
useEffect(() => { if (request === null) void load(false); }, [request === null]);
const items = view?.catalog?.items ?? [];
const context = { plugins: view?.plugins ?? {}, records: view?.records.items ?? {}, builtinThemes: props.builtinThemes, userThemes: props.userThemes };
const categories = useMemo(() => [...new Set(items.filter(item => kind === 'all' || item.kind === kind).map(item => item.category))].sort(), [items, kind]);
const shown = filterItems(items, query, kind, category);
const updates = items.filter(item => itemState(item, context).state === 'update');
const ago = (iso: string | null) => {
if (!iso) return '';
const at = Date.parse(iso);
return Number.isFinite(at) ? props.relativeTime(Math.min(at, Date.now())) : '';
};
async function removeItem(item: StoreItem) {
if (!view) return;
try {
if (!(await props.onRemove(item, view))) return;
notify(t('wb.store.removed', { name: item.name }));
await load(false);
} catch (error) { notify(errorText(error), true); }
}
const status = view?.error
? <span className="wbs-status is-warn" role="status">{view.catalog ? t('wb.store.offline', { when: ago(view.fetchedAt), error: errorText(view.error) }) : t('wb.store.unreachableShort')}</span>
: view?.catalog ? <span className="wbs-status is-ok" role="status"><svg width="13" height="13" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l7 3v5c0 4.6-3 8.5-7 10-4-1.5-7-5.4-7-10V6zM8.5 12l2.5 2.5 4.5-5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>{t('wb.store.verified', { when: ago(view.fetchedAt) })}</span> : null;
return <div className="wbs">
<p className="wbs-intro">{t('wb.store.intro')}</p>
<div className="wbs-toolbar">
<SearchField label={t('wb.store.search')} placeholder={t('wb.store.searchPlaceholder')} value={query} onChange={setQuery}/>
<Segmented label={t('wb.store.kind')} size="sm" value={kind} onChange={next => { setKind(next); setCategory('all'); }} options={[{ value: 'all', label: t('wb.store.all') }, { value: 'theme', label: t('wb.store.themes') }, { value: 'plugin', label: t('wb.store.pluginsTab') }]}/>
<Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button>
</div>
<div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}>
{['all', ...categories].map(id => <button key={id} className={category === id ? 'is-on' : ''} aria-pressed={category === id} onClick={() => setCategory(id)}>{id === 'all' ? t('wb.store.everything') : categoryLabel(id, t)}</button>)}
<span className="wbs-cats-end"/>
{status}
</div>
{updates.length > 0 && <div className="wbs-updates" role="status"><strong>{t('wb.store.updates', { count: updates.length })}</strong><span>{updates.map(item => item.name).join(', ')}</span></div>}
{!view && loading && <div className="wbs-grid" aria-busy="true">{Array.from({ length: 6 }, (_, i) => <div key={i} className="wbs-card is-skeleton"/>)}</div>}
{view && !view.catalog && <EmptyState icon={STORE_ICON} title={t('wb.store.unreachable')} action={<Button size="sm" onClick={() => void load(true)}>{t('wb.store.tryAgain')}</Button>}>
{view.error ? errorText(view.error).replace(/\.?$/, '.') : t('wb.store.noCatalog')} {t('wb.store.nothingChanged')}
</EmptyState>}
{view?.catalog && shown.length === 0 && <EmptyState icon={STORE_ICON} title={t('wb.store.noMatch')}>{t('wb.store.noMatchHint')}</EmptyState>}
<div className="wbs-grid">
{shown.map(item => {
const state = itemState(item, context);
return <article key={`${item.kind}:${item.id}`} className={`wbs-card is-${item.kind}`}>
<Preview item={item}/>
<div className="wbs-card-body">
<header>
<h3>{item.name}</h3>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : t('wb.store.plugin')}</Badge>
</header>
<p className="wbs-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {categoryLabel(item.category, t)}</p>
<p className="wbs-desc">{item.description}</p>
{item.kind === 'plugin' && <ul className="wbs-perms" aria-label={t('wb.store.permissions')}>
{permissionBadges(item.permissions, t, site).map(badge => <li key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</li>)}
</ul>}
<Action item={item} state={state} busy={request !== null} t={t} ui={ui}
onInstall={() => void controller.requestStoreItem(item)}
onRemove={() => void removeItem(item)}
onUse={() => void props.onUse(item).then(() => notify(t('wb.store.themeNow', { name: item.name }))).catch(error => notify(errorText(error), true))}/>
</div>
</article>;
})}
</div>
<p className="wbs-foot">{t('wb.store.foot')}</p>
</div>;
}