// 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 { featureFiles } from './featureModel.ts'; 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 = ; /** A bundled plugin's name/description in the active language (`plugin..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(null); const [error, setError] = useState(''); const [busy, setBusy] = useState(null); const query = useSettingsQuery(); const [records, setRecords] = useState>({}); const [removing, setRemoving] = useState(null); const refresh = () => { invoke<{ items: Record }>('install_records').then(value => setRecords(value.items ?? {})).catch(() => {}); return invoke('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('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('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); } } // 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 = void invoke('plugins_open_folder').catch(err => notify(getError(err), true))}>{t('wb.plugins.openFolder')} void refresh()}>{t('wb.plugins.rescan')} ; return 0 || table) ? folder : undefined}> {error && {error}} {listed?.length === 0 && !query && !table && {t('wb.plugins.noneHint')} {PLUGIN_EXAMPLE} } {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); return {text.description || plugin.file}{plugin.author ? ` ยท ${plugin.author}` : ''} {permissionBadges(plugin.permissions, frameText, site().name).map(badge => {badge.label})} {source && {source}} {(plugin.problems ?? []).map(problem => {t('wb.plugins.headerProblem')})} >} keywords={`plugin ${plugin.file} ${plugin.name} ${(plugin.permissions ?? ['legacy']).join(' ')}`} badge={{plugin.version || t('wb.plugins.noVersion')}}> {!removable ? null : removing === plugin.file ? <> void remove(plugin)}>{t('wb.plugins.deleteFile')} setRemoving(null)}>{t('wb.plugins.keep')}> : setRemoving(plugin.file)}>{t('wb.common.remove')}} void toggle(plugin)}/> ; })} ; } /** 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('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 {dirty ? t('wb.css.unsaved') : loaded ? (saved.trim() ? t('wb.css.applied.short') : t('wb.css.empty')) : ''}}> setCss(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); void apply(); } }}/> {t('wb.appearance.cssLines', { count: css.split('\n').length })} {dirty && setCss(saved)}>{t('wb.common.discard')}} void apply()}>{t('wb.common.apply')} ; }
{PLUGIN_EXAMPLE}