waybetter/packages/shell/src/InstallDialog.tsx
CRT 37e3d8e5fc install screen: where an install comes from, in the owner's language
The source line ("wayBetter Store (signed catalog, sha256 verified)", "Link: <host>", "A file you
dropped") is built from the source kind and URL with the wb.install.source.* messages instead of
showing native code's English label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 12:47:09 +07:00

286 lines
17 KiB
TypeScript

// 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;
}
/** Where it comes from, in the owner's language (native code's `label` is English). */
function sourceLabel(source: InstallPreview['source'], t: StoreText): string {
if (source.kind === 'store') return t('wb.install.source.store');
if (source.kind === 'link') {
let host = '';
try { host = new URL(source.url ?? '').hostname; } catch { /* no host */ }
return t('wb.install.source.link', { host });
}
return t('wb.install.source.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>{sourceLabel(preview.source, t)}</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}/>}
</>;
}