shell: the panel, createPanel(site) (moved from wayBetter for X)

packages/shell/src/panel (waybetter/shell/panel): an app's own tab. An app describes itself
(PanelSite: brand and the home page's words, its own sections and their order, its theme store,
catalog and the preview component a theme document is drawn in, Make's examples and docs, the
install controller, its languages, what its native side serves) and createPanel returns the
component for ShellSite.panel. It is in the shell package because it is drawn in the frame and
shares its stores, native bridge and language.

- Panel.tsx (header, settings search over every settings section, navigation, toasts; Accounts
  and Updates), nav.ts (which built-in sections an app gets: each shows only when the app serves
  what it needs; the app's sections in its order), Home.tsx (hero, highlights, About from the
  app's data), controls.tsx + panel.css.
- Appearance.tsx, ThemeBuilder.tsx + builderModel.ts + builder.css, fonts/ (FontBrowser, FontRoles,
  catalog, the offline Google Fonts list; scripts/google-fonts-catalog.mjs regenerates it):
  the theme documents are the runtime's, the store, catalog, accents, draft palette, file suffix
  and preview are the app's (PanelSite.themes).
- Plugins.tsx (the plugins list and custom CSS over the host's plugins_*/custom_css_*),
  StoreSection.tsx, MakePanel.tsx + makeModel.ts + MarkdownDoc.tsx + markdown.ts + make.css (the
  examples, the theme file and the docs are the app's), Settings.tsx (links and session over
  settings_get/set with `siteLinks`, keyword alerts, the media panel), FeatureToggles.tsx
  (useFeatures + FeatureGroups over features_get/set: the app names its flags and groups),
  PowerSettings.tsx (deck defaults from site.deck: its flags and presets; DeckPreset gets `name`
  and `hint`), BackupPanel.tsx + backup.css, DeveloperPanel.tsx, LanguageSettings.tsx, compare.ts.
- frame: language.ts (createLanguage: follow the site / the system / one language, i18n_set;
  moved from the app), appI18n.ts (createAppI18n: the app's typed i18n instance, useT, dates and
  numbers; the app passes React's useSyncExternalStore), formatDate in i18n.ts (ShellI18n.date).
- tests/panel.test.ts: every panel key has English and is used, sections per app, the builder
  model, the font catalog, plugin header rules, the UI kit demos, Markdown, compare.
- npm package: exports ./shell/panel, ./shell/panel/*, ./shell/panel/*.css; the build is
  scripts/build.mjs (the shell is compiled with the runtime sources it imports under one root and
  its imports are pointed at dist/runtime; stylesheets and the font list are copied).
This commit is contained in:
CRTkafa 2026-09-30 14:03:40 +07:00
parent 6ef78c0c30
commit 00b193506f
44 changed files with 4864 additions and 2 deletions

View file

@ -0,0 +1,144 @@
// Plugins: the `*.plugin.js` files in the app's plugins folder (on/off live in every site tab, their
// declared permissions, where each came from, removal through the install records) and the custom
// CSS editor. Native code serves them (waybetter-host `plugins_*`, `custom_css_*`).
import { useEffect, useState } from 'react';
import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts';
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 { panelSite } from './site.ts';
import './plugins.css';
/** A `*.plugin.js` file from the local plugins folder (waybetter-host `plugins::ScriptPlugin`). */
export type ScriptPlugin = {
file: string;
name: string;
description: string;
version: string;
author: string;
enabled: boolean;
/** Declared `@permissions`; null/absent = no line (legacy: full API, full page access). */
permissions?: string[] | null;
/** Header problems (e.g. an unknown permission name). */
problems?: string[];
};
type Notify = (text: string, error?: boolean) => void;
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
const PLUG = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0zM12 17v4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>;
/** A bundled plugin's name/description in the active language (`plugin.<file stem>.name`), else its header's. */
export const pluginText = (plugin: { file: string; name: string; description?: string }) => {
const ns = plugin.file.replace(/\.plugin\.js$/i, '');
return { name: tx(`plugin.${ns}.name`, undefined, plugin.name), description: tx(`plugin.${ns}.description`, undefined, plugin.description ?? '') };
};
const PLUGIN_EXAMPLE = '/** @name Hello @description Says hi */\nmodule.exports = class {\n start() { console.log("hi"); }\n stop() {}\n};';
/** BetterDiscord-style JavaScript plugins loaded from the local plugins folder into the site's page. */
export function ScriptPlugins({ notify }: { notify: Notify }) {
const t = useT();
const [plugins, setPlugins] = useState<ScriptPlugin[] | null>(null);
const [error, setError] = useState('');
const [busy, setBusy] = useState<string | null>(null);
const query = useSettingsQuery();
const [records, setRecords] = useState<Record<string, InstallRecord>>({});
const [removing, setRemoving] = useState<string | null>(null);
const refresh = () => {
invoke<{ items: Record<string, InstallRecord> }>('install_records').then(value => setRecords(value.items ?? {})).catch(() => {});
return invoke<ScriptPlugin[]>('plugins_list').then(items => { setPlugins(items); setError(''); }).catch(err => setError(getError(err)));
};
useEffect(() => {
void refresh();
// The install screen (links, dropped files, the Store) added or updated one.
const again = () => void refresh();
window.addEventListener('bt-plugins-changed', again);
return () => window.removeEventListener('bt-plugins-changed', again);
}, []);
async function remove(plugin: ScriptPlugin) {
setRemoving(null);
setBusy(plugin.file);
try {
setPlugins(await invoke<ScriptPlugin[]>('plugin_remove', { file: plugin.file }));
notify(t('wb.common.removedNamed', { name: pluginText(plugin).name }));
} catch (err) { notify(getError(err), true); }
finally { setBusy(null); }
}
async function toggle(plugin: ScriptPlugin) {
setBusy(plugin.file);
try {
setPlugins(await invoke<ScriptPlugin[]>('plugin_set_enabled', { file: plugin.file, enabled: !plugin.enabled }));
notify(plugin.enabled ? t('wb.plugins.stopped', { name: pluginText(plugin).name }) : t('wb.plugins.started', { name: pluginText(plugin).name }));
} catch (err) { notify(getError(err), true); }
finally { setBusy(null); }
}
// Removing a file goes through the install screen's native side (`plugin_remove`).
const removable = !!panelSite().store;
const folder = <div className="bt-inline">
<Button size="sm" onClick={() => void invoke('plugins_open_folder').catch(err => notify(getError(err), true))}>{t('wb.plugins.openFolder')}</Button>
<Button size="sm" tone="ghost" onClick={() => void refresh()}>{t('wb.plugins.rescan')}</Button>
</div>;
return <Section title={t('wb.plugins.title')} hint={t('wb.plugins.hint')}
action={plugins && plugins.length > 0 ? folder : undefined}>
{error && <div className="bt-alert" role="alert">{error}</div>}
{plugins?.length === 0 && !query && <EmptyState icon={PLUG} title={t('wb.plugins.none')} action={folder}>
{t('wb.plugins.noneHint')}
<code className="bt-snippet" style={{ display: 'block' }}>{PLUGIN_EXAMPLE}</code>
</EmptyState>}
{plugins?.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);
return <Row key={plugin.file} label={text.name} hint={<>{text.description || plugin.file}{plugin.author ? ` · ${plugin.author}` : ''}
<span className="wbx-perms">
{permissionBadges(plugin.permissions, frameText, site().name).map(badge => <span key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</span>)}
{source && <span className="is-source" title={record?.url ?? t('wb.plugins.source.fileTitle')}>{source}</span>}
{(plugin.problems ?? []).map(problem => <span key={problem} className="is-warn" title={problem}>{t('wb.plugins.headerProblem')}</span>)}
</span></>} keywords={`plugin ${plugin.file} ${plugin.name} ${(plugin.permissions ?? ['legacy']).join(' ')}`}
badge={<Badge>{plugin.version || t('wb.plugins.noVersion')}</Badge>}>
{!removable ? null : removing === plugin.file
? <><Button size="sm" tone="danger" onClick={() => void remove(plugin)}>{t('wb.plugins.deleteFile')}</Button><Button size="sm" tone="ghost" onClick={() => setRemoving(null)}>{t('wb.plugins.keep')}</Button></>
: <Button size="sm" tone="ghost" disabled={busy === plugin.file} onClick={() => setRemoving(plugin.file)}>{t('wb.common.remove')}</Button>}
<Toggle label={t('wb.plugins.enabled', { name: text.name })} checked={plugin.enabled} disabled={busy === plugin.file} onChange={() => void toggle(plugin)}/>
</Row>;
})}
</Section>;
}
/** Free-form CSS applied to the site's page, like BetterDiscord's Custom CSS. */
export function CustomCssEditor({ notify }: { notify: Notify }) {
const t = useT();
const [css, setCss] = useState('');
const [saved, setSaved] = useState('');
const [loaded, setLoaded] = useState(false);
const query = useSettingsQuery();
useEffect(() => { invoke<string>('custom_css_get').then(value => { setCss(value); setSaved(value); setLoaded(true); }).catch(err => notify(getError(err), true)); }, []);
async function apply() {
try { await invoke('custom_css_set', { css }); setSaved(css); notify(t('wb.css.applied')); }
catch (err) { notify(getError(err), true); }
}
if (query && !`custom css stylesheet style code ${t('wb.css.title')}`.toLowerCase().includes(query.toLowerCase().trim())) return null;
const dirty = css !== saved;
return <Section title={t('wb.css.title')} hint={t('wb.css.hint')}
action={<span className={`bt-status ${dirty ? 'is-warn' : ''}`}>{dirty ? t('wb.css.unsaved') : loaded ? (saved.trim() ? t('wb.css.applied.short') : t('wb.css.empty')) : ''}</span>}>
<div className="bt-code">
<textarea aria-label={t('wb.css.label')} spellCheck={false} value={css} placeholder={panelSite().cssExamples?.custom ?? '/* CSS for the page */'} onChange={event => setCss(event.target.value)}
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); void apply(); } }}/>
<div className="bt-code-bar">
<small>{t('wb.appearance.cssLines', { count: css.split('\n').length })}</small>
{dirty && <Button size="sm" tone="ghost" onClick={() => setCss(saved)}>{t('wb.common.discard')}</Button>}
<Button size="sm" tone="primary" disabled={!loaded || !dirty} onClick={() => void apply()}>{t('wb.common.apply')}</Button>
</div>
</div>
</Section>;
}