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.
This commit is contained in:
CRTkafa 2026-09-29 04:08:04 +00:00
parent 39ea005bd0
commit 74e06e5e15
63 changed files with 7345 additions and 53 deletions

View file

@ -0,0 +1,275 @@
// The install screen, shared by every wayBetter app: every theme or plugin that is not copied into
// the plugins folder by hand (a waybetter:// link, a dropped file, the Store) is shown here first
// with its name, author, version, where it came from, its sha256, the permissions a plugin declares
// and the exact code or CSS that will be written. Nothing installs until Install is pressed (enabled
// after a moment, so a stray click or Enter cannot confirm it). Lives in the shell; the app hides
// its tab webviews while it is open (`setOverlay`). Styles: `store.css` (framework `--wb-*` tokens).
import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import type { InstallController, InstallRequest } from './installController.ts';
import type { StoreText } from './storeMessages.ts';
import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts';
/** Milliseconds before Install can be pressed (native code refuses a commit faster than 600 ms). */
export const REVIEW_MS = 1000;
const PREVIEW_LINES = 160;
/** Class names for the app's own buttons (defaults: the framework's `.wb-btn`). */
export type InstallClassNames = { primary: string; secondary: string; icon: string; pop: string };
const DEFAULT_CLASSES: InstallClassNames = { primary: 'wb-btn is-primary', secondary: 'wb-btn', icon: 'wb-icon-btn', pop: '' };
export type InstallHostProps<Theme> = {
controller: InstallController<Theme>;
t: StoreText;
/** The site's name in messages ("X"). */
site: string;
/** Shows or hides the app's tab webviews under the screen (+1 when it opens, -1 when it closes). */
setOverlay(delta: 1 | -1): void;
/** "Open Plugins" / "Open Appearance" after an install. */
openSection(kind: InstallKind): void;
/** A live preview of a staged theme (the app's theme preview). */
renderThemePreview?(theme: Theme): ReactNode;
/** Drops on elements matching this selector are handled by them (e.g. an import box). */
ownDropTargets?: string;
closeIcon?: ReactNode;
classNames?: Partial<InstallClassNames>;
};
/** Re-renders with the controller's current request. */
export function useInstallRequest<Theme>(controller: InstallController<Theme>): InstallRequest<Theme> | null {
return useSyncExternalStore(controller.subscribe, controller.current, controller.current);
}
function Glyph({ d, size = 18 }: { d: string; size?: number }) {
return <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true"><path d={d} fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"/></svg>;
}
const G = {
plugin: 'M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0zM12 17v4',
theme: 'M12 3a9 9 0 1 0 0 18c1.5 0 2-1 2-1.8 0-1.2-.9-1.5-.9-2.5 0-1 .8-1.7 1.8-1.7h2A4.2 4.2 0 0 0 21 10.8 8.8 8.8 0 0 0 12 3zM7.5 11h.01M10.5 7.5h.01M15 8h.01',
shield: 'M12 3l7 3v5c0 4.6-3 8.5-7 10-4-1.5-7-5.4-7-10V6z',
check: 'M5 12.5l4.2 4.2L19 7',
link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
file: 'M7 3h7l5 5v13H7zM14 3v5h5',
warn: 'M12 4l9 16H3zM12 10v4M12 17h.01',
copy: 'M9 9h10v10H9zM5 15V5h10',
close: 'M6 6l12 12M18 6L6 18',
};
function Fact({ label, children, wide }: { label: string; children: ReactNode; wide?: boolean }) {
return <div className={`wbi-fact${wide ? ' is-wide' : ''}`}><dt>{label}</dt><dd>{children}</dd></div>;
}
function CodePreview({ text, label, t }: { text: string; label: string; t: StoreText }) {
const [all, setAll] = useState(false);
const { lines, hidden } = previewLines(text, PREVIEW_LINES, all);
return <section className="wbi-code" aria-label={label}>
<header><span>{label}</span><small>{t('wb.install.lines', { count: text.split('\n').length })}</small></header>
<pre tabIndex={0}><code>{lines.map((line, i) => <span key={i} className="wbi-line"><i>{i + 1}</i>{line || ' '}</span>)}</code></pre>
{hidden > 0 && <button className="wbi-more" onClick={() => setAll(true)}>{t('wb.install.moreLines', { count: hidden })}</button>}
</section>;
}
function sourceIcon(preview: InstallPreview) {
return preview.source.kind === 'store' ? G.shield : preview.source.kind === 'link' ? G.link : G.file;
}
type Shared<Theme> = Omit<InstallHostProps<Theme>, 'classNames'> & { classes: InstallClassNames };
function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Theme>, { status: 'ready' | 'installing' }>; props: Shared<Theme> }) {
const { t, site, controller, classes } = props;
const preview = request.preview;
const ready = request.status === 'ready' ? request : null;
const theme = ready ? ready.theme : null;
const facts = theme !== null ? controller.facts(theme) : null;
const plugin = preview.plugin;
const [armed, setArmed] = useState(false);
// On by default only when it is from the signed store or declares its permissions and the code
// scan found nothing to point out; otherwise the owner turns it on deliberately.
const [enable, setEnable] = useState(preview.kind === 'theme' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0))));
const [copied, setCopied] = useState(false);
useEffect(() => { const timer = setTimeout(() => setArmed(true), REVIEW_MS); return () => clearTimeout(timer); }, [preview.token]);
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? t('wb.install.untitled');
const author = plugin?.author || facts?.author || preview.theme?.author || '';
const version = preview.version || preview.store?.version || '';
const updating = preview.existing && !preview.existing.same;
const verb = preview.existing?.same ? t('wb.install.reinstall') : updating || ready?.replaces ? t('wb.install.update') : t('wb.store.install');
const eyebrow = t(preview.existing?.same ? 'wb.install.eyebrow.reinstall' : updating || ready?.replaces ? 'wb.install.eyebrow.update' : 'wb.install.eyebrow.install', { kind: preview.kind });
const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : [];
const installing = request.status === 'installing';
const description = plugin?.description || facts?.description;
return <>
<header className="wbi-head">
<div className={`wbi-tile is-${preview.kind}`} style={facts?.tile ? { background: facts.tile.background, color: facts.tile.color, boxShadow: `inset 0 0 0 1px ${facts.tile.border}` } : undefined}>
<Glyph d={preview.kind === 'plugin' ? G.plugin : G.theme} size={22}/>
</div>
<div className="wbi-title">
<span className="wbi-eyebrow">{eyebrow}</span>
<h2 id="wbi-title">{name}</h2>
<p>{[author && t('wb.store.by', { author }), version && `v${version}`].filter(Boolean).join(' · ') || t('wb.install.noAuthor')}</p>
</div>
<button className={`${classes.icon} wbi-close`} aria-label={t('wb.install.cancel')} onClick={() => void controller.cancel()}>{props.closeIcon ?? <Glyph d={G.close} size={16}/>}</button>
</header>
<div className="wbi-body">
<div className={`wbi-source is-${preview.source.kind}`}>
<Glyph d={sourceIcon(preview)}/>
<div>
<strong>{preview.source.label}</strong>
{preview.source.url && <code title={preview.source.url}>{preview.source.url}</code>}
</div>
{preview.source.signed && <span className="wbi-verified"><Glyph d={G.check} size={14}/>{t('wb.install.verified')}</span>}
</div>
{description && <p className="wbi-desc">{description}</p>}
<dl className="wbi-facts">
{preview.file && <Fact label={t('wb.install.file')}>{preview.file}</Fact>}
<Fact label={t('wb.install.size')}>{formatBytes(preview.size)}</Fact>
{preview.existing && <Fact label={t('wb.install.installedNow')}>{preview.existing.same ? t('wb.install.identical', { version: preview.existing.version || '?' }) : `v${preview.existing.version || '?'}${preview.existing.enabled ? ` · ${t('wb.install.on')}` : ''}`}</Fact>}
{ready?.replaces && <Fact label={t('wb.install.replaces')}>{t('wb.install.replacesValue')}</Fact>}
<Fact label="SHA-256" wide>
<span className="wbi-hash">{preview.sha256}</span>
<button className="wbi-copy" aria-label={t('wb.install.copyHash')} onClick={() => void navigator.clipboard?.writeText(preview.sha256).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1400); }).catch(() => {})}>
<Glyph d={copied ? G.check : G.copy} size={14}/>
</button>
</Fact>
</dl>
{preview.kind === 'plugin' && <section className="wbi-perms" aria-label={t('wb.store.permissions')}>
<h3>{t('wb.install.permissions')}</h3>
<ul>
{badges.map(badge => <li key={badge.id} className={`is-${badge.tone}`}><span className="wbi-chip">{badge.label}</span><span>{badge.detail}</span></li>)}
</ul>
<p className="wbi-note"><Glyph d={G.warn} size={14}/>{t('wb.install.pageAccess', { site })}</p>
{preview.findings.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.theCode')}</strong>{preview.findings.map(finding => <span key={finding}>{finding}</span>)}</div>}
</section>}
{theme !== null && <section className="wbi-theme">
{props.renderThemePreview?.(theme)}
{(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>}
</section>}
{facts?.css ? <CodePreview t={t} text={facts.css} label={t('wb.install.themeCss', { site })}/> : null}
<CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : t('wb.install.themeFile')}/>
</div>
<footer className="wbi-foot">
<label className="wbi-check">
<input type="checkbox" checked={enable} disabled={installing || Boolean(preview.existing?.enabled)} onChange={event => setEnable(event.target.checked)}/>
<span>{preview.kind === 'plugin' ? (preview.existing?.enabled ? t('wb.install.staysOn') : t('wb.install.turnOn')) : t('wb.install.useNow')}</span>
</label>
<span className="wbi-foot-end"/>
<button className={classes.secondary} onClick={() => void controller.cancel()} disabled={installing}>{t('wb.install.cancel')}</button>
<button className={`${classes.primary} wbi-install${armed ? '' : ' is-arming'}`} disabled={!armed || installing} onClick={() => void controller.confirm(enable)}>
{installing ? t('wb.install.installing') : verb}
</button>
</footer>
</>;
}
function Done<Theme>({ request, props }: { request: Extract<InstallRequest<Theme>, { status: 'done' }>; props: Shared<Theme> }) {
const { t, site, controller, classes } = props;
return <div className="wbi-state">
<div className="wbi-state-icon is-ok"><Glyph d={G.check} size={26}/></div>
<h2 id="wbi-title">{t('wb.install.done', { name: request.name })}</h2>
<p>{request.kind === 'plugin'
? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff'))
: (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p>
{request.fonts.length > 0 && <p className="wbi-muted">{t('wb.install.done.fonts', { fonts: request.fonts.join(', ') })}</p>}
<div className="wbi-state-actions">
<button className={classes.secondary} onClick={() => { controller.close(); props.openSection(request.kind); }}>{request.kind === 'plugin' ? t('wb.install.openPlugins') : t('wb.install.openAppearance')}</button>
<button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.doneButton')}</button>
</div>
</div>;
}
function Dialog<Theme>({ request, props }: { request: InstallRequest<Theme>; props: Shared<Theme> }) {
const { t, controller, classes, setOverlay } = props;
const box = useRef<HTMLDivElement>(null);
useEffect(() => {
setOverlay(1);
return () => setOverlay(-1);
}, []);
useEffect(() => { box.current?.querySelector<HTMLElement>('.wbi-close, [autofocus]')?.focus(); }, [request.status]);
const dismiss = () => (request.status === 'ready' ? void controller.cancel() : request.status === 'installing' ? undefined : controller.close());
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') { event.preventDefault(); dismiss(); }
// Enter never confirms an install; only a click on Install does.
if (event.key === 'Enter' && (event.target as HTMLElement).classList.contains('wbi-install')) event.preventDefault();
};
return createPortal(<div className="wbi-backdrop" onMouseDown={dismiss}>
<div ref={box} className={`wbi ${classes.pop} is-${request.status}`.replace(/\s+/g, ' ')} role="dialog" aria-modal="true" aria-labelledby="wbi-title" onMouseDown={event => event.stopPropagation()} onKeyDown={onKey}>
{request.status === 'loading' && <div className="wbi-state">
<div className="wbi-spinner" aria-hidden="true"/>
<h2 id="wbi-title">{request.title}</h2>
<p>{request.detail}</p>
<div className="wbi-state-actions"><button className={classes.secondary} onClick={controller.close}>{t('wb.install.cancel')}</button></div>
</div>}
{(request.status === 'ready' || request.status === 'installing') && <Ready request={request} props={props}/>}
{request.status === 'done' && <Done request={request} props={props}/>}
{request.status === 'error' && <div className="wbi-state">
<div className="wbi-state-icon is-warn"><Glyph d={G.warn} size={26}/></div>
<h2 id="wbi-title">{request.title}</h2>
<p>{request.message}</p>
<div className="wbi-state-actions"><button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.close')}</button></div>
</div>}
</div>
</div>, document.body);
}
const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []).includes('Files');
/**
* Install links, the screen, and file drops on the window. A file dragged over the shell (tab
* strip, titlebar, settings) shows a drop target over the whole window; files dragged straight into
* a site tab stay the site's (e.g. images for a post).
*/
export function InstallHost<Theme>(props: InstallHostProps<Theme>) {
const { t, controller, setOverlay, ownDropTargets } = props;
const shared: Shared<Theme> = { ...props, classes: { ...DEFAULT_CLASSES, ...props.classNames } };
const request = useInstallRequest(controller);
const [dropping, setDropping] = useState(false);
useEffect(() => controller.start(), [controller]);
useEffect(() => {
let last = 0;
let timer: ReturnType<typeof setInterval> | undefined;
const own = (event: DragEvent) => Boolean(ownDropTargets && (event.target as Element | null)?.closest?.(ownDropTargets));
const stop = () => { clearInterval(timer); timer = undefined; setDropping(false); };
const over = (event: DragEvent) => {
if (!hasFiles(event) || own(event)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
last = Date.now();
if (!timer) {
setDropping(true);
// Esc or leaving the window ends a drag without an event here.
timer = setInterval(() => { if (Date.now() - last > 900) stop(); }, 200);
}
};
const drop = (event: DragEvent) => {
if (!hasFiles(event) || own(event)) return;
event.preventDefault();
stop();
const file = event.dataTransfer?.files[0];
if (file) void controller.requestFile(file);
};
window.addEventListener('dragenter', over, true);
window.addEventListener('dragover', over, true);
window.addEventListener('drop', drop, true);
return () => { stop(); window.removeEventListener('dragenter', over, true); window.removeEventListener('dragover', over, true); window.removeEventListener('drop', drop, true); };
}, [controller, ownDropTargets]);
useEffect(() => {
if (!dropping) return;
setOverlay(1);
return () => setOverlay(-1);
}, [dropping]);
return <>
{dropping && createPortal(<div className="wbi-drop" aria-hidden="true"><div>
<Glyph d={G.file} size={30}/>
<strong>{t('wb.install.drop')}</strong>
<span>{t('wb.install.dropHint')}</span>
</div></div>, document.body)}
{request && <Dialog request={request} props={shared}/>}
</>;
}

View file

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

View file

@ -0,0 +1,202 @@
// The install screen's state machine, shared by every wayBetter app. Requests come from
// `waybetter://install` links (the native `install-link` event, plus links that arrived before the
// shell listened), files dropped on the window and the Store view. Each request is staged natively
// (downloaded/validated, hashed) and shown on the install screen; nothing is written until the owner
// presses Install there. The app supplies how it talks to native code (Tauri `invoke`/`listen`) and
// how its themes are parsed and saved; plugins need nothing app-specific.
import { freeThemeId, installedThemeId, kindForFile, MAX_FILE_BYTES, errorText, type InstallKind, type InstallPreview, type InstallRecord, type LinkEvent, type StoreItem } from './storeModel.ts';
import type { StoreText } from './storeMessages.ts';
/** How the controller reaches native code (the app passes Tauri's `invoke` and `listen`). */
export type StoreBackend = {
invoke<T>(command: string, args?: Record<string, unknown>): Promise<T>;
/** Subscribes to a shell event; resolves to the unsubscribe function. */
listen<T>(event: string, handler: (payload: T) => void): Promise<() => void>;
};
/** What the install screen shows of a theme (the app's theme format stays the app's). */
export type ThemeFacts = {
name: string;
author?: string;
description?: string;
/** Theme CSS, shown as its own code block (it has custom-CSS trust). */
css?: string;
/** The theme's own colors for the tile at the top. */
tile?: { background: string; color: string; border: string };
};
export type ThemeAdapter<Theme> = {
/** Parses (and sanitizes) a theme file the way the app's theme import does. */
parse(text: string): { theme: Theme; warnings: string[] } | { error: string };
/** Loads the app's theme state and resolves to the owner's own theme ids. */
userThemes(): Promise<string[]>;
/** Theme ids that ship with the app. */
builtinThemes: readonly string[];
/** The id a theme asks for (a free one is chosen from it). */
idOf(theme: Theme): string;
facts(theme: Theme): ThemeFacts;
/**
* Saves the theme the owner confirmed under `id` (replacing the owner's copy `replaces`), and
* makes it the current theme when `enable`. Resolves to whether it is current now and the font
* names it uses that are not available yet.
*/
save(theme: Theme, id: string, options: { replaces: string | null; enable: boolean }): Promise<{ enabled: boolean; fonts: string[] }>;
};
export type InstallRequest<Theme> =
| { status: 'loading'; title: string; detail: string }
| { status: 'ready'; preview: InstallPreview; theme: Theme | null; warnings: string[]; replaces: string | null }
| { status: 'installing'; preview: InstallPreview; theme: Theme | null }
| { status: 'done'; kind: InstallKind; name: string; themeId?: string; fonts: string[]; enabled: boolean }
| { status: 'error'; title: string; message: string };
export type InstallControllerOptions<Theme> = {
backend: StoreBackend;
/** The app's translator (framework catalogs merged in); called at request time. */
t: StoreText;
/** The site's name in messages ("X"). */
site: string;
theme: ThemeAdapter<Theme>;
/** A plugin was installed (the app refreshes its plugin list). */
onPluginsChanged?(): void;
/** A theme was installed (the app refreshes its store/theme views). */
onThemesChanged?(): void;
};
export type InstallController<Theme> = {
current(): InstallRequest<Theme> | null;
subscribe(listener: () => void): () => void;
/** A validated `waybetter://install` link: download it natively and show the screen. */
requestLink(link: { kind: InstallKind; url: string }): Promise<void>;
/** A file dropped on the window. */
requestFile(file: { name: string; size: number; text(): Promise<string> }): Promise<void>;
/** A store item: downloaded natively and checked against the signed catalog. */
requestStoreItem(item: StoreItem): Promise<void>;
linkRejected(error: string): void;
/** Closes the screen and drops what was staged. */
cancel(): Promise<void>;
close(): void;
/** The owner pressed Install. `enable`: turn the plugin on / use the theme now. */
confirm(enable: boolean): Promise<void>;
/** Listens for install links (once). Returns a disposer. */
start(): () => void;
facts(theme: Theme): ThemeFacts;
};
export function createInstallController<Theme>(options: InstallControllerOptions<Theme>): InstallController<Theme> {
const { backend, t, theme: themes } = options;
let current: InstallRequest<Theme> | null = null;
let records: Record<string, InstallRecord> = {};
let started = false;
const listeners = new Set<() => void>();
const set = (next: InstallRequest<Theme> | null) => { current = next; for (const listener of [...listeners]) listener(); };
async function refreshRecords() {
try { records = (await backend.invoke<{ items: Record<string, InstallRecord> }>('install_records')).items ?? {}; } catch { /* Keep the last copy. */ }
}
/** Parses a staged theme the way the app's import does, and finds the theme it would update. */
async function prepared(preview: InstallPreview): Promise<InstallRequest<Theme>> {
if (preview.kind === 'plugin') return { status: 'ready', preview, theme: null, warnings: [], replaces: null };
const parsed = themes.parse(preview.text);
if ('error' in parsed) return { status: 'error', title: t('wb.install.err.theme'), message: parsed.error };
const userThemes = await themes.userThemes();
const replaces = preview.store ? installedThemeId(preview.store, records, userThemes) : null;
return { status: 'ready', preview, theme: parsed.theme, warnings: parsed.warnings, replaces };
}
async function stage(title: string, detail: string, run: () => Promise<InstallPreview>) {
set({ status: 'loading', title, detail });
try {
await Promise.all([themes.userThemes(), refreshRecords()]);
const preview = await run();
set(await prepared(preview));
} catch (error) {
set({ status: 'error', title, message: errorText(error) });
}
}
const controller: InstallController<Theme> = {
current: () => current,
subscribe(listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
requestLink(link) {
let host = link.url;
try { host = new URL(link.url).host; } catch { /* Shown as is. */ }
return stage(t('wb.install.stage.link', { kind: link.kind, host }), t('wb.install.stage.linkDetail'), () => backend.invoke<InstallPreview>('install_stage_link', { kind: link.kind, url: link.url }));
},
async requestFile(file) {
const kind = kindForFile(file.name);
if (!kind) {
set({ status: 'error', title: t('wb.install.err.kind', { file: file.name }), message: t('wb.install.err.kindHint', { site: options.site }) });
return;
}
if (file.size > MAX_FILE_BYTES[kind]) {
set({ status: 'error', title: t('wb.install.err.large', { file: file.name }), message: t('wb.install.err.largeHint', { kind }) });
return;
}
await stage(t('wb.install.stage.named', { name: file.name }), t('wb.install.stage.fileDetail'), async () => backend.invoke<InstallPreview>('install_stage_file', { name: file.name, text: await file.text() }));
},
requestStoreItem(item) {
return stage(t('wb.install.stage.named', { name: item.name }), t('wb.install.stage.storeDetail'), () => backend.invoke<InstallPreview>('store_stage', { item: { kind: item.kind, id: item.id } }));
},
linkRejected(error) {
set({ status: 'error', title: t('wb.install.err.link'), message: error.replace(/^LINK: /, '') });
},
async cancel() {
const request = current;
set(null);
if (request && request.status === 'ready') await backend.invoke('install_cancel', { token: request.preview.token }).catch(() => {});
},
close: () => set(null),
async confirm(enable) {
const request = current;
if (!request || request.status !== 'ready') return;
const { preview } = request;
set({ status: 'installing', preview, theme: request.theme });
try {
if (preview.kind === 'plugin') {
await backend.invoke('install_commit', { token: preview.token, enable, themeId: null });
options.onPluginsChanged?.();
set({ status: 'done', kind: 'plugin', name: preview.plugin?.name ?? preview.file ?? 'Plugin', fonts: [], enabled: enable || Boolean(preview.existing?.enabled) });
return;
}
const own = await themes.userThemes();
const wanted = themes.idOf(request.theme!);
const taken = [...themes.builtinThemes, ...own.filter(id => id !== request.replaces)];
const id = request.replaces ?? freeThemeId(wanted, taken);
const outcome = await backend.invoke<{ themeText: string | null }>('install_commit', { token: preview.token, enable, themeId: id });
// The exact bytes native code staged and hashed; parsed and sanitized again here.
const parsed = themes.parse(outcome.themeText ?? '');
if ('error' in parsed) throw new Error(parsed.error);
const saved = await themes.save(parsed.theme, id, { replaces: request.replaces, enable });
options.onThemesChanged?.();
set({ status: 'done', kind: 'theme', name: themes.facts(parsed.theme).name, themeId: id, fonts: saved.fonts, enabled: saved.enabled });
} catch (error) {
set({ status: 'error', title: t('wb.install.err.notInstalled', { kind: preview.kind }), message: errorText(error) });
}
},
start() {
if (started) return () => {};
started = true;
const handle = (event: LinkEvent) => {
if (event.link) void controller.requestLink(event.link);
else if (event.error) controller.linkRejected(event.error);
};
// Native code queues every link and also emits it; a handled event clears the queue so a
// reload of the shell does not show it again.
const unlisten = backend.listen<LinkEvent>('install-link', event => { handle(event); void backend.invoke('install_pending').catch(() => {}); });
// Links that arrived before the shell listened (the app was started by one): the newest.
void unlisten.then(() => backend.invoke<LinkEvent[]>('install_pending').then(events => {
const last = events[events.length - 1];
if (last && current === null) handle(last);
})).catch(() => {});
return () => { started = false; void unlisten.then(off => off()).catch(() => {}); };
},
facts: theme => themes.facts(theme),
};
return controller;
}

View file

@ -0,0 +1,227 @@
/* wayBetter Store view (StoreView.tsx, `.wbs`), install screen and window drop target
(InstallDialog.tsx, `.wbi*`). Themed with the framework tokens below; an app maps them to its own
theme on `.wbs, .wbi-backdrop, .wbi-drop` (the screen is portaled to <body>). Defaults: a dark
neutral look, so the components work before an app themes them.
Tokens: --wb-text, --wb-text-2, --wb-text-rgb, --wb-muted, --wb-faint, --wb-elevated (screen),
--wb-card, --wb-field, --wb-ground (code), --wb-border, --wb-border-soft, --wb-border-strong,
--wb-hover, --wb-press, --wb-accent, --wb-accent-rgb, --wb-accent-soft, --wb-accent-ink,
--wb-on-accent, --wb-ok, --wb-warn, --wb-font, --wb-font-mono, --wb-shadow-pop, --wb-ring,
--wb-t2, --wb-t3, --wb-ease, --wb-ease-out. */
:where(.wbs, .wbi-backdrop, .wbi-drop) {
--wb-text: #eef0f7; --wb-text-2: #c3c7d4; --wb-text-rgb: 238 240 247; --wb-muted: #8a90a6; --wb-faint: #5d6379;
--wb-elevated: #0d1017; --wb-card: #0d1017; --wb-field: #11141c; --wb-ground: #07080c;
--wb-border: #1e2333; --wb-border-soft: #161a26; --wb-border-strong: #2a3044;
--wb-hover: rgb(238 240 247 / .06); --wb-press: rgb(238 240 247 / .1);
--wb-accent: #1d9bf0; --wb-accent-rgb: 29 155 240; --wb-accent-soft: rgb(29 155 240 / .14); --wb-accent-ink: #cfe6ff; --wb-on-accent: #fff;
--wb-ok: #3ecf8e; --wb-warn: #ffb020;
--wb-font: system-ui, sans-serif; --wb-font-mono: ui-monospace, monospace;
--wb-shadow-pop: 0 18px 44px -14px rgba(0, 0, 0, .75), 0 3px 10px rgba(0, 0, 0, .35);
--wb-ring: 0 0 0 2px rgb(29 155 240 / .6);
--wb-t2: 160ms; --wb-t3: 240ms; --wb-ease: ease; --wb-ease-out: cubic-bezier(.2, .8, .2, 1);
}
/* ---- Install screen ------------------------------------------------------------------------- */
.wbi-backdrop {
position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 28px 16px;
background: rgba(3, 4, 7, .6);
animation: wbi-fade var(--wb-t2) var(--wb-ease-out);
}
.wbi {
width: min(760px, 100%); max-height: min(88vh, 900px); display: flex; flex-direction: column;
background: var(--wb-elevated); color: var(--wb-text); border-radius: 16px;
box-shadow: var(--wb-shadow-pop), 0 0 0 1px var(--wb-border-strong);
font: 400 13px/1.45 var(--wb-font); overflow: hidden;
animation: wbi-rise var(--wb-t3) var(--wb-ease-out);
}
@keyframes wbi-fade { from { opacity: 0; } }
@keyframes wbi-rise { from { opacity: 0; transform: translateY(8px) scale(.985); } }
@media (prefers-reduced-motion: reduce) { .wbi, .wbi-backdrop { animation: none; } }
.wbi-head { display: flex; align-items: flex-start; gap: 14px; padding-block: 20px 14px; padding-inline: 22px 18px; border-bottom: 1px solid var(--wb-border-soft); }
.wbi-tile {
flex: none; width: 48px; height: 48px; border-radius: 13px; display: grid; place-items: center;
background: var(--wb-accent-soft); color: var(--wb-accent); box-shadow: inset 0 0 0 1px rgb(var(--wb-accent-rgb) / .35);
}
.wbi-title { min-width: 0; flex: 1; }
.wbi-eyebrow { display: block; font: 600 11px/1 var(--wb-font-mono); letter-spacing: .08em; text-transform: uppercase; color: var(--wb-muted); margin: 3px 0 7px; }
.wbi-title h2 { margin: 0; font: 700 21px/1.15 var(--wb-font); letter-spacing: -.02em; overflow-wrap: anywhere; }
.wbi-title p { margin: 5px 0 0; color: var(--wb-text-2); font-size: 13px; }
.wbi-close { flex: none; }
.wbi-body { overflow-y: auto; padding: 16px 22px 18px; display: grid; gap: 14px; min-height: 0; }
.wbi-source {
display: flex; align-items: center; gap: 12px; padding-block: 11px; padding-inline: 14px 12px; border-radius: 12px;
background: var(--wb-field); box-shadow: inset 0 0 0 1px var(--wb-border);
}
.wbi-source > svg { flex: none; color: var(--wb-muted); }
.wbi-source.is-store > svg { color: #3ecf8e; }
.wbi-source > div { min-width: 0; flex: 1; display: grid; gap: 2px; }
.wbi-source strong { font-weight: 600; }
.wbi-source code { font: 12px/1.4 var(--wb-font-mono); color: var(--wb-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wbi-verified {
flex: none; display: inline-flex; align-items: center; gap: 5px; padding-block: 4px; padding-inline: 7px 9px; border-radius: 999px;
font: 600 11.5px/1 var(--wb-font); color: #3ecf8e; background: rgb(62 207 142 / .12); box-shadow: inset 0 0 0 1px rgb(62 207 142 / .35);
}
.wbi-desc { margin: 0; color: var(--wb-text-2); }
.wbi-facts { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px 16px; margin: 0; }
.wbi-fact { min-width: 0; }
.wbi-fact.is-wide { grid-column: 1 / -1; }
.wbi-fact dt { font: 600 10.5px/1 var(--wb-font-mono); letter-spacing: .07em; text-transform: uppercase; color: var(--wb-faint); margin-bottom: 5px; }
.wbi-fact dd { margin: 0; display: flex; align-items: center; gap: 8px; overflow-wrap: anywhere; }
.wbi-hash { font: 12px/1.45 var(--wb-font-mono); color: var(--wb-text-2); word-break: break-all; }
.wbi-copy {
flex: none; display: grid; place-items: center; width: 26px; height: 26px; border-radius: 7px; border: 0;
background: var(--wb-hover); color: var(--wb-muted); cursor: pointer;
}
.wbi-copy:hover { background: var(--wb-press); color: var(--wb-text); }
.wbi-perms h3 { margin: 0 0 8px; font: 650 13px/1.2 var(--wb-font); }
.wbi-perms ul { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.wbi-perms li { display: grid; grid-template-columns: minmax(118px, auto) 1fr; gap: 10px; align-items: baseline; color: var(--wb-text-2); }
.wbi-chip {
justify-self: start; padding: 3px 9px; border-radius: 999px; font: 600 11.5px/1.3 var(--wb-font);
background: rgb(var(--wb-text-rgb) / .07); color: var(--wb-text); box-shadow: inset 0 0 0 1px var(--wb-border-strong);
}
.wbi-perms li.is-warn .wbi-chip { background: rgb(255 176 32 / .12); color: #ffc55c; box-shadow: inset 0 0 0 1px rgb(255 176 32 / .35); }
.wbi-perms li.is-ok .wbi-chip { background: rgb(62 207 142 / .12); color: #58d9a0; box-shadow: inset 0 0 0 1px rgb(62 207 142 / .32); }
.wbi-note { display: flex; gap: 8px; margin: 10px 0 0; padding: 9px 11px; border-radius: 10px; color: var(--wb-text-2); background: rgb(var(--wb-text-rgb) / .035); font-size: 12.5px; }
.wbi-note svg { flex: none; margin-top: 2px; color: #ffc55c; }
.wbi-findings { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; font-size: 12.5px; color: var(--wb-text-2); }
.wbi-findings strong { margin-inline-end: 2px; }
.wbi-findings span { padding: 2px 8px; border-radius: 6px; background: rgb(255 176 32 / .1); color: #ffc55c; }
.wbi-theme { display: grid; gap: 8px; }
.wbi-theme-preview { border-radius: 12px; overflow: hidden; box-shadow: 0 0 0 1px var(--wb-border); }
.wbi-warnings { margin: 0; padding-inline-start: 18px; color: #ffc55c; font-size: 12.5px; }
.wbi-code { direction: ltr; border-radius: 12px; background: var(--wb-ground); box-shadow: inset 0 0 0 1px var(--wb-border); overflow: hidden; }
.wbi-code header { display: flex; justify-content: space-between; align-items: baseline; padding: 9px 12px; border-bottom: 1px solid var(--wb-border-soft); font-weight: 600; }
.wbi-code header small { color: var(--wb-faint); font: 11.5px var(--wb-font-mono); }
.wbi-code pre { margin: 0; max-height: 280px; overflow: auto; padding: 8px 0; font: 12px/1.55 var(--wb-font-mono); color: var(--wb-text-2); }
.wbi-code pre:focus-visible { outline: none; box-shadow: var(--wb-ring); }
.wbi-line { display: block; white-space: pre; padding-right: 14px; } /* rtl-ok: code is always left to right (.wbi-code is dir=ltr) */
.wbi-line i { display: inline-block; width: 44px; padding-right: 12px; text-align: right; font-style: normal; color: var(--wb-faint); user-select: none; } /* rtl-ok: code line numbers */
.wbi-more { width: 100%; border: 0; border-top: 1px solid var(--wb-border-soft); padding: 8px; background: transparent; color: var(--wb-accent-ink); font: 600 12px var(--wb-font); cursor: pointer; }
.wbi-more:hover { background: var(--wb-hover); }
.wbi-foot { display: flex; align-items: center; gap: 10px; padding-block: 12px 14px; padding-inline: 22px 18px; border-top: 1px solid var(--wb-border-soft); background: rgb(var(--wb-text-rgb) / .015); }
.wbi-foot-end { flex: 1; }
.wbi-check { display: inline-flex; align-items: center; gap: 8px; color: var(--wb-text-2); cursor: pointer; user-select: none; }
.wbi-check input { width: 15px; height: 15px; accent-color: var(--wb-accent); }
.wbi-install { position: relative; min-width: 104px; justify-content: center; overflow: hidden; }
.wbi-install.is-arming::after {
content: ''; position: absolute; left: 0; bottom: 0; height: 2px; width: 100%; background: rgb(255 255 255 / .7);
transform-origin: left; animation: wbi-arm 1s linear forwards;
}
@keyframes wbi-arm { from { transform: scaleX(0); } to { transform: scaleX(1); } }
.wbi-state { display: grid; justify-items: center; text-align: center; gap: 8px; padding: 34px 32px 26px; }
.wbi-state h2 { margin: 6px 0 0; font: 700 19px/1.2 var(--wb-font); letter-spacing: -.015em; }
.wbi-state p { margin: 0; max-width: 480px; color: var(--wb-text-2); }
.wbi-state .wbi-muted { color: var(--wb-muted); font-size: 12.5px; }
.wbi-state-actions { display: flex; gap: 10px; margin-top: 14px; }
.wbi-state-icon { width: 54px; height: 54px; border-radius: 50%; display: grid; place-items: center; }
.wbi-state-icon.is-ok { color: #3ecf8e; background: rgb(62 207 142 / .12); box-shadow: inset 0 0 0 1px rgb(62 207 142 / .35); }
.wbi-state-icon.is-warn { color: #ffc55c; background: rgb(255 176 32 / .12); box-shadow: inset 0 0 0 1px rgb(255 176 32 / .35); }
.wbi-spinner { width: 34px; height: 34px; border-radius: 50%; border: 3px solid rgb(var(--wb-text-rgb) / .1); border-top-color: var(--wb-accent); animation: wbi-spin .8s linear infinite; }
@keyframes wbi-spin { to { transform: rotate(360deg); } }
.wbi-drop {
position: fixed; inset: 0; z-index: 95; display: grid; place-items: center; padding: 24px; pointer-events: none;
background: rgb(var(--wb-accent-rgb) / .1);
box-shadow: inset 0 0 0 3px rgb(var(--wb-accent-rgb) / .7);
}
.wbi-drop > div {
display: grid; justify-items: center; gap: 8px; max-width: 420px; padding: 26px 30px; border-radius: 16px; text-align: center;
background: var(--wb-elevated); box-shadow: var(--wb-shadow-pop), 0 0 0 1px var(--wb-border-strong); color: var(--wb-text-2);
}
.wbi-drop svg { color: var(--wb-accent); }
.wbi-drop strong { font: 700 17px/1.2 var(--wb-font); color: var(--wb-text); }
.wbi-drop code { font: 12px var(--wb-font-mono); color: var(--wb-accent-ink); }
@media (max-width: 560px) {
.wbi-perms li { grid-template-columns: 1fr; gap: 3px; }
.wbi-head { padding-block: 16px 12px; padding-inline: 16px 12px; }
.wbi-body { padding: 14px 16px; }
.wbi-foot { flex-wrap: wrap; padding: 12px 16px; }
}
/* ---- Store view ----------------------------------------------------------------------------- */
.wbs { display: grid; gap: 14px; }
.wbs-intro { margin: -4px 0 0; color: var(--wb-muted); max-width: 720px; }
.wbs-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
.wbs-toolbar > :first-child { flex: 1 1 240px; min-width: 0; }
.wbs-cats { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.wbs-cats button {
height: 28px; padding: 0 12px; border-radius: 999px; border: 1px solid var(--wb-border); background: transparent;
color: var(--wb-text-2); font: 540 12.5px/1 inherit; cursor: pointer; transition: background-color .15s, border-color .15s;
}
.wbs-cats button:hover { background: var(--wb-field); }
.wbs-cats button.is-on { background: var(--wb-accent-soft); border-color: rgb(var(--wb-accent-rgb) / .45); color: var(--wb-text); }
.wbs-cats-end { flex: 1; }
.wbs-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--wb-muted); }
.wbs-status.is-ok svg { color: var(--wb-ok); }
.wbs-status.is-warn { color: var(--wb-warn); }
.wbs-updates {
display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; padding: 10px 14px; border-radius: 12px;
background: var(--wb-accent-soft); border: 1px solid rgb(var(--wb-accent-rgb) / .35); color: var(--wb-text-2);
}
.wbs-updates strong { color: var(--wb-text); }
.wbs-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 14px; }
.wbs-card {
display: flex; flex-direction: column; min-width: 0; border-radius: 14px; overflow: hidden;
background: var(--wb-card); border: 1px solid var(--wb-border); transition: border-color .15s, transform .15s var(--wb-ease, ease);
}
.wbs-card:hover { border-color: var(--wb-border-strong); }
.wbs-card.is-skeleton { height: 290px; background: linear-gradient(100deg, var(--wb-card) 30%, var(--wb-field) 50%, var(--wb-card) 70%) 0 0 / 300% 100%; animation: wbs-shimmer 1.4s linear infinite; }
@keyframes wbs-shimmer { to { background-position: -150% 0; } }
@media (prefers-reduced-motion: reduce) { .wbs-card.is-skeleton { animation: none; } }
.wbs-img { display: block; width: 100%; aspect-ratio: 16 / 10; object-fit: cover; background: var(--wb-field); border-bottom: 1px solid var(--wb-border-soft); }
.wbs-swatch { position: relative; display: grid; place-items: center; }
.wbs-swatch span { position: absolute; left: 22%; right: 22%; top: 16%; bottom: 0; border-radius: 10px 10px 0 0; border: 0 solid; opacity: .95; }
.wbs-swatch i { position: absolute; left: 30%; width: 34%; top: 32%; height: 8px; border-radius: 4px; opacity: .8; }
.wbs-swatch b { position: absolute; left: 30%; width: 18%; top: 50%; height: 18px; border-radius: 9px; }
.wbs-swatch strong { font: 700 42px/1 inherit; color: var(--wb-muted); }
.wbs-card-body { display: flex; flex-direction: column; gap: 6px; padding: 12px 14px 14px; flex: 1; }
.wbs-card-body header { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.wbs-card-body h3 { margin: 0; font: 650 15px/1.2 inherit; letter-spacing: -.01em; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wbs-meta { margin: 0; color: var(--wb-muted); font-size: 12px; }
.wbs-desc { margin: 0; color: var(--wb-text-2); font-size: 12.5px; line-height: 1.45; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.wbs-perms { display: flex; flex-wrap: wrap; gap: 5px; list-style: none; margin: 2px 0 0; padding: 0; }
.wbs-perms li { padding: 2px 8px; border-radius: 999px; font-size: 11px; line-height: 1.5; color: var(--wb-text-2); background: rgb(var(--wb-text-rgb) / .06); border: 1px solid var(--wb-border); }
.wbs-perms li.is-warn { color: var(--wb-warn); border-color: color-mix(in srgb, var(--wb-warn) 40%, transparent); background: color-mix(in srgb, var(--wb-warn) 10%, transparent); }
.wbs-perms li.is-ok { color: var(--wb-ok); border-color: color-mix(in srgb, var(--wb-ok) 35%, transparent); background: color-mix(in srgb, var(--wb-ok) 9%, transparent); }
.wbs-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: auto; padding-top: 8px; }
.wbs-state { font-size: 12px; color: var(--wb-muted); margin-inline-end: auto; }
.wbs-state.is-ok { color: var(--wb-ok); }
.wbs-foot { margin: 4px 0 0; color: var(--wb-muted); font-size: 12.5px; }
.wbs-foot code { font-family: var(--wb-font-mono, ui-monospace, monospace); color: var(--wb-text-2); }
/* ---- Default controls (an app usually passes its own) ---------------------------------------- */
.wb-btn {
display: inline-flex; align-items: center; gap: 6px; height: 32px; padding: 0 14px; border-radius: 9px; cursor: pointer;
border: 1px solid var(--wb-border-strong); background: var(--wb-field); color: var(--wb-text); font: 600 12.5px/1 var(--wb-font);
}
.wb-btn.is-sm { height: 28px; padding: 0 11px; }
.wb-btn:hover:not(:disabled) { background: var(--wb-press); }
.wb-btn:disabled { opacity: .5; cursor: default; }
.wb-btn.is-primary { background: var(--wb-accent); border-color: transparent; color: var(--wb-on-accent); }
.wb-btn.is-ghost { background: transparent; border-color: transparent; color: var(--wb-text-2); }
.wb-btn.is-danger { background: color-mix(in srgb, #f4212e 16%, transparent); border-color: color-mix(in srgb, #f4212e 45%, transparent); color: #ff7b85; }
.wb-icon-btn { display: grid; place-items: center; width: 30px; height: 30px; border: 0; border-radius: 8px; background: transparent; color: var(--wb-muted); cursor: pointer; }
.wb-icon-btn:hover { background: var(--wb-hover); color: var(--wb-text); }
.wb-field { height: 32px; padding: 0 12px; border-radius: 9px; border: 1px solid var(--wb-border); background: var(--wb-field); color: var(--wb-text); font: 13px var(--wb-font); }
.wb-segmented { display: inline-flex; gap: 2px; padding: 2px; border-radius: 9px; background: var(--wb-field); border: 1px solid var(--wb-border); }
.wb-segmented button { height: 26px; padding: 0 12px; border: 0; border-radius: 7px; background: transparent; color: var(--wb-text-2); font: 600 12px/1 var(--wb-font); cursor: pointer; }
.wb-segmented button.is-on { background: var(--wb-accent-soft); color: var(--wb-text); }
.wb-empty { display: grid; justify-items: center; gap: 8px; padding: 32px 16px; text-align: center; color: var(--wb-text-2); }
.wb-empty p { margin: 0; max-width: 460px; color: var(--wb-muted); }
.wb-badge { padding: 2px 8px; border-radius: 999px; font: 600 11px/1.4 var(--wb-font); color: var(--wb-text-2); background: rgb(var(--wb-text-rgb) / .07); }

View file

@ -0,0 +1,133 @@
// The Store, the install screen and the plugin permission words in English. They live in the
// framework catalogs (`waybetter/locales/<bcp47>.json`: `wb.store.*`, `wb.install.*`,
// `wb.permission.*`), so every wayBetter app shows them in its language: merge the framework
// catalogs into the app's i18n (as for the kit and shell words) and pass its `t` to the components
// (`StoreText`). Placeholders: `{site}` is the site's name ("X", "WhatsApp"); `{kind}` is plugin or
// theme (a select); `wb.permission.storage.detail`: keep the API names in parentheses unchanged.
export const STORE_MESSAGES = {
'wb.permission.storage.label': 'Storage',
'wb.permission.storage.detail': 'Keeps its own settings in this app (api.storage).',
'wb.permission.ui.label': 'Dialogs',
'wb.permission.ui.detail': 'Shows dialogs, prompts and notifications (api.ui, api.toast).',
'wb.permission.clipboard.label': 'Clipboard',
'wb.permission.clipboard.detail': 'Copies text to your clipboard (api.copyText).',
'wb.permission.account.label': 'Your account',
'wb.permission.account.detail': 'Reads which {site} account is signed in: handle, name, avatar (api.account).',
'wb.permission.commands.label': 'Commands',
'wb.permission.commands.detail': 'Adds commands to the command palette (Ctrl+K) that run in this page (api.commands).',
'wb.permission.users.label': 'Account details',
'wb.permission.users.detail': "Reads what {site}'s own responses said about accounts: verified, follows you (api.users).",
'wb.permission.network.label': 'Internet',
'wb.permission.network.detail': 'Says it contacts servers on the internet.',
'wb.permission.networkNone.label': 'No network',
'wb.permission.networkNone.detail': 'Says it never contacts a server; the install check found no network calls in its code.',
'wb.permission.legacy.label': 'Legacy · full page access',
'wb.permission.legacy.detail': 'No @permissions line: it gets the whole plugin API, like plugins before permissions.',
'wb.permission.none.label': 'No special access',
'wb.permission.none.detail': 'Only the basic page helpers (CSS, DOM, routes, keys, theme).',
'wb.permission.unknown': 'Unknown permission.',
'wb.store.category.reading': 'Reading',
'wb.store.category.writing': 'Writing',
'wb.store.category.filters': 'Filters',
'wb.store.category.focus': 'Focus',
'wb.store.category.tools': 'Tools',
'wb.store.category.dark': 'Dark',
'wb.store.category.light': 'Light',
'wb.store.builtIn': 'Built in',
'wb.store.use': 'Use',
'wb.store.install': 'Install',
'wb.store.updateTo': 'Update to {version}',
'wb.store.modifiedTitle': "The installed file differs from the store's (edited, or from elsewhere). The store leaves it alone.",
'wb.store.modified': 'Changed locally',
'wb.store.replace': 'Replace',
'wb.store.installed': 'Installed',
'wb.store.installedVersion': 'Installed · v{version}',
'wb.store.offline': 'Offline copy from {when}: {error}',
'wb.store.unreachableShort': 'Store unreachable',
'wb.store.verified': 'Signed catalog verified · updated {when}',
'wb.store.intro': "Themes and plugins from the wayBetter Store. The catalog is signed; wayBetter checks the signature and every download's SHA-256 before it shows the install screen. Plugins list the permissions they ask for.",
'wb.store.search': 'Search the store',
'wb.store.searchPlaceholder': 'Search themes and plugins',
'wb.store.kind': 'Kind',
'wb.store.themes': 'Themes',
'wb.store.checking': 'Checking…',
'wb.store.refresh': 'Refresh',
'wb.store.categories': 'Categories',
'wb.store.everything': 'Everything',
'wb.store.updates': '{count, plural, one {# update} other {# updates}} available',
'wb.store.unreachable': 'The store is not reachable',
'wb.store.tryAgain': 'Try again',
'wb.store.noCatalog': 'No catalog yet.',
'wb.store.nothingChanged': 'Nothing was installed or changed.',
'wb.store.noMatch': 'Nothing matches',
'wb.store.noMatchHint': 'Try another word or category.',
'wb.store.plugin': 'Plugin',
'wb.store.by': 'by {author}',
'wb.store.permissions': 'Permissions',
'wb.store.themeNow': '{name} is your theme now.',
'wb.store.foot': 'Have a theme or plugin file? Drop it on the wayBetter window, or open a waybetter://install link from waybetter.fyi. You always see this install screen first.',
'wb.install.lines': '{count, plural, one {# line} other {# lines}}',
'wb.install.moreLines': 'Show {count, plural, one {# more line} other {# more lines}}',
'wb.install.reinstall': 'Reinstall',
'wb.install.update': 'Update',
'wb.install.eyebrow.install': '{kind, select, plugin {Install plugin} theme {Install theme} other {Install}}',
'wb.install.eyebrow.update': '{kind, select, plugin {Update plugin} theme {Update theme} other {Update}}',
'wb.install.eyebrow.reinstall': '{kind, select, plugin {Reinstall plugin} theme {Reinstall theme} other {Reinstall}}',
'wb.install.noAuthor': 'No author or version given',
'wb.install.verified': 'Verified',
'wb.install.installedNow': 'Installed now',
'wb.install.identical': 'v{version} (identical)',
'wb.install.on': 'on',
'wb.install.replaces': 'Replaces',
'wb.install.replacesValue': 'your copy of this theme',
'wb.install.copyHash': 'Copy SHA-256',
'wb.install.permissions': 'Permissions it declares',
'wb.install.pageAccess': 'Plugins run inside {site} with the same access as the page: they can read what {site} shows you and act in it. Permissions limit what the wayBetter API gives a plugin, not the page. Install only code you trust.',
'wb.install.theCode': 'The code',
'wb.install.themeCss': 'Theme CSS (runs in {site} like your Custom CSS)',
'wb.install.code': 'Code that will be installed',
'wb.install.staysOn': 'It stays on',
'wb.install.turnOn': 'Turn it on now',
'wb.install.useNow': 'Use it now',
'wb.install.installing': 'Installing…',
'wb.install.done': '{name} is installed',
'wb.install.done.pluginOn': 'It is running in your {site} tabs now. Turn it off any time in Plugins.',
'wb.install.done.pluginOff': 'It is off. Turn it on in Plugins when you want it.',
'wb.install.done.themeOn': 'It is your theme now. Switch back any time in Appearance.',
'wb.install.done.themeOff': 'It is in your themes in Appearance.',
'wb.install.done.fonts': 'It names Google fonts ({fonts}). Appearance can download them for you; until then it uses its fallback fonts.',
'wb.install.openPlugins': 'Open Plugins',
'wb.install.openAppearance': 'Open Appearance',
'wb.install.doneButton': 'Done',
'wb.install.drop': 'Drop to install',
'wb.install.dropHint': 'A theme (.json) or a plugin (.plugin.js). You will see what it is before anything is installed.',
'wb.install.err.theme': 'This theme cannot be installed',
'wb.install.stage.link': '{kind, select, plugin {Install plugin from {host}} theme {Install theme from {host}} other {Install from {host}}}',
'wb.install.stage.linkDetail': 'Downloading and checking…',
'wb.install.err.kind': '“{file}” is not a theme or a plugin',
'wb.install.err.kindHint': 'wayBetter installs themes (.json) and plugins (.plugin.js). To attach a file to a post, drop it on {site}’s composer instead.',
'wb.install.err.large': '“{file}” is too large',
'wb.install.err.largeHint': '{kind, select, theme {Themes are limited to 2 MB.} other {Plugins are limited to 2 MB.}}',
'wb.install.stage.named': 'Install {name}',
'wb.install.stage.fileDetail': 'Checking the file…',
'wb.install.stage.storeDetail': 'Downloading from the wayBetter Store and checking its signature…',
'wb.install.err.link': 'This install link cannot be used',
'wb.install.err.notInstalled': '{kind, select, theme {The theme was not installed} other {The plugin was not installed}}',
'wb.install.untitled': 'Untitled',
'wb.install.file': 'File',
'wb.install.size': 'Size',
'wb.install.themeFile': 'Theme file',
'wb.store.all': 'All',
'wb.store.pluginsTab': 'Plugins',
'wb.store.theme': 'Theme',
'wb.store.remove': 'Remove',
'wb.store.keep': 'Keep',
'wb.store.removed': '{name} removed.',
'wb.install.cancel': 'Cancel',
'wb.install.close': 'Close',
} as const;
export type StoreKey = keyof typeof STORE_MESSAGES;
export type StoreParams = Readonly<Record<string, string | number>>;
/** The app's translator for these keys (framework catalogs merged in): the formatted message. */
export type StoreText = (key: StoreKey, params?: StoreParams) => string;

View file

@ -0,0 +1,189 @@
// The wayBetter Store and install screen, pure part: the wire types of the native store commands
// (waybetter-host `store`), what each plugin permission means, where a dropped file goes, which id a
// new theme gets, whether a store item is installed, current or has an update, search, and preview
// lines. Native code validates everything again; nothing here decides what may be installed.
import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts';
export type InstallKind = 'theme' | 'plugin';
export type SourceKind = 'store' | 'link' | 'file';
export type PermissionTone = 'plain' | 'warn' | 'ok';
export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone };
/** A store catalog item (waybetter-host `CatalogItem`; the catalog format is documented in docs/STORE.md). */
export type StoreItem = {
/** The wayBetter apps it is for; native code only hands an app its own items. */
apps?: string[];
kind: InstallKind; id: string; name: string; author: string; version: string; description: string;
category: string; tags: string[]; url: string; file?: string; sha256: string; size: number;
preview?: string; permissions?: string[] | null; colors?: { bg: string; surface?: string; text: string; accent: string } | null;
};
export type InstallRecord = { kind: InstallKind; source: SourceKind; url?: string; storeId?: string; version: string; sha256: string; installedAt: string };
export type InstalledPlugin = { version: string; sha256: string; enabled: boolean };
/** What `store_catalog` returns (waybetter-host `StoreView`): this app's items and what is installed. */
export type StoreCatalogView = {
catalog: { format?: number; name: string; generatedAt: string; items: StoreItem[] } | null;
fetchedAt: string | null;
error: string | null;
plugins: Record<string, InstalledPlugin>;
records: { items: Record<string, InstallRecord> };
};
export type ScriptPluginMeta = {
file: string; name: string; description: string; version: string; author: string; enabled: boolean;
permissions: string[] | null; problems?: string[];
};
/** What `install_stage_*` / `store_stage` return (waybetter-host `InstallPreview`). */
export type InstallPreview = {
token: string;
kind: InstallKind;
source: { kind: SourceKind; url: string | null; label: string; signed: boolean };
sha256: string;
size: number;
file: string | null;
/** The exact text that will be written. */
text: string;
version: string;
plugin: ScriptPluginMeta | null;
theme: { name: string; author: string; description: string; cssChars: number } | null;
findings: string[];
existing: { version: string; enabled: boolean; same: boolean } | null;
store: StoreItem | null;
};
/** The `install-link` event and `install_pending` entries (waybetter-host `LinkEvent`). */
export type LinkEvent = { link?: { kind: InstallKind; url: string }; error?: string };
/** Plugin permissions (waybetter-host `PERMISSIONS`, runtime `permissions.ts`) and how much they allow. */
export const PERMISSION_TONES: Readonly<Record<string, PermissionTone>> = {
storage: 'plain',
ui: 'plain',
clipboard: 'plain',
account: 'warn',
commands: 'plain',
users: 'warn',
network: 'warn',
'network:none': 'ok',
};
/** `t(key)` for a key assembled at runtime, or `fallback` when the framework has no such message. */
function lookup(t: StoreText, key: string, params: Record<string, string> | undefined, fallback: string): string {
return key in STORE_MESSAGES ? t(key as StoreKey, params) : fallback;
}
/** Badges for a plugin's declared permissions; `null` = no `@permissions` line (legacy). `site`: the site's name. */
export function permissionBadges(permissions: readonly string[] | null | undefined, t: StoreText, site: string): PermissionBadge[] {
if (permissions == null) return [{ id: 'legacy', label: t('wb.permission.legacy.label'), detail: t('wb.permission.legacy.detail'), tone: 'warn' }];
if (permissions.length === 0) return [{ id: 'none', label: t('wb.permission.none.label'), detail: t('wb.permission.none.detail'), tone: 'ok' }];
return permissions.map(id => {
const tone = PERMISSION_TONES[id];
if (!tone) return { id, label: id, detail: t('wb.permission.unknown'), tone: 'warn' as const };
const name = id.replace(':none', 'None');
return { id, label: lookup(t, `wb.permission.${name}.label`, undefined, id), detail: lookup(t, `wb.permission.${name}.detail`, { site }, ''), tone };
});
}
/** A store category's name (`wb.store.category.<id>`); unknown ones show their id. */
export function categoryLabel(id: string, t: StoreText): string {
return lookup(t, `wb.store.category.${id}`, undefined, id);
}
/** What a dropped file is, by name: `.plugin.js` → plugin, `.json` → theme, else nothing. */
export function kindForFile(name: string): InstallKind | null {
const lower = name.toLowerCase();
if (lower.endsWith('.plugin.js')) return 'plugin';
if (lower.endsWith('.json')) return 'theme';
return null;
}
/** Largest file the shell reads before handing it to native validation (same caps as native). */
export const MAX_FILE_BYTES: Readonly<Record<InstallKind, number>> = { theme: 2 * 1024 * 1024, plugin: 2 * 1024 * 1024 };
/** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */
export function freeThemeId(wanted: string, taken: Iterable<string>): string {
const used = new Set(taken);
if (!used.has(wanted)) return wanted;
for (let n = 2; ; n += 1) {
const id = `${wanted.slice(0, 36)}-${n}`;
if (!used.has(id)) return id;
}
}
/** `a` newer than `b` (numeric dot parts; same rule as native `newer_version`). */
export function newerVersion(a: string, b: string): boolean {
const parts = (value: string) => value.split(/[.+-]/).map(part => Number.parseInt(part, 10) || 0);
const [x, y] = [parts(a), parts(b)];
for (let i = 0; i < Math.max(x.length, y.length); i += 1) {
const [p, q] = [x[i] ?? 0, y[i] ?? 0];
if (p !== q) return p > q;
}
return false;
}
export type ItemState =
| { state: 'install' }
| { state: 'builtin' }
| { state: 'installed'; version: string; enabled?: boolean }
| { state: 'update'; version: string; enabled?: boolean }
/** Installed but changed locally (edited file, or a copy from somewhere else): the store leaves it alone unless asked. */
| { state: 'modified'; version: string; enabled?: boolean };
export type ItemContext = {
plugins: Record<string, InstalledPlugin>;
records: Record<string, InstallRecord>;
/** Theme ids that ship with the app (a store copy of one is "built in"). */
builtinThemes: readonly string[];
/** The owner's own theme ids right now. */
userThemes: readonly string[];
};
/**
* Where a store item stands on this machine. Plugins: by their file in the plugins folder.
* Themes: built-in ids are part of the app; otherwise the install record for a theme the owner
* still has.
*/
export function itemState(item: StoreItem, context: ItemContext): ItemState {
if (item.kind === 'plugin') {
const installed = item.file ? context.plugins[item.file] : undefined;
if (!installed) return { state: 'install' };
const base = { version: installed.version, enabled: installed.enabled };
if (installed.sha256 === item.sha256) return { state: 'installed', ...base };
if (newerVersion(item.version, installed.version)) return { state: 'update', ...base };
return { state: 'modified', ...base };
}
if (context.builtinThemes.includes(item.id)) return { state: 'builtin' };
const id = installedThemeId(item, context.records, context.userThemes);
if (!id) return { state: 'install' };
const value = context.records[`theme:${id}`]!;
if (value.sha256 === item.sha256) return { state: 'installed', version: value.version };
return newerVersion(item.version, value.version) ? { state: 'update', version: value.version } : { state: 'installed', version: value.version };
}
/** The installed user theme id a store theme item was installed as (for updates in place). */
export function installedThemeId(item: StoreItem, records: Record<string, InstallRecord>, userThemes: readonly string[]): string | null {
for (const [key, value] of Object.entries(records)) {
if (key.startsWith('theme:') && value.storeId === item.id && userThemes.includes(key.slice(6))) return key.slice(6);
}
return null;
}
/** Search and category filter for the store list. */
export function filterItems(items: readonly StoreItem[], query: string, kind: InstallKind | 'all', category: string | 'all'): StoreItem[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
return items.filter(item => (kind === 'all' || item.kind === kind) && (category === 'all' || item.category === category)
&& words.every(word => [item.name, item.description, item.author, item.category, ...item.tags, ...(item.permissions ?? [])].join(' ').toLowerCase().includes(word)));
}
export const formatBytes = (bytes: number) => bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(2)} MB`;
/** Lines of a preview with their numbers, the first `limit` only unless `all`. */
export function previewLines(text: string, limit: number, all = false): { lines: string[]; hidden: number } {
const lines = text.replace(/\r\n?/g, '\n').split('\n');
if (all || lines.length <= limit) return { lines, hidden: 0 };
return { lines: lines.slice(0, limit), hidden: lines.length - limit };
}
/** An error from a native command, without its `CODE: ` prefix. */
export const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^[A-Z]+: /, '');