String packs in the shell: the install screen shows a pack's language, coverage against the site's inventory (and what is ignored or cannot be replaced yet), a sample, that it is data only, and any item's licence and credits; the Store lists string packs under Languages and removes them; the Languages section turns packs on and off, orders and removes them and hands the site tabs the new delivery; English words (wb.strings.*, wb.install.strings.*, wb.install.license/credits and the strings variants)

This commit is contained in:
CRTkafa 2026-10-01 04:14:41 +07:00
parent f422326af1
commit ce9578e27d
12 changed files with 411 additions and 28 deletions

View file

@ -10,6 +10,7 @@ import { createPortal } from 'react-dom';
import type { InstallController, InstallRequest } from './installController.ts'; import type { InstallController, InstallRequest } from './installController.ts';
import type { StoreText } from './storeMessages.ts'; import type { StoreText } from './storeMessages.ts';
import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts'; import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts';
import { coveragePercent, type StringsSummary } from './stringPacksModel.ts';
/** Milliseconds before Install can be pressed (native code refuses a commit faster than 600 ms). */ /** Milliseconds before Install can be pressed (native code refuses a commit faster than 600 ms). */
export const REVIEW_MS = 1000; export const REVIEW_MS = 1000;
@ -30,6 +31,8 @@ export type InstallHostProps<Theme> = {
openSection(kind: InstallKind): void; openSection(kind: InstallKind): void;
/** A live preview of a staged theme (the app's theme preview). */ /** A live preview of a staged theme (the app's theme preview). */
renderThemePreview?(theme: Theme): ReactNode; renderThemePreview?(theme: Theme): ReactNode;
/** A string pack's coverage against the site's inventory (the app has the inventory). */
stringsSummary?(text: string): StringsSummary | null;
/** Drops on elements matching this selector are handled by them (e.g. an import box). */ /** Drops on elements matching this selector are handled by them (e.g. an import box). */
ownDropTargets?: string; ownDropTargets?: string;
closeIcon?: ReactNode; closeIcon?: ReactNode;
@ -54,6 +57,7 @@ const G = {
warn: 'M12 4l9 16H3zM12 10v4M12 17h.01', warn: 'M12 4l9 16H3zM12 10v4M12 17h.01',
copy: 'M9 9h10v10H9zM5 15V5h10', copy: 'M9 9h10v10H9zM5 15V5h10',
close: 'M6 6l12 12M18 6L6 18', close: 'M6 6l12 12M18 6L6 18',
strings: 'M4 5h9M8.5 3v2M11 5c-.8 3.8-3.4 6.6-7 8M6.5 8.5c1.1 1.6 2.7 3 4.5 3.8M13 21l4-9 4 9M14.4 18h5.2',
}; };
function Fact({ label, children, wide }: { label: string; children: ReactNode; wide?: boolean }) { function Fact({ label, children, wide }: { label: string; children: ReactNode; wide?: boolean }) {
@ -97,22 +101,25 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
const [armed, setArmed] = useState(false); const [armed, setArmed] = useState(false);
// On by default only when it is from the signed store or declares its permissions and the code // 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. // 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 [enable, setEnable] = useState(preview.kind === 'theme' || preview.kind === 'strings' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0))));
const [copied, setCopied] = useState(false); const [copied, setCopied] = useState(false);
useEffect(() => { const timer = setTimeout(() => setArmed(true), REVIEW_MS); return () => clearTimeout(timer); }, [preview.token]); 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 strings = preview.kind === 'strings' ? preview.strings ?? null : null;
const author = plugin?.author || facts?.author || preview.theme?.author || ''; const summary = strings ? props.stringsSummary?.(preview.text) ?? null : null;
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? strings?.name ?? t('wb.install.untitled');
const author = plugin?.author || facts?.author || preview.theme?.author || strings?.authors.join(', ') || '';
const version = preview.version || preview.store?.version || ''; const version = preview.version || preview.store?.version || '';
const updating = preview.existing && !preview.existing.same; 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 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 step = preview.existing?.same ? 'reinstall' : updating || ready?.replaces ? 'update' : 'install';
const eyebrow = preview.kind === 'strings' ? t(`wb.install.eyebrow.strings.${step}`) : t(`wb.install.eyebrow.${step}`, { kind: preview.kind });
const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : []; const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : [];
const installing = request.status === 'installing'; const installing = request.status === 'installing';
const description = plugin?.description || facts?.description; const description = plugin?.description || facts?.description || strings?.description;
return <> return <>
<header className="wbi-head"> <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}> <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}/> <Glyph d={preview.kind === 'plugin' ? G.plugin : preview.kind === 'strings' ? G.strings : G.theme} size={22}/>
</div> </div>
<div className="wbi-title"> <div className="wbi-title">
<span className="wbi-eyebrow">{eyebrow}</span> <span className="wbi-eyebrow">{eyebrow}</span>
@ -139,6 +146,8 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
<Fact label={t('wb.install.size')}>{formatBytes(preview.size)}</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>} {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>} {ready?.replaces && <Fact label={t('wb.install.replaces')}>{t('wb.install.replacesValue')}</Fact>}
{preview.store?.license && <Fact label={t('wb.install.license')}>{preview.store.license}</Fact>}
{preview.store?.credits && <Fact label={t('wb.install.credits')} wide>{preview.store.credits}</Fact>}
<Fact label="SHA-256" wide> <Fact label="SHA-256" wide>
<span className="wbi-hash">{preview.sha256}</span> <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(() => {})}> <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(() => {})}>
@ -156,13 +165,32 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
{preview.findings.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.theCode')}</strong>{preview.findings.map(finding => <span key={finding}>{finding}</span>)}</div>} {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>} </section>}
{strings && <section className="wbi-perms wbi-strings" aria-label={t('wb.store.stringsItem')}>
<p className="wbi-note is-ok"><Glyph d={G.check} size={14}/>{t('wb.install.strings.dataOnly', { site })}</p>
<dl className="wbi-facts">
<Fact label={t('wb.install.strings.language')}>{strings.language}</Fact>
<Fact label={t('wb.install.strings.coverage')} wide>
{summary && !summary.otherCatalog
? t('wb.install.strings.coverageValue', { translated: String(summary.translated), translatable: String(summary.translatable), site, percent: coveragePercent(summary) })
: t('wb.install.strings.count', { count: strings.strings })}
</Fact>
</dl>
{summary?.otherCatalog && <p className="wbi-note"><Glyph d={G.warn} size={14}/>{t('wb.install.strings.otherCatalog', { site })}</p>}
{summary && !summary.otherCatalog && <ul className="wbi-strings-notes">
{summary.closed > 0 && <li>{t('wb.install.strings.closed', { count: summary.closed, site })}</li>}
{summary.unknown > 0 && <li>{t('wb.install.strings.unknown', { count: summary.unknown, site })}</li>}
{summary.refused > 0 && <li>{t('wb.install.strings.refused', { count: summary.refused, site })}</li>}
</ul>}
{summary && summary.sample.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.strings.sample')}</strong>{summary.sample.map(text => <span key={text}>{text}</span>)}</div>}
</section>}
{theme !== null && <section className="wbi-theme"> {theme !== null && <section className="wbi-theme">
{props.renderThemePreview?.(theme)} {props.renderThemePreview?.(theme)}
{(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>} {(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>}
</section>} </section>}
{facts?.css ? <CodePreview t={t} text={facts.css} label={t('wb.install.themeCss', { site })}/> : null} {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')}/> <CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : preview.kind === 'strings' ? t('wb.install.strings.file') : t('wb.install.themeFile')}/>
</div> </div>
<footer className="wbi-foot"> <footer className="wbi-foot">
@ -186,10 +214,12 @@ function Done<Theme>({ request, props }: { request: Extract<InstallRequest<Theme
<h2 id="wbi-title">{t('wb.install.done', { name: request.name })}</h2> <h2 id="wbi-title">{t('wb.install.done', { name: request.name })}</h2>
<p>{request.kind === 'plugin' <p>{request.kind === 'plugin'
? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff')) ? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff'))
: request.kind === 'strings'
? (request.enabled ? t('wb.install.done.stringsOn', { site }) : t('wb.install.done.stringsOff'))
: (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p> : (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>} {request.fonts.length > 0 && <p className="wbi-muted">{t('wb.install.done.fonts', { fonts: request.fonts.join(', ') })}</p>}
<div className="wbi-state-actions"> <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.secondary} onClick={() => { controller.close(); props.openSection(request.kind); }}>{request.kind === 'plugin' ? t('wb.install.openPlugins') : request.kind === 'strings' ? t('wb.install.openStrings') : t('wb.install.openAppearance')}</button>
<button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.doneButton')}</button> <button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.doneButton')}</button>
</div> </div>
</div>; </div>;

View file

@ -90,7 +90,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
const [view, setView] = useState<StoreCatalogView | null>(null); const [view, setView] = useState<StoreCatalogView | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [kind, setKind] = useState<'all' | 'theme' | 'plugin'>('all'); const [kind, setKind] = useState<'all' | 'theme' | 'plugin' | 'strings'>('all');
const [category, setCategory] = useState<string>('all'); const [category, setCategory] = useState<string>('all');
const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current); const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current);
@ -137,7 +137,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<p className="wbs-intro">{t('wb.store.intro')}</p> <p className="wbs-intro">{t('wb.store.intro')}</p>
<div className="wbs-toolbar"> <div className="wbs-toolbar">
<SearchField label={t('wb.store.search')} placeholder={t('wb.store.searchPlaceholder')} value={query} onChange={setQuery}/> <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') }]}/> <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') }, ...(items.some(item => item.kind === 'strings') ? [{ value: 'strings' as const, label: t('wb.store.strings') }] : [])]}/>
<Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button> <Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button>
</div> </div>
<div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}> <div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}>
@ -159,9 +159,9 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<div className="wbs-card-body"> <div className="wbs-card-body">
<header> <header>
<h3>{item.name}</h3> <h3>{item.name}</h3>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : t('wb.store.plugin')}</Badge> <Badge>{item.kind === 'theme' ? t('wb.store.theme') : item.kind === 'strings' ? t('wb.store.stringsItem') : t('wb.store.plugin')}</Badge>
</header> </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-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {item.kind === 'strings' && item.language ? item.language : categoryLabel(item.category, t)}{item.license ? ` · ${item.license}` : ''}</p>
<p className="wbs-desc">{item.description}</p> <p className="wbs-desc">{item.description}</p>
{item.kind === 'plugin' && <ul className="wbs-perms" aria-label={t('wb.store.permissions')}> {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>)} {permissionBadges(item.permissions, t, site).map(badge => <li key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</li>)}

View file

@ -62,6 +62,8 @@ export type InstallControllerOptions<Theme> = {
onPluginsChanged?(): void; onPluginsChanged?(): void;
/** A theme was installed (the app refreshes its store/theme views). */ /** A theme was installed (the app refreshes its store/theme views). */
onThemesChanged?(): void; onThemesChanged?(): void;
/** A string pack was installed (the app hands the site tabs the packs that are on). */
onStringsChanged?(): void | Promise<void>;
}; };
export type InstallController<Theme> = { export type InstallController<Theme> = {
@ -98,7 +100,7 @@ export function createInstallController<Theme>(options: InstallControllerOptions
/** Parses a staged theme the way the app's import does, and finds the theme it would update. */ /** 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>> { async function prepared(preview: InstallPreview): Promise<InstallRequest<Theme>> {
if (preview.kind === 'plugin') return { status: 'ready', preview, theme: null, warnings: [], replaces: null }; if (preview.kind === 'plugin' || preview.kind === 'strings') return { status: 'ready', preview, theme: null, warnings: [], replaces: null };
const parsed = themes.parse(preview.text); const parsed = themes.parse(preview.text);
if ('error' in parsed) return { status: 'error', title: t('wb.install.err.theme'), message: parsed.error }; if ('error' in parsed) return { status: 'error', title: t('wb.install.err.theme'), message: parsed.error };
const userThemes = await themes.userThemes(); const userThemes = await themes.userThemes();
@ -135,7 +137,7 @@ export function createInstallController<Theme>(options: InstallControllerOptions
return; return;
} }
if (file.size > MAX_FILE_BYTES[kind]) { 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 }) }); set({ status: 'error', title: t('wb.install.err.large', { file: file.name }), message: kind === 'strings' ? t('wb.install.err.stringsLarge') : t('wb.install.err.largeHint', { kind }) });
return; 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() })); 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() }));
@ -164,6 +166,12 @@ export function createInstallController<Theme>(options: InstallControllerOptions
set({ status: 'done', kind: 'plugin', name: preview.plugin?.name ?? preview.file ?? 'Plugin', fonts: [], enabled: enable || Boolean(preview.existing?.enabled) }); set({ status: 'done', kind: 'plugin', name: preview.plugin?.name ?? preview.file ?? 'Plugin', fonts: [], enabled: enable || Boolean(preview.existing?.enabled) });
return; return;
} }
if (preview.kind === 'strings') {
await backend.invoke('install_commit', { token: preview.token, enable, themeId: null });
await options.onStringsChanged?.();
set({ status: 'done', kind: 'strings', name: preview.strings?.name ?? 'String pack', fonts: [], enabled: enable || Boolean(preview.existing?.enabled) });
return;
}
const own = await themes.userThemes(); const own = await themes.userThemes();
const wanted = themes.idOf(request.theme!); const wanted = themes.idOf(request.theme!);
const taken = [...themes.builtinThemes, ...own.filter(id => id !== request.replaces)]; const taken = [...themes.builtinThemes, ...own.filter(id => id !== request.replaces)];
@ -176,7 +184,7 @@ export function createInstallController<Theme>(options: InstallControllerOptions
options.onThemesChanged?.(); options.onThemesChanged?.();
set({ status: 'done', kind: 'theme', name: themes.facts(parsed.theme).name, themeId: id, fonts: saved.fonts, enabled: saved.enabled }); set({ status: 'done', kind: 'theme', name: themes.facts(parsed.theme).name, themeId: id, fonts: saved.fonts, enabled: saved.enabled });
} catch (error) { } catch (error) {
set({ status: 'error', title: t('wb.install.err.notInstalled', { kind: preview.kind }), message: errorText(error) }); set({ status: 'error', title: preview.kind === 'strings' ? t('wb.install.err.stringsNotInstalled') : t('wb.install.err.notInstalled', { kind: preview.kind }), message: errorText(error) });
} }
}, },
start() { start() {

View file

@ -15,7 +15,7 @@ import { useThemeState } from './themes.ts';
import './plugins.css'; import './plugins.css';
const CONTROLS: Partial<StoreControls> = { Button, SearchField, Segmented, EmptyState, Badge }; const CONTROLS: Partial<StoreControls> = { Button, SearchField, Segmented, EmptyState, Badge };
const RELOAD_ON = ['bt-plugins-changed', 'bt-store-changed']; const RELOAD_ON = ['bt-plugins-changed', 'bt-store-changed', 'bt-strings-changed'];
export function StoreSection({ notify }: { notify: Notify }) { export function StoreSection({ notify }: { notify: Notify }) {
const t = useT(); const t = useT();
@ -26,6 +26,11 @@ export function StoreSection({ notify }: { notify: Notify }) {
const userThemes = themes.choice.themes.map(theme => theme.id); const userThemes = themes.choice.themes.map(theme => theme.id);
async function remove(item: StoreItem, view: StoreCatalogView): Promise<boolean> { async function remove(item: StoreItem, view: StoreCatalogView): Promise<boolean> {
if (item.kind === 'strings') {
await invoke('strings_remove', { id: item.id });
window.dispatchEvent(new CustomEvent('bt-strings-changed'));
return true;
}
if (item.kind === 'plugin' && item.file) { if (item.kind === 'plugin' && item.file) {
await invoke('plugin_remove', { file: item.file }); await invoke('plugin_remove', { file: item.file });
window.dispatchEvent(new CustomEvent('bt-plugins-changed')); window.dispatchEvent(new CustomEvent('bt-plugins-changed'));

View file

@ -0,0 +1,112 @@
// The Languages section: the installed string packs (waybetter/docs/STRING-PACKS.md), which are on
// and in which order, with each pack's coverage against the site's inventory. Every change hands the
// site tabs the new delivery (`strings_apply`: the packs that are on, in order, with the inventory
// slice their keys need); the tabs reload to show it. Packs are data only: nothing here runs code.
import { useEffect, useState } from 'react';
import type { PageInventory } from '../../../runtime/src/stringPacks.ts';
import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts';
import { t as translate } from '../frame/i18n.ts';
import { site } from '../frame/site.ts';
import { buildDelivery, coveragePercent, packSummary, type InstalledStrings, type StringsSummary } from '../stringPacksModel.ts';
import { Badge, Button, EmptyState, Section, Toggle, useSettingsQuery } from './controls.tsx';
import type { PanelSection, SectionProps } from './site.ts';
import './strings.css';
const MAX_ON = 8;
const ICON = 'M2.5 3.5h7M6 2v1.5M8 3.5c-.6 2.9-2.6 5-5.4 6.1M4.6 6.2c.8 1.2 2 2.2 3.4 2.9M9.5 14l3-7 3 7M10.6 11.8h3.8';
type Row = InstalledStrings & { summary: StringsSummary | null };
/** Hands the site tabs the packs that are on (in `packs` order). */
export async function applyStringPacks(inventory: PageInventory, packs?: InstalledStrings[]): Promise<void> {
const list = packs ?? (await invoke<{ packs: InstalledStrings[] }>('strings_list')).packs;
const texts: string[] = [];
for (const pack of list) if (pack.enabled) texts.push(await invoke<string>('strings_read', { id: pack.id }));
await invoke('strings_apply', { delivery: buildDelivery(texts, inventory) });
}
export function createStringPacksSection(options: { inventory: PageInventory; id?: string; icon?: string }): PanelSection {
const { inventory } = options;
function StringPacks({ notify, openSection }: SectionProps) {
const t = useT();
const query = useSettingsQuery();
const name = site().name;
const [rows, setRows] = useState<Row[] | null>(null);
const [busy, setBusy] = useState(false);
const load = async () => {
const { packs } = await invoke<{ packs: InstalledStrings[] }>('strings_list');
const next: Row[] = [];
for (const pack of packs) {
const text = await invoke<string>('strings_read', { id: pack.id }).catch(() => '');
next.push({ ...pack, summary: text ? packSummary(text, inventory) : null });
}
setRows(next);
};
useEffect(() => {
void load().catch(error => notify(String(error), true));
const reload = () => void load().catch(() => {});
window.addEventListener('bt-strings-changed', reload);
return () => window.removeEventListener('bt-strings-changed', reload);
}, []);
/** Saves order and on/off, then hands the tabs the new delivery. */
const save = async (next: Row[]) => {
setBusy(true);
try {
const { packs } = await invoke<{ packs: InstalledStrings[] }>('strings_set', { order: next.map(row => row.id), enabled: next.filter(row => row.enabled).map(row => row.id) });
await applyStringPacks(inventory, packs);
setRows(packs.map(pack => ({ ...pack, summary: next.find(row => row.id === pack.id)?.summary ?? null })));
notify(t('wb.strings.applied', { site: name }));
} catch (error) {
notify(String(error), true);
} finally {
setBusy(false);
}
};
if (query) return null;
if (rows === null) return null;
const on = rows.filter(row => row.enabled).length;
const move = (index: number, by: number) => {
const next = [...rows];
const [row] = next.splice(index, 1);
next.splice(index + by, 0, row!);
void save(next);
};
return <Section title={t('wb.strings.title')} hint={t('wb.strings.intro', { site: name })}>
{rows.length === 0
? <EmptyState title={t('wb.strings.empty')} action={<Button onClick={() => openSection('store')}>{t('wb.strings.openStore')}</Button>}>{t('wb.strings.emptyHint')}</EmptyState>
: <ul className="btp-strings" aria-label={t('wb.strings.title')}>
{rows.map((row, index) => <li key={row.id} className={`btp-strings-row${row.enabled ? ' is-on' : ''}`}>
<Toggle label={t('wb.strings.on', { name: row.name })} checked={row.enabled} disabled={busy || (!row.enabled && on >= MAX_ON)}
onChange={checked => void save(rows.map(item => (item.id === row.id ? { ...item, enabled: checked } : item)))}/>
<div className="btp-strings-text">
<strong>{row.name}</strong> <Badge>{row.language}</Badge> <Badge tone="ok">{t('wb.strings.dataOnly')}</Badge>
<small>
{[row.authors.length ? t('wb.strings.by', { authors: row.authors.join(', ') }) : '', row.version && `v${row.version}`,
row.summary && !row.summary.otherCatalog ? t('wb.install.strings.coverageValue', { translated: String(row.summary.translated), translatable: String(row.summary.translatable), site: name, percent: coveragePercent(row.summary) }) : t('wb.install.strings.count', { count: row.strings })]
.filter(Boolean).join(' · ')}
</small>
</div>
<Button size="sm" label={t('wb.strings.up')} disabled={busy || index === 0} onClick={() => move(index, -1)}>↑</Button>
<Button size="sm" label={t('wb.strings.down')} disabled={busy || index === rows.length - 1} onClick={() => move(index, 1)}>↓</Button>
<Button size="sm" tone="danger" disabled={busy} onClick={() => {
setBusy(true);
void invoke<{ packs: InstalledStrings[] }>('strings_remove', { id: row.id })
.then(async ({ packs }) => { await applyStringPacks(inventory, packs); notify(t('wb.strings.removed', { name: row.name })); await load(); })
.catch(error => notify(String(error), true))
.finally(() => setBusy(false));
}}>{t('wb.strings.remove')}</Button>
</li>)}
</ul>}
{on >= MAX_ON && <p className="btp-hint">{t('wb.strings.limit')}</p>}
</Section>;
}
// The nav label: the plain translator (the panel calls `label()` outside React too).
return { id: options.id ?? 'languages', label: () => translate('wb.strings.section'), icon: options.icon ?? ICON, component: StringPacks };
}

View file

@ -0,0 +1,6 @@
/* The Languages section (StringPacks.tsx): one row per installed string pack. */
.btp-strings { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.btp-strings-row { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 10px; background: var(--c-surface-2, var(--c-surface)); }
.btp-strings-row.is-on { box-shadow: inset 0 0 0 1px var(--c-accent); }
.btp-strings-text { flex: 1; min-width: 0; display: grid; gap: 2px; }
.btp-strings-text small { color: var(--c-text-2, var(--c-muted)); overflow-wrap: anywhere; }

View file

@ -225,3 +225,6 @@
.wb-empty { display: grid; justify-items: center; gap: 8px; padding: 32px 16px; text-align: center; color: var(--wb-text-2); } .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-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); } .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); }
/* String packs on the install screen: what is ignored or cannot be replaced yet. */
.wbi-strings-notes { margin: 6px 0 0; padding-left: 18px; color: var(--wb-muted, inherit); font-size: 12.5px; }

View file

@ -99,14 +99,52 @@ export const STORE_MESSAGES = {
'wb.install.done.fonts': 'It names Google fonts ({fonts}). Appearance can download them for you; until then it uses its fallback fonts.', '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.openPlugins': 'Open Plugins',
'wb.install.openAppearance': 'Open Appearance', 'wb.install.openAppearance': 'Open Appearance',
'wb.install.eyebrow.strings.install': 'Install string pack',
'wb.install.eyebrow.strings.update': 'Update string pack',
'wb.install.eyebrow.strings.reinstall': 'Reinstall string pack',
'wb.install.err.stringsLarge': 'String packs are limited to 2 MB.',
'wb.install.err.stringsNotInstalled': 'The string pack was not installed',
'wb.install.license': 'Licence',
'wb.install.credits': 'Credits',
'wb.install.strings.dataOnly': 'Data only: text that replaces {site}’s own words. No code and no styles; nothing in it runs. Words it does not change stay as {site} shows them.',
'wb.install.strings.language': 'Language',
'wb.install.strings.count': '{count, plural, one {# string} other {# strings}}',
'wb.install.strings.coverage': 'Coverage',
'wb.install.strings.coverageValue': '{translated} of {translatable} of {site}’s strings ({percent})',
'wb.install.strings.closed': '{count, plural, one {# more string of {site} cannot be replaced by a pack yet (rich text, number formats)} other {# more strings of {site} cannot be replaced by a pack yet (rich text, number formats)}}',
'wb.install.strings.unknown': '{count, plural, one {# key {site} does not have is ignored} other {# keys {site} does not have are ignored}}',
'wb.install.strings.refused': '{count, plural, one {# string does not fit {site}’s own and is not used} other {# strings do not fit {site}’s own and are not used}}',
'wb.install.strings.otherCatalog': 'This pack is for another version of {site} (a different set of strings); it would change nothing here.',
'wb.install.strings.sample': 'A sample',
'wb.install.strings.file': 'The pack file',
'wb.install.done.stringsOn': 'Your {site} tabs reload to show it. Turn it off any time in Languages.',
'wb.install.done.stringsOff': 'It is off. Turn it on in Languages when you want it.',
'wb.install.openStrings': 'Open Languages',
'wb.store.strings': 'Languages',
'wb.store.stringsItem': 'String pack',
'wb.strings.section': 'Languages',
'wb.strings.title': 'String packs',
'wb.strings.intro': 'A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.',
'wb.strings.empty': 'No string packs yet',
'wb.strings.emptyHint': 'Get one from the Store, or drop a .strings.json file on the window.',
'wb.strings.openStore': 'Open the Store',
'wb.strings.by': 'by {authors}',
'wb.strings.on': 'Use {name}',
'wb.strings.up': 'Move up',
'wb.strings.down': 'Move down',
'wb.strings.remove': 'Remove',
'wb.strings.removed': '{name} is removed.',
'wb.strings.applied': 'Your {site} tabs reload to apply it.',
'wb.strings.limit': 'At most 8 packs can be on at once.',
'wb.strings.dataOnly': 'Data only',
'wb.install.doneButton': 'Done', 'wb.install.doneButton': 'Done',
'wb.install.drop': 'Drop to install', '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.dropHint': 'A theme (.json), a plugin (.plugin.js) or a string pack (.strings.json). You will see what it is before anything is installed.',
'wb.install.err.theme': 'This theme cannot be 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.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.stage.linkDetail': 'Downloading and checking…',
'wb.install.err.kind': '“{file}” is not a theme or a plugin', 'wb.install.err.kind': '“{file}” is not a theme, a plugin or a string pack',
'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.kindHint': 'wayBetter installs themes (.json), plugins (.plugin.js) and string packs (.strings.json). 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.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.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.named': 'Install {name}',

View file

@ -4,8 +4,9 @@
// lines. Native code validates everything again; nothing here decides what may be installed. // lines. Native code validates everything again; nothing here decides what may be installed.
import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts'; import { STORE_MESSAGES, type StoreKey, type StoreText } from './storeMessages.ts';
import type { StringsInfo } from './stringPacksModel.ts';
export type InstallKind = 'theme' | 'plugin'; export type InstallKind = 'theme' | 'plugin' | 'strings';
export type SourceKind = 'store' | 'link' | 'file'; export type SourceKind = 'store' | 'link' | 'file';
export type PermissionTone = 'plain' | 'warn' | 'ok'; export type PermissionTone = 'plain' | 'warn' | 'ok';
export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone }; export type PermissionBadge = { id: string; label: string; detail: string; tone: PermissionTone };
@ -17,6 +18,10 @@ export type StoreItem = {
kind: InstallKind; id: string; name: string; author: string; version: string; description: 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; 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; preview?: string; permissions?: string[] | null; colors?: { bg: string; surface?: string; text: string; accent: string } | null;
/** String packs: the pack's language tag. */
language?: string;
/** Any kind: its licence and who made, translated or reviewed it. */
license?: string; credits?: string;
}; };
export type InstallRecord = { kind: InstallKind; source: SourceKind; url?: string; storeId?: string; version: string; sha256: string; installedAt: string }; 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 }; export type InstalledPlugin = { version: string; sha256: string; enabled: boolean };
@ -48,6 +53,8 @@ export type InstallPreview = {
version: string; version: string;
plugin: ScriptPluginMeta | null; plugin: ScriptPluginMeta | null;
theme: { name: string; author: string; description: string; cssChars: number } | null; theme: { name: string; author: string; description: string; cssChars: number } | null;
/** String packs: what the pack says about itself (coverage comes from the site's inventory). */
strings?: StringsInfo | null;
findings: string[]; findings: string[];
existing: { version: string; enabled: boolean; same: boolean } | null; existing: { version: string; enabled: boolean; same: boolean } | null;
store: StoreItem | null; store: StoreItem | null;
@ -90,16 +97,17 @@ export function categoryLabel(id: string, t: StoreText): string {
return lookup(t, `wb.store.category.${id}`, undefined, id); return lookup(t, `wb.store.category.${id}`, undefined, id);
} }
/** What a dropped file is, by name: `.plugin.js` → plugin, `.json` → theme, else nothing. */ /** What a dropped file is, by name: `.plugin.js` → plugin, `.strings.json` → string pack, `.json` → theme, else nothing. */
export function kindForFile(name: string): InstallKind | null { export function kindForFile(name: string): InstallKind | null {
const lower = name.toLowerCase(); const lower = name.toLowerCase();
if (lower.endsWith('.plugin.js')) return 'plugin'; if (lower.endsWith('.plugin.js')) return 'plugin';
if (lower.endsWith('.strings.json')) return 'strings';
if (lower.endsWith('.json')) return 'theme'; if (lower.endsWith('.json')) return 'theme';
return null; return null;
} }
/** Largest file the shell reads before handing it to native validation (same caps as native). */ /** 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 }; export const MAX_FILE_BYTES: Readonly<Record<InstallKind, number>> = { theme: 2 * 1024 * 1024, plugin: 2 * 1024 * 1024, strings: 2 * 1024 * 1024 };
/** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */ /** A free theme id: `wanted`, else `wanted-2`, `-3`, … (the way an import names copies). */
export function freeThemeId(wanted: string, taken: Iterable<string>): string { export function freeThemeId(wanted: string, taken: Iterable<string>): string {
@ -153,6 +161,12 @@ export function itemState(item: StoreItem, context: ItemContext): ItemState {
if (newerVersion(item.version, installed.version)) return { state: 'update', ...base }; if (newerVersion(item.version, installed.version)) return { state: 'update', ...base };
return { state: 'modified', ...base }; return { state: 'modified', ...base };
} }
if (item.kind === 'strings') {
const record = context.records[`strings:${item.id}`];
if (!record) return { state: 'install' };
if (record.sha256 === item.sha256) return { state: 'installed', version: record.version };
return newerVersion(item.version, record.version) ? { state: 'update', version: record.version } : { state: 'installed', version: record.version };
}
if (context.builtinThemes.includes(item.id)) return { state: 'builtin' }; if (context.builtinThemes.includes(item.id)) return { state: 'builtin' };
const id = installedThemeId(item, context.records, context.userThemes); const id = installedThemeId(item, context.records, context.userThemes);
if (!id) return { state: 'install' }; if (!id) return { state: 'install' };
@ -173,7 +187,7 @@ export function installedThemeId(item: StoreItem, records: Record<string, Instal
export function filterItems(items: readonly StoreItem[], query: string, kind: InstallKind | 'all', category: string | 'all'): StoreItem[] { export function filterItems(items: readonly StoreItem[], query: string, kind: InstallKind | 'all', category: string | 'all'): StoreItem[] {
const words = query.toLowerCase().split(/\s+/).filter(Boolean); const words = query.toLowerCase().split(/\s+/).filter(Boolean);
return items.filter(item => (kind === 'all' || item.kind === kind) && (category === 'all' || item.category === category) 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))); && words.every(word => [item.name, item.description, item.author, item.category, item.language ?? '', ...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`; export const formatBytes = (bytes: number) => bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(2)} MB`;

View file

@ -0,0 +1,88 @@
// String packs in the shell, pure part (waybetter/docs/STRING-PACKS.md): what the install screen and
// the Languages section say about a pack (coverage against the site's inventory, what is ignored, a
// sample), and the delivery the site tabs get (the packs that are on, in order, with the slice of the
// inventory their keys need). Native code only keeps the data; it never sees the inventory.
import {
compilePack, inventoryLookup, sliceInventory, translatable, type PageInventory,
} from '../../runtime/src/stringPacks.ts';
/** What `strings_list` returns per pack (waybetter-host `InstalledStrings`). */
export type InstalledStrings = {
id: string; site: string; catalog: string; language: string; name: string; authors: string[];
version: string; description: string; strings: number; sha256: string; enabled: boolean;
};
/** The pack as the install screen gets it from native code (waybetter-host `StringsInfo`). */
export type StringsInfo = Omit<InstalledStrings, 'id' | 'sha256' | 'enabled'>;
export type StringsSummary = {
language: string;
/** Strings of the site the pack replaces / strings a pack can replace. */
translated: number;
translatable: number;
/** Keys the site has but no pack can replace yet (rich text, formatters). */
closed: number;
/** Keys the site does not have: ignored. */
unknown: number;
/** Values that do not fit the site's own string (parameters, plural forms, markup): not used. */
refused: number;
/** A few of the pack's own texts, for the screen. */
sample: string[];
/** The pack is for another catalog of the site than this inventory. */
otherCatalog: boolean;
};
const MAX_SAMPLE = 6;
/** Coverage and a sample of a pack's text; `null` when the text is not a pack at all. */
export function packSummary(text: string, inventory: PageInventory): StringsSummary | null {
let pack: unknown;
try { pack = JSON.parse(text); } catch { return null; }
const record = pack as { catalog?: unknown; language?: unknown; strings?: unknown };
if (!record || typeof record !== 'object' || typeof record.strings !== 'object' || record.strings === null) return null;
const language = typeof record.language === 'string' ? record.language : '';
const lookup = inventoryLookup(inventory);
let translatableCount = 0;
let closed = 0;
// The page inventory lists every key once, in its groups: count what a pack can replace.
for (const ids of [inventory.text, inventory.closed]) if (ids) for (const id of ids.split(' ')) { if (lookup(id) && translatable(lookup(id)!.kind)) translatableCount += 1; else closed += 1; }
translatableCount += Object.keys(inventory.message).length;
if (record.catalog !== inventory.catalog) {
return { language, translated: 0, translatable: translatableCount, closed, unknown: Object.keys(record.strings).length, refused: 0, sample: [], otherCatalog: true };
}
let compiled;
try { compiled = compilePack(pack, inventory); } catch { return null; }
const sample: string[] = [];
for (const [id, value] of Object.entries(record.strings as Record<string, unknown>)) {
if (sample.length >= MAX_SAMPLE) break;
if (compiled.values.has(id) && typeof value === 'string' && !value.includes('{') && value.length <= 40) sample.push(value);
}
return {
language, translated: compiled.values.size, translatable: translatableCount, closed,
unknown: compiled.report.unknown.length, refused: compiled.report.rejected.length, sample, otherCatalog: false,
};
}
/** `translated / translatable` as a percentage with one decimal. */
export const coveragePercent = (summary: Pick<StringsSummary, 'translated' | 'translatable'>) =>
summary.translatable ? `${(Math.round(summary.translated / summary.translatable * 1000) / 10).toFixed(1)}%` : '0%';
/**
* What the site tabs get: the texts of the packs that are on, in application order, with the slice
* of the inventory their keys need. `null` when no usable pack is on (the tabs then drop theirs).
*/
export function buildDelivery(texts: readonly string[], inventory: PageInventory): string | null {
const packs: unknown[] = [];
const ids = new Set<string>();
for (const text of texts) {
let pack: unknown;
try { pack = JSON.parse(text); } catch { continue; }
let compiled;
try { compiled = compilePack(pack, inventory); } catch { continue; }
if (!compiled.values.size) continue;
packs.push(pack);
for (const id of compiled.values.keys()) ids.add(id);
if (packs.length >= 8) break;
}
if (!packs.length) return null;
return JSON.stringify({ inventory: sliceInventory(inventory, ids), packs });
}

View file

@ -0,0 +1,41 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { buildDelivery, coveragePercent, packSummary } from '../src/stringPacksModel.ts';
import { kindForFile, itemState, type StoreItem } from '../src/storeModel.ts';
import type { PageInventory } from '../../runtime/src/stringPacks.ts';
const INVENTORY: PageInventory = { site: 'demo', catalog: 'web', text: 'a0000001 a0000002 a0000003', message: { b0000001: 'count*' }, closed: 'c0000001' };
const pack = (strings: Record<string, string>, extra: Record<string, unknown> = {}) => JSON.stringify({
format: 1, site: 'demo', catalog: 'web', language: 'eo', name: 'Esperanto', authors: ['A'], strings, ...extra,
});
test('pack summary: coverage against the inventory, ignored and refused keys, a sample of the pack\'s own text', () => {
const summary = packSummary(pack({ a0000001: 'Hejmo', a0000002: 'Esplori', b0000001: '{count, plural, one {# afiŝo} other {# afiŝoj}}', zzzzzzzz: 'x', a0000003: '<b>x</b>', c0000001: 'y' }), INVENTORY)!;
assert.deepEqual(summary, { language: 'eo', translated: 3, translatable: 4, closed: 1, unknown: 1, refused: 2, sample: ['Hejmo', 'Esplori'], otherCatalog: false });
assert.equal(coveragePercent(summary), '75.0%');
assert.equal(packSummary('not json', INVENTORY), null);
assert.equal(packSummary('{"strings": 1}', INVENTORY), null);
assert.equal(packSummary(pack({ a0000001: 'x' }, { catalog: 'guest' }), INVENTORY)!.otherCatalog, true);
});
test('delivery: the packs that are on, in order, with only the inventory slice their keys need', () => {
const first = pack({ a0000001: 'Hejmo' });
const second = pack({ a0000002: 'Esplori', b0000001: '{count}' }, { name: 'Second' });
const delivery = JSON.parse(buildDelivery([first, second], INVENTORY)!);
assert.deepEqual(delivery.inventory, { site: 'demo', catalog: 'web', text: 'a0000001 a0000002', message: { b0000001: 'count*' }, closed: '', partial: true });
assert.deepEqual(delivery.packs.map((p: { name: string }) => p.name), ['Esperanto', 'Second']);
// Nothing usable: no delivery (the tabs drop theirs).
assert.equal(buildDelivery([], INVENTORY), null);
assert.equal(buildDelivery([pack({ zzzzzzzz: 'x' }), 'junk'], INVENTORY), null);
});
test('store model: string packs by file name and by install record', () => {
assert.equal(kindForFile('eo.strings.json'), 'strings');
assert.equal(kindForFile('theme.json'), 'theme');
const item = { kind: 'strings', id: 'esperanto', version: '1.1.0', sha256: 'b'.repeat(64) } as StoreItem;
const context = { plugins: {}, builtinThemes: [], userThemes: [], records: {} as Record<string, never> };
assert.deepEqual(itemState(item, context), { state: 'install' });
const record = { kind: 'strings' as const, source: 'store' as const, version: '1.0.0', sha256: 'a'.repeat(64), installedAt: '' };
assert.deepEqual(itemState(item, { ...context, records: { 'strings:esperanto': record } as never }), { state: 'update', version: '1.0.0' });
assert.deepEqual(itemState(item, { ...context, records: { 'strings:esperanto': { ...record, sha256: 'b'.repeat(64) } } as never }), { state: 'installed', version: '1.0.0' });
});

View file

@ -124,12 +124,12 @@
"wb.install.openAppearance": "Open Appearance", "wb.install.openAppearance": "Open Appearance",
"wb.install.doneButton": "Done", "wb.install.doneButton": "Done",
"wb.install.drop": "Drop to install", "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.dropHint": "A theme (.json), a plugin (.plugin.js) or a string pack (.strings.json). You will see what it is before anything is installed.",
"wb.install.err.theme": "This theme cannot be 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.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.stage.linkDetail": "Downloading and checking…",
"wb.install.err.kind": "“{file}” is not a theme or a plugin", "wb.install.err.kind": "“{file}” is not a theme, a plugin or a string pack",
"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.kindHint": "wayBetter installs themes (.json), plugins (.plugin.js) and string packs (.strings.json). 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.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.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.named": "Install {name}",
@ -1184,6 +1184,44 @@
"wb.menu.reportTitle": "Report a problem", "wb.menu.reportTitle": "Report a problem",
"wb.menu.reportLede": "This is everything the report contains: versions and what is switched on. No account, no address, nothing from the pages you have open. Copy it, then paste it into your report.", "wb.menu.reportLede": "This is everything the report contains: versions and what is switched on. No account, no address, nothing from the pages you have open. Copy it, then paste it into your report.",
"wb.menu.reportOpen": "Open the issue page", "wb.menu.reportOpen": "Open the issue page",
"wb.menu.reportNoPage": "This app has no public issue page yet. Copy the text and send it to the developer." "wb.menu.reportNoPage": "This app has no public issue page yet. Copy the text and send it to the developer.",
"wb.install.license": "Licence",
"wb.install.credits": "Credits",
"wb.install.strings.dataOnly": "Data only: text that replaces {site}’s own words. No code and no styles; nothing in it runs. Words it does not change stay as {site} shows them.",
"wb.install.strings.language": "Language",
"wb.install.strings.count": "{count, plural, one {# string} other {# strings}}",
"wb.install.strings.coverage": "Coverage",
"wb.install.strings.coverageValue": "{translated} of {translatable} of {site}’s strings ({percent})",
"wb.install.strings.closed": "{count, plural, one {# more string of {site} cannot be replaced by a pack yet (rich text, number formats)} other {# more strings of {site} cannot be replaced by a pack yet (rich text, number formats)}}",
"wb.install.strings.unknown": "{count, plural, one {# key {site} does not have is ignored} other {# keys {site} does not have are ignored}}",
"wb.install.strings.refused": "{count, plural, one {# string does not fit {site}’s own and is not used} other {# strings do not fit {site}’s own and are not used}}",
"wb.install.strings.otherCatalog": "This pack is for another version of {site} (a different set of strings); it would change nothing here.",
"wb.install.strings.sample": "A sample",
"wb.install.strings.file": "The pack file",
"wb.install.done.stringsOn": "Your {site} tabs reload to show it. Turn it off any time in Languages.",
"wb.install.done.stringsOff": "It is off. Turn it on in Languages when you want it.",
"wb.install.openStrings": "Open Languages",
"wb.store.strings": "Languages",
"wb.store.stringsItem": "String pack",
"wb.strings.section": "Languages",
"wb.strings.title": "String packs",
"wb.strings.intro": "A string pack replaces {site}’s own words with text: a language {site} does not offer, a better translation, or your own wording. Packs apply in this order; a later one wins where two change the same word. Words no pack changes stay exactly as {site} shows them.",
"wb.strings.empty": "No string packs yet",
"wb.strings.emptyHint": "Get one from the Store, or drop a .strings.json file on the window.",
"wb.strings.openStore": "Open the Store",
"wb.strings.by": "by {authors}",
"wb.strings.on": "Use {name}",
"wb.strings.up": "Move up",
"wb.strings.down": "Move down",
"wb.strings.remove": "Remove",
"wb.strings.removed": "{name} is removed.",
"wb.strings.applied": "Your {site} tabs reload to apply it.",
"wb.strings.limit": "At most 8 packs can be on at once.",
"wb.strings.dataOnly": "Data only",
"wb.install.eyebrow.strings.install": "Install string pack",
"wb.install.eyebrow.strings.update": "Update string pack",
"wb.install.eyebrow.strings.reinstall": "Reinstall string pack",
"wb.install.err.stringsLarge": "String packs are limited to 2 MB.",
"wb.install.err.stringsNotInstalled": "The string pack was not installed"
} }
} }