From a834b0b513aa9ed4397f7a82a539da291c2cdea1 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 30 Sep 2026 11:34:14 +0000 Subject: [PATCH] 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 --- packages/runtime/src/featureModules.ts | 21 +-- packages/runtime/src/ui.ts | 6 + .../shell/src/frame/pluginCommandStore.ts | 9 +- packages/shell/src/panel/Appearance.tsx | 1 + packages/shell/src/panel/Modes.tsx | 171 ++++++++++++++++++ packages/shell/src/panel/Panel.tsx | 13 +- packages/shell/src/panel/PluginFeatures.tsx | 161 +++++++++++++++++ packages/shell/src/panel/Plugins.tsx | 11 +- packages/shell/src/panel/controls.tsx | 5 +- packages/shell/src/panel/featureModel.ts | 126 +++++++++++++ packages/shell/src/panel/index.ts | 9 +- packages/shell/src/panel/panelMessages.ts | 28 +++ packages/shell/src/panel/plugins.css | 36 ++++ packages/shell/src/panel/site.ts | 17 ++ packages/shell/tests/panel.test.ts | 64 +++++++ packages/waybetter/locales/en.json | 35 +++- 16 files changed, 689 insertions(+), 24 deletions(-) create mode 100644 packages/shell/src/panel/Modes.tsx create mode 100644 packages/shell/src/panel/PluginFeatures.tsx create mode 100644 packages/shell/src/panel/featureModel.ts diff --git a/packages/runtime/src/featureModules.ts b/packages/runtime/src/featureModules.ts index 9ce8ea0..fb6838b 100644 --- a/packages/runtime/src/featureModules.ts +++ b/packages/runtime/src/featureModules.ts @@ -27,23 +27,13 @@ import type { CommandDefinition } from './commands.ts'; import type { PluginI18n } from './pluginI18n.ts'; import type { Dispose, PluginScope, PluginStorage } from './pluginApi.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). */ export const AREA_COMMAND_BUDGET = 5; /** Misses in a row (separate visits) before a feature pauses itself. */ 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. */ export type Probe = string | { selector: string; english?: boolean }; @@ -132,7 +122,7 @@ export type FeatureRegistryOptions = { label: string; /** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */ 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; locale?(): string; /** The signed hotfix data, when the app has any (selector overrides and kill flags). */ @@ -195,8 +185,9 @@ export function createFeatureRegistry(options: FeatureR let stopRoutes: Dispose | null = null; let visit = 0; - const text = (key: keyof typeof FEATURE_MESSAGES, params: Params = {}) => - formatMessage(options.message?.(key) ?? FEATURE_MESSAGES[key], params, options.locale?.() ?? 'en'); + // The registry's own words are the kit's (`kit.feature.*`, `kit.save`): English unless the app delivers them. + 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 english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en'); const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild; @@ -393,7 +384,7 @@ export function createFeatureRegistry(options: FeatureR actions: forms.length ? [ { label: text('kit.cancel') }, { - label: text('kit.feature.save'), tone: 'primary', default: true, + label: text('kit.save'), tone: 'primary', default: true, onClick: handle => { const failed = forms.filter(item => !item.entry.settings.set(item.form.read())); if (failed.length) { handle.setError(text('kit.failed')); return false; } diff --git a/packages/runtime/src/ui.ts b/packages/runtime/src/ui.ts index ae0101b..a95dfd9 100644 --- a/packages/runtime/src/ui.ts +++ b/packages/runtime/src/ui.ts @@ -151,6 +151,12 @@ export const KIT_MESSAGES = { 'kit.value': 'Value', 'kit.checkValue': 'Please check this value.', '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; export type KitKey = keyof typeof KIT_MESSAGES; diff --git a/packages/shell/src/frame/pluginCommandStore.ts b/packages/shell/src/frame/pluginCommandStore.ts index fb5e3e5..2d5f9f6 100644 --- a/packages/shell/src/frame/pluginCommandStore.ts +++ b/packages/shell/src/frame/pluginCommandStore.ts @@ -11,6 +11,13 @@ type Reported = { id: string; title: string; keywords: string }; const byTab = new Map(); let names: Record = {}; +/** Owners that are not plugin files: an app's area plugins, by the owner id their commands carry. */ +let owners: Record = {}; + +/** Names for command owners the Plugins list does not know (createPanel: the feature table's areas). */ +export function setCommandOwnerNames(value: Record) { + owners = { ...value }; +} /** The last web tab that was active (the palette may be opened from the app's panel). */ let lastWebTab: string | null = null; @@ -45,7 +52,7 @@ export function focusedCommands(): { tab: string; items: PluginCommandItem[] } | if (!tab) return undefined; const reported = byTab.get(tab); 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) { diff --git a/packages/shell/src/panel/Appearance.tsx b/packages/shell/src/panel/Appearance.tsx index c586f18..7d93265 100644 --- a/packages/shell/src/panel/Appearance.tsx +++ b/packages/shell/src/panel/Appearance.tsx @@ -278,6 +278,7 @@ export function Appearance({ notify }: { notify: Notify }) { + {(panelSite().appearance?.extra ?? []).map((Extra, index) => window.dispatchEvent(new CustomEvent('bt-panel-section', { detail: id }))}/>)} ; } diff --git a/packages/shell/src/panel/Modes.tsx b/packages/shell/src/panel/Modes.tsx new file mode 100644 index 0000000..ec6aca4 --- /dev/null +++ b/packages/shell/src/panel/Modes.tsx @@ -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(cached); + useEffect(() => { + listeners.add(setState); + if (!cached && featureTable()?.modes.length) invoke('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): Promise { + const plugins = await invoke('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('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
+ {table.modes.map(mode => )} +
; +} + +/** The default illustration: how much of the page a mode touches, as filled bars. */ +function ModeBars({ index, count }: { index: number; count: number }) { + return + {Array.from({ length: count + 2 }, (_, bar) => )} + ; +} + +/** 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(state.existing ? null : recommended); + const [busy, setBusy] = useState(false); + const mode = modeById(table, selected); + + async function finish(next: () => Promise) { + 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('mode_set', { mode: state.mode, onboarded: true })); + + return
+ +

{t('wb.modes.title', { app: panel.brand.name })}

+

{t('wb.modes.lede')}

+ + {state.existing &&

{t('wb.modes.existing', { app: panel.brand.name })}

} +
+ {state.existing && } + {mode && state.existing && } + {mode && } +
+
; +} + +/** 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 ? : 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('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
+ {table.modes.map(mode => { + const current = state.mode === mode.id; + return {current && {t('wb.modes.current')}}{mode.recommended && {t('wb.modes.recommended')}}}> + {asking?.to === mode.id + ? {t('wb.modes.keepQuestion')} {t('wb.modes.keepHint', { count: asking.changes })} + + + + + : } + ; + })} +
; +} + +/** + * 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('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(() => {}); +} diff --git a/packages/shell/src/panel/Panel.tsx b/packages/shell/src/panel/Panel.tsx index aa2b94e..3cf6012 100644 --- a/packages/shell/src/panel/Panel.tsx +++ b/packages/shell/src/panel/Panel.tsx @@ -19,6 +19,8 @@ import { LanguageSettings } from './LanguageSettings.tsx'; import { MakePanel } from './MakePanel.tsx'; import { navEntries } from './nav.ts'; import { NavIcon } from './NavIcon.tsx'; +import { ModeSettings, Onboarding, useModeState } from './Modes.tsx'; +import { AreaPlugins } from './PluginFeatures.tsx'; import { ScriptPlugins } from './Plugins.tsx'; import { PowerSettings } from './PowerSettings.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 Custom = entry?.component ?? null; 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
+ + {notice &&
setNotice(null)}>{notice.text}
} +
; return
@@ -76,7 +84,7 @@ export default function Panel({ section: requested }: { section?: { name: string {!Custom && section === 'home' && } {!Custom && section === 'themes' && } {!Custom && section === 'builder' && } - {!Custom && section === 'plugins' && } + {!Custom && section === 'plugins' && <>} {!Custom && section === 'store' && } {!Custom && section === 'make' && } {!Custom && section === 'accounts' && } @@ -97,6 +105,7 @@ function SettingsSection(props: SectionProps) { const panel = panelSite(); return <> {panel.languages && } + {panel.settings?.alerts && } {site().media && } @@ -124,7 +133,9 @@ function SearchResults({ query, notify, openSection, onClear }: SectionProps & { {panel.languages && } {panel.themes && } {(panel.sections ?? []).filter(section => section.searchable).map(section => )} + + {site().deck && } {panel.settings?.alerts && } diff --git a/packages/shell/src/panel/PluginFeatures.tsx b/packages/shell/src/panel/PluginFeatures.tsx new file mode 100644 index 0000000..212f6d4 --- /dev/null +++ b/packages/shell/src/panel/PluginFeatures.tsx @@ -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, () => Promise] { + const [flags, setFlags] = useState(null); + const latest = useRef(null); + latest.current = flags; + const load = () => invoke('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([]); + useEffect(() => { + const load = () => invoke('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 ? : 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>({}); + const [asking, setAsking] = useState(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('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 {text.description} + {copy && !row.on && {t('wb.features.ownCopy', { name: copy.name ?? copy.file })}} + {asking === row.spec.id && copy && {t('wb.features.ownCopyAsk', { name: copy.name ?? copy.file })} + + + }} + badge={<> + {row.isDefault && {t('wb.features.default')}} + {card && row.spec.backing === 'app' && {t('wb.features.inApp')}} + {row.kind === 'plugin' && {row.missing ? t('wb.features.missing') : t('wb.features.pluginFile')}} + }> + void toggle(row, next)}/> + ; + }; + + const visibleCards = cards.filter(card => !query || card.rows.some(row => shown(row, card))); + return <> + {visibleCards.length > 0 &&
+ {visibleCards.map(card => { + const expanded = !!query || !!open[card.area.id]; + return
+
+ + + {card.settings && hasFeature('pluginCommands') && } + void choose({ [areaFlag(card.area.id)]: next })}/> +
+ {expanded &&
+ {card.groups.map(group => { + const rows = group.rows.map(row => featureRow(row, card)).filter(Boolean); + if (!rows.length) return null; + return
+ {group.id &&

{tx(`features.group.${group.id}`, undefined, group.id)}

} + {rows} +
; + })} +
} +
; + })} +
} + {fixes.some(row => shown(row)) &&
+ {fixes.map(row => featureRow(row))} +
} + ; +} diff --git a/packages/shell/src/panel/Plugins.tsx b/packages/shell/src/panel/Plugins.tsx index d2eed75..0c0344c 100644 --- a/packages/shell/src/panel/Plugins.tsx +++ b/packages/shell/src/panel/Plugins.tsx @@ -8,6 +8,7 @@ import { t as frameText, tx } from '../frame/i18n.ts'; import { site } from '../frame/site.ts'; import { permissionBadges, type InstallRecord } from '../storeModel.ts'; import { Badge, Button, EmptyState, Row, Section, Toggle, useSettingsQuery } from './controls.tsx'; +import { featureFiles } from './featureModel.ts'; import { panelSite } from './site.ts'; import './plugins.css'; @@ -78,6 +79,10 @@ export function ScriptPlugins({ notify }: { notify: Notify }) { 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`). const removable = !!panelSite().store; const folder =
@@ -86,13 +91,13 @@ export function ScriptPlugins({ notify }: { notify: Notify }) {
; return
0 ? folder : undefined}> + action={plugins && (plugins.length > 0 || table) ? folder : undefined}> {error &&
{error}
} - {plugins?.length === 0 && !query && + {listed?.length === 0 && !query && !table && {t('wb.plugins.noneHint')} {PLUGIN_EXAMPLE} } - {plugins?.map(plugin => { + {listed?.map(plugin => { 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 text = pluginText(plugin); diff --git a/packages/shell/src/panel/controls.tsx b/packages/shell/src/panel/controls.tsx index c8a9b27..d6d96a1 100644 --- a/packages/shell/src/panel/controls.tsx +++ b/packages/shell/src/panel/controls.tsx @@ -13,7 +13,8 @@ import { useT } from '../frame/hooks.ts'; const SearchContext = createContext(''); export const SearchProvider = SearchContext.Provider; export const useSettingsQuery = () => useContext(SearchContext); -const matches = (query: string, ...texts: Array) => { +/** Whether every word of the settings search is in one of `texts`. */ +export const matchesQuery = (query: string, ...texts: Array) => { const words = query.toLowerCase().split(/\s+/).filter(Boolean); const hay = texts.filter(Boolean).join(' ').toLowerCase(); 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 }) { const query = useSettingsQuery(); 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
{badge}
diff --git a/packages/shell/src/panel/featureModel.ts b/packages/shell/src/panel/featureModel.ts new file mode 100644 index 0000000..dbf5bc1 --- /dev/null +++ b/packages/shell/src/panel/featureModel.ts @@ -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, plugins: ReadonlyArray): 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, plugins: ReadonlyArray): 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, 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 { + 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, plugins: ReadonlyArray, 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) => { + const defaults = tableDefaults(table); + return Object.keys(defaults).every(key => flags[key] === defaults[key]); +}; diff --git a/packages/shell/src/panel/index.ts b/packages/shell/src/panel/index.ts index 4e41a63..4d702fe 100644 --- a/packages/shell/src/panel/index.ts +++ b/packages/shell/src/panel/index.ts @@ -12,6 +12,7 @@ // before the panel renders. import type { ComponentType } from 'react'; +import { setCommandOwnerNames } from '../frame/pluginCommandStore.ts'; import Panel from './Panel.tsx'; 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. */ export function createPanel(site: PanelSite): PanelComponent { 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; } @@ -31,8 +34,12 @@ export { BUILTIN_SECTIONS, panelSite } from './site.ts'; export { NAV_ICONS, navEntries } from './nav.ts'; // Building blocks for the app's own sections: the panel's controls and the generic pieces. 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, } from './controls.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'; diff --git a/packages/shell/src/panel/panelMessages.ts b/packages/shell/src/panel/panelMessages.ts index 47a2063..d02881c 100644 --- a/packages/shell/src/panel/panelMessages.ts +++ b/packages/shell/src/panel/panelMessages.ts @@ -281,7 +281,20 @@ export const PANEL_MESSAGES = { 'wb.dev.title': 'Live reload', 'wb.dev.turnOn': 'Turn developer mode on to watch your files.', '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.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.builtIn': 'Built-in & system', '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.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.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.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', diff --git a/packages/shell/src/panel/plugins.css b/packages/shell/src/panel/plugins.css index 3cadcfd..bac7aed 100644 --- a/packages/shell/src/panel/plugins.css +++ b/packages/shell/src/panel/plugins.css @@ -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-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); } + +/* 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; } diff --git a/packages/shell/src/panel/site.ts b/packages/shell/src/panel/site.ts index f09f5cb..0f9a6ce 100644 --- a/packages/shell/src/panel/site.ts +++ b/packages/shell/src/panel/site.ts @@ -5,6 +5,7 @@ // frame/site.ts) is read too: the deck (Power User), the media panel and the native features. import type { ComponentType } from 'react'; +import type { FeatureTable } from '../../../runtime/src/featureTable.ts'; import type { ThemeCatalog, ThemeChoice } from '../../../runtime/src/themeChoice.ts'; import type { FontChoice, ThemeColors, ThemeSpec } from '../../../runtime/src/themeSpec.ts'; import type { ResolvedTheme } from '../../../runtime/src/themeApi.ts'; @@ -140,6 +141,22 @@ export type PanelSite = { order?: readonly string[]; /** Themes (Appearance, Theme Builder); omit for an app without them. */ themes?: PanelThemes; + /** What the app adds to Appearance, above the custom CSS editor (X: its logo and wording). */ + appearance?: { extra?: ReadonlyArray> }; + /** + * 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; + /** 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. */ store?: { controller: InstallController }; make?: PanelMake; diff --git a/packages/shell/tests/panel.test.ts b/packages/shell/tests/panel.test.ts index 083cd71..958cfc0 100644 --- a/packages/shell/tests/panel.test.ts +++ b/packages/shell/tests/panel.test.ts @@ -14,6 +14,8 @@ import { compareLines } from '../src/panel/compare.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 { 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 { PANEL_MESSAGES } from '../src/panel/panelMessages.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.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'); +}); diff --git a/packages/waybetter/locales/en.json b/packages/waybetter/locales/en.json index 9bb9f54..422c5d4 100644 --- a/packages/waybetter/locales/en.json +++ b/packages/waybetter/locales/en.json @@ -14,6 +14,11 @@ "kit.value": "Value", "kit.checkValue": "Please check this value.", "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.signedOut": "{handle} · signed out", "wb.account.newName": "New account", @@ -1089,6 +1094,34 @@ "wb.installer.webview2Downloading": "Downloading WebView2 bootstrapper...", "wb.installer.webview2InstallError": "Error: Installing WebView2 failed with exit code {code}", "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" } }