Panel: area plugin cards with per-feature toggles, the Fixes list, modes (first-run screen and Settings)

- PanelSite.features: the app's feature table; AreaPlugins draws one card per area (switch, count, grouped features, Settings button that runs the area's command in the site tab) and the core flags as Fixes
- a feature still backed by an old plugin file is switched through plugin_set_enabled from its card and left out of the JavaScript plugins list
- Modes: Onboarding (three cards, recommended preselected; an existing setup may be kept) and ModeSettings with the keep-my-changes question; openOnboardingWhenDue for ShellSite.start
- flags are saved sparsely (only what differs from the table's defaults)
- PanelSite.appearance.extra; palette commands of an area are listed under its name
- the kit's words for feature settings and health notes; English in the framework catalog
This commit is contained in:
CRTkafa 2026-09-30 18:34:14 +07:00
parent 365f55f604
commit d8619c7482
16 changed files with 689 additions and 24 deletions

View file

@ -27,23 +27,13 @@ import type { CommandDefinition } from './commands.ts';
import type { PluginI18n } from './pluginI18n.ts'; import type { PluginI18n } from './pluginI18n.ts';
import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts'; import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts';
import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts'; import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts';
import type { UiKit } from './ui.ts'; import { KIT_MESSAGES, type KitKey, type UiKit } from './ui.ts';
/** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */ /** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */
export const AREA_COMMAND_BUDGET = 5; export const AREA_COMMAND_BUDGET = 5;
/** Misses in a row (separate visits) before a feature pauses itself. */ /** Misses in a row (separate visits) before a feature pauses itself. */
export const PROBE_STRIKES = 3; export const PROBE_STRIKES = 3;
/** The registry's own words in the page (English source; `kit.feature.*` in the framework catalogs). */
export const FEATURE_MESSAGES = {
'kit.feature.paused': '{feature} ({area}) is paused: this page changed.',
'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.',
'kit.feature.needsEnglish': '{feature} needs the site in English.',
'kit.feature.settings': '{name} settings',
'kit.feature.save': 'Save',
'kit.cancel': 'Cancel',
'kit.failed': 'Something went wrong.',
} as const;
/** A selector a feature depends on; `english`: it reads an English label, so it only counts on an English page. */ /** A selector a feature depends on; `english`: it reads an English label, so it only counts on an English page. */
export type Probe = string | { selector: string; english?: boolean }; export type Probe = string | { selector: string; english?: boolean };
@ -132,7 +122,7 @@ export type FeatureRegistryOptions<Api extends RegistryApi> = {
label: string; label: string;
/** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */ /** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */
surfaces(): readonly string[]; surfaces(): readonly string[];
/** The app catalog's message for `key` in the active language (the registry's `kit.feature.*` words). */ /** The app catalog's message for `key` in the active language (the registry's words are the kit's: `kit.feature.*`, `kit.save`). */
message?(key: string): string | undefined; message?(key: string): string | undefined;
locale?(): string; locale?(): string;
/** The signed hotfix data, when the app has any (selector overrides and kill flags). */ /** The signed hotfix data, when the app has any (selector overrides and kill flags). */
@ -195,8 +185,9 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
let stopRoutes: Dispose | null = null; let stopRoutes: Dispose | null = null;
let visit = 0; let visit = 0;
const text = (key: keyof typeof FEATURE_MESSAGES, params: Params = {}) => // The registry's own words are the kit's (`kit.feature.*`, `kit.save`): English unless the app delivers them.
formatMessage(options.message?.(key) ?? FEATURE_MESSAGES[key], params, options.locale?.() ?? 'en'); const text = (key: KitKey, params: Params = {}) =>
formatMessage(options.message?.(key) ?? KIT_MESSAGES[key], params, options.locale?.() ?? 'en');
const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } }; const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } };
const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en'); const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en');
const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild; const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild;
@ -393,7 +384,7 @@ export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureR
actions: forms.length ? [ actions: forms.length ? [
{ label: text('kit.cancel') }, { label: text('kit.cancel') },
{ {
label: text('kit.feature.save'), tone: 'primary', default: true, label: text('kit.save'), tone: 'primary', default: true,
onClick: handle => { onClick: handle => {
const failed = forms.filter(item => !item.entry.settings.set(item.form.read())); const failed = forms.filter(item => !item.entry.settings.set(item.form.read()));
if (failed.length) { handle.setError(text('kit.failed')); return false; } if (failed.length) { handle.setError(text('kit.failed')); return false; }

View file

@ -151,6 +151,12 @@ export const KIT_MESSAGES = {
'kit.value': 'Value', 'kit.value': 'Value',
'kit.checkValue': 'Please check this value.', 'kit.checkValue': 'Please check this value.',
'kit.failed': 'Something went wrong.', 'kit.failed': 'Something went wrong.',
// Feature modules (featureModules.ts): the settings dialog and the health notes.
'kit.save': 'Save',
'kit.feature.paused': '{feature} ({area}) is paused: this page changed.',
'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.',
'kit.feature.needsEnglish': '{feature} needs the site in English.',
'kit.feature.settings': '{name} settings',
} as const; } as const;
export type KitKey = keyof typeof KIT_MESSAGES; export type KitKey = keyof typeof KIT_MESSAGES;

View file

@ -11,6 +11,13 @@ type Reported = { id: string; title: string; keywords: string };
const byTab = new Map<string, Reported[]>(); const byTab = new Map<string, Reported[]>();
let names: Record<string, string> = {}; let names: Record<string, string> = {};
/** Owners that are not plugin files: an app's area plugins, by the owner id their commands carry. */
let owners: Record<string, string> = {};
/** Names for command owners the Plugins list does not know (createPanel: the feature table's areas). */
export function setCommandOwnerNames(value: Record<string, string>) {
owners = { ...value };
}
/** The last web tab that was active (the palette may be opened from the app's panel). */ /** The last web tab that was active (the palette may be opened from the app's panel). */
let lastWebTab: string | null = null; let lastWebTab: string | null = null;
@ -45,7 +52,7 @@ export function focusedCommands(): { tab: string; items: PluginCommandItem[] } |
if (!tab) return undefined; if (!tab) return undefined;
const reported = byTab.get(tab); const reported = byTab.get(tab);
if (!reported?.length) return undefined; if (!reported?.length) return undefined;
return { tab, items: pluginCommandItems(reported, names) }; return { tab, items: pluginCommandItems(reported, { ...owners, ...names }) };
} }
export function runPluginCommand(tab: string, command: string) { export function runPluginCommand(tab: string, command: string) {

View file

@ -278,6 +278,7 @@ export function Appearance({ notify }: { notify: Notify }) {
</Section> </Section>
<DownloadedFonts notify={notify}/> <DownloadedFonts notify={notify}/>
{(panelSite().appearance?.extra ?? []).map((Extra, index) => <Extra key={index} notify={notify} openSection={id => window.dispatchEvent(new CustomEvent('bt-panel-section', { detail: id }))}/>)}
<CustomCssEditor notify={notify}/> <CustomCssEditor notify={notify}/>
</>; </>;
} }

View file

@ -0,0 +1,171 @@
// Modes: the presets an app's feature table defines (Basic / Advanced / Power User, or whatever the
// app calls them). `Onboarding` is the first-run screen: three cards, one recommended and
// preselected; someone who set the app up before modes existed may dismiss it and keep exactly
// what they have. `ModeSettings` is the same choice later, in Settings, with the question whether
// the owner's own changes stay. A mode is a starting point: choosing one writes flag values
// (`features_set`) and remembers the choice (`mode_get/set`); it never takes a switch away.
import { useEffect, useState, type ComponentType } from 'react';
import { modeById, sparseFlags as sparse, type FeatureTable, type Flags } from '../../../runtime/src/featureTable.ts';
import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts';
import { tx } from '../frame/i18n.ts';
import { shell } from '../frame/state.ts';
import { Badge, Button, Row, Section } from './controls.tsx';
import { modePlan, type PluginFileState } from './featureModel.ts';
import { featureTable, flagsChanged, useFlags } from './PluginFeatures.tsx';
import { panelSite, type Notify } from './site.ts';
import './plugins.css';
/** The onboarding state native code keeps (waybetter-host `modes::ModeState`). */
export type ModeState = { mode: string | null; onboarded: boolean; existing: boolean };
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
const listeners = new Set<(state: ModeState) => void>();
let cached: ModeState | null = null;
/** The mode state, loaded once and shared by the first-run screen and Settings. Null until loaded (or without modes). */
export function useModeState(): [ModeState | null, (next: ModeState) => void] {
const [state, setState] = useState<ModeState | null>(cached);
useEffect(() => {
listeners.add(setState);
if (!cached && featureTable()?.modes.length) invoke<ModeState>('mode_get').then(value => { cached = value; for (const listener of listeners) listener(value); }).catch(() => {});
return () => { listeners.delete(setState); };
}, []);
return [state, next => { cached = next; for (const listener of listeners) listener(next); }];
}
/**
* Applies mode `to`: saves its flags (over the owner's own changes, or under them with `keep`),
* turns off the old plugin files a fresh mode does not have, records the choice and runs the app's
* own step for the mode.
*/
async function applyMode(table: FeatureTable, flags: Flags, from: string | null, to: string, keep: boolean, save: (flags: Flags) => Promise<boolean>): Promise<ModeState | null> {
const plugins = await invoke<PluginFileState[]>('plugins_list').catch(() => [] as PluginFileState[]);
const plan = modePlan(table, flags, plugins, from, to, keep);
if (!await save(plan.flags)) return null;
for (const file of plan.disable) await invoke('plugin_set_enabled', { file, enabled: false }).catch(() => {});
if (plan.disable.length) window.dispatchEvent(new CustomEvent('bt-plugins-changed'));
const state = await invoke<ModeState>('mode_set', { mode: to, onboarded: true });
flagsChanged();
await panelSite().features?.onMode?.(to);
return state;
}
function ModeCards({ table, selected, onSelect, Art }: { table: FeatureTable; selected: string | null; onSelect(id: string): void; Art?: ComponentType<{ mode: string }> }) {
const t = useT();
return <div className="wbm-cards" role="radiogroup" aria-label={t('wb.modes.section')}>
{table.modes.map(mode => <button key={mode.id} type="button" role="radio" aria-checked={selected === mode.id} className={`wbm-card ${selected === mode.id ? 'is-on' : ''}`} onClick={() => onSelect(mode.id)}>
<span className="wbm-art" aria-hidden="true">{Art ? <Art mode={mode.id}/> : <ModeBars index={table.modes.indexOf(mode)} count={table.modes.length}/>}</span>
<strong>{tx(mode.name, undefined, mode.id)}{mode.recommended && <Badge tone="accent">{t('wb.modes.recommended')}</Badge>}</strong>
<span>{tx(mode.description, undefined, '')}</span>
</button>)}
</div>;
}
/** The default illustration: how much of the page a mode touches, as filled bars. */
function ModeBars({ index, count }: { index: number; count: number }) {
return <svg viewBox="0 0 96 40" width="96" height="40">
{Array.from({ length: count + 2 }, (_, bar) => <rect key={bar} x={8 + bar * (80 / (count + 2))} y={8} width={80 / (count + 2) - 5} height={24} rx={3}
fill="currentColor" opacity={bar <= index + 1 ? 0.85 : 0.16}/>)}
</svg>;
}
/** The first-run screen. `done` runs once a mode was chosen or the screen was dismissed. */
export function Onboarding({ state, done, notify }: { state: ModeState; done(next: ModeState): void; notify: Notify }) {
const t = useT();
const table = featureTable()!;
const panel = panelSite();
const [flags] = useFlags(table, notify);
const recommended = table.modes.find(mode => mode.recommended)?.id ?? table.modes[0]?.id ?? null;
// Someone who set the app up before keeps what they have unless they pick a mode themselves.
const [selected, setSelected] = useState<string | null>(state.existing ? null : recommended);
const [busy, setBusy] = useState(false);
const mode = modeById(table, selected);
async function finish(next: () => Promise<ModeState | null>) {
setBusy(true);
try { const result = await next(); if (result) done(result); }
catch (err) { notify(getError(err), true); }
finally { setBusy(false); }
}
const save = async (next: Flags) => { await invoke('features_set', { features: sparse(table, next) }); return true; };
const start = (keep: boolean) => flags && selected && void finish(() => applyMode(table, flags, state.mode, selected, keep, save));
const dismiss = () => void finish(() => invoke<ModeState>('mode_set', { mode: state.mode, onboarded: true }));
return <div className="wbm-onboarding" role="dialog" aria-labelledby="wbm-title">
<img src={panel.brand.logo} alt="" width={44} height={44}/>
<h1 id="wbm-title">{t('wb.modes.title', { app: panel.brand.name })}</h1>
<p>{t('wb.modes.lede')}</p>
<ModeCards table={table} selected={selected} onSelect={setSelected} Art={panel.features?.ModeArt}/>
{state.existing && <p className="wbm-note">{t('wb.modes.existing', { app: panel.brand.name })}</p>}
<div className="wbm-actions">
{state.existing && <Button tone={selected ? 'ghost' : 'primary'} disabled={busy} onClick={dismiss}>{t('wb.modes.keepSetup')}</Button>}
{mode && state.existing && <Button disabled={busy || !flags} onClick={() => start(true)}>{t('wb.modes.keep')}</Button>}
{mode && <Button tone="primary" disabled={busy || !flags} onClick={() => start(false)}>{t('wb.modes.start', { mode: tx(mode.name, undefined, mode.id) })}</Button>}
</div>
</div>;
}
/** Settings: the mode in use and the way to another one, keeping or dropping the owner's changes. */
export function ModeSettings({ notify }: { notify: Notify }) {
const table = featureTable();
return table?.modes.length ? <ModeSettingsOf table={table} notify={notify}/> : null;
}
function ModeSettingsOf({ table, notify }: { table: FeatureTable; notify: Notify }) {
const t = useT();
const [state, setState] = useModeState();
const [flags, , reload] = useFlags(table, notify);
const [asking, setAsking] = useState<{ to: string; changes: number } | null>(null);
if (!state || !flags) return null;
const name = (id: string) => tx(modeById(table, id)?.name ?? id, undefined, id);
const save = async (next: Flags) => { await invoke('features_set', { features: sparse(table, next) }); return true; };
async function apply(to: string, keep: boolean) {
setAsking(null);
try {
const next = await applyMode(table, flags!, state!.mode, to, keep, save);
if (next) { setState(next); await reload(); notify(t('wb.modes.applied', { mode: name(to) })); }
} catch (err) { notify(getError(err), true); }
}
async function choose(to: string) {
const plugins = await invoke<PluginFileState[]>('plugins_list').catch(() => [] as PluginFileState[]);
const changes = modePlan(table, flags!, plugins, state!.mode, to, false).changes;
if (changes > 0) setAsking({ to, changes }); else void apply(to, false);
}
return <Section title={t('wb.modes.section')} hint={t('wb.modes.sectionHint')} id="modes">
{table.modes.map(mode => {
const current = state.mode === mode.id;
return <Row key={mode.id} label={name(mode.id)} hint={tx(mode.description, undefined, '')} keywords={`mode preset ${mode.id}`}
badge={<>{current && <Badge tone="accent">{t('wb.modes.current')}</Badge>}{mode.recommended && <Badge>{t('wb.modes.recommended')}</Badge>}</>}>
{asking?.to === mode.id
? <span className="wbf-ask" role="alertdialog">{t('wb.modes.keepQuestion')} <small>{t('wb.modes.keepHint', { count: asking.changes })}</small>
<Button size="sm" tone="primary" onClick={() => void apply(mode.id, true)}>{t('wb.modes.keep')}</Button>
<Button size="sm" onClick={() => void apply(mode.id, false)}>{t('wb.modes.reset', { mode: name(mode.id) })}</Button>
<Button size="sm" tone="ghost" onClick={() => setAsking(null)}>{t('wb.common.cancel')}</Button>
</span>
: <Button size="sm" onClick={() => void choose(mode.id)}>{t('wb.modes.use')}</Button>}
</Row>;
})}
</Section>;
}
/**
* Opens the app's panel (which shows the first-run screen) when the screen has not been answered.
* Call it from the app's `ShellSite.start`: it waits until the shell has restored its tabs.
*/
export function openOnboardingWhenDue(): void {
if (!featureTable()?.modes.length) return;
invoke<ModeState>('mode_get').then(state => {
cached = state;
if (state.onboarded) return;
let tries = 0;
const timer = setInterval(() => {
tries += 1;
const api = shell.api;
if (api && !shell.restoring && api.panels.length > 0) { clearInterval(timer); shell.openPanel(api.activePanel?.id); }
else if (tries > 80) clearInterval(timer);
}, 250);
}).catch(() => {});
}

View file

@ -19,6 +19,8 @@ import { LanguageSettings } from './LanguageSettings.tsx';
import { MakePanel } from './MakePanel.tsx'; import { MakePanel } from './MakePanel.tsx';
import { navEntries } from './nav.ts'; import { navEntries } from './nav.ts';
import { NavIcon } from './NavIcon.tsx'; import { NavIcon } from './NavIcon.tsx';
import { ModeSettings, Onboarding, useModeState } from './Modes.tsx';
import { AreaPlugins } from './PluginFeatures.tsx';
import { ScriptPlugins } from './Plugins.tsx'; import { ScriptPlugins } from './Plugins.tsx';
import { PowerSettings } from './PowerSettings.tsx'; import { PowerSettings } from './PowerSettings.tsx';
import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx'; import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx';
@ -58,6 +60,12 @@ export default function Panel({ section: requested }: { section?: { name: string
const entry = entries.find(item => item.id === section); const entry = entries.find(item => item.id === section);
const Custom = entry?.component ?? null; const Custom = entry?.component ?? null;
const props: SectionProps = { notify, openSection: go }; const props: SectionProps = { notify, openSection: go };
// The first-run screen stands in for the whole panel until it is answered.
const [modeState, setModeState] = useModeState();
if (modeState && !modeState.onboarded) return <div className="btp-root"><div className="btp is-onboarding">
<Onboarding state={modeState} done={setModeState} notify={notify}/>
{notice && <div key={notice.id} className={`btp-toast ${notice.error ? 'is-error' : ''}`} role={notice.error ? 'alert' : 'status'} onClick={() => setNotice(null)}>{notice.text}</div>}
</div></div>;
return <div className="btp-root"><div className={`btp ${searching ? 'is-searching' : ''}`}> return <div className="btp-root"><div className={`btp ${searching ? 'is-searching' : ''}`}>
<header className="btp-head"> <header className="btp-head">
@ -76,7 +84,7 @@ export default function Panel({ section: requested }: { section?: { name: string
{!Custom && section === 'home' && <Home go={go}/>} {!Custom && section === 'home' && <Home go={go}/>}
{!Custom && section === 'themes' && <Appearance notify={notify}/>} {!Custom && section === 'themes' && <Appearance notify={notify}/>}
{!Custom && section === 'builder' && <ThemeBuilder notify={notify}/>} {!Custom && section === 'builder' && <ThemeBuilder notify={notify}/>}
{!Custom && section === 'plugins' && <ScriptPlugins notify={notify}/>} {!Custom && section === 'plugins' && <><AreaPlugins notify={notify}/><ScriptPlugins notify={notify}/></>}
{!Custom && section === 'store' && <StoreSection notify={notify}/>} {!Custom && section === 'store' && <StoreSection notify={notify}/>}
{!Custom && section === 'make' && <MakePanel {...props}/>} {!Custom && section === 'make' && <MakePanel {...props}/>}
{!Custom && section === 'accounts' && <Accounts/>} {!Custom && section === 'accounts' && <Accounts/>}
@ -97,6 +105,7 @@ function SettingsSection(props: SectionProps) {
const panel = panelSite(); const panel = panelSite();
return <> return <>
{panel.languages && <LanguageSettings/>} {panel.languages && <LanguageSettings/>}
<ModeSettings notify={props.notify}/>
<BrowserSettings notify={props.notify}/> <BrowserSettings notify={props.notify}/>
{panel.settings?.alerts && <AlertSettings notify={props.notify}/>} {panel.settings?.alerts && <AlertSettings notify={props.notify}/>}
{site().media && <MediaSettingsRows notify={props.notify}/>} {site().media && <MediaSettingsRows notify={props.notify}/>}
@ -124,7 +133,9 @@ function SearchResults({ query, notify, openSection, onClear }: SectionProps & {
{panel.languages && <LanguageSettings/>} {panel.languages && <LanguageSettings/>}
{panel.themes && <Appearance notify={notify}/>} {panel.themes && <Appearance notify={notify}/>}
{(panel.sections ?? []).filter(section => section.searchable).map(section => <section.component key={section.id} {...props}/>)} {(panel.sections ?? []).filter(section => section.searchable).map(section => <section.component key={section.id} {...props}/>)}
<AreaPlugins notify={notify}/>
<ScriptPlugins notify={notify}/> <ScriptPlugins notify={notify}/>
<ModeSettings notify={notify}/>
<BrowserSettings notify={notify}/> <BrowserSettings notify={notify}/>
{site().deck && <PowerSettings notify={notify}/>} {site().deck && <PowerSettings notify={notify}/>}
{panel.settings?.alerts && <AlertSettings notify={notify}/>} {panel.settings?.alerts && <AlertSettings notify={notify}/>}

View file

@ -0,0 +1,161 @@
// Area plugins: one card per area of the app's feature table (runtime featureTable.ts), each with
// its switch, its features grouped with a toggle per feature, and a Settings button that opens the
// area's settings dialog in the site tab. Under the cards, the core flags as "Fixes": on in every
// mode, owned by no plugin. Flags are the host's (`features_get/set`, stored sparsely); a feature
// that is still an old plugin file is switched with `plugin_set_enabled`.
import { useEffect, useRef, useState } from 'react';
import { areaFlag, normalizeFlags, sparseFlags, type FeatureTable, type Flags } from '../../../runtime/src/featureTable.ts';
import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts';
import { tx } from '../frame/i18n.ts';
import { focusedCommands, runPluginCommand } from '../frame/pluginCommandStore.ts';
import { hasFeature } from '../frame/site.ts';
import { Badge, Button, Row, Section, Toggle, matchesQuery, useSettingsQuery } from './controls.tsx';
import { areaCards, fixRows, rowKeywords, type AreaCard, type FeatureRow, type PluginFileState } from './featureModel.ts';
import { NavIcon } from './NavIcon.tsx';
import { panelSite, type Notify } from './site.ts';
import './plugins.css';
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
const AREA_ICON = 'M6 2.5v3M10 2.5v3M4 5.5h8V8a4 4 0 0 1-8 0zM8 12v1.5';
/** The app's feature table (an app without one has no area cards). */
export const featureTable = (): FeatureTable | null => panelSite().features?.table ?? null;
/**
* The saved flags as a full map (defaults filled in) and a setter that shows a change at once,
* saves only what differs from the defaults and reverts when native code refuses it.
*/
export function useFlags(table: FeatureTable, notify: Notify): [Flags | null, (patch: Flags) => Promise<boolean>, () => Promise<void>] {
const [flags, setFlags] = useState<Flags | null>(null);
const latest = useRef<Flags | null>(null);
latest.current = flags;
const load = () => invoke<unknown>('features_get').then(value => setFlags(normalizeFlags(table, value))).catch(err => notify(getError(err), true));
useEffect(() => {
void load();
// Another part of the panel changed them (a mode was chosen).
const again = () => void load();
window.addEventListener('wb-features-changed', again);
return () => window.removeEventListener('wb-features-changed', again);
}, []);
async function choose(patch: Flags) {
const before = latest.current;
if (!before) return false;
const next = { ...before, ...patch };
setFlags(next);
try { await invoke('features_set', { features: sparseFlags(table, next) }); return true; }
catch (err) { setFlags(before); notify(getError(err), true); return false; }
}
return [flags, choose, load];
}
/** Tells every `useFlags` that the saved flags changed. */
export const flagsChanged = () => window.dispatchEvent(new CustomEvent('wb-features-changed'));
function usePluginFiles(): [PluginFileState[], (list: PluginFileState[]) => void] {
const [plugins, setPlugins] = useState<PluginFileState[]>([]);
useEffect(() => {
const load = () => invoke<PluginFileState[]>('plugins_list').then(setPlugins).catch(() => {});
void load();
window.addEventListener('bt-plugins-changed', load);
return () => window.removeEventListener('bt-plugins-changed', load);
}, []);
return [plugins, setPlugins];
}
/** The area cards and the Fixes list. Renders nothing for an app without a feature table. */
export function AreaPlugins({ notify }: { notify: Notify }) {
const table = featureTable();
return table ? <AreaPluginsOf table={table} notify={notify}/> : null;
}
function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify }) {
const t = useT();
const query = useSettingsQuery().trim();
const [flags, choose] = useFlags(table, notify);
const [plugins, setPlugins] = usePluginFiles();
const [open, setOpen] = useState<Record<string, boolean>>({});
const [asking, setAsking] = useState<string | null>(null);
if (!flags) return null;
const cards = areaCards(table, flags, plugins);
const fixes = fixRows(table, flags, panelSite().features?.elsewhere);
const words = (row: FeatureRow) => ({ label: tx(row.label, undefined, row.spec.id), description: tx(row.description, undefined, '') });
const shown = (row: FeatureRow, card?: AreaCard) => !query || matchesQuery(query, words(row).label, words(row).description, rowKeywords(row, card?.area));
async function setPlugin(file: string, enabled: boolean) {
try { setPlugins(await invoke<PluginFileState[]>('plugin_set_enabled', { file, enabled })); window.dispatchEvent(new CustomEvent('bt-plugins-changed')); return true; }
catch (err) { notify(getError(err), true); return false; }
}
async function toggle(row: FeatureRow, next: boolean) {
if (row.kind === 'plugin') { await setPlugin(row.spec.file!, next); return; }
// Never the owner's own copy of the old plugin and the built-in feature at once.
if (next && row.ownCopy?.enabled) { setAsking(row.spec.id); return; }
await choose({ [row.spec.id]: next });
}
async function useBuiltIn(row: FeatureRow) {
setAsking(null);
if (row.ownCopy && await setPlugin(row.ownCopy.file, false)) await choose({ [row.spec.id]: true });
}
function openSettings(card: AreaCard) {
const commands = focusedCommands();
const id = `${card.area.owner}:settings`;
if (commands?.items.some(item => item.id === id)) runPluginCommand(commands.tab, id);
else notify(t('wb.features.settingsNoTab'), true);
}
const featureRow = (row: FeatureRow, card?: AreaCard) => {
if (!shown(row, card)) return null;
const text = words(row);
const copy = row.ownCopy;
const locked = row.missing || (!!card && !card.enabled && row.kind === 'flag');
return <Row key={row.spec.id} label={text.label} keywords={`${rowKeywords(row, card?.area)} ${text.description}`}
hint={<>{text.description}
{copy && !row.on && <span className="wbf-note">{t('wb.features.ownCopy', { name: copy.name ?? copy.file })}</span>}
{asking === row.spec.id && copy && <span className="wbf-ask" role="alertdialog">{t('wb.features.ownCopyAsk', { name: copy.name ?? copy.file })}
<Button size="sm" tone="primary" onClick={() => void useBuiltIn(row)}>{t('wb.features.useBuiltIn')}</Button>
<Button size="sm" tone="ghost" onClick={() => setAsking(null)}>{t('wb.common.cancel')}</Button>
</span>}</>}
badge={<>
{row.isDefault && <Badge>{t('wb.features.default')}</Badge>}
{card && row.spec.backing === 'app' && <Badge>{t('wb.features.inApp')}</Badge>}
{row.kind === 'plugin' && <Badge tone={row.missing ? 'warn' : 'plain'}>{row.missing ? t('wb.features.missing') : t('wb.features.pluginFile')}</Badge>}
</>}>
<Toggle label={text.label} checked={row.on} disabled={locked} onChange={next => void toggle(row, next)}/>
</Row>;
};
const visibleCards = cards.filter(card => !query || card.rows.some(row => shown(row, card)));
return <>
{visibleCards.length > 0 && <Section title={t('wb.features.areas')} hint={query ? undefined : t('wb.features.areasHint')} id="areas">
{visibleCards.map(card => {
const expanded = !!query || !!open[card.area.id];
return <div key={card.area.id} className={`wbf-area ${card.enabled ? '' : 'is-off'}`} data-area={card.area.id}>
<div className="wbf-head">
<span className="wbf-icon" aria-hidden="true"><NavIcon d={card.area.icon ?? AREA_ICON}/></span>
<button type="button" className="wbf-title" aria-expanded={expanded} onClick={() => setOpen({ ...open, [card.area.id]: !expanded })}>
<strong>{card.area.name}</strong>
<span className="wbf-count">{t('wb.features.count', { on: card.on, total: card.total })}</span>
<small>{card.enabled ? tx(card.area.description, undefined, '') : t('wb.features.off')}</small>
</button>
{card.settings && hasFeature('pluginCommands') && <Button size="sm" tone="ghost" onClick={() => openSettings(card)}>{t('wb.panel.section.settings')}</Button>}
<Toggle label={t('wb.plugins.enabled', { name: card.area.name })} checked={card.enabled} onChange={next => void choose({ [areaFlag(card.area.id)]: next })}/>
</div>
{expanded && <div className="wbf-body">
{card.groups.map(group => {
const rows = group.rows.map(row => featureRow(row, card)).filter(Boolean);
if (!rows.length) return null;
return <div key={group.id} className="wbf-group">
{group.id && <h3>{tx(`features.group.${group.id}`, undefined, group.id)}</h3>}
{rows}
</div>;
})}
</div>}
</div>;
})}
</Section>}
{fixes.some(row => shown(row)) && <Section title={t('wb.features.fixes')} hint={query ? undefined : t('wb.features.fixesHint')} id="fixes">
{fixes.map(row => featureRow(row))}
</Section>}
</>;
}

View file

@ -8,6 +8,7 @@ import { t as frameText, tx } from '../frame/i18n.ts';
import { site } from '../frame/site.ts'; import { site } from '../frame/site.ts';
import { permissionBadges, type InstallRecord } from '../storeModel.ts'; import { permissionBadges, type InstallRecord } from '../storeModel.ts';
import { Badge, Button, EmptyState, Row, Section, Toggle, useSettingsQuery } from './controls.tsx'; import { Badge, Button, EmptyState, Row, Section, Toggle, useSettingsQuery } from './controls.tsx';
import { featureFiles } from './featureModel.ts';
import { panelSite } from './site.ts'; import { panelSite } from './site.ts';
import './plugins.css'; import './plugins.css';
@ -78,6 +79,10 @@ export function ScriptPlugins({ notify }: { notify: Notify }) {
finally { setBusy(null); } finally { setBusy(null); }
} }
// A plugin file that is a feature of an area card (until it is ported) is switched there.
const table = panelSite().features?.table;
const inCards = table ? featureFiles(table) : null;
const listed = plugins && inCards ? plugins.filter(plugin => !inCards.has(plugin.file)) : plugins;
// Removing a file goes through the install screen's native side (`plugin_remove`). // Removing a file goes through the install screen's native side (`plugin_remove`).
const removable = !!panelSite().store; const removable = !!panelSite().store;
const folder = <div className="bt-inline"> const folder = <div className="bt-inline">
@ -86,13 +91,13 @@ export function ScriptPlugins({ notify }: { notify: Notify }) {
</div>; </div>;
return <Section title={t('wb.plugins.title')} hint={t('wb.plugins.hint')} return <Section title={t('wb.plugins.title')} hint={t('wb.plugins.hint')}
action={plugins && plugins.length > 0 ? folder : undefined}> action={plugins && (plugins.length > 0 || table) ? folder : undefined}>
{error && <div className="bt-alert" role="alert">{error}</div>} {error && <div className="bt-alert" role="alert">{error}</div>}
{plugins?.length === 0 && !query && <EmptyState icon={PLUG} title={t('wb.plugins.none')} action={folder}> {listed?.length === 0 && !query && !table && <EmptyState icon={PLUG} title={t('wb.plugins.none')} action={folder}>
{t('wb.plugins.noneHint')} {t('wb.plugins.noneHint')}
<code className="bt-snippet" style={{ display: 'block' }}>{PLUGIN_EXAMPLE}</code> <code className="bt-snippet" style={{ display: 'block' }}>{PLUGIN_EXAMPLE}</code>
</EmptyState>} </EmptyState>}
{plugins?.map(plugin => { {listed?.map(plugin => {
const record = records[`plugin:${plugin.file}`]; const record = records[`plugin:${plugin.file}`];
const source = record ? (record.source === 'store' ? t('wb.panel.section.store') : record.source === 'link' ? t('wb.plugins.source.link') : t('wb.plugins.source.file')) : null; const source = record ? (record.source === 'store' ? t('wb.panel.section.store') : record.source === 'link' ? t('wb.plugins.source.link') : t('wb.plugins.source.file')) : null;
const text = pluginText(plugin); const text = pluginText(plugin);

View file

@ -13,7 +13,8 @@ import { useT } from '../frame/hooks.ts';
const SearchContext = createContext(''); const SearchContext = createContext('');
export const SearchProvider = SearchContext.Provider; export const SearchProvider = SearchContext.Provider;
export const useSettingsQuery = () => useContext(SearchContext); export const useSettingsQuery = () => useContext(SearchContext);
const matches = (query: string, ...texts: Array<string | undefined>) => { /** Whether every word of the settings search is in one of `texts`. */
export const matchesQuery = (query: string, ...texts: Array<string | undefined>) => {
const words = query.toLowerCase().split(/\s+/).filter(Boolean); const words = query.toLowerCase().split(/\s+/).filter(Boolean);
const hay = texts.filter(Boolean).join(' ').toLowerCase(); const hay = texts.filter(Boolean).join(' ').toLowerCase();
return words.every(word => hay.includes(word)); return words.every(word => hay.includes(word));
@ -46,7 +47,7 @@ export function Section({ title, hint, action, children, id }: { title: string;
export function Row({ label, hint, children, keywords, wide, badge }: { label: string; hint?: ReactNode; children?: ReactNode; keywords?: string; wide?: boolean; badge?: ReactNode }) { export function Row({ label, hint, children, keywords, wide, badge }: { label: string; hint?: ReactNode; children?: ReactNode; keywords?: string; wide?: boolean; badge?: ReactNode }) {
const query = useSettingsQuery(); const query = useSettingsQuery();
const id = useId(); const id = useId();
if (query && !matches(query, label, typeof hint === 'string' ? hint : '', keywords)) return null; if (query && !matchesQuery(query, label, typeof hint === 'string' ? hint : '', keywords)) return null;
return <div className={`bt-row ${wide ? 'is-wide' : ''}`} role="group" aria-labelledby={id}> return <div className={`bt-row ${wide ? 'is-wide' : ''}`} role="group" aria-labelledby={id}>
<div className="bt-row-copy"> <div className="bt-row-copy">
<div className="bt-row-label" id={id}><Mark text={label}/>{badge}</div> <div className="bt-row-label" id={id}><Mark text={label}/>{badge}</div>

View file

@ -0,0 +1,126 @@
// What the Plugins section shows of an app's feature table (runtime featureTable.ts): one card per
// area with its features grouped, the core flags as the Fixes list, and what choosing a mode
// changes. Pure (no React, no native calls), unit-tested under node.
//
// A feature's switch is its flag, or, while it is still an old plugin file that has not been ported
// into its area, that file's enabled state. The card shows both the same way; `kind` says which
// native call a toggle makes.
import {
areaFeatures, areaFlag, coreFeatures, featureWords, manualChanges, switchMode, tableDefaults,
type AreaSpec, type FeatureSpec, type FeatureTable, type Flags,
} from '../../../runtime/src/featureTable.ts';
/** A plugin file as the Plugins list knows it (`plugins_list`). */
export type PluginFileState = { file: string; enabled: boolean; name?: string };
export type FeatureRow = {
spec: FeatureSpec;
/** `flag`: `features_set`; `plugin`: `plugin_set_enabled` on `spec.file`. */
kind: 'flag' | 'plugin';
/** As the owner set it. */
on: boolean;
/** A plugin-backed feature whose file is not in the plugins folder (the owner deleted it). */
missing: boolean;
/** The owner's own copy of the plugin file this feature replaced is still there (null: none). */
ownCopy: PluginFileState | null;
/** On unless the owner turned it off. */
isDefault: boolean;
/** Catalog keys. */
label: string;
description: string;
};
export type AreaCard = {
area: AreaSpec;
/** The area's switch. */
enabled: boolean;
groups: Array<{ id: string; rows: FeatureRow[] }>;
rows: FeatureRow[];
/** Features that are on (whatever the switch says) and how many there are. */
on: number;
total: number;
/** A feature with settings of its own is running: the card offers "Settings". */
settings: boolean;
};
function rowOf(spec: FeatureSpec, flags: Readonly<Flags>, plugins: ReadonlyArray<PluginFileState>): FeatureRow {
const words = featureWords(spec);
const file = spec.backing === 'plugin' ? plugins.find(plugin => plugin.file === spec.file) : undefined;
const ownCopy = spec.backing !== 'plugin' && spec.supersedes ? plugins.find(plugin => plugin.file === spec.supersedes) ?? null : null;
return {
spec,
kind: spec.backing === 'plugin' ? 'plugin' : 'flag',
on: spec.backing === 'plugin' ? !!file?.enabled : flags[spec.id] === true,
missing: spec.backing === 'plugin' && !file,
ownCopy,
isDefault: spec.default,
label: words.label,
description: words.description,
};
}
/** One card per area, in table order; rows keep the table's order inside their group. */
export function areaCards(table: FeatureTable, flags: Readonly<Flags>, plugins: ReadonlyArray<PluginFileState>): AreaCard[] {
return table.areas.map(area => {
const rows = areaFeatures(table, area.id).map(spec => rowOf(spec, flags, plugins));
const groups: AreaCard['groups'] = [];
for (const row of rows) {
const id = row.spec.group ?? '';
const group = groups.find(item => item.id === id) ?? groups[groups.push({ id, rows: [] }) - 1]!;
group.rows.push(row);
}
const enabled = flags[areaFlag(area.id)] !== false;
return {
area, enabled, groups, rows,
on: rows.filter(row => row.on).length,
total: rows.length,
settings: enabled && rows.some(row => row.spec.settings && row.on),
};
});
}
/** The core flags, minus the ones the app shows elsewhere (branding in Appearance, a row in Settings). */
export function fixRows(table: FeatureTable, flags: Readonly<Flags>, elsewhere: readonly string[] = []): FeatureRow[] {
return coreFeatures(table).filter(spec => !elsewhere.includes(spec.id)).map(spec => rowOf(spec, flags, []));
}
/** The plugin files that are rows of a card (the Plugins list below the cards leaves them out). */
export function featureFiles(table: FeatureTable): Set<string> {
return new Set(table.features.filter(feature => feature.backing === 'plugin' && feature.file).map(feature => feature.file!));
}
export type ModePlan = {
/** The full flag map to save. */
flags: Flags;
/** Old plugin files to turn off (a mode starts with none of them; kept when the owner keeps their changes). */
disable: string[];
/** How many of the owner's own choices the new mode would replace (flags and plugin files). */
changes: number;
};
/**
* What choosing mode `to` does while on `from` (null: never chosen). With `keep`, whatever the
* owner changed by hand stays: flags that differ from `from`'s preset, and the old plugin files
* they turned on.
*/
export function modePlan(table: FeatureTable, flags: Readonly<Flags>, plugins: ReadonlyArray<PluginFileState>, from: string | null, to: string, keep: boolean): ModePlan {
const files = featureFiles(table);
const on = plugins.filter(plugin => plugin.enabled && files.has(plugin.file)).map(plugin => plugin.file);
return {
flags: switchMode(table, flags, from, to, keep),
disable: keep ? [] : on,
changes: manualChanges(table, flags, from).length + on.length,
};
}
/** Words the panel search matches for a row besides its label and description. */
export function rowKeywords(row: FeatureRow, area?: AreaSpec): string {
return [row.spec.id, row.spec.keywords, row.spec.file, row.spec.supersedes, area?.name].filter(Boolean).join(' ');
}
/** Whether every flag is what the table starts from (nothing stored). */
export const untouched = (table: FeatureTable, flags: Readonly<Flags>) => {
const defaults = tableDefaults(table);
return Object.keys(defaults).every(key => flags[key] === defaults[key]);
};

View file

@ -12,6 +12,7 @@
// before the panel renders. // before the panel renders.
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import { setCommandOwnerNames } from '../frame/pluginCommandStore.ts';
import Panel from './Panel.tsx'; import Panel from './Panel.tsx';
import { configurePanel, type PanelSite } from './site.ts'; import { configurePanel, type PanelSite } from './site.ts';
@ -21,6 +22,8 @@ export type PanelComponent = ComponentType<{ section?: { name: string; nonce: nu
/** Sets the panel's site for every panel module and returns the panel's root component. Call once. */ /** Sets the panel's site for every panel module and returns the panel's root component. Call once. */
export function createPanel(site: PanelSite): PanelComponent { export function createPanel(site: PanelSite): PanelComponent {
configurePanel(site); configurePanel(site);
// Palette commands of an area plugin are listed under the area's name.
if (site.features) setCommandOwnerNames(Object.fromEntries(site.features.table.areas.map(area => [area.owner, area.name])));
return Panel; return Panel;
} }
@ -31,8 +34,12 @@ export { BUILTIN_SECTIONS, panelSite } from './site.ts';
export { NAV_ICONS, navEntries } from './nav.ts'; export { NAV_ICONS, navEntries } from './nav.ts';
// Building blocks for the app's own sections: the panel's controls and the generic pieces. // Building blocks for the app's own sections: the panel's controls and the generic pieces.
export { export {
Badge, Button, ChipList, ColorField, EmptyState, InputRow, Row, SearchField, SearchProvider, Section, Segmented, Select, Slider, Stepper, Toggle, useSettingsQuery, Badge, Button, ChipList, ColorField, EmptyState, InputRow, Row, SearchField, SearchProvider, Section, Segmented, Select, Slider, Stepper, Toggle, matchesQuery, useSettingsQuery,
type Option, type Option,
} from './controls.tsx'; } from './controls.tsx';
export { FeatureGroups, useFeatures } from './FeatureToggles.tsx'; export { FeatureGroups, useFeatures } from './FeatureToggles.tsx';
// Area plugins and modes (PanelSite.features): the cards, the Fixes list, the first-run screen.
export { AreaPlugins, featureTable, flagsChanged, useFlags } from './PluginFeatures.tsx';
export { ModeSettings, Onboarding, openOnboardingWhenDue, useModeState, type ModeState } from './Modes.tsx';
export { areaCards, featureFiles, fixRows, modePlan, type AreaCard, type FeatureRow, type ModePlan, type PluginFileState } from './featureModel.ts';
export { compareLines } from './compare.ts'; export { compareLines } from './compare.ts';

View file

@ -281,7 +281,20 @@ export const PANEL_MESSAGES = {
'wb.dev.title': 'Live reload', 'wb.dev.title': 'Live reload',
'wb.dev.turnOn': 'Turn developer mode on to watch your files.', 'wb.dev.turnOn': 'Turn developer mode on to watch your files.',
'wb.dev.watching': 'Watching', 'wb.dev.watching': 'Watching',
'wb.features.areas': 'Area plugins',
'wb.features.areasHint': 'One plugin for each part of {site}. Switch a whole plugin off, or open it and pick its features one by one.',
'wb.features.count': '{on} of {total} on',
'wb.features.default': 'default', 'wb.features.default': 'default',
'wb.features.fixes': 'Fixes',
'wb.features.fixesHint': 'On in every mode. No plugin switches them off.',
'wb.features.inApp': 'runs in the app',
'wb.features.missing': 'not installed',
'wb.features.off': 'Off. Its features are paused; your choices are kept.',
'wb.features.ownCopy': 'You have your own copy of {name}, so the built-in feature is off.',
'wb.features.ownCopyAsk': 'Your own copy of {name} is on. Turn it off and use the built-in one?',
'wb.features.pluginFile': 'plugin file',
'wb.features.settingsNoTab': 'Open a {site} tab first, then choose Settings again.',
'wb.features.useBuiltIn': 'Use the built-in one',
'wb.fonts.asSite': 'As {site} draws it', 'wb.fonts.asSite': 'As {site} draws it',
'wb.fonts.builtIn': 'Built-in & system', 'wb.fonts.builtIn': 'Built-in & system',
'wb.fonts.category': 'Category', 'wb.fonts.category': 'Category',
@ -451,6 +464,21 @@ export const PANEL_MESSAGES = {
'wb.make.warn.permissions': 'No @permissions line: the plugin is listed as “legacy, full page access” and gets the whole API. Declare what it uses, e.g. @permissions storage, ui, network:none.', 'wb.make.warn.permissions': 'No @permissions line: the plugin is listed as “legacy, full page access” and gets the whole API. Declare what it uses, e.g. @permissions storage, ui, network:none.',
'wb.make.warn.stop': 'Add stop() that undoes everything start() did (scope.dispose() does it for a scope).', 'wb.make.warn.stop': 'Add stop() that undoes everything start() did (scope.dispose() does it for a scope).',
'wb.make.warn.tag': 'The header has no {tag}.', 'wb.make.warn.tag': 'The header has no {tag}.',
'wb.modes.applied': '{mode} is on.',
'wb.modes.current': 'in use',
'wb.modes.existing': 'You already set {app} up. Nothing changes unless you pick a mode.',
'wb.modes.keep': 'Keep my changes',
'wb.modes.keepHint': '{count, plural, one {# setting you changed would be replaced.} other {# settings you changed would be replaced.}}',
'wb.modes.keepQuestion': 'Keep your manual changes?',
'wb.modes.keepSetup': 'Keep my current setup',
'wb.modes.lede': 'Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.',
'wb.modes.recommended': 'Recommended',
'wb.modes.reset': 'Use {mode} as it is',
'wb.modes.section': 'Mode',
'wb.modes.sectionHint': 'A starting point, not a lock. Changing it never takes a switch away.',
'wb.modes.start': 'Start with {mode}',
'wb.modes.title': 'How much should {app} change {site}?',
'wb.modes.use': 'Use this mode',
'wb.panel.accounts.add': '+ Add account', 'wb.panel.accounts.add': '+ Add account',
'wb.panel.accounts.hint': 'Each account is its own {site} sign-in on this computer and stays signed in across restarts. Click one to open its feed beside this pane.', 'wb.panel.accounts.hint': 'Each account is its own {site} sign-in on this computer and stays signed in across restarts. Click one to open its feed beside this pane.',
'wb.panel.accounts.newTabsBadge': 'new tabs', 'wb.panel.accounts.newTabsBadge': 'new tabs',

View file

@ -16,3 +16,39 @@
.wbx-perms span.is-warn { color: var(--c-warn); border-color: color-mix(in srgb, var(--c-warn) 35%, transparent); } .wbx-perms span.is-warn { color: var(--c-warn); border-color: color-mix(in srgb, var(--c-warn) 35%, transparent); }
.wbx-perms span.is-ok { color: var(--c-ok); border-color: color-mix(in srgb, var(--c-ok) 30%, transparent); } .wbx-perms span.is-ok { color: var(--c-ok); border-color: color-mix(in srgb, var(--c-ok) 30%, transparent); }
.wbx-perms span.is-source { color: var(--c-accent); border-color: rgb(var(--c-accent-rgb) / .3); } .wbx-perms span.is-source { color: var(--c-accent); border-color: rgb(var(--c-accent-rgb) / .3); }
/* Area plugins (PluginFeatures.tsx): one card per area, its features inside. */
.wbf-area + .wbf-area { border-top: 1px solid var(--c-line-soft); }
.wbf-head { display: flex; align-items: center; gap: 12px; padding: 12px 16px; min-height: 60px; }
.wbf-icon { flex: none; display: grid; place-items: center; width: 34px; height: 34px; border-radius: 9px; background: var(--c-accent-soft); color: var(--c-accent); }
.wbf-area.is-off .wbf-icon { background: var(--c-field); color: var(--c-muted); }
.wbf-title { flex: 1; min-width: 0; display: grid; grid-template-columns: auto 1fr; align-items: baseline; column-gap: 8px; padding: 0; border: 0; background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; }
.wbf-title strong { font-size: 14px; font-weight: 620; }
.wbf-title small { grid-column: 1 / -1; margin-top: 2px; color: var(--c-muted); font-size: 12px; line-height: 1.45; }
.wbf-title:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 4px; border-radius: 6px; }
.wbf-count { color: var(--c-muted); font: 500 11px/1 var(--f-mono, ui-monospace, monospace); }
.wbf-body { border-top: 1px solid var(--c-line-soft); background: color-mix(in srgb, var(--c-field) 45%, transparent); }
.wbf-area.is-off .wbf-body .bt-row-copy { opacity: .6; }
.wbf-group h3 { margin: 0; padding: 12px 16px 2px; color: var(--c-muted); font-size: 11px; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; }
.wbf-group + .wbf-group { border-top: 1px solid var(--c-line-soft); }
.wbf-note { display: block; margin-top: 4px; color: var(--c-warn); }
.wbf-ask { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 6px; color: var(--c-text); }
.wbf-ask small { flex-basis: 100%; color: var(--c-muted); }
/* Modes (Modes.tsx): the first-run screen and its cards. */
.btp.is-onboarding { display: grid; place-items: center; overflow: auto; }
.wbm-onboarding { display: flex; flex-direction: column; align-items: center; gap: 10px; width: min(880px, 100%); padding: 40px 24px; text-align: center; }
.wbm-onboarding > img { border-radius: 22%; }
.wbm-onboarding h1 { margin: 8px 0 0; font-size: 24px; font-weight: 680; letter-spacing: -.01em; text-wrap: balance; }
.wbm-onboarding > p { margin: 0; max-width: 58ch; color: var(--c-muted); font-size: 13px; line-height: 1.5; }
.wbm-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 12px; width: 100%; margin: 18px 0 6px; }
.wbm-card { display: flex; flex-direction: column; gap: 8px; padding: 16px; border: 1px solid var(--c-line-soft); border-radius: 14px; background: var(--c-card); color: inherit; font: inherit; text-align: start; cursor: pointer; transition: border-color .12s var(--ease, ease), box-shadow .12s var(--ease, ease); }
.wbm-card:hover { border-color: var(--c-line-strong); }
.wbm-card.is-on { border-color: var(--c-accent); box-shadow: 0 0 0 1px var(--c-accent); }
.wbm-card:focus-visible { outline: 2px solid var(--c-accent); outline-offset: 3px; }
.wbm-card strong { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 15px; font-weight: 640; }
.wbm-card > span:last-child { color: var(--c-muted); font-size: 12.5px; line-height: 1.5; }
.wbm-art { display: grid; place-items: center; height: 72px; border-radius: 10px; background: var(--c-field); color: var(--c-muted); }
.wbm-card.is-on .wbm-art { color: var(--c-accent); }
.wbm-note { color: var(--c-text-2, var(--c-muted)); }
.wbm-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 10px; margin-top: 12px; }

View file

@ -5,6 +5,7 @@
// frame/site.ts) is read too: the deck (Power User), the media panel and the native features. // frame/site.ts) is read too: the deck (Power User), the media panel and the native features.
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import type { FeatureTable } from '../../../runtime/src/featureTable.ts';
import type { ThemeCatalog, ThemeChoice } from '../../../runtime/src/themeChoice.ts'; import type { ThemeCatalog, ThemeChoice } from '../../../runtime/src/themeChoice.ts';
import type { FontChoice, ThemeColors, ThemeSpec } from '../../../runtime/src/themeSpec.ts'; import type { FontChoice, ThemeColors, ThemeSpec } from '../../../runtime/src/themeSpec.ts';
import type { ResolvedTheme } from '../../../runtime/src/themeApi.ts'; import type { ResolvedTheme } from '../../../runtime/src/themeApi.ts';
@ -140,6 +141,22 @@ export type PanelSite = {
order?: readonly string[]; order?: readonly string[];
/** Themes (Appearance, Theme Builder); omit for an app without them. */ /** Themes (Appearance, Theme Builder); omit for an app without them. */
themes?: PanelThemes; themes?: PanelThemes;
/** What the app adds to Appearance, above the custom CSS editor (X: its logo and wording). */
appearance?: { extra?: ReadonlyArray<ComponentType<SectionProps>> };
/**
* Area plugins and modes: the app's feature table (waybetter/runtime/featureTable). With it the
* Plugins section lists one card per area with a toggle per feature, then the core flags as
* "Fixes"; with modes in the table, the first-run screen and Settings offer them.
*/
features?: {
table: FeatureTable;
/** Core flags that have a control of their own elsewhere (not listed under Fixes). */
elsewhere?: readonly string[];
/** Runs after a mode was chosen and its flags were saved (the app's own step for that mode). */
onMode?(mode: string): void | Promise<void>;
/** The illustration on a mode's card of the first-run screen (default: plain bars). */
ModeArt?: ComponentType<{ mode: string }>;
};
/** The install screen's controller: the Store section, and removing a plugin from the list. */ /** The install screen's controller: the Store section, and removing a plugin from the list. */
store?: { controller: InstallController<ThemeSpec> }; store?: { controller: InstallController<ThemeSpec> };
make?: PanelMake; make?: PanelMake;

View file

@ -14,6 +14,8 @@ import { compareLines } from '../src/panel/compare.ts';
import { defaultWeights, parseCatalog, searchFonts, stackFor } from '../src/panel/fonts/catalog.ts'; import { defaultWeights, parseCatalog, searchFonts, stackFor } from '../src/panel/fonts/catalog.ts';
import { CREATE_COMMANDS, KIT_DEMOS, cssVarOf, parsePluginHeader, pluginFileFor, pluginWarnings, validPluginFileName } from '../src/panel/makeModel.ts'; import { CREATE_COMMANDS, KIT_DEMOS, cssVarOf, parsePluginHeader, pluginFileFor, pluginWarnings, validPluginFileName } from '../src/panel/makeModel.ts';
import { anchorOf, inlineTokens, parseMarkdown, resolveLink } from '../src/panel/markdown.ts'; import { anchorOf, inlineTokens, parseMarkdown, resolveLink } from '../src/panel/markdown.ts';
import { sparseFlags, tableDefaults, type FeatureTable } from '../../runtime/src/featureTable.ts';
import { areaCards, featureFiles, fixRows, modePlan, rowKeywords } from '../src/panel/featureModel.ts';
import { navEntries } from '../src/panel/nav.ts'; import { navEntries } from '../src/panel/nav.ts';
import { PANEL_MESSAGES } from '../src/panel/panelMessages.ts'; import { PANEL_MESSAGES } from '../src/panel/panelMessages.ts';
import type { PanelSite } from '../src/panel/site.ts'; import type { PanelSite } from '../src/panel/site.ts';
@ -169,3 +171,65 @@ test('compare: changed lines are marked on both sides', () => {
assert.deepEqual(diff.current.map(line => line.changed), [false, true, false]); assert.deepEqual(diff.current.map(line => line.changed), [false, true, false]);
assert.equal(diff.current[1]!.text, '2'); assert.equal(diff.current[1]!.text, '2');
}); });
// ---------------------------------------------------------------------------------------------
// Area plugins: what the cards show of a feature table, and what choosing a mode changes.
const FEATURE_TABLE: FeatureTable = {
areas: [
{ id: 'navigation', name: 'Navigation+', description: 'plugin.navigation-plus.description', owner: 'wb-navigation-plus.plugin.js', namespace: 'navigation-plus' },
{ id: 'reader', name: 'Reader+', description: 'plugin.reader-plus.description', owner: 'wb-reader-plus.plugin.js', namespace: 'reader-plus' },
],
features: [
{ id: 'logo', area: null, group: 'branding', default: true, backing: 'app' },
{ id: 'fixScroll', area: null, group: 'fixes', default: true, backing: 'app' },
{ id: 'hideTrends', area: 'navigation', group: 'sidebar', default: false, backing: 'module' },
{ id: 'navigation.focusMode', area: 'navigation', group: 'tools', default: false, backing: 'module', settings: true, supersedes: 'wb-focus-mode.plugin.js', keywords: 'Focus Mode' },
{ id: 'hideAds', area: 'reader', group: 'timeline', default: true, backing: 'app' },
{ id: 'reader.cleanLinks', area: 'reader', group: 'posts', default: false, backing: 'plugin', file: 'wb-clean-links.plugin.js', label: 'plugin.clean-links.name' },
{ id: 'reader.readingTime', area: 'reader', group: 'posts', default: false, backing: 'plugin', file: 'wb-reading-time.plugin.js' },
],
modes: [
{ id: 'basic', name: 'mode.basic', description: 'mode.basic.text', flags: { 'area.navigation': false, 'area.reader': false, logo: false } },
{ id: 'advanced', name: 'mode.advanced', description: 'mode.advanced.text', recommended: true, flags: {} },
],
};
test('area cards: a feature is its flag or, until it is ported, its plugin file; the Fixes list is what no area owns', () => {
const flags = { ...tableDefaults(FEATURE_TABLE), 'navigation.focusMode': true };
const plugins = [{ file: 'wb-clean-links.plugin.js', enabled: true, name: 'Clean Links' }, { file: 'mine.plugin.js', enabled: true }];
const [navigation, reader] = areaCards(FEATURE_TABLE, flags, plugins);
assert.deepEqual([navigation!.on, navigation!.total, navigation!.enabled, navigation!.settings], [1, 2, true, true]);
assert.deepEqual(navigation!.groups.map(group => [group.id, group.rows.map(row => row.spec.id)]), [['sidebar', ['hideTrends']], ['tools', ['navigation.focusMode']]]);
assert.deepEqual(reader!.rows.map(row => [row.spec.id, row.kind, row.on, row.missing]), [
['hideAds', 'flag', true, false],
['reader.cleanLinks', 'plugin', true, false],
['reader.readingTime', 'plugin', false, true],
], 'an old plugin file is on when it is enabled; a deleted one cannot be switched');
assert.equal(reader!.rows[1]!.label, 'plugin.clean-links.name');
assert.equal(reader!.rows[0]!.label, 'features.hideAds.label');
assert.deepEqual([...featureFiles(FEATURE_TABLE)].sort(), ['wb-clean-links.plugin.js', 'wb-reading-time.plugin.js'], 'listed in a card, so not again under JavaScript plugins');
// The area's switch off: the card says so and offers no Settings; the feature's own choice is kept.
const off = areaCards(FEATURE_TABLE, { ...flags, 'area.navigation': false }, plugins)[0]!;
assert.deepEqual([off.enabled, off.settings, off.on], [false, false, 1]);
// The owner kept an edited copy of the plugin a feature replaced.
const own = areaCards(FEATURE_TABLE, tableDefaults(FEATURE_TABLE), [{ file: 'wb-focus-mode.plugin.js', enabled: true, name: 'Focus Mode' }])[0]!;
assert.equal(own.rows[1]!.ownCopy?.enabled, true);
assert.equal(own.rows[1]!.on, false, 'never both: the built-in feature stays off while their copy is on');
assert.match(rowKeywords(own.rows[1]!, own.area), /Focus Mode.*wb-focus-mode\.plugin\.js.*Navigation\+/, 'the search finds a feature by its old plugin name');
assert.deepEqual(fixRows(FEATURE_TABLE, flags, ['logo']).map(row => row.spec.id), ['fixScroll'], 'core flags, minus what has a control elsewhere');
});
test('modes: a mode replaces the owner\'s changes or keeps them, old plugin files included', () => {
const defaults = tableDefaults(FEATURE_TABLE);
const mine = { ...defaults, hideTrends: true };
const plugins = [{ file: 'wb-clean-links.plugin.js', enabled: true }, { file: 'mine.plugin.js', enabled: true }];
const fresh = modePlan(FEATURE_TABLE, mine, plugins, null, 'basic', false);
assert.equal(fresh.changes, 2, 'one flag and one old plugin file');
assert.deepEqual(fresh.disable, ['wb-clean-links.plugin.js'], 'a plugin of the owner\'s own is never touched');
assert.deepEqual(sparseFlags(FEATURE_TABLE, fresh.flags), { 'area.navigation': false, 'area.reader': false, logo: false });
const kept = modePlan(FEATURE_TABLE, mine, plugins, null, 'basic', true);
assert.deepEqual(kept.disable, []);
assert.deepEqual(sparseFlags(FEATURE_TABLE, kept.flags), { 'area.navigation': false, 'area.reader': false, logo: false, hideTrends: true });
assert.equal(modePlan(FEATURE_TABLE, defaults, [], 'advanced', 'basic', false).changes, 0, 'nothing of the owner\'s to ask about');
});

View file

@ -14,6 +14,11 @@
"kit.value": "Value", "kit.value": "Value",
"kit.checkValue": "Please check this value.", "kit.checkValue": "Please check this value.",
"kit.failed": "Something went wrong.", "kit.failed": "Something went wrong.",
"kit.save": "Save",
"kit.feature.paused": "{feature} ({area}) is paused: this page changed.",
"kit.feature.pausedOne": "A feature of {area} is paused: this page changed.",
"kit.feature.needsEnglish": "{feature} needs the site in English.",
"kit.feature.settings": "{name} settings",
"wb.account.notSignedIn": "Not signed in yet", "wb.account.notSignedIn": "Not signed in yet",
"wb.account.signedOut": "{handle} · signed out", "wb.account.signedOut": "{handle} · signed out",
"wb.account.newName": "New account", "wb.account.newName": "New account",
@ -1089,6 +1094,34 @@
"wb.installer.webview2Downloading": "Downloading WebView2 bootstrapper...", "wb.installer.webview2Downloading": "Downloading WebView2 bootstrapper...",
"wb.installer.webview2InstallError": "Error: Installing WebView2 failed with exit code {code}", "wb.installer.webview2InstallError": "Error: Installing WebView2 failed with exit code {code}",
"wb.installer.webview2InstallSuccess": "WebView2 installed successfully", "wb.installer.webview2InstallSuccess": "WebView2 installed successfully",
"wb.installer.deleteAppData": "Delete the application data" "wb.installer.deleteAppData": "Delete the application data",
"wb.features.areas": "Area plugins",
"wb.features.areasHint": "One plugin for each part of {site}. Switch a whole plugin off, or open it and pick its features one by one.",
"wb.features.count": "{on} of {total} on",
"wb.features.fixes": "Fixes",
"wb.features.fixesHint": "On in every mode. No plugin switches them off.",
"wb.features.inApp": "runs in the app",
"wb.features.missing": "not installed",
"wb.features.off": "Off. Its features are paused; your choices are kept.",
"wb.features.ownCopy": "You have your own copy of {name}, so the built-in feature is off.",
"wb.features.ownCopyAsk": "Your own copy of {name} is on. Turn it off and use the built-in one?",
"wb.features.pluginFile": "plugin file",
"wb.features.settingsNoTab": "Open a {site} tab first, then choose Settings again.",
"wb.features.useBuiltIn": "Use the built-in one",
"wb.modes.applied": "{mode} is on.",
"wb.modes.current": "in use",
"wb.modes.existing": "You already set {app} up. Nothing changes unless you pick a mode.",
"wb.modes.keep": "Keep my changes",
"wb.modes.keepHint": "{count, plural, one {# setting you changed would be replaced.} other {# settings you changed would be replaced.}}",
"wb.modes.keepQuestion": "Keep your manual changes?",
"wb.modes.keepSetup": "Keep my current setup",
"wb.modes.lede": "Pick a starting point. Every plugin and feature stays individually switchable, and you can change the mode later in Settings.",
"wb.modes.recommended": "Recommended",
"wb.modes.reset": "Use {mode} as it is",
"wb.modes.section": "Mode",
"wb.modes.sectionHint": "A starting point, not a lock. Changing it never takes a switch away.",
"wb.modes.start": "Start with {mode}",
"wb.modes.title": "How much should {app} change {site}?",
"wb.modes.use": "Use this mode"
} }
} }