create-waybetter: a new app gets the real panel, the composed runtime and the host's commands

- src/shell/Panel.tsx is createPanel (waybetter/shell/panel) with the app's home page: Home,
  Plugins with custom CSS, Accounts and Settings, growing with what the app serves.
- src/runtime/main.ts is composed with waybetter/runtime/siteRuntime (feature flags, page strings,
  plugin API views per @permissions, the floating panel button).
- Native: the host serves the plugin, custom CSS, feature flag and settings commands
  (AppConfig::new(&SITE, title, &plugins::HOST), app::page_scripts on a loaded page); the app keeps
  tab_report and site_ready. site-tab grants the host's open_panel on the site only, checked with
  assert_site_only.
- HOST_COMMANDS follows commands.rs again (shell_ready, tab_still_ready and the new ones; SITE).
This commit is contained in:
CRTkafa 2026-09-30 14:28:55 +07:00
parent 290123f0b4
commit cceb5182e9
2 changed files with 150 additions and 176 deletions

View file

@ -131,21 +131,32 @@ export function normalizeAppOptions(input) {
/** Where `npm run build` writes what native code and Tauri load (tests check these exist). */ /** Where `npm run build` writes what native code and Tauri load (tests check these exist). */
export const APP_OUTPUTS = { runtime: 'src-tauri/runtime/runtime.js', shell: 'dist/index.html' }; export const APP_OUTPUTS = { runtime: 'src-tauri/runtime/runtime.js', shell: 'dist/index.html' };
/** The app's own native commands and who may call them (build.rs manifest and capability files). */ /**
* The app's own native commands and who may call them (build.rs manifest and capability files).
* A new app has no shell command of its own: the host serves the plugins, custom CSS, tweak flags
* and settings.
*/
const COMMANDS = { const COMMANDS = {
shell: ['plugins_list', 'plugin_set_enabled', 'plugins_open_folder'], shell: [],
tab: ['tab_report'], tab: ['tab_report'],
site: ['site_ready'], site: ['site_ready'],
}; };
/** /**
* The commands waybetter-host serves for every app (`waybetter_host::commands::SHELL` / `TAB`: * The commands waybetter-host serves for every app (`waybetter_host::commands::SHELL` / `TAB` / `SITE`:
* tab layout and actions, shell raise, external links, window menu, profiles, language; tab * tab layout and actions, the shell's focus, first paint and raise, external links, the window
* shortcuts and link drags). The capability files grant them; a test keeps this list in step. * menu, profiles, language, the plugins folder and custom CSS, the page's feature flags and the
* shell's settings; tab shortcuts and link drags; opening the app's panel from a site page). The
* capability files grant them; a test keeps this list in step.
*/ */
export const HOST_COMMANDS = { export const HOST_COMMANDS = {
shell: ['tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_raise', 'window_system_menu', 'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set'], shell: [
'tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu',
'profiles_get', 'profiles_set', 'i18n_get', 'i18n_set',
'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'settings_get', 'settings_set',
],
tab: ['tab_shortcut', 'tab_link_drag'], tab: ['tab_shortcut', 'tab_link_drag'],
site: ['open_panel'],
}; };
const permission = command => `allow-${command.replace(/_/g, '-')}`; const permission = command => `allow-${command.replace(/_/g, '-')}`;
@ -357,10 +368,11 @@ function siteRs(o) {
function pluginsRs(o) { function pluginsRs(o) {
return lines( return lines(
'//! BetterDiscord-style plugins for the site page: `*.plugin.js` files in the app-data', '//! BetterDiscord-style plugins for the site page: `*.plugin.js` files in the app-data',
'//! `plugins` folder and custom CSS, on the waybetter-host plugin store.', '//! `plugins` folder and custom CSS. The plugin store and its commands are the host\'s',
'//! (`waybetter_host::app`: `plugins_list`, `plugin_set_enabled`, `custom_css_*`); this is what the',
'//! app tells it (`AppConfig::new(&SITE, title, &plugins::HOST)`).',
'', '',
'use std::path::PathBuf;', 'use waybetter_host::plugins::PluginHost;',
'use waybetter_host::plugins::{PluginHost, PluginStore};',
'', '',
'pub static HOST: PluginHost = PluginHost {', 'pub static HOST: PluginHost = PluginHost {',
` runtime_global: ${rustStr(o.runtimeGlobal)},`, ` runtime_global: ${rustStr(o.runtimeGlobal)},`,
@ -374,11 +386,6 @@ function pluginsRs(o) {
' bundled: &[],', ' bundled: &[],',
'};', '};',
'', '',
'/// The plugin store in `dir` (the app-data `plugins` folder).',
'pub fn store(dir: PathBuf) -> PluginStore {',
' PluginStore::new(dir, &HOST)',
'}',
'',
'#[cfg(test)]', '#[cfg(test)]',
'mod tests {', 'mod tests {',
' use super::*;', ' use super::*;',
@ -434,83 +441,24 @@ function desktopRs(o) {
'//! The app on the wayBetter host: `waybetter_host::app` makes the window, the trusted local', '//! The app on the wayBetter host: `waybetter_host::app` makes the window, the trusted local',
'//! `shell` webview filling it and one native child webview per tab (placed over the pane', '//! `shell` webview filling it and one native child webview per tab (placed over the pane',
'//! rectangles the shell reports), registers the Tauri plugins and serves the generic commands', '//! rectangles the shell reports), registers the Tauri plugins and serves the generic commands',
'//! (tab layout and actions, shell raise, profiles, language). This file adds the site hooks and', '//! (tab layout and actions, shell raise, profiles, language, the plugins folder and custom CSS,',
'//! the app\'s own commands. Every command re-checks its caller: the capability files are not the', '//! the page\'s feature flags, the shell\'s settings, opening the panel from a site page). This',
'//! boundary.', '//! file adds the site hooks and the app\'s own commands. Every command re-checks its caller: the',
'//! capability files are not the boundary.',
'', '',
'use crate::{plugins, site::SITE};', 'use crate::{plugins, site::SITE};',
'use serde::{Deserialize, Serialize};', 'use serde::{Deserialize, Serialize};',
'use std::sync::{Mutex, MutexGuard};', 'use tauri::{AppHandle, Webview};',
'use tauri::{AppHandle, Manager, State, Webview};',
'use url::Url;', 'use url::Url;',
'use waybetter_host::app::{App, AppConfig, NewTab, SiteHooks};', 'use waybetter_host::app::{self, App, AppConfig, NewTab, SiteHooks};',
'use waybetter_host::bridge::{self, BridgeOptions};', 'use waybetter_host::bridge::{self, BridgeOptions};',
'use waybetter_host::host;', 'use waybetter_host::host;',
'use waybetter_host::plugins::{PluginStore, ScriptPlugin};',
'use waybetter_host::profiles::Account;', 'use waybetter_host::profiles::Account;',
'use waybetter_host::tabs::TabState;', 'use waybetter_host::tabs::TabState;',
'', '',
'/// The page runtime (src/runtime/main.ts), written by `npm run build`.', '/// The page runtime (src/runtime/main.ts), written by `npm run build`.',
'const RUNTIME: &str = include_str!("../runtime/runtime.js");', 'const RUNTIME: &str = include_str!("../runtime/runtime.js");',
'', '',
'struct AppState {',
' plugins: Mutex<PluginStore>,',
'}',
'',
'fn store<\'a>(state: &\'a State<\'_, AppState>) -> Result<MutexGuard<\'a, PluginStore>, String> {',
' state.plugins.lock().map_err(|_| "PLUGINS: state unavailable".to_string())',
'}',
'',
'// ---------------------------------------------------------------------------------------------',
'// Shell-only commands',
'',
'#[tauri::command]',
'async fn plugins_list(webview: Webview, state: State<\'_, AppState>) -> Result<Vec<ScriptPlugin>, String> {',
' host::shell_only(&webview)?;',
' store(&state)?.list()',
'}',
'',
'/// Turns a plugin on or off and starts/stops it live in every site tab.',
'#[tauri::command]',
'async fn plugin_set_enabled(',
' webview: Webview,',
' app: AppHandle,',
' state: State<\'_, AppState>,',
' file: String,',
' enabled: bool,',
') -> Result<Vec<ScriptPlugin>, String> {',
' host::shell_only(&webview)?;',
' let store = store(&state)?;',
' // Built first, so a broken file is reported before it is marked enabled.',
' let script = if enabled {',
' store.start_script(&file)?',
' } else {',
' waybetter_host::plugins::stop_script(&plugins::HOST, &file)?',
' };',
' store.set_enabled(&file, enabled)?;',
' let list = store.list()?;',
' drop(store);',
' host::eval_in_site_tabs(&app, &SITE, &script);',
' Ok(list)',
'}',
'',
'#[tauri::command]',
'async fn plugins_open_folder(webview: Webview, state: State<\'_, AppState>) -> Result<(), String> {',
' host::shell_only(&webview)?;',
' let dir = {',
' let store = store(&state)?;',
' store.ensure()?;',
' store.dir().to_path_buf()',
' };',
' #[cfg(target_os = "windows")]',
' let opener = "explorer";',
' #[cfg(target_os = "macos")]',
' let opener = "open";',
' #[cfg(not(any(target_os = "windows", target_os = "macos")))]',
' let opener = "xdg-open";',
' std::process::Command::new(opener).arg(dir).spawn().map(|_| ()).map_err(|error| format!("PLUGINS: {error}"))',
'}',
'',
'// ---------------------------------------------------------------------------------------------', '// ---------------------------------------------------------------------------------------------',
'// Tab commands', '// Tab commands',
'', '',
@ -572,28 +520,23 @@ function desktopRs(o) {
'struct Site;', 'struct Site;',
'', '',
'impl SiteHooks for Site {', 'impl SiteHooks for Site {',
' fn init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec<String> {', ' fn init_scripts(&self, app: &AppHandle, _tab: &NewTab) -> Vec<String> {',
' vec![', ' vec![',
' // The framework tab bridge: reports each tab\'s URL and title to the address bar and', ' // The framework tab bridge: reports each tab\'s URL and title to the address bar and',
' // forwards its browser shortcuts and link drags to the shell (the shell frame handles both).', ' // forwards its browser shortcuts and link drags to the shell (the shell frame handles both).',
' bridge::script(BridgeOptions::ALL),', ' bridge::script(BridgeOptions::ALL),',
' // The runtime\'s words in the owner\'s language from the first paint (the site only).',
' app::i18n_page_script(app),',
' // The runtime checks the origin itself and stays inert on other sites.', ' // The runtime checks the origin itself and stays inert on other sites.',
' RUNTIME.to_owned(),', ' RUNTIME.to_owned(),',
' ]', ' ]',
' }', ' }',
'', '',
' /// Enabled plugins and custom CSS, evaluated natively (the page\'s CSP cannot block them).', ' /// The page state the host keeps (the feature flags, where links open, custom CSS, the enabled',
' /// plugins), evaluated natively: the page\'s CSP cannot block it.',
' fn site_page_loaded(&self, app: &AppHandle, tab: &Webview, _url: &Url) {', ' fn site_page_loaded(&self, app: &AppHandle, tab: &Webview, _url: &Url) {',
' let scripts = app', ' let mut scripts = vec![app::i18n_page_script(app)];',
' .state::<AppState>()', ' scripts.extend(app::page_scripts(app).map(app::PageScripts::all).unwrap_or_default());',
' .plugins',
' .lock()',
' .map(|store| {',
' let mut scripts: Vec<String> = waybetter_host::plugins::css_script(&plugins::HOST, &store.css()).into_iter().collect();',
' scripts.extend(store.start_scripts());',
' scripts',
' })',
' .unwrap_or_default();',
' for script in scripts {', ' for script in scripts {',
' let _ = tab.eval(&script);', ' let _ = tab.eval(&script);',
' }', ' }',
@ -609,16 +552,10 @@ function desktopRs(o) {
' min_window_size: (720.0, 480.0),', ' min_window_size: (720.0, 480.0),',
' // The shell frame draws the titlebar (tabs in it, caption buttons on Windows).', ' // The shell frame draws the titlebar (tabs in it, caption buttons on Windows).',
' custom_titlebar: true,', ' custom_titlebar: true,',
' ..AppConfig::new(&SITE, SITE.product)', ' // The plugin store (app data `plugins`), the feature flags and the settings are the host\'s.',
' ..AppConfig::new(&SITE, SITE.product, &plugins::HOST)',
' };', ' };',
' App::new(config, Site)', ` App::new(config, Site).run(tauri::generate_context!(), tauri::generate_handler![${[...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site].join(', ')}]);`,
' .setup(|app| {',
' let store = plugins::store(app.path().app_data_dir()?.join("plugins"));',
' store.ensure()?;',
' app.manage(AppState { plugins: Mutex::new(store) });',
' Ok(())',
' })',
` .run(tauri::generate_context!(), tauri::generate_handler![${[...COMMANDS.shell, ...COMMANDS.tab, ...COMMANDS.site].join(', ')}]);`,
'}', '}',
); );
} }
@ -630,6 +567,7 @@ function securityRs(o) {
`//! Who may call which command, read from the capability files, and whether each command checks`, `//! Who may call which command, read from the capability files, and whether each command checks`,
'//! its caller first (waybetter-host `testkit`). Runs with `npm run test:rust`.', '//! its caller first (waybetter-host `testkit`). Runs with `npm run test:rust`.',
'', '',
`use ${o.lib}::site::SITE;`,
'use waybetter_host::testkit::{assert_guarded, assert_host_guards, Capabilities};', 'use waybetter_host::testkit::{assert_guarded, assert_host_guards, Capabilities};',
'', '',
'fn capabilities() -> Capabilities {', 'fn capabilities() -> Capabilities {',
@ -638,21 +576,31 @@ function securityRs(o) {
'', '',
'#[test]', '#[test]',
'fn host_commands_keep_their_callers() {', 'fn host_commands_keep_their_callers() {',
' capabilities().assert_host_commands();', ' let caps = capabilities();',
' caps.assert_host_commands();',
' assert_host_guards();', ' assert_host_guards();',
' // The host\'s site commands (opening the panel from a page) are for tabs on the site only.',
' for command in waybetter_host::commands::SITE {',
' caps.assert_site_only(command, &SITE);',
' }',
'}', '}',
'', '',
'#[test]', '#[test]',
'fn app_commands_keep_their_callers() {', 'fn app_commands_keep_their_callers() {',
' let caps = capabilities();', ' let caps = capabilities();',
' let source = include_str!("../src/desktop.rs");', ' let source = include_str!("../src/desktop.rs");',
...(COMMANDS.shell.length ? [
` for command in [${quote(COMMANDS.shell)}] {`, ` for command in [${quote(COMMANDS.shell)}] {`,
' caps.assert_shell_only(command);', ' caps.assert_shell_only(command);',
' assert_guarded(source, command, "host::shell_only(&webview)?");', ' assert_guarded(source, command, "host::shell_only(&webview)?");',
' }', ' }',
` for command in [${quote([...COMMANDS.tab, ...COMMANDS.site])}] {`, ] : []),
` for command in [${quote(COMMANDS.tab)}] {`,
' caps.assert_tab_only(command);', ' caps.assert_tab_only(command);',
' }', ' }',
` for command in [${quote(COMMANDS.site)}] {`,
' caps.assert_site_only(command, &SITE);',
' }',
' assert_guarded(source, "tab_report", "host::tab_only(&webview)?");', ' assert_guarded(source, "tab_report", "host::tab_only(&webview)?");',
' assert_guarded(source, "site_ready", "host::site_tab_only(&SITE, &webview)?");', ' assert_guarded(source, "site_ready", "host::site_tab_only(&SITE, &webview)?");',
' // Only Rust drives the Tauri plugins; no capability exposes their JS APIs.', ' // Only Rust drives the Tauri plugins; no capability exposes their JS APIs.',
@ -704,7 +652,7 @@ function capabilities(o) {
path: 'src-tauri/capabilities/shell.json', path: 'src-tauri/capabilities/shell.json',
content: cap({ content: cap({
identifier: 'shell', identifier: 'shell',
description: 'The trusted local shell: tabs (the wayBetter host\'s layout, actions, profiles and language) and plugins. No generic filesystem or shell APIs.', description: 'The trusted local shell: the wayBetter host\'s commands (tab layout and actions, profiles, language, plugins and custom CSS, tweaks, settings). No generic filesystem or shell APIs.',
webviews: [/** policy::SHELL_LABEL */ 'shell'], webviews: [/** policy::SHELL_LABEL */ 'shell'],
local: true, local: true,
permissions: ['core:event:default', ...WINDOW_PERMISSIONS, ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)], permissions: ['core:event:default', ...WINDOW_PERMISSIONS, ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)],
@ -725,11 +673,11 @@ function capabilities(o) {
path: 'src-tauri/capabilities/site-tab.json', path: 'src-tauri/capabilities/site-tab.json',
content: cap({ content: cap({
identifier: 'site-tab', identifier: 'site-tab',
description: `Tabs on ${o.site.hosts.join(', ')} only: the app's short, reviewed list of site commands.`, description: `Tabs on ${o.site.hosts.join(', ')} only: the app's short, reviewed list of site commands, and the host's (opening the app's panel).`,
webviews: ['tab-*'], webviews: ['tab-*'],
local: false, local: false,
remote: { urls: o.site.hosts.map(host => `https://${host}/*`) }, remote: { urls: o.site.hosts.map(host => `https://${host}/*`) },
permissions: COMMANDS.site.map(permission), permissions: [...COMMANDS.site.map(permission), ...HOST_COMMANDS.site.map(permission)],
}), }),
}, },
]; ];
@ -849,45 +797,61 @@ function addressTs(o) {
); );
} }
function runtimeTs() { function runtimeTs(o) {
return lines( return lines(
'// The page runtime, injected into every tab and active only on the site\'s origin (top frame).', '// The page runtime, injected into every tab and active only on the site\'s origin (top frame).',
'// It sets `window.<runtimeGlobal>` (and the `window.wayBetter` alias plugins use) with the', '// It is composed with the framework\'s helpers (waybetter/runtime/siteRuntime): the runtime',
'// plugin API; native code then evaluates the enabled `*.plugin.js` files against it.', '// object under `window.<runtimeGlobal>` (and the `window.wayBetter` name plugins use) with the',
'// plugin API and what native code delivers (the feature flags, the link setting, the language);',
'// native code then evaluates the enabled `*.plugin.js` files against it.',
'', '',
"import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';", "import { installAccountReport } from 'waybetter/runtime/accountReport';",
"import { createCorePluginApi, type CorePluginApi } from 'waybetter/runtime/pluginApi';",
"import { installAccountReport, type Invoke } from 'waybetter/runtime/accountReport';",
"import { installLinkRouting } from 'waybetter/runtime/linkRouting';", "import { installLinkRouting } from 'waybetter/runtime/linkRouting';",
"import { createPageStrings } from 'waybetter/runtime/pageStrings';",
"import { installPanelButton } from 'waybetter/runtime/panelButton';",
"import { createPluginContext } from 'waybetter/runtime/permissions';",
"import { createCorePluginApi } from 'waybetter/runtime/pluginApi';",
"import { configureRuntime, isSiteUrl } from 'waybetter/runtime/site';",
"import { createFeatureFlags, installSiteRuntime, pageInvoke, type FlagInstaller } from 'waybetter/runtime/siteRuntime';",
"import { KIT_MESSAGES } from 'waybetter/runtime/ui';",
"import { SITE } from '../site.ts';", "import { SITE } from '../site.ts';",
'', '',
'type Runtime = {', '/**',
' api: CorePluginApi;', ' * PLACEHOLDER: the app\'s page tweaks. Each flag is a boolean the owner toggles in the panel',
' /** Running plugins by file (native start/stop scripts manage this). */', ' * (waybetter/shell/panel `useFeatures` + `FeatureGroups`; native `features_set` delivers them); a part that',
' plugins: Record<string, unknown>;', ' * installs when its flag turns on and disposes when it turns off goes into `INSTALLERS`.',
' /** Load errors by plugin file. */', ' */',
' errors: Record<string, string>;', 'const FLAGS: Record<string, boolean> = {};',
'};', 'const INSTALLERS: FlagInstaller<typeof FLAGS>[] = [];',
'', '',
'type TauriInternals = { invoke(command: string, args: Record<string, unknown>): Promise<unknown> };', '/** The app\'s logo for the floating panel button (a data URI: the site\'s CSP may block other images). */',
`const LOGO = ${str(`data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="${o.site.accent}"/></svg>`)}`)};`,
'', '',
'function install(): void {', 'function install(): void {',
' if (window.top !== window || !isSiteUrl(SITE, location.href)) return;', ' if (window.top !== window || !isSiteUrl(SITE, location.href)) return;',
' const globals = window as unknown as Record<string, unknown>;', ' if ((window as unknown as Record<string, unknown>)[SITE.runtimeGlobal]) return;',
' if (globals[SITE.runtimeGlobal]) return;',
' configureRuntime(SITE);', ' configureRuntime(SITE);',
' const invoke = pageInvoke(window, SITE.product);',
' const flags = createFeatureFlags({ defaults: FLAGS, label: SITE.product, installers: INSTALLERS, document });',
' // English for the plugin UI kit\'s own words; native code delivers the owner\'s language (i18n_set).',
" const strings = createPageStrings({ english: { ...KIT_MESSAGES }, prefixes: ['kit.', 'plugin.'], label: SITE.product });",
' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`', ' // No theme engine yet: `api.theme` reports the page\'s own colors. Pass `{ theme: source }`',
' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.',
' const api = createCorePluginApi(window, SITE.plugins);', ' const api = createCorePluginApi(window, SITE.plugins, { i18n: strings.source });',
' const runtime: Runtime = { api, plugins: {}, errors: {} };', ' // Each plugin gets an API view for its declared @permissions, with its own strings.',
' globals[SITE.runtimeGlobal] = runtime;', ' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));',
' globals.wayBetter = runtime;', ' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;',
'',
' const ipc = (globals.__TAURI_INTERNALS__ ?? null) as TauriInternals | null;',
' const invoke: Invoke | undefined = ipc ? (command, args) => ipc.invoke(command, args) : undefined;',
' if (SITE.account) installAccountReport(window, SITE.account, invoke);', ' if (SITE.account) installAccountReport(window, SITE.account, invoke);',
' const runtime = installSiteRuntime({',
' win: window, site: SITE, version: \'0.1.0\', invoke, plugins, strings,',
' pluginFailed: error => `Plugin failed: ${error}`,',
' features: flags,',
' // "same" until native code configures it: in-page clicks are left alone.', ' // "same" until native code configures it: in-page clicks are left alone.',
' if (SITE.links) installLinkRouting(window, SITE.links);', ' links,',
' });',
' // The way into the app\'s panel from the page: a small floating button (add `mountNav` to put',
' // an entry into the site\'s own navigation instead).',
` installPanelButton(window, { id: ${str(`${o.prefix}-panel-button`)}, logo: LOGO, title: () => SITE.product }, () => runtime.open());`,
" invoke?.('site_ready', {}).catch(() => {});", " invoke?.('site_ready', {}).catch(() => {});",
'}', '}',
'', '',
@ -905,9 +869,9 @@ function shellTs(o) {
const handleChars = handle.extra.replace(/[\\\]^-]/g, ch => `\\${ch}`); const handleChars = handle.extra.replace(/[\\\]^-]/g, ch => `\\${ch}`);
return lines( return lines(
'// The shell: the wayBetter shell frame (waybetter/shell/frame) with this site\'s pages and the', '// The shell: the wayBetter shell frame (waybetter/shell/frame) with this site\'s pages and the',
'// app\'s own panel. Tabs in the titlebar, splits, the address bar, the new-tab page, the command', '// app\'s panel (Panel.tsx: waybetter/shell/panel). Tabs in the titlebar, splits, the address bar,',
'// palette (Ctrl+K) and the account switcher are the framework\'s; native code places each tab\'s', '// the new-tab page, the command palette (Ctrl+K) and the account switcher are the framework\'s;',
'// webview over its pane (tabs_sync).', '// native code places each tab\'s webview over its pane (tabs_sync).',
'', '',
"import { createRoot } from 'react-dom/client';", "import { createRoot } from 'react-dom/client';",
"import { createI18n } from 'waybetter/i18n';", "import { createI18n } from 'waybetter/i18n';",
@ -946,7 +910,12 @@ function shellTs(o) {
' },', ' },',
' palette: {', ' palette: {',
" placeholder: () => 'Search tabs, pages and settings',", " placeholder: () => 'Search tabs, pages and settings',",
" sections: [{ id: 'plugins', label: () => 'Plugins', keywords: 'extensions js', icon: 'grid' }],", ' // The panel\'s sections in Ctrl+K.',
' sections: [',
" { id: 'plugins', label: () => 'Plugins', keywords: 'extensions js custom css', icon: 'grid' },",
" { id: 'accounts', label: () => 'Accounts', keywords: 'profiles logins', icon: 'user' },",
" { id: 'settings', label: () => 'Settings', keywords: 'home page links session', icon: 'settings' },",
' ],',
' },', ' },',
' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,', ' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,',
' // plugins::commands): the frame shows nothing of them until they are switched on here.', ' // plugins::commands): the frame shows nothing of them until they are switched on here.',
@ -959,31 +928,32 @@ function shellTs(o) {
); );
} }
function panelTsx() { function panelTsx(o) {
return lines( return lines(
'// The app\'s own tab (Ctrl+Shift+W, the brand button, Ctrl+K "Plugins"): its settings. Here: the', '// The app\'s own tab (Ctrl+Shift+W, the brand button, the floating button in the site\'s page,',
'// plugins in the plugins folder, each switched on or off live in every site tab.', '// Ctrl+K "Plugins"): the wayBetter panel (waybetter/shell/panel). The framework brings the',
'// sections this app serves: Home, Plugins (with custom CSS), Accounts and Settings. It grows',
'// with the app: `themes` adds Appearance and the Theme Builder, `store` the Store, `make` the Make',
'// section, `backup` and `updates` theirs, `sections` the app\'s own (see `PanelSite`).',
'', '',
"import { useEffect, useState } from 'react';", "import { createPanel } from 'waybetter/shell/panel';",
"import { SITE } from '../site.ts';",
'', '',
'type Plugin = { file: string; name: string; description: string; version: string; author: string; enabled: boolean };', 'export const Panel = createPanel({',
'', " brand: { name: SITE.product, logo: './icon.png' },",
'export function Panel(_props: { section?: { name: string; nonce: number } }) {', ' home: {',
' const [plugins, setPlugins] = useState<Plugin[]>([]);', ` kicker: { name: 'wayBetter', rest: ${str(` for ${o.label}`)} },`,
" const [error, setError] = useState('');", ` title: () => [${str(`${o.label}, `)}, 'extended', '.'],`,
' const { invoke } = window.__TAURI__.core;', ` lede: () => ${str(`${o.site.hosts[0]} in a light native window: tabs, split panes, accounts side by side and plugins. The page is the site's own; this app extends it in place.`)},`,
" const run = (promise: Promise<Plugin[] | void>) => promise.then(list => { if (list) setPlugins(list); setError(''); }, failure => setError(String(failure)));", " actions: [{ section: 'plugins', label: () => 'Plugins' }, { section: 'settings', label: () => 'Settings' }],",
" useEffect(() => { void run(invoke<Plugin[]>('plugins_list')); }, []);", ' highlights: [',
' return <div className="app-panel">', " { section: 'plugins', title: () => 'Plugins', text: () => 'One file each, switched on and off live.' },",
' <h1>Plugins</h1>', " { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },",
' {error && <p className="app-error" role="alert">{error}</p>}', ' ],',
' {plugins.map(plugin => <label key={plugin.file} className="app-row">', ' },',
" <input type=\"checkbox\" checked={plugin.enabled} onChange={event => void run(invoke<Plugin[]>('plugin_set_enabled', { file: plugin.file, enabled: event.target.checked }))}/>", ' // Placeholder CSS in the custom CSS editor, written with this site\'s own selectors.',
' <span><strong>{plugin.name}</strong> {plugin.version}<small>{plugin.description}</small></span>', ` cssExamples: { custom: ${str(`/* Example */\n${o.site.selectors.item} { outline: 1px dashed; }`)} },`,
' </label>)}', '});',
" <button type=\"button\" onClick={() => void run(invoke<void>('plugins_open_folder'))}>Open plugins folder</button>",
' </div>;',
'}',
); );
} }
@ -1037,16 +1007,10 @@ function indexHtml(o) {
/** @param {AppOptions} o */ /** @param {AppOptions} o */
function appCss(o) { function appCss(o) {
return lines( return lines(
"/* The app's own panel. The shell frame's styles come with it (dockview and the frame's CSS,", "/* The app's own styles. The shell frame's and the panel's styles come with them (dockview, the",
' bundled into dist/shell.css); its colors are the --wb-c-* tokens (Night Ink by default). */', " frame's and the panel's CSS, bundled into dist/shell.css); their colors are the --wb-c-* tokens",
' (Night Ink by default). */',
`:root { --app-accent: ${o.site.accent}; }`, `:root { --app-accent: ${o.site.accent}; }`,
'.app-panel { height: 100%; box-sizing: border-box; overflow: auto; padding: 24px 28px; color: var(--wb-c-text, #eef0f7); background: var(--wb-c-ground, #07080c); font: 14px/1.45 system-ui, sans-serif; }',
'.app-panel h1 { margin: 0 0 16px; font-size: 18px; }',
'.app-row { display: flex; gap: 10px; align-items: flex-start; padding: 10px 0; border-bottom: 1px solid var(--wb-c-line, #1e2333); }',
'.app-row small { display: block; color: var(--wb-c-muted, #8a90a6); }',
'.app-panel button { margin-top: 16px; font: inherit; color: inherit; background: var(--wb-c-raised, #141823); border: 1px solid var(--wb-c-line, #1e2333); border-radius: 8px; padding: 6px 12px; cursor: pointer; }',
'.app-panel input { accent-color: var(--app-accent); }',
'.app-error { color: #ffb4b4; }',
); );
} }
@ -1131,12 +1095,12 @@ function readme(o) {
'```', '```',
'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)',
'src/address.ts address bar chips for the site\'s pages', 'src/address.ts address bar chips for the site\'s pages',
'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, account report', 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, tweaks, account report, the panel button',
'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages', 'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages',
'src/shell/Panel.tsx the app\'s own tab (its settings: the plugins)', 'src/shell/Panel.tsx the app\'s own tab: the wayBetter panel (createPanel) with this app\'s home page',
'plugins/example.plugin.js written (disabled) into a new plugins folder', 'plugins/example.plugin.js written (disabled) into a new plugins folder',
'src-tauri/src/site.rs SiteSpec: the native half (hosts, runtime global, account rules)', 'src-tauri/src/site.rs SiteSpec: the native half (hosts, runtime global, account rules)',
'src-tauri/src/plugins.rs the plugin store (PluginHost)', 'src-tauri/src/plugins.rs PluginHost: what the host\'s plugin store needs to know about this app',
'src-tauri/src/desktop.rs config, site hooks and the app\'s own commands (waybetter_host::app runs the rest)', 'src-tauri/src/desktop.rs config, site hooks and the app\'s own commands (waybetter_host::app runs the rest)',
'src-tauri/capabilities/ shell / tab-chrome / site-tab, keyed by webview label', 'src-tauri/capabilities/ shell / tab-chrome / site-tab, keyed by webview label',
'src-tauri/tests/security.rs who may call what (waybetter_host::testkit)', 'src-tauri/tests/security.rs who may call what (waybetter_host::testkit)',
@ -1150,7 +1114,9 @@ function readme(o) {
'2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.', '2. Keep `hosts` and the runtime global identical in `site.ts` and `site.rs`.',
'3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,', '3. Add site-only commands like `site_ready`: `host::site_tab_only(&SITE, &webview)?` first,',
' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.', ' then list them in `build.rs`, `capabilities/site-tab.json` and `tests/security.rs`.',
'4. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes', '4. Page tweaks: add flags to `FLAGS` in `src/runtime/main.ts` and a section with',
' `useFeatures` and `FeatureGroups` (waybetter/shell/panel) to `sections` in `src/shell/Panel.tsx`.',
'5. Next steps from the framework: account profiles (`waybetter_host::profiles`), split panes',
' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes', ' (`waybetter/shell/paneModel`), the rail hider (`waybetter/runtime/paneNav`), themes',
' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the', ' (`waybetter/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the',
' `AppConfig`, `plugins.updater` and `bundle.createUpdaterArtifacts` in tauri.conf.json, then', ' `AppConfig`, `plugins.updater` and `bundle.createUpdaterArtifacts` in tauri.conf.json, then',
@ -1217,9 +1183,9 @@ export function appFiles(o) {
{ path: 'scripts/build.mjs', content: buildMjs() }, { path: 'scripts/build.mjs', content: buildMjs() },
{ path: 'src/site.ts', content: siteTs(o) }, { path: 'src/site.ts', content: siteTs(o) },
{ path: 'src/address.ts', content: addressTs(o) }, { path: 'src/address.ts', content: addressTs(o) },
{ path: 'src/runtime/main.ts', content: runtimeTs() }, { path: 'src/runtime/main.ts', content: runtimeTs(o) },
{ path: 'src/shell/main.tsx', content: shellTs(o) }, { path: 'src/shell/main.tsx', content: shellTs(o) },
{ path: 'src/shell/Panel.tsx', content: panelTsx() }, { path: 'src/shell/Panel.tsx', content: panelTsx(o) },
{ path: 'src/shell/index.html', content: indexHtml(o) }, { path: 'src/shell/index.html', content: indexHtml(o) },
{ path: 'src/shell/app.css', content: appCss(o) }, { path: 'src/shell/app.css', content: appCss(o) },
{ path: 'src/tauri.d.ts', content: tauriTypes() }, { path: 'src/tauri.d.ts', content: tauriTypes() },

View file

@ -312,7 +312,10 @@ test('app: every site skeleton is consistent across its native and page halves',
assert.deepEqual(handler, manifest); assert.deepEqual(handler, manifest);
const caps = ['shell', 'tab-chrome', 'site-tab'].map(name => JSON.parse(file('src-tauri', 'capabilities', `${name}.json`))); const caps = ['shell', 'tab-chrome', 'site-tab'].map(name => JSON.parse(file('src-tauri', 'capabilities', `${name}.json`)));
const granted = caps.flatMap(cap => cap.permissions).filter(p => p.startsWith('allow-')).map(p => p.slice(6).replace(/-/g, '_')).sort(); const granted = caps.flatMap(cap => cap.permissions).filter(p => p.startsWith('allow-')).map(p => p.slice(6).replace(/-/g, '_')).sort();
assert.deepEqual(granted, [...manifest, ...HOST_COMMANDS.shell, ...HOST_COMMANDS.tab].sort()); assert.deepEqual(granted, [...manifest, ...HOST_COMMANDS.shell, ...HOST_COMMANDS.tab, ...HOST_COMMANDS.site].sort());
// A new app has no shell command of its own: the host serves plugins, custom CSS, tweaks and settings.
assert.deepEqual(manifest, ['site_ready', 'tab_report']);
assert.deepEqual(caps[2].permissions, ['allow-site-ready', 'allow-open-panel'], 'site tabs: the app\'s site command and the host\'s');
assert.deepEqual(caps[1].permissions, ['allow-tab-report', 'allow-tab-shortcut', 'allow-tab-link-drag'], 'any tab: only about itself'); assert.deepEqual(caps[1].permissions, ['allow-tab-report', 'allow-tab-shortcut', 'allow-tab-link-drag'], 'any tab: only about itself');
for (const command of HOST_COMMANDS.shell) assert.ok(caps[0].permissions.includes(`allow-${command.replace(/_/g, '-')}`), `the shell has ${command}`); for (const command of HOST_COMMANDS.shell) assert.ok(caps[0].permissions.includes(`allow-${command.replace(/_/g, '-')}`), `the shell has ${command}`);
assert.match(file('src-tauri', 'tests', 'security.rs'), /assert_host_commands\(\)/); assert.match(file('src-tauri', 'tests', 'security.rs'), /assert_host_commands\(\)/);
@ -336,6 +339,10 @@ test('app: every site skeleton is consistent across its native and page halves',
for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`); for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`);
// The shell is the framework's shell frame (createShell), not a copy; it needs the window calls. // The shell is the framework's shell frame (createShell), not a copy; it needs the window calls.
assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /); assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /);
// The app's tab is the framework's panel (createPanel); the page runtime is composed by the framework.
assert.match(file('src', 'shell', 'Panel.tsx'), /export const Panel = createPanel\(\{/);
assert.match(file('src', 'runtime', 'main.ts'), /installSiteRuntime\(\{/);
assert.match(file('src-tauri', 'src', 'desktop.rs'), /AppConfig::new\(&SITE, SITE\.product, &plugins::HOST\)/);
assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips'); assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips');
// Icons Tauri decodes at compile time. // Icons Tauri decodes at compile time.
const png = readFileSync(join(work, dir, 'src-tauri', 'icons', 'icon.png')); const png = readFileSync(join(work, dir, 'src-tauri', 'icons', 'icon.png'));
@ -355,6 +362,7 @@ test('app: the host command list matches waybetter-host (commands.rs)', () => {
const list = name => new RegExp(`pub const ${name}: &\\[&str\\] = &\\[([^\\]]*)\\]`).exec(source)[1].match(/"([a-z0-9_]+)"/g).map(c => c.slice(1, -1)); const list = name => new RegExp(`pub const ${name}: &\\[&str\\] = &\\[([^\\]]*)\\]`).exec(source)[1].match(/"([a-z0-9_]+)"/g).map(c => c.slice(1, -1));
assert.deepEqual(HOST_COMMANDS.shell, list('SHELL')); assert.deepEqual(HOST_COMMANDS.shell, list('SHELL'));
assert.deepEqual(HOST_COMMANDS.tab, list('TAB')); assert.deepEqual(HOST_COMMANDS.tab, list('TAB'));
assert.deepEqual(HOST_COMMANDS.site, list('SITE'));
}); });
test('app: host crate sources (submodule default, git)', async () => { test('app: host crate sources (submodule default, git)', async () => {