diff --git a/README.md b/README.md index 3936ad6..62a9419 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,8 @@ crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfi src/profiles.rs profiles, per-profile data dirs, native-owned accounts src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades src/plugins/commands.rs palette commands site tabs report, and the script that runs one + src/settings.rs the shell's settings (home page, where links open, session restore) and the + page's feature flags, as validated data and the scripts that deliver them src/hotfix.rs signed data-only hotfix channel (minisign) src/update.rs silent-update scheduling and crash handshake src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation, @@ -92,6 +94,7 @@ crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfi src/host.rs (feature "tauri") webview helpers, shell events, system menu src/app.rs (feature "app") the whole app around a site: run_app / App, AppConfig, SiteHooks, the window, shell and tab webviews, the generic commands + (tabs, profiles, language, plugins and custom CSS, feature flags, settings) src/commands.rs the commands the host serves and who may call them; manifest() for build.rs src/testkit.rs capability/caller-check assertions for an app's tests/security.rs packages/runtime/src/ page runtime core (TypeScript, no dependencies) @@ -105,6 +108,11 @@ packages/runtime/src/ page runtime core (TypeScript, no dependencies) column.ts deck columns: hide site chrome, fill the width, filters, unread count linkRouting.ts divert in-page clicks to a pane/tab/browser per setting accountReport.ts report the signed-in account of this tab's profile + siteRuntime.ts the runtime's composition: the IPC bridge, flag-controlled parts with a deck + column's overrides, the runtime object under its window names, native queues + pageStrings.ts the page's language: English built in, native deliveries checked as data + panelButton.ts the way into the panel from the page (navigation entry or floating button) + commandReport.ts the palette command report and developer-mode start errors packages/shell/src/ shell core (TypeScript) and the shell frame (React) addressModel.ts address bar chips (site pages named by the adapter) paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync @@ -119,9 +127,15 @@ packages/shell/src/ shell core (TypeScript) and the shell frame (React) installController.ts the install screen's state machine (links, drops, store items, confirm) InstallDialog.tsx StoreView.tsx store.css the install screen and the Store view (React peer, --wb-* tokens) frame/ the shell frame: createShell(site) (see "The shell frame" below) + panel/ the panel: createPanel(site), the app's own tab (see "The panel" below) + installerMessages.ts the Windows installer's words (wb.installer.*) packages/waybetter/ the published npm package (runtime + shell as ESM + .d.ts, theme.schema.json, - store-catalog.schema.json, the `waybetter store build|sign|verify` and - `waybetter release windows|macos` commands, `waybetter/build`) + store-catalog.schema.json, the `waybetter store build|sign|verify`, + `waybetter release windows|macos`, `waybetter i18n check|extract`, + `waybetter privacy-scan` and `waybetter build-env` commands, `waybetter/build`, locales/ (51 catalogs and translator notes), + windows/ (the installer template and its language files)) +dev-tools/ development harnesses for a running or built app (perf probes, close and + stress checks); not published (dev-tools/README.md) docs/STORE.md the Store: shared catalog format, signing and keys, tooling, trust model, how to add it packages/create-waybetter/ `npm create waybetter`: plugin, theme and app scaffolds (no dependencies) ``` @@ -187,6 +201,71 @@ features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sy listens to `tab-state`, `tab-open`, `tab-shortcut`, `link-drag`, `open-panel`, `profiles-changed`, `tab-commands`, `dev-event`, `update-status`, `tab-still` and `clipboard-changed`. +## The panel + +`packages/shell/src/panel` (`waybetter/shell/panel`) is an app's own tab in the shell: a home page, +Appearance (the theme gallery, customization, account and pane themes, downloaded fonts, theme +import/export) and the Theme Builder (undo/redo, a palette from three colors, a contrast report, a +font per role with the Google Fonts browser), plugins and custom CSS, the Store, Make (example +plugins, the plugin UI kit, the theme API, bundled docs), accounts, Power User (deck settings), +settings (language, links and session, keyword alerts, the media panel), backup and sync, developer +mode, updates, and a search across every setting. It lives in the shell package, next to the frame +it renders in: it uses the frame's stores (profiles, decks, themes, sync, developer mode), its +native bridge and its language, so `createShell` comes first. + +```tsx +import { createPanel, type PanelSite } from 'waybetter/shell/panel'; + +const panel: PanelSite = { brand: { name: 'wayBetter', logo }, home, themes, sections, order, make, + store, languages, settings, power, backup: true, updates: true }; +const Panel = createPanel(panel); +const Shell = createShell({ ...site, panel: { id: 'app', title: 'wayBetter', component: Panel } }, options); +``` + +What the app supplies (`panel/site.ts`, every field documented there): + +- `brand` and `home`: the header and the home page's words (kicker, title, lede, chips, actions, + highlight cards, the About block), `version()` for its chip; +- `sections` and `order`: its own sections (a label, an icon path, a component that gets `notify` + and `openSection`; `searchable` ones also show in the settings search), placed among the built-in + ones. X adds Tweaks and Drafts; +- `themes`: its theme store and catalog (`createThemeStore`, `createThemeCatalog`), accent swatches, + the **preview** component (a miniature of the site drawn from a theme document, used by the gallery + and the builder), the site font's name, the palette a draft starts from, and for Make's theme view + `resolved(choice, mode)` with the site's own display modes; +- `make`: example plugins, an example theme file and bundled Markdown docs; +- `store`: the install controller (the Store section, and removing a plugin from the list); +- `languages`: the language list and state (`createLanguage`, `frame/language.ts`); +- `settings`, `power`, `cssExamples`: keyword alerts, extra settings rows, which column flags and + which memory measure Power User lists, placeholder CSS with the site's selectors. + +A built-in section shows only when the app serves what it needs: Appearance, the Theme Builder and +the Store with `themes` (and `store`), Make with `make`, Power User with `site.deck`, backup with +`backup` (its sync half with the frame's `sync` feature), Developer with the frame's `developer` +feature, Updates with `updates`. An app with nothing but plugins gets Home, Plugins, Accounts and +Settings (this is what `npm create waybetter app` generates). + +Building blocks for the app's own sections: the panel's controls (`Section`, `Row`, `Toggle`, +`Segmented`, `Select`, `Slider`, `ColorField`, `Button`, `Badge`, ...; `panel/controls`), the +feature toggles (`useFeatures` + `FeatureGroups` over `features_get/set`: the app names its flags +and groups, its catalog has `features..label` and `.description`), and `compareLines`. + +The panel's words are `wb.*` messages too (English source in `panel/panelMessages.ts`, translator +notes in `locales/en.meta.json`). Three families of keys stay the app's, by convention, because +they name its own things: `plugin..name|description` (its bundled plugins), +`theme..description` (its built-in themes) and `features.*` (its tweaks). + +Native commands the panel calls: the host's `plugins_list`, `plugin_set_enabled`, +`plugins_open_folder`, `custom_css_get/set`, `features_get/set`, `settings_get/set`, +`profiles_*` and `open_external_url`, and for what the app turns on `alerts_get/set`, +`media_get/set`/`gallery_add_folder`/`clip_remove`, `backup_*`, `sync_*`, `dev_*`, the theme +store's commands and `gfonts_*`, `install_records`/`install_forget`/`plugin_remove`/`store_catalog`, +`app_ready`/`update_status`/`apply_update`. + +The Google Fonts list the font browser shows is an offline snapshot +(`panel/fonts/googleFontsCatalog.json`; `packages/shell/scripts/google-fonts-catalog.mjs` +regenerates it). The app never fetches the list, only the font files the owner picks (natively). + ## The site adapter A site adapter is three small, explicit things. @@ -246,15 +325,27 @@ Each runtime module takes only its piece (`installPaneNav(window, KICK.rail!)`, `installLinkRouting(window, KICK.links!)`, `installAccountReport(window, KICK.account!, invoke)`, `createCorePluginApi(window, KICK.plugins)`), so a site without a rail simply does not install it. +What every runtime entry does the same way is composed by `runtime/siteRuntime`: +`pageInvoke(window, product)` (the IPC bridge, read at call time), `createFeatureFlags({ defaults, +installers, apply })` (parts that install on enable and dispose on disable; a deck column's flag +overrides sit on top of the owner's) and `installSiteRuntime({ win, site, version, plugins, strings, +features, theme, fonts, pane, links, column, extra, queues })`, which builds the runtime object +(`features.apply`, `i18n.set`, `links.configure`, `pane.set`, `fonts.provide`, `column.set`, +`open()`, `api`, `withPlugin`, `devError`), publishes it as `window.wayBetter` and the app's own +names, takes over what native code queued before it existed and starts the palette command report. +`createPageStrings` (`runtime/pageStrings`) is the page's language and `installPanelButton` +(`runtime/panelButton`) keeps the way into the panel on the page: the adapter's `mountNav` puts +an entry into the site's own navigation, and where the page has none a floating button stands in. + ### 3. Capabilities (Tauri JSON, keyed by webview label) The security model is the same for every app and must stay keyed by webview label: | webview | may call | | --- | --- | -| `shell` (local assets only) | app, settings, vault, and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, ...) | +| `shell` (local assets only) | the app's own commands and the host's `commands::SHELL` (`tabs_sync`, `tab_navigate`, `tab_action`, `shell_raise`, `profiles_*`, `i18n_*`, `plugins_*`, `custom_css_*`, `features_*`, `settings_*`, ...) | | `tab-*` (any site) | only tab chrome about itself: `tab_report`, `tab_shortcut`, `tab_link_drag` | -| `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands | +| `tab-*` on the exact site origin | the app's short, reviewed list of site-only commands, and the host's `commands::SITE` (`open_panel`) | | other local webviews (`popover-*`, ...) | their own narrow capability | ```json @@ -276,7 +367,8 @@ site, and a shell save can never change it (`ProfileSettings::keep_accounts_from `waybetter_host::testkit` checks this in an app's own tests: `Capabilities::from_dir` reads every capability file, `assert_host_commands` keeps the host's commands shell-only / tab-only, -`assert_shell_only` / `assert_tab_only` do the same for the app's, `assert_no_plugin_apis` refuses +`assert_shell_only` / `assert_tab_only` do the same for the app's, `assert_site_only(command, &SITE)` +checks that a site command is granted only on the site's own URLs, `assert_no_plugin_apis` refuses Tauri plugin JS APIs, and `assert_guarded` / `assert_host_guards` check that each command's first statement checks its caller. @@ -291,8 +383,15 @@ statement checks its caller. webview (transparent: it can rise above the tabs; macOS needs the `macos-private-api` feature). It serves `commands::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`) and `commands::TAB` (`tab_shortcut`, `tab_link_drag`), each checking its - caller first, and dispatches every other command to the app's handler. Tab webviews get their + `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`), + `commands::TAB` (`tab_shortcut`, `tab_link_drag`) and `commands::SITE` (`open_panel`), each + checking its caller first, and dispatches every other command to the app's handler. It keeps + the page state those commands read and save (`PageState`: the plugin store in app data + `plugins`, made from the `PluginHost` in `AppConfig::new(site, title, plugins)`; the feature flags + in `features.json`; `ShellSettings` in `settings.json`): the app reads it with `page(app)`, gets a + loaded document's scripts from `page_scripts(app)` (flags, links, custom CSS, plugins) and writes + it with `set_features`, `set_settings` and `set_custom_css` (a backup import). Tab webviews get their profile's data folder, the app's document-start scripts, navigation/pop-up/load/title/download handling, stills and memory targets; `SiteHooks` is where the app says what only it knows (page scripts, legacy domains, link routing, per-tab state, what a finished site page gets). Helpers: @@ -302,7 +401,10 @@ statement checks its caller. `AppConfig::defer_window_show = true` and `ShellSite.deferWindowShow = true`, and grant the shell `allow-shell-ready`. The default still shows the window immediately. An opted-in app shows it after initial `tabs_sync`, with a three-second fallback if shell startup fails. -- `commands`: the host's command list and `manifest(&[..])` for the app's `build.rs`. +- `commands`: the host's command lists (`SHELL`, `TAB`, `SITE`) and `manifest(&[..])` for the app's `build.rs`. +- `settings`: `ShellSettings` (home page, where links to other sites and to the site's own pages + open, session restore; missing fields take the defaults), `links_script`, and the feature flags' + validation (a small map of booleans) and `features_script`. - `testkit`: see the capabilities section. - `policy`: `SHELL_LABEL`, `tab_id`, `require_local`, `require_site_tab`, `clamp_tab_rect` (tabs never cover the titlebar or, while restored, the resize band). @@ -355,6 +457,30 @@ The npm package adds the app-side tooling: `/upload`, `latest.json` (other platforms of the version kept); macOS: signs a universal build's updater bundle and adds both darwin platforms. It never uploads: it prints the steps. The key is read only into the build's environment or handed to the Tauri signer by path. +- `waybetter build-env -- ` and `waybetter privacy-scan`: nothing an app publishes may + name the person who built it. A Rust binary embeds the absolute paths of its sources (the Cargo + registry, the rustup toolchain, the workspace: about 1,400 strings holding the account name in + one app), so `build-env` runs a build with those roots remapped to `/home`, `/src`, `/cargo`, + `/rustup` and `/target` (`--remap-path-prefix` appended to the flags already set, + `/PDBALTPATH:%_PDB%` on MSVC, `-ffile-prefix-map` for C sources on gcc and clang): + `waybetter build-env -- tauri build`, on every platform. `privacy-scan` is the proof: it searches + files, binaries (UTF-8, UTF-16), archives (npm tarballs, zip, tar, .deb, DMG; NSIS installers and + AppImages through 7-Zip), git-tracked files and, with `--history`, every blob, path, commit + message and identity of a repository for the terms in a file kept outside every repository + (`"forbiddenTerms"` in `waybetter.release.json`, or `WAYBETTER_FORBIDDEN_TERMS`) plus the + machine's account name, and prints hits masked (`m***`). `waybetter release` builds with + `build-env` and refuses to release an artifact with a hit or one it could not open. The `.pdb` + next to a Windows binary still holds every path: never publish it. +- `waybetter i18n check|extract`: an app's locale catalogs against the framework's rules (file + shape, keys English lacks, ICU syntax, placeholder parity, plural forms, no markup), the + framework's catalogs in the same languages, the generated `languages.json` and native + localization files (macOS `Info.plist` and `InfoPlist.strings`, the Linux `.desktop` template), + bundled plugins' inline English, and the keys the code looks up; configured by the app's + `waybetter.i18n.json`. +- `waybetter/windows/languages/.nsh`: the installer's messages for the 17 languages + Tauri does not ship itself, generated from the framework catalogs (`wb.installer.*`; + `node packages/waybetter/scripts/installer-languages.mjs --write`). An app lists them under + `bundle.windows.nsis.customLanguageFiles`. - `waybetter/windows/installer.nsi`: the Windows installer, a template for Tauri's NSIS bundler (`bundle.windows.nsis.template`). No wizard and no UAC: it installs for the current user, makes the Desktop and Start menu shortcuts and opens the app. Run again by hand, it only installs when @@ -395,6 +521,11 @@ bun run check # typecheck + build:packages + test bun run check:tauri # cargo check with the app feature (slow: builds Tauri and its plugins) bun run build # typecheck + cargo build bun run pack:check # npm pack --dry-run of waybetter and create-waybetter +node packages/waybetter/scripts/installer-languages.mjs [--write] # windows/languages/*.nsh from the catalogs +node packages/shell/scripts/google-fonts-catalog.mjs # the font browser's offline list ``` +`dev-tools/` has the harnesses for a running or built app (perf probes, the graceful-close check, +tab and webview stress); see its README. + Requires Bun 1.4.2+, Node 24+ and Rust 1.88+. diff --git a/bun.lock b/bun.lock index 13e2f4a..63afffe 100644 --- a/bun.lock +++ b/bun.lock @@ -30,7 +30,7 @@ }, "packages/waybetter": { "name": "waybetter", - "version": "0.4.0", + "version": "0.6.0", "bin": { "waybetter": "bin/waybetter.mjs", }, diff --git a/crates/waybetter-host/src/app.rs b/crates/waybetter-host/src/app.rs index eb151e3..a0ffc15 100644 --- a/crates/waybetter-host/src/app.rs +++ b/crates/waybetter-host/src/app.rs @@ -1,15 +1,17 @@ //! The whole wayBetter app around one site: [`run_app`] (or [`App`]) makes the window, the trusted //! local shell webview and one child webview per tab, registers the Tauri plugins every app uses, //! and serves the generic commands ([`crate::commands`]): tab layout and actions, the shell's -//! focus and raise, external links, the window menu, account profiles and the language. +//! focus and raise, external links, the window menu, account profiles, the language, the plugins +//! folder and custom CSS, the page's feature flags and the shell's settings ([`PageState`]). //! -//! The app hands it an [`AppConfig`] (its site, window title and size, which plugins it -//! configures) and a [`SiteHooks`] implementation for what only it knows (the page scripts of a -//! new tab, what happens when a site page loads, its own per-tab state), plus its own commands. +//! The app hands it an [`AppConfig`] (its site, window title and size, its plugin host, which +//! Tauri plugins it configures) and a [`SiteHooks`] implementation for what only it knows (the page +//! scripts of a new tab, what happens when a site page loads, its own per-tab state), plus its own +//! commands. //! //! ```ignore //! pub fn run() { -//! waybetter_host::app::App::new(CONFIG, MySite) +//! waybetter_host::app::App::new(AppConfig::new(&SITE, "My app", &PLUGINS), MySite) //! .setup(|app| { app.manage(MyState::load(app)); Ok(()) }) //! .run(tauri::generate_context!(), tauri::generate_handler![my_command]); //! } @@ -17,10 +19,13 @@ use crate::{ commands, - host::{self, emit_shell, emit_tab_state, read_json, shell_only, tab_only, tab_webview, write_json}, + host::{self, emit_shell, emit_tab_state, read_json, shell_only, site_tab_only, tab_only, tab_webview, write_json}, i18n::{self, NativeStrings}, - layout, policy, + layout, + plugins::{self, PluginHost, PluginStore, ScriptPlugin}, + policy, profiles::{self, AccountSeen, ProfileSettings}, + settings::{self, ShellSettings, ShellSettingsInput}, site::SiteSpec, tabs::{self, parse_web_url, OpenRequest, TabLayout, TabState}, }; @@ -38,6 +43,12 @@ use url::Url; pub const PROFILES_FILE: &str = "profiles.json"; /// The owner's language and the strings native code needs (app data), see [`i18n`]. pub const I18N_FILE: &str = "i18n.json"; +/// The shell's settings (app data), see [`settings::ShellSettings`]. +pub const SETTINGS_FILE: &str = "settings.json"; +/// The page's feature flags (app data): a small map of booleans. +pub const FEATURES_FILE: &str = "features.json"; +/// The plugins folder in app data (`*.plugin.js` files, `custom.css`, the enabled list). +pub const PLUGINS_DIR: &str = "plugins"; /// What differs between wayBetter apps at the window level. #[derive(Clone, Copy, Debug)] @@ -63,12 +74,18 @@ pub struct AppConfig { pub updater: bool, /// The language strings site tabs receive (key prefixes, e.g. `["x.", "kit.", "plugin."]`). pub page_string_prefixes: &'static [&'static str], + /// The app's plugin host: the page runtime's global, the site's origin, the custom CSS element + /// and the plugins shipped with the app. The plugin store lives in app data [`PLUGINS_DIR`]. + pub plugins: &'static PluginHost, + /// The home page before the owner sets one (default: the site's first origin). + pub home_url: Option<&'static str>, } impl AppConfig { /// The defaults: 1360x900 (at least 900x560), a near-black background, the shell's own - /// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs. - pub const fn new(site: &'static SiteSpec, title: &'static str) -> Self { + /// titlebar, no deep links or updater, the UI kit's and plugins' strings for site tabs, the + /// site's first origin as the home page. + pub const fn new(site: &'static SiteSpec, title: &'static str, plugins: &'static PluginHost) -> Self { Self { site, title, @@ -81,8 +98,15 @@ impl AppConfig { deep_link: false, updater: false, page_string_prefixes: &["kit.", "plugin."], + plugins, + home_url: None, } } + + /// The home page before the owner sets one. + pub fn home(&self) -> String { + self.home_url.map(str::to_owned).unwrap_or_else(|| format!("{}/", self.site.primary_origin())) + } } /// A tab webview about to be created ([`SiteHooks::init_scripts`]). @@ -127,17 +151,18 @@ pub trait SiteHooks: Send + Sync + 'static { false } - /// A navigation starts in tab `label`. Returns whether links to other sites go to the - /// system browser (the owner's setting), or None when the app's state is unavailable (the - /// navigation is refused). - fn navigation_started(&self, _app: &AppHandle, _label: &str) -> Option { - Some(false) + /// A navigation starts in tab `label`. Returns whether links to other sites go to the system + /// browser (the owner's setting, [`ShellSettings::external_in_browser`]), or None when the + /// state is unavailable (the navigation is refused). + fn navigation_started(&self, app: &AppHandle, _label: &str) -> Option { + page(app).ok().map(|page| page.settings.external_in_browser()) } /// Where a new-window request (target=_blank, window.open) for `url` opens: "tab", "pane" or - /// "browser". - fn new_window_mode(&self, _app: &AppHandle, _url: &Url) -> String { - "tab".into() + /// "browser" (the owner's link settings; a page on the site's origin counts as the site's). + fn new_window_mode(&self, app: &AppHandle, url: &Url) -> String { + let on_site = config(app).site.is_origin(url) || self.site_navigation(url); + page(app).map(|page| page.settings.new_window_mode(on_site).to_owned()).unwrap_or_else(|_| "tab".into()) } /// A new document started loading in `tab`. @@ -170,8 +195,19 @@ pub struct ProfileState { pub tab_profiles: HashMap, } +/// What every site page gets and the shell's settings: the plugin store (plugins, custom CSS), +/// the feature flags and [`ShellSettings`]. The host's commands read and save them; the app reads +/// them through [`page`] (its page scripts, backups, developer mode). +pub struct PageState { + pub plugins: PluginStore, + /// A JSON object of booleans ([`settings::validate_features`]). + pub features: serde_json::Value, + pub settings: ShellSettings, +} + struct Profiles(Mutex); struct Strings(Mutex); +struct Page(Mutex); struct Host { config: AppConfig, @@ -197,6 +233,93 @@ pub fn profiles(app: &AppHandle) -> Result, String> .map_err(|_| "DATABASE: workspace state unavailable; restart safely".into()) } +/// The page state lock (plugins, feature flags, settings). Never call an app hook while holding +/// it; an app that holds a lock of its own may take this one after it, never the other way round. +pub fn page(app: &AppHandle) -> Result, String> { + app.try_state::() + .ok_or("DATABASE: workspace state unavailable; restart safely")? + .inner() + .0 + .lock() + .map_err(|_| "DATABASE: workspace state unavailable; restart safely".into()) +} + +/// The scripts a freshly loaded site document gets from the page state, in the order they apply. +pub struct PageScripts { + /// The feature flags ([`settings::features_script`]). + pub features: String, + /// Where clicked site pages open ([`settings::links_script`]). + pub links: String, + /// The owner's custom CSS, when there is any. + pub css: Option, + /// One start script per enabled plugin. + pub plugins: Vec, +} + +impl PageScripts { + /// Flags, links, custom CSS, then the plugins. + pub fn all(self) -> Vec { + let mut scripts = vec![self.features, self.links]; + scripts.extend(self.css); + scripts.extend(self.plugins); + scripts + } +} + +/// The page state as scripts for a site document that just loaded (evaluate them natively, so the +/// page's CSP cannot block them). An app with scripts of its own places them between these. +pub fn page_scripts(app: &AppHandle) -> Result { + let site = config(app).site; + let page = page(app)?; + let css = page.plugins.css(); + Ok(PageScripts { + features: settings::features_script(site, &page.features), + links: settings::links_script(site, &page.settings), + css: if css.is_empty() { None } else { plugins::css_script(page.plugins.host(), &css).ok() }, + plugins: page.plugins.start_scripts(), + }) +} + +/// Evaluates `script` in every tab that is on the site right now. +pub fn eval_in_site_tabs(app: &AppHandle, script: &str) { + host::eval_in_site_tabs(app, config(app).site, script); +} + +/// Replaces the feature flags (validated booleans), saves them and applies them in every site tab. +/// For the app's own writers (a backup import); the shell uses `features_set`. +pub fn set_features(app: &AppHandle, features: serde_json::Map) -> Result<(), String> { + settings::validate_features(&features)?; + let value = serde_json::Value::Object(features); + write_json(app, FEATURES_FILE, &value)?; + let script = settings::features_script(config(app).site, &value); + page(app)?.features = value; + eval_in_site_tabs(app, &script); + Ok(()) +} + +/// Replaces the shell's settings (validated), saves them and tells every site tab where its links open. +/// For the app's own writers (a backup import); the shell uses `settings_set`. +pub fn set_settings(app: &AppHandle, input: ShellSettingsInput) -> Result { + let config = config(app); + let next = ShellSettings::from_input(input, &config.home())?; + write_json(app, SETTINGS_FILE, &next)?; + page(app)?.settings = next.clone(); + eval_in_site_tabs(app, &settings::links_script(config.site, &next)); + Ok(next) +} + +/// Replaces the custom CSS, saves it and applies it in every site tab. +pub fn set_custom_css(app: &AppHandle, css: &str) -> Result<(), String> { + let script = { + let page = page(app)?; + let script = plugins::css_script(page.plugins.host(), css)?; + page.plugins.set_css(css)?; + script + }; + eval_in_site_tabs(app, &script); + Ok(()) +} + /// The profile tab webview `label` belongs to. pub fn tab_profile(app: &AppHandle, label: &str) -> Option { profiles(app).ok()?.tab_profiles.get(label).cloned() @@ -528,6 +651,82 @@ async fn i18n_set(webview: Webview, app: AppHandle, strings: NativeStrings) -> R Ok(()) } +#[tauri::command] +async fn plugins_list(webview: Webview, app: AppHandle) -> Result, String> { + shell_only(&webview)?; + page(&app)?.plugins.list() +} + +/// Turns a plugin on or off and starts or stops it live in every site tab. +#[tauri::command] +async fn plugin_set_enabled(webview: Webview, app: AppHandle, file: String, enabled: bool) -> Result, String> { + shell_only(&webview)?; + let (script, list) = { + let page = page(&app)?; + // Build the start script first so a broken file is reported before it is marked enabled. + let script = if enabled { page.plugins.start_script(&file)? } else { plugins::stop_script(page.plugins.host(), &file)? }; + page.plugins.set_enabled(&file, enabled)?; + (script, page.plugins.list()?) + }; + eval_in_site_tabs(&app, &script); + Ok(list) +} + +/// Opens the plugins folder in the system's file manager. +#[tauri::command] +async fn plugins_open_folder(webview: Webview, app: AppHandle) -> Result<(), String> { + shell_only(&webview)?; + let dir = { + let page = page(&app)?; + page.plugins.ensure()?; + page.plugins.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}")) +} + +#[tauri::command] +async fn custom_css_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + Ok(page(&app)?.plugins.css()) +} + +#[tauri::command] +async fn custom_css_set(webview: Webview, app: AppHandle, css: String) -> Result<(), String> { + shell_only(&webview)?; + set_custom_css(&app, &css) +} + +#[tauri::command] +async fn features_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + Ok(page(&app)?.features.clone()) +} + +/// Feature flags are booleans only; the page normalizes them again before use. +#[tauri::command] +async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Map) -> Result<(), String> { + shell_only(&webview)?; + set_features(&app, features) +} + +#[tauri::command] +async fn settings_get(webview: Webview, app: AppHandle) -> Result { + shell_only(&webview)?; + Ok(page(&app)?.settings.clone()) +} + +#[tauri::command] +async fn settings_set(webview: Webview, app: AppHandle, settings: ShellSettingsInput) -> Result { + shell_only(&webview)?; + set_settings(&app, settings) +} + /// Browser shortcuts pressed while a tab has keyboard focus, forwarded to the shell. #[tauri::command] async fn tab_shortcut(webview: Webview, app: AppHandle, shortcut: String) -> Result<(), String> { @@ -544,6 +743,21 @@ async fn tab_link_drag(webview: Webview, app: AppHandle, phase: String, url: Opt host::forward_link_drag(&app, id, phase, url) } +/// The app's entry in the site's page (its navigation item, the floating button) opens the app's +/// panel in the shell, at a section. Only from a tab that is on the site right now. +#[tauri::command] +async fn open_panel(webview: Webview, app: AppHandle, section: Option) -> Result<(), String> { + site_tab_only(config(&app).site, &webview)?; + let id = tab_only(&webview)?; + #[derive(Clone, Serialize)] + struct Open { + from: String, + section: Option, + } + emit_shell(&app, tabs::EVENT_OPEN_PANEL, Open { from: id, section: section.filter(|s| s.len() <= 32) }); + Ok(()) +} + // --------------------------------------------------------------------------------------------- // Tab webviews @@ -715,7 +929,7 @@ pub fn reset_lost_geometry(window: &tauri::Window, size: (f64, f64), min: (f64, } } -/// The host's commands ([`commands::SHELL`], [`commands::TAB`]). +/// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]). fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static { tauri::generate_handler![ tabs_sync, @@ -731,8 +945,18 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 's 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_shortcut, - tab_link_drag + tab_link_drag, + open_panel ] } @@ -758,7 +982,8 @@ impl App { } /// Runs the app: `context` is `tauri::generate_context!()` and `handler` the app's own - /// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`] and [`commands::TAB`]). + /// `tauri::generate_handler![...]` (the host serves [`commands::SHELL`], [`commands::TAB`] and + /// [`commands::SITE`]). pub fn run(self, context: tauri::Context, handler: H) where H: Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static, @@ -806,6 +1031,21 @@ impl App { tauri_app.manage(Profiles(Mutex::new(ProfileState { settings, tab_profiles: HashMap::new() }))); let strings = read_json::(&handle, I18N_FILE).and_then(|strings| strings.validated().ok()).unwrap_or_default(); tauri_app.manage(Strings(Mutex::new(strings))); + // The plugins folder (bundled plugins are upgraded at startup, not only when the + // Plugins list is opened: enabled ones would otherwise keep running the previous + // version's code), the feature flags and the shell's settings. + let plugins = PluginStore::new(directory.join(PLUGINS_DIR), config.plugins); + if let Err(error) = plugins.ensure() { + eprintln!("{}: {error}", config.title); + } + let home = config.home(); + let settings = read_json::(&handle, SETTINGS_FILE) + .and_then(|value| ShellSettings::from_value(value, &home).ok()) + .unwrap_or_else(|| ShellSettings::defaults(&home)); + let features = read_json::(&handle, FEATURES_FILE) + .filter(serde_json::Value::is_object) + .unwrap_or_else(|| serde_json::json!({})); + tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings }))); tauri_app.manage(Host { config, hooks }); if let Some(setup) = setup { setup(&handle)?; diff --git a/crates/waybetter-host/src/commands.rs b/crates/waybetter-host/src/commands.rs index 263f656..7cfbf5a 100644 --- a/crates/waybetter-host/src/commands.rs +++ b/crates/waybetter-host/src/commands.rs @@ -1,9 +1,10 @@ //! The Tauri commands [`crate::app::run_app`] registers for every app, and who may call them. //! //! An app's `build.rs` lists its own commands plus these in the app-command manifest -//! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only and -//! [`TAB`] to tab webviews only; [`crate::testkit`] checks both. Every command re-checks its caller -//! natively (`host::shell_only` / `host::tab_only`) before anything else. +//! ([`manifest`]), and its capability files grant [`SHELL`] to the local `shell` webview only, +//! [`TAB`] to tab webviews only and [`SITE`] to tab webviews on the site's origin only; +//! [`crate::testkit`] checks them. Every command re-checks its caller natively +//! (`host::shell_only` / `host::tab_only` / `host::site_tab_only`) before anything else. /// Shell-only: the local `shell` webview (debug builds also accept the dev server). pub const SHELL: &[&str] = &[ @@ -20,14 +21,27 @@ pub const SHELL: &[&str] = &[ "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-only: any tab webview, speaking only about itself. pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"]; +/// Site-tab-only: a tab webview that is on the site's origin right now (the page runtime asks +/// the shell to open the app's panel). Grant these in a capability limited to the site's URLs. +pub const SITE: &[&str] = &["open_panel"]; + /// Whether `command` is one of the host's (dispatched to the host, never to the app's handler). pub fn is_host(command: &str) -> bool { - SHELL.contains(&command) || TAB.contains(&command) + SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) } /// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`). @@ -42,8 +56,8 @@ pub fn permission(command: &str) -> String { /// tauri_build::AppManifest::new().commands(waybetter_host::commands::manifest(&["draft_list"])) /// ``` pub fn manifest(app: &[&'static str]) -> &'static [&'static str] { - let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len()); - for command in app.iter().chain(SHELL).chain(TAB) { + let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len()); + for command in app.iter().chain(SHELL).chain(TAB).chain(SITE) { if !all.contains(command) { all.push(command); } @@ -60,7 +74,7 @@ mod tests { let all = manifest(&["draft_list", "tabs_sync"]); assert_eq!(all[0], "draft_list"); assert_eq!(all.iter().filter(|c| **c == "tabs_sync").count(), 1); - for command in SHELL.iter().chain(TAB) { + for command in SHELL.iter().chain(TAB).chain(SITE) { assert!(all.contains(command), "{command}"); assert!(is_host(command)); } @@ -70,6 +84,7 @@ mod tests { #[test] fn shell_and_tab_commands_do_not_overlap() { - assert!(!SHELL.iter().any(|command| TAB.contains(command))); + assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command))); + assert!(!TAB.iter().any(|command| SITE.contains(command))); } } diff --git a/crates/waybetter-host/src/lib.rs b/crates/waybetter-host/src/lib.rs index b67d5e6..b940963 100644 --- a/crates/waybetter-host/src/lib.rs +++ b/crates/waybetter-host/src/lib.rs @@ -23,6 +23,8 @@ //! shows, its page color and delivery script) over a site's built-in themes. //! - [`workspaces`]: saved tab/pane/deck layouts, bounded and well-formed (never evaluated). //! - [`devmode`]: developer mode's debounced watcher of plugins, custom CSS and a theme file. +//! - [`settings`]: the shell's settings (home page, where links open, session restore) and the page's +//! feature flags, as validated data and the scripts that hand them to site tabs. //! - [`alerts`]: local keyword alerts (keywords, snippets, per-item/per-keyword rate limits). //! - [`media`]: gallery folders (path containment) and the opt-in clipboard history (private copies skipped). //! - [`gfonts`]: self-hosted Google Fonts: CSS parsing, URL/woff2 checks, the cache format, the page script; @@ -37,7 +39,8 @@ //! With the `tauri` feature, [`host`] adds the Tauri glue that does not depend on app state; with //! `tauri` and `net`, [`updater`] runs signed native updates and the hotfix channel. With `app`, //! [`app`] is the whole app around a site: [`app::run_app`] makes the window, the shell and the tab -//! webviews, registers the plugins and serves the generic commands; the app adds its own. +//! webviews, registers the plugins and serves the generic commands (tab layout and actions, profiles, +//! language, the plugins folder and custom CSS, page tweaks, the shell's settings); the app adds its own. pub mod alerts; pub mod backup; @@ -54,6 +57,7 @@ pub mod media; pub mod plugins; pub mod policy; pub mod profiles; +pub mod settings; pub mod site; pub mod store; pub mod sync; diff --git a/crates/waybetter-host/src/settings.rs b/crates/waybetter-host/src/settings.rs new file mode 100644 index 0000000..1a71276 --- /dev/null +++ b/crates/waybetter-host/src/settings.rs @@ -0,0 +1,181 @@ +//! What the shell's settings and the page tweaks are, as data the host keeps for every app: +//! [`ShellSettings`] (the home page, where links open, session restore; `settings.json`) and the +//! feature flags (a small map of booleans the page runtime applies; `features.json`). Pure: the +//! commands that read and save them are in [`crate::app`]. + +use crate::site::SiteSpec; +use crate::tabs; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use url::Url; + +/// The home page, where links open and session restore. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShellSettings { + /// Page for new tabs and the first launch. + pub home_url: String, + /// Links to other sites opened from a tab: "pane" (split beside it), "tab" or "browser". + pub external_links: String, + /// The site's own pages clicked in the page: "same" (the site's in-place navigation), "pane", + /// "tab" or "browser". The page runtime diverts only those clicks; see [`links_script`]. + pub site_links: String, + /// Reopen the previous session's tabs and splits on launch. + pub restore_tabs: bool, +} + +/// Settings as they arrive (the shell, `settings.json`, a backup): any field may be missing. +/// `xLinks` is what wayBetter for X called `siteLinks` before the host kept the settings. +#[derive(Clone, Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct ShellSettingsInput { + pub home_url: Option, + pub external_links: Option, + #[serde(alias = "xLinks")] + pub site_links: Option, + pub restore_tabs: Option, +} + +impl ShellSettings { + /// The settings before the owner changes anything; `home` is the app's home page. + pub fn defaults(home: &str) -> Self { + Self { home_url: home.to_owned(), external_links: "pane".into(), site_links: "same".into(), restore_tabs: true } + } + + /// `input` over the defaults, validated: an http(s) home page and known link modes. + pub fn from_input(input: ShellSettingsInput, home: &str) -> Result { + let defaults = Self::defaults(home); + Self { + home_url: input.home_url.unwrap_or(defaults.home_url), + external_links: input.external_links.unwrap_or(defaults.external_links), + site_links: input.site_links.unwrap_or(defaults.site_links), + restore_tabs: input.restore_tabs.unwrap_or(defaults.restore_tabs), + } + .validated() + } + + /// Settings from JSON (a file, a backup section), over the defaults and validated. + pub fn from_value(value: Value, home: &str) -> Result { + let input: ShellSettingsInput = serde_json::from_value(value).map_err(|error| format!("VALIDATION: {error}"))?; + Self::from_input(input, home) + } + + pub fn validated(mut self) -> Result { + let home = Url::parse(self.home_url.trim()).map_err(|_| "VALIDATION: invalid home page URL")?; + if !matches!(home.scheme(), "http" | "https") { + return Err("VALIDATION: home page must be an http(s) URL".into()); + } + self.home_url = home.to_string(); + if !tabs::valid_external_mode(&self.external_links) { + return Err("VALIDATION: external links must be \"pane\", \"tab\" or \"browser\"".into()); + } + if !tabs::valid_site_mode(&self.site_links) { + return Err("VALIDATION: site links must be \"same\", \"pane\", \"tab\" or \"browser\"".into()); + } + Ok(self) + } + + /// Where a new-window request (a link with target=_blank, window.open) opens; `on_site`: the + /// request is for one of the site's own pages. + pub fn new_window_mode(&self, on_site: bool) -> &str { + // "same" only concerns ordinary clicks; an explicit new window on the site still gets a tab. + tabs::new_window_mode(on_site, &self.site_links, &self.external_links) + } + + /// Links to other sites go to the system browser. + pub fn external_in_browser(&self) -> bool { + self.external_links == "browser" + } +} + +/// Tells a site tab where clicked site pages open (`site_links`); the page runtime diverts only +/// "pane", "tab" and "browser" clicks, as a plain new-window request that +/// [`ShellSettings::new_window_mode`] routes. Queued in `__btLinks` until the runtime exists. +pub fn links_script(site: &SiteSpec, settings: &ShellSettings) -> String { + let links = serde_json::json!({ "site": settings.site_links }); + tabs::deliver_script(site.runtime_global, "links", "configure", "__btLinks", &links.to_string()) +} + +/// Feature flags are booleans only, in a small map; the page normalizes them again before use. +pub fn validate_features(features: &Map) -> Result<(), String> { + if features.len() > 64 || features.iter().any(|(key, value)| key.len() > 64 || !value.is_boolean()) { + return Err("VALIDATION: features must be a small map of booleans".into()); + } + Ok(()) +} + +/// Hands a site tab the feature flags (`.features.apply`), queued in `__btFeatures` until +/// the runtime exists. +pub fn features_script(site: &SiteSpec, features: &Value) -> String { + tabs::deliver_script(site.runtime_global, "features", "apply", "__btFeatures", &features.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::site::testing::SITE; + use serde_json::json; + + const HOME: &str = "https://x.com/home"; + + #[test] + fn missing_fields_take_the_defaults_and_the_old_name_is_read() { + let defaults = ShellSettings::defaults(HOME); + assert_eq!(ShellSettings::from_value(json!({}), HOME).unwrap(), defaults); + let old = ShellSettings::from_value(json!({ "homeUrl": "https://x.com/explore", "xLinks": "tab", "restoreTabs": false }), HOME).unwrap(); + assert_eq!(old.site_links, "tab"); + assert_eq!(old.home_url, "https://x.com/explore"); + assert!(!old.restore_tabs); + assert_eq!(old.external_links, "pane"); + let new = ShellSettings::from_value(json!({ "siteLinks": "browser" }), HOME).unwrap(); + assert_eq!(new.site_links, "browser"); + // What the shell reads back. + assert_eq!( + serde_json::to_value(&new).unwrap(), + json!({ "homeUrl": HOME, "externalLinks": "pane", "siteLinks": "browser", "restoreTabs": true }) + ); + } + + #[test] + fn bad_values_are_refused() { + for bad in [ + json!({ "homeUrl": "javascript:alert(1)" }), + json!({ "homeUrl": "not a url" }), + json!({ "externalLinks": "same" }), + json!({ "siteLinks": "window" }), + json!({ "restoreTabs": "yes" }), + ] { + assert!(ShellSettings::from_value(bad.clone(), HOME).is_err(), "{bad}"); + } + } + + #[test] + fn new_windows_follow_the_link_settings() { + let mut settings = ShellSettings::defaults(HOME); + assert_eq!(settings.new_window_mode(true), "tab", "\"same\" is about plain clicks; a new window on the site is a tab"); + assert_eq!(settings.new_window_mode(false), "pane"); + settings.site_links = "browser".into(); + settings.external_links = "browser".into(); + assert_eq!(settings.new_window_mode(true), "browser"); + assert!(settings.external_in_browser()); + } + + #[test] + fn scripts_deliver_data_to_the_runtime() { + let links = links_script(&SITE, &ShellSettings::defaults(HOME)); + assert!(links.contains(r#"{"site":"same"}"#) && links.contains("R.links.configure(v)") && links.contains("window.__btLinks=v"), "{links}"); + let features = features_script(&SITE, &json!({ "hideTrends": true })); + assert!(features.contains(r#"{"hideTrends":true}"#) && features.contains("R.features.apply(v)") && features.contains("window.__btFeatures=v"), "{features}"); + } + + #[test] + fn features_are_a_small_map_of_booleans() { + let map = |value: Value| value.as_object().cloned().unwrap(); + assert!(validate_features(&map(json!({ "a": true, "b": false }))).is_ok()); + assert!(validate_features(&map(json!({ "a": "yes" }))).is_err()); + let long: Map = [("x".repeat(65), Value::Bool(true))].into_iter().collect(); + assert!(validate_features(&long).is_err()); + let many: Map = (0..65).map(|n| (format!("f{n}"), Value::Bool(true))).collect(); + assert!(validate_features(&many).is_err()); + } +} diff --git a/crates/waybetter-host/src/tabs.rs b/crates/waybetter-host/src/tabs.rs index 6a430e1..a5b38fb 100644 --- a/crates/waybetter-host/src/tabs.rs +++ b/crates/waybetter-host/src/tabs.rs @@ -11,6 +11,8 @@ pub const EVENT_TAB_OPEN: &str = "tab-open"; pub const EVENT_TAB_SHORTCUT: &str = "tab-shortcut"; pub const EVENT_LINK_DRAG: &str = "link-drag"; pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed"; +/// A site tab asks the shell to open the app's panel (`{ from, section }`). +pub const EVENT_OPEN_PANEL: &str = "open-panel"; /// One pane as the shell lays it out (`tabs_sync`). #[derive(Debug, Deserialize)] diff --git a/crates/waybetter-host/src/testkit.rs b/crates/waybetter-host/src/testkit.rs index ae5b9e3..50dc896 100644 --- a/crates/waybetter-host/src/testkit.rs +++ b/crates/waybetter-host/src/testkit.rs @@ -132,12 +132,31 @@ impl Capabilities { assert!(granting.is_empty(), "{permission} is granted by {granting:?}"); } - /// The host's commands ([`commands::SHELL`], [`commands::TAB`]) keep their callers. + /// `command` is granted, and only to tab webviews on `site`'s own pages: every capability + /// granting it is a tab capability whose remote URLs are exactly `https:///*` of the + /// site's hosts. + pub fn assert_site_only(&self, command: &str, site: &crate::site::SiteSpec) { + self.assert_tab_only(command); + let permission = commands::permission(command); + let allowed: Vec = site.hosts.iter().map(|host| format!("https://{host}/*")).collect(); + for cap in self.granting(&permission) { + let urls: Vec<&str> = cap.json["remote"]["urls"].as_array().map(|list| list.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + assert!( + !urls.is_empty() && urls.iter().all(|url| allowed.iter().any(|ok| ok == url)), + "{permission} is for {allowed:?} only, but capability {:?} ({}) grants it on {urls:?}", + cap.identifier(), + cap.file + ); + } + } + + /// The host's commands ([`commands::SHELL`], [`commands::TAB`], [`commands::SITE`]) keep their + /// callers. Check the site commands' URLs with [`Self::assert_site_only`] too. pub fn assert_host_commands(&self) { for command in commands::SHELL { self.assert_shell_only(command); } - for command in commands::TAB { + for command in commands::TAB.iter().chain(commands::SITE) { self.assert_tab_only(command); } } @@ -179,15 +198,23 @@ pub fn assert_host_guards() { for command in commands::TAB { assert_guarded(source, command, "tab_only(&webview)?"); } + for command in commands::SITE { + assert_guarded(source, command, "site_tab_only(config(&app).site, &webview)?"); + } } #[cfg(test)] mod tests { use super::*; - fn caps(shell_extra: &str, tab_extra: &str) -> Capabilities { + fn caps_with(shell_extra: &str, tab_extra: &str, site_extra: &str) -> Capabilities { let host_shell: Vec = commands::SHELL.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); let host_tab: Vec = commands::TAB.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); + let host_site: Vec = commands::SITE.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect(); + let site = format!( + r#"{{"identifier":"site-tab","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://x.com/*"]}},"permissions":[{}{site_extra}]}}"#, + host_site.join(",") + ); let shell = format!( r#"{{"identifier":"shell","webviews":["shell"],"local":true,"permissions":["core:event:default",{}{shell_extra}]}}"#, host_shell.join(",") @@ -196,7 +223,11 @@ mod tests { r#"{{"identifier":"tab-chrome","webviews":["tab-*"],"local":false,"remote":{{"urls":["https://*/*"]}},"permissions":[{}{tab_extra}]}}"#, host_tab.join(",") ); - Capabilities::from_sources(&[("shell.json", &shell), ("tab-chrome.json", &tab)]) + Capabilities::from_sources(&[("shell.json", &shell), ("tab-chrome.json", &tab), ("site-tab.json", &site)]) + } + + fn caps(shell_extra: &str, tab_extra: &str) -> Capabilities { + caps_with(shell_extra, tab_extra, "") } #[test] @@ -219,6 +250,15 @@ mod tests { caps(r#","allow-tab-shortcut""#, "").assert_host_commands(); } + #[test] + fn site_commands_are_for_the_site_only() { + use crate::site::testing::SITE; + caps("", "").assert_site_only("open_panel", &SITE); + // Granted to every tab (any site), a site command fails. + let wide = std::panic::catch_unwind(|| caps("", r#","allow-open-panel""#).assert_site_only("open_panel", &SITE)); + assert!(wide.is_err()); + } + #[test] #[should_panic(expected = "plugin API")] fn plugin_apis_are_refused() { diff --git a/dev-tools/README.md b/dev-tools/README.md new file mode 100644 index 0000000..86784ab --- /dev/null +++ b/dev-tools/README.md @@ -0,0 +1,27 @@ +# dev-tools + +Development harnesses for a wayBetter app. They are not part of the npm package and nothing here +ships in an app: they probe a build you start yourself. Each file's header says exactly what it +does and what it never does (site pages are only read and reloaded, never clicked; nothing is +uploaded; the owner's session is not touched unless the header says a disposable profile is +needed). + +An app calls them with its own values. wayBetter for X keeps thin wrappers +(`apps/desktop/scripts/*`, `verification/live-check/*`) that pass X's origin, process name, theme +commands, scripts and fixtures. + +| Tool | Runs against | What it measures or checks | +| --- | --- | --- | +| `perf-probe.mjs` (`runPerfProbe`) | headless Chromium, the app's injected scripts, the app's fixtures | script evaluation time, fetch/XHR wrapper layers and overhead, Response clones, large JSON parses, observer / rAF / timer work of the scripts, long tasks | +| `runtime-start-check.mjs` (`runtimeStartCheck`) | headless Chromium, the built page runtime, static fixtures | the runtime installs at document start; every feature flag on, off, default without a console or page error | +| `resize-perf.mjs` | a running release build with a WebView2 CDP port | `theme` (first paint vs. theme applied), `drag` (divider drag: shell frames, `tabs_sync`, native lag), `switch` (click to tab visible), `window` (with `window-resize.ps1`) | +| `window-resize.ps1` | the app's window (Windows) | a repeatable ~2 s resize workload; never activates the window | +| `close-check.ps1` | the app's release exe (Windows) | the app exits on a plain `taskkill /PID` in every window state and on a simulated sign-out | +| `native-tab-stress.mjs` | a running build with a CDP port | opens shell start tabs, measures responsiveness, closes them | +| `native-webview-stress.mjs` | a running build with a CDP port, a fresh WebView2 profile | ramps native site tabs (6, 12, 24) and records process memory; stops at a memory limit | +| `native-stress-watch.ps1` | the app's process tree (Windows) | independent CPU and memory telemetry while a stress run is going | +| `native-stale-shortcut-check.mjs` | an isolated release build with a CDP port | a stale tab id in a shortcut never targets the active tab | + +Requirements: Node 24+, and for the headless probes `playwright` in the app (the probe takes the +app's `chromium`). The CDP tools need the app started with +`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=`. diff --git a/dev-tools/close-check.ps1 b/dev-tools/close-check.ps1 new file mode 100644 index 0000000..9f0e5b2 --- /dev/null +++ b/dev-tools/close-check.ps1 @@ -0,0 +1,137 @@ +# Graceful-close regression check (Windows): the app must exit on a plain `taskkill /PID` (WM_CLOSE, +# no /F) in every window state, and on a simulated sign-out (WM_QUERYENDSESSION + WM_ENDSESSION). +# +# Why: tao's thread event target and the single-instance plugin's message window are visible 1 px +# unowned top-level windows. taskkill closes only the first such window in z-order; a minimized +# window sinks below them, so before the fix the close destroyed a helper and the app stayed alive. +# +# powershell -ExecutionPolicy Bypass -File dev-tools/close-check.ps1 -Exe [-Cases normal,minimized,...] +# +# Cases: normal, minimized, maximized, +# unfocused (another window in front), debugport (WebView2 remote debugging on), endsession +# (minimized, then the sign-out messages). Every case restarts the app with the owner's saved +# layout (tabs, deck columns); "webviews" counts the shell plus every tab/column webview. Any +# running copy of the same exe is closed first; a copy that does not exit is only force-killed when +# its path is this exe. Relaunch the app normally afterwards. + +param( + [Parameter(Mandatory = $true)][string]$Exe, + [string[]]$Cases = @('normal', 'minimized', 'maximized', 'unfocused', 'debugport', 'endsession'), + [int]$StartupSeconds = 10, + [int]$ExitSeconds = 10 +) + +$ErrorActionPreference = 'Stop' +$Exe = (Resolve-Path $Exe).Path +$ProcessName = [IO.Path]::GetFileNameWithoutExtension($Exe) + +Add-Type @" +using System; using System.Text; using System.Runtime.InteropServices; using System.Collections.Generic; +public static class CloseCheckWin { + public delegate bool EnumProc(IntPtr h, IntPtr l); + [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc p, IntPtr l); + [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder s, int n); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h); + [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, IntPtr w, IntPtr l, uint flags, uint ms, out IntPtr r); + public static List Windows(uint pid) { + var r = new List(); + EnumWindows((h, l) => { uint p; GetWindowThreadProcessId(h, out p); if (p == pid) r.Add(h); return true; }, IntPtr.Zero); + return r; + } + [DllImport("user32.dll")] static extern bool EnumChildWindows(IntPtr h, EnumProc p, IntPtr l); + public static int CountChildren(IntPtr parent, string cls) { + int n = 0; + EnumChildWindows(parent, (h, l) => { if (ClassOf(h) == cls) n++; return true; }, IntPtr.Zero); + return n; + } + public static string ClassOf(IntPtr h) { var c = new StringBuilder(256); GetClassName(h, c, 256); return c.ToString(); } +} +"@ + +function Get-Ours { Get-Process $ProcessName -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $Exe } } + +function Describe-Windows([int]$ProcessId) { + ([CloseCheckWin]::Windows([uint32]$ProcessId) | Where-Object { [CloseCheckWin]::IsWindowVisible($_) } | ForEach-Object { + $class = [CloseCheckWin]::ClassOf($_) + if ([CloseCheckWin]::IsIconic($_)) { "$class(min)" } else { $class } + }) -join ' > ' +} + +function Stop-Ours { + foreach ($p in @(Get-Ours)) { + & taskkill.exe /PID $p.Id 2>&1 | Out-Null + if (-not $p.WaitForExit($ExitSeconds * 1000)) { + Write-Host " (force-killing leftover $($p.Id) at $($p.Path))" + Stop-Process -Id $p.Id -Force + $p.WaitForExit(5000) | Out-Null + } + } +} + +function Start-Ours([hashtable]$Vars = @{}) { + $saved = @{} + foreach ($key in $Vars.Keys) { $saved[$key] = [Environment]::GetEnvironmentVariable($key); [Environment]::SetEnvironmentVariable($key, $Vars[$key]) } + try { Start-Process $Exe -WindowStyle Normal } finally { + foreach ($key in $saved.Keys) { [Environment]::SetEnvironmentVariable($key, $saved[$key]) } + } + $deadline = (Get-Date).AddSeconds(30) + do { + Start-Sleep -Milliseconds 500 + $p = Get-Ours | Select-Object -First 1 + $main = if ($p) { [CloseCheckWin]::Windows([uint32]$p.Id) | Where-Object { [CloseCheckWin]::ClassOf($_) -eq 'Tauri Window' -and [CloseCheckWin]::IsWindowVisible($_) } | Select-Object -First 1 } + } until ($main -or (Get-Date) -gt $deadline) + if (-not $main) { throw "the app window did not appear" } + Start-Sleep -Seconds $StartupSeconds # tabs, deck columns and plugins load + return @{ Process = $p; Main = $main } +} + +function Wait-Exit($p) { + $watch = [Diagnostics.Stopwatch]::StartNew() + $exited = $p.WaitForExit($ExitSeconds * 1000) + return @{ Exited = $exited; Seconds = [math]::Round($watch.Elapsed.TotalSeconds, 1) } +} + +$results = @() +Stop-Ours +foreach ($case in $Cases) { + $extra = if ($case -eq 'debugport') { @{ WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=9333' } } else { @{} } + $app = Start-Ours $extra + $p = $app.Process; $main = $app.Main + switch ($case) { + 'minimized' { [CloseCheckWin]::ShowWindow($main, 6) | Out-Null } + 'endsession' { [CloseCheckWin]::ShowWindow($main, 6) | Out-Null } + 'maximized' { [CloseCheckWin]::ShowWindow($main, 3) | Out-Null } + 'unfocused' { + [CloseCheckWin]::ShowWindow($main, 9) | Out-Null + $shell = Get-Process explorer -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1 + if ($shell) { [CloseCheckWin]::SetForegroundWindow($shell.MainWindowHandle) | Out-Null } + } + } + Start-Sleep -Seconds 2 + $order = Describe-Windows $p.Id + $webviews = [CloseCheckWin]::CountChildren($main, 'WRY_WEBVIEW') + if ($case -eq 'endsession') { + # What Windows sends every top-level window at sign-out (ENDSESSION_LOGOFF). + $r = [IntPtr]::Zero + foreach ($h in [CloseCheckWin]::Windows([uint32]$p.Id)) { [CloseCheckWin]::SendMessageTimeout($h, 0x11, [IntPtr]::Zero, [IntPtr]0x80000000, 2, 2000, [ref]$r) | Out-Null } + foreach ($h in [CloseCheckWin]::Windows([uint32]$p.Id)) { [CloseCheckWin]::SendMessageTimeout($h, 0x16, [IntPtr]1, [IntPtr]0x80000000, 2, 2000, [ref]$r) | Out-Null } + } else { + & taskkill.exe /PID $p.Id 2>&1 | Out-Null + } + $outcome = Wait-Exit $p + $leftover = if ($outcome.Exited) { '' } else { Describe-Windows $p.Id } + $pass = $outcome.Exited + $results += [pscustomobject]@{ Case = $case; Pass = $pass; Seconds = $outcome.Seconds; Webviews = $webviews; WindowsBefore = $order; Leftover = $leftover } + Write-Host ('{0} {1,-16} exited={2} in {3}s webviews={5} [{4}]' -f ($(if ($pass) { 'ok ' } else { 'FAIL' })), $case, $outcome.Exited, $outcome.Seconds, $order, $webviews) + if (-not $pass) { Write-Host " still open: $leftover"; Stop-Ours } +} + +$failed = @($results | Where-Object { -not $_.Pass }) +Write-Host '' +Write-Host ("{0}/{1} close cases passed" -f ($results.Count - $failed.Count), $results.Count) +if ($failed.Count) { exit 1 } +exit 0 diff --git a/dev-tools/native-stale-shortcut-check.mjs b/dev-tools/native-stale-shortcut-check.mjs new file mode 100644 index 0000000..d36c710 --- /dev/null +++ b/dev-tools/native-stale-shortcut-check.mjs @@ -0,0 +1,52 @@ +// In an isolated release flavor, verify a stale explicit tab ID never targets the active tab. +// Usage: node dev-tools/native-stale-shortcut-check.mjs +const port = Number(process.argv[2]); +if (!Number.isInteger(port)) throw new Error('Invalid CDP port'); +const sitePage = process.argv[3] ?? process.env.SITE_PAGE; +if (!sitePage) throw new Error('A page of the site to open is required (argument 2 or SITE_PAGE)'); +const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); +const target = list.find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/')); +if (!target) throw new Error('Shell CDP target not found'); +const socket = new WebSocket(target.webSocketDebuggerUrl); +await new Promise(resolve => { socket.onopen = resolve; }); +let serial = 0; +const pending = new Map(); +socket.onmessage = event => { + const message = JSON.parse(event.data); + if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); } +}; +const evaluate = expression => new Promise((resolve, reject) => { + const id = ++serial; + const timer = setTimeout(() => { pending.delete(id); reject(new Error('Shell CDP timed out')); }, 30_000); + pending.set(id, message => { + clearTimeout(timer); + if (message.result?.exceptionDetails) reject(new Error(JSON.stringify(message.result.exceptionDetails).slice(0, 500))); + else resolve(message.result?.result?.value); + }); + socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, awaitPromise: true, returnByValue: true } })); +}); +try { + const result = await evaluate(`(async () => { + const ids = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')] + .map(tab => tab.dataset.panelId); + const before = ids(); + if (before.length !== 1) throw new Error('Expected one isolated initial tab'); + await window.__TAURI__.event.emit('tab-open', { url: ${JSON.stringify(sitePage)}, background: true }); + const waitFor = async count => { + const deadline = performance.now() + 10_000; + while (ids().length !== count && performance.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50)); + if (ids().length !== count) throw new Error('Timed out waiting for ' + count + ' tabs'); + }; + await waitFor(2); + const created = ids().find(id => !before.includes(id)); + await window.__TAURI__.event.emit('tab-shortcut', { id: created, shortcut: 'close-tab' }); + await waitFor(1); + for (const shortcut of ['close-tab', 'split-right', 'open-panel']) { + await window.__TAURI__.event.emit('tab-shortcut', { id: created, shortcut }); + await new Promise(resolve => setTimeout(resolve, 200)); + if (ids().join() !== before.join()) throw new Error('Stale ' + shortcut + ' changed live tabs'); + } + return { before, created, after: ids(), staleShortcuts: ['close-tab', 'split-right', 'open-panel'] }; + })()`); + console.log(JSON.stringify(result)); +} finally { socket.close(); } diff --git a/dev-tools/native-stress-watch.ps1 b/dev-tools/native-stress-watch.ps1 new file mode 100644 index 0000000..c4198a4 --- /dev/null +++ b/dev-tools/native-stress-watch.ps1 @@ -0,0 +1,57 @@ +param( + [Parameter(Mandatory = $true)][int]$AppPid, + [Parameter(Mandatory = $true)][string]$OutputPath, + [int]$Seconds = 90, + [int]$IntervalSeconds = 2, + [int]$AbortAtWorkingSetMB = 0, + [string]$ExpectedExecutable = '' +) + +# Independent telemetry for native-webview-stress.mjs. Follow only descendants of the +# isolated app PID; a hung shell CDP target cannot stop this watcher from recording CPU. +$previousCpu = @{} +$watch = [System.Diagnostics.Stopwatch]::StartNew() +while ($watch.Elapsed.TotalSeconds -lt $Seconds) { + $all = @(Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId) + $ids = @($AppPid) + do { + $children = @($all | Where-Object { + $ids -contains $_.ParentProcessId -and $ids -notcontains $_.ProcessId + } | Select-Object -ExpandProperty ProcessId) + $ids += $children + } while ($children.Count -gt 0) + + $processes = @(Get-Process -Id $ids -ErrorAction SilentlyContinue) + if (-not ($processes | Where-Object Id -EQ $AppPid)) { break } + $rows = @($processes | ForEach-Object { + $cpu = if ($null -eq $_.CPU) { 0 } else { [double]$_.CPU } + $before = if ($previousCpu.ContainsKey($_.Id)) { $previousCpu[$_.Id] } else { $cpu } + $previousCpu[$_.Id] = $cpu + [pscustomobject]@{ + pid = $_.Id + name = $_.ProcessName + cpuDeltaSeconds = [math]::Round($cpu - $before, 3) + cpuTotalSeconds = [math]::Round($cpu, 3) + workingSetMB = [math]::Round($_.WorkingSet64 / 1MB) + privateMB = [math]::Round($_.PrivateMemorySize64 / 1MB) + } + } | Sort-Object cpuDeltaSeconds -Descending) + $totalWorkingSetMB = ($rows | Measure-Object workingSetMB -Sum).Sum + [pscustomobject]@{ + elapsedSeconds = [math]::Round($watch.Elapsed.TotalSeconds, 2) + processCount = $rows.Count + totalCpuDeltaSeconds = [math]::Round(($rows | Measure-Object cpuDeltaSeconds -Sum).Sum, 3) + totalWorkingSetMB = $totalWorkingSetMB + top = @($rows | Select-Object -First 8) + } | ConvertTo-Json -Depth 5 -Compress | Add-Content -LiteralPath $OutputPath + if ($AbortAtWorkingSetMB -gt 0 -and $totalWorkingSetMB -ge $AbortAtWorkingSetMB) { + $app = Get-CimInstance Win32_Process -Filter "ProcessId=$AppPid" + if ($app -and $ExpectedExecutable -and $app.ExecutablePath -ieq $ExpectedExecutable) { + [pscustomobject]@{ event = 'memory-abort'; appPid = $AppPid; workingSetMB = $totalWorkingSetMB } | + ConvertTo-Json -Compress | Add-Content -LiteralPath $OutputPath + Stop-Process -Id $AppPid -Force + } + break + } + Start-Sleep -Seconds $IntervalSeconds +} diff --git a/dev-tools/native-tab-stress.mjs b/dev-tools/native-tab-stress.mjs new file mode 100644 index 0000000..31c66cc --- /dev/null +++ b/dev-tools/native-tab-stress.mjs @@ -0,0 +1,70 @@ +// Native shell stress for a wayBetter app through WebView2 CDP. Run only against an app started with +// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=. +// Opens 24 shell start tabs, measures responsiveness, then closes those tabs. +const port = process.argv[2] ?? '9344'; +const count = Number(process.argv[3] ?? 24); +const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); +const target = list.find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/')); +if (!target) throw new Error('Shell CDP target not found'); +const socket = new WebSocket(target.webSocketDebuggerUrl); +const ready = new Promise(resolve => { socket.onopen = resolve; }); +const pending = new Map(); +let serial = 0; +socket.onmessage = event => { + const message = JSON.parse(event.data); + if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); } +}; +await ready; +const send = (method, params = {}) => new Promise(resolve => { + const id = ++serial; + pending.set(id, resolve); + socket.send(JSON.stringify({ id, method, params })); +}); +const evaluate = async expression => { + let timeout; + const result = await Promise.race([ + send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }), + new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Shell unresponsive for 20 s')), 20_000); }), + ]).finally(() => clearTimeout(timeout)); + if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails)); + return result.result?.result?.value; +}; +const expression = `\n(async () => { + const count = ${count}; + const before = document.querySelectorAll('.dv-tab').length; + const delays = []; + const longTasks = []; + const observer = new PerformanceObserver(list => { + for (const entry of list.getEntries()) longTasks.push(entry.duration); + }); + observer.observe({ entryTypes: ['longtask'] }); + let expected = performance.now() + 50; + const interval = setInterval(() => { + const now = performance.now(); + delays.push(Math.max(0, now - expected)); + expected = now + 50; + }, 50); + const key = key => window.dispatchEvent(new KeyboardEvent('keydown', { key, ctrlKey: true, bubbles: true })); + const start = performance.now(); + for (let i = 0; i < count; i++) key('t'); + const dispatchMs = performance.now() - start; + await new Promise(resolve => setTimeout(resolve, 1500)); + const opened = document.querySelectorAll('.dv-tab').length; + for (let i = 0; i < count; i++) key('w'); + await new Promise(resolve => setTimeout(resolve, 300)); + clearInterval(interval); + observer.disconnect(); + return { + before, opened, afterCleanup: document.querySelectorAll('.dv-tab').length, + dispatchMs: Math.round(dispatchMs), + maxDelayMs: Math.round(Math.max(0, ...delays)), + maxLongTaskMs: Math.round(Math.max(0, ...longTasks)), + }; +})()`; +try { + const result = await evaluate(expression); + console.log(JSON.stringify(result, null, 2)); + if (result.opened !== result.before + count || result.afterCleanup !== result.before) process.exitCode = 1; +} finally { + socket.close(); +} diff --git a/dev-tools/native-webview-stress.mjs b/dev-tools/native-webview-stress.mjs new file mode 100644 index 0000000..5fc28ef --- /dev/null +++ b/dev-tools/native-webview-stress.mjs @@ -0,0 +1,203 @@ +// Exercise native WebView creation with actual site pages. Start the app's release build with +// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port= and, preferably, +// WEBVIEW2_USER_DATA_FOLDER pointing to a fresh directory. Nothing is clicked on the site. +// Usage: SITE_PAGES=https://x.com/home,https://x.com/explore node dev-tools/native-webview-stress.mjs [6,12,24] [app-pid] +// (the first page is opened in every tab; with the mixed route mode the second in every other tab) +import { writeFile, unlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +const port = process.argv[2] ?? '9344'; +const stages = (process.argv[3] ?? '6,12,24').split(',').map(Number); +const appPid = process.argv[4] ? Number(process.argv[4]) : null; +const memoryLimitMB = Number(process.env.WAYBETTER_STRESS_MEMORY_LIMIT_MB ?? 6144); +const sitePages = (process.env.SITE_PAGES ?? '').split(',').map(page => page.trim()).filter(Boolean); +if (!sitePages.length) throw new Error('SITE_PAGES is required (pages of the site to open, comma separated)'); +const siteOrigin = new URL(sitePages[0]).origin; +const routeMode = process.env.WAYBETTER_STRESS_ROUTE_MODE ?? 'home'; +if (!stages.length || stages.some((n, i) => !Number.isInteger(n) || n < 1 || n > 24 || (i && n <= stages[i - 1]))) { + throw new Error('Stages must increase from 1 to at most 24'); +} +if (appPid !== null && (!Number.isInteger(appPid) || appPid < 1)) throw new Error('Invalid app PID'); +if (!Number.isFinite(memoryLimitMB) || memoryLimitMB < 1) throw new Error('Invalid memory limit'); +if (!['home', 'mixed-home-explore'].includes(routeMode)) throw new Error('Invalid route mode'); +const run = promisify(execFile); +async function processSnapshot() { + if (!appPid) return null; + const command = `$all=Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId;$ids=@(${appPid});do{$n=@($all | Where-Object { $ids -contains $_.ParentProcessId -and $ids -notcontains $_.ProcessId } | Select-Object -ExpandProperty ProcessId);$ids+= $n}while($n.Count -gt 0);@(Get-Process -Id $ids -ErrorAction SilentlyContinue | Select-Object Id,ProcessName,CPU,WorkingSet64) | ConvertTo-Json -Compress`; + const { stdout } = await run('powershell', ['-NoProfile', '-Command', command], { timeout: 15_000 }); + const parsed = JSON.parse(stdout); + return Array.isArray(parsed) ? parsed : [parsed]; +} +function processDelta(before, after) { + if (!before || !after) return null; + const old = new Map(before.map(item => [item.Id, item.CPU ?? 0])); + const rows = after.map(item => ({ + pid: item.Id, name: item.ProcessName, + cpuSeconds: Math.round(((item.CPU ?? 0) - (old.get(item.Id) ?? 0)) * 10) / 10, + memoryMB: Math.round((item.WorkingSet64 ?? 0) / 1024 / 1024), + })).sort((a, b) => b.cpuSeconds - a.cpuSeconds); + return { + totalCpuSeconds: Math.round(rows.reduce((sum, row) => sum + row.cpuSeconds, 0) * 10) / 10, + totalMemoryMB: rows.reduce((sum, row) => sum + row.memoryMB, 0), + top: rows.slice(0, 6), + }; +} +const targets = async () => (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()); +const target = (await targets()).find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/')); +if (!target) throw new Error('Shell CDP target not found'); +const socket = new WebSocket(target.webSocketDebuggerUrl); +const ready = new Promise(resolve => { socket.onopen = resolve; }); +const pending = new Map(); +let serial = 0; +socket.onmessage = event => { + const message = JSON.parse(event.data); + if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); } +}; +await ready; +const send = (method, params = {}) => new Promise(resolve => { + const id = ++serial; + pending.set(id, resolve); + socket.send(JSON.stringify({ id, method, params })); +}); +const evaluate = async (expression, timeoutMs = 45_000) => { + let timeout; + const result = await Promise.race([ + send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }), + new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error(`Shell unresponsive for ${timeoutMs / 1000} s`)), timeoutMs); }), + ]).finally(() => clearTimeout(timeout)); + if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails).slice(0, 600)); + return result.result?.result?.value; +}; + +const backup = join(tmpdir(), `waybetter-layout-before-stress-${process.pid}.json`); +let completed = false; +try { + const original = await evaluate(`(() => { + if (!window.__TAURI__?.event?.emit) throw new Error('Tauri event API unavailable'); + const liveIds = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')] + .map(tab => tab.dataset.panelId); + const originalIds = liveIds(); + if (new Set(originalIds).size !== originalIds.length) throw new Error('Duplicate live panel IDs'); + const saved = JSON.parse(localStorage.getItem('bt.shell.layout.v1') || 'null'); + if (Object.keys(saved?.panels ?? {}).length !== originalIds.length) { + throw new Error('Saved panel count does not match live tabs; wait for initial layout persistence'); + } + window.__webStress = { + originalIds: new Set(originalIds), + initialCount: originalIds.length, + layout: localStorage.getItem('bt.shell.layout.v1'), + delays: [], longTasks: [], expected: performance.now() + 50, + }; + const s = window.__webStress; + s.observer = new PerformanceObserver(list => { + for (const entry of list.getEntries()) s.longTasks.push(entry.duration); + }); + s.observer.observe({ entryTypes: ['longtask'] }); + s.interval = setInterval(() => { + const now = performance.now(); + s.delays.push(Math.max(0, now - s.expected)); + s.expected = now + 50; + }, 50); + return { initialCount: s.initialCount, layout: s.layout }; + })()`); + // This file is a recovery copy if the shell dies before its tabs can be closed. It is deleted + // after a successful cleanup; its contents are never printed or committed. + await writeFile(backup, JSON.stringify({ layout: original.layout }), { mode: 0o600 }); + console.log(JSON.stringify({ initialTabs: original.initialCount, recoveryFile: backup })); + let previous = 0; + let stopReason = null; + for (const count of stages) { + const beforeProcesses = await processSnapshot(); + const added = count - previous; + const urls = Array.from({ length: added }, (_, index) => + routeMode === 'mixed-home-explore' && (previous + index) % 2 === 1 + ? sitePages[1] ?? sitePages[0] : sitePages[0]); + const stage = await evaluate(`(async () => { + const s = window.__webStress; + const start = performance.now(); + const calls = ${JSON.stringify(urls)}.map(url => window.__TAURI__.event.emit('tab-open', { + url, background: true, + })); + await Promise.all(calls); + const dispatchMs = performance.now() - start; + const expected = s.initialCount + ${count}; + const deadline = performance.now() + 30_000; + while (document.querySelectorAll('.dv-tab').length < expected && performance.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 100)); + } + await new Promise(resolve => setTimeout(resolve, 8_000)); + const saved = JSON.parse(localStorage.getItem('bt.shell.layout.v1') || 'null'); + const liveIds = [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')] + .map(tab => tab.dataset.panelId); + const extraIds = liveIds.filter(id => !s.originalIds.has(id)); + return { + requested: ${count}, routeMode: ${JSON.stringify(routeMode)}, tabs: liveIds.length, liveExtraIds: extraIds.length, + savedExtraIds: Object.keys(saved?.panels ?? {}).filter(id => !s.originalIds.has(id)).length, + dispatchMs: Math.round(dispatchMs), + maxDelayMs: Math.round(Math.max(0, ...s.delays)), + maxLongTaskMs: Math.round(Math.max(0, ...s.longTasks)), + }; + })()`, 50_000); + const list = await targets(); + stage.xTargets = list.filter(item => item.type === 'page' && item.url.startsWith(`${siteOrigin}/`)).length; + stage.processes = processDelta(beforeProcesses, await processSnapshot()); + console.log(JSON.stringify(stage)); + if (stage.tabs !== original.initialCount + count || stage.liveExtraIds !== count) { + throw new Error('New live tab count or panel ID count did not reach target'); + } + previous = count; + if (stage.maxDelayMs > 1500 || (stage.processes?.totalMemoryMB ?? 0) > memoryLimitMB) { + stopReason = stage.maxDelayMs > 1500 ? 'shell timer lag exceeded 1.5 s' : `process working sets exceeded ${memoryLimitMB} MB`; + break; + } + } + if (stopReason) console.log(JSON.stringify({ stoppedAt: previous, reason: stopReason })); + completed = previous === stages.at(-1); + if (!completed) console.error(`Ramp incomplete: reached ${previous} of ${stages.at(-1)} requested site tabs`); +} finally { + try { + const cleaned = await evaluate(`(async () => { + const s = window.__webStress; + if (!s) return { error: 'probe missing' }; + clearInterval(s.interval); + s.observer.disconnect(); + await new Promise(resolve => setTimeout(resolve, 600)); + const panelIds = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')] + .map(tab => tab.dataset.panelId); + const extras = panelIds().filter(id => !s.originalIds.has(id)); + for (const id of extras) { + // Explicit missing IDs are ignored. Confirm each live ID before sending, then wait for + // that exact panel to disappear before closing the next one. + if (!panelIds().includes(id)) continue; + await window.__TAURI__.event.emit('tab-shortcut', { id, shortcut: 'close-tab' }); + const deadline = performance.now() + 3000; + while (panelIds().includes(id) && performance.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 50)); + } + if (panelIds().includes(id)) throw new Error('Panel close did not persist: ' + id); + } + await new Promise(resolve => setTimeout(resolve, 500)); + const remainingIds = panelIds(); + if (s.layout === null) localStorage.removeItem('bt.shell.layout.v1'); + else localStorage.setItem('bt.shell.layout.v1', s.layout); + return { extraTabs: extras.length, remainingTabs: remainingIds.length, + expectedTabs: s.initialCount, + originalIdsRestored: remainingIds.length === s.originalIds.size && remainingIds.every(id => s.originalIds.has(id)), + layoutRestored: localStorage.getItem('bt.shell.layout.v1') === s.layout }; + })()`, 90_000); + console.log(JSON.stringify({ cleanup: cleaned })); + if (cleaned.remainingTabs !== cleaned.expectedTabs || !cleaned.originalIdsRestored || !cleaned.layoutRestored) { + completed = false; + } else { + await unlink(backup); + } + } catch (error) { + completed = false; + console.error(`Cleanup failed: ${error.message}; recovery layout is at ${backup}`); + } + socket.close(); + if (!completed) process.exitCode = 1; +} diff --git a/dev-tools/perf-probe.mjs b/dev-tools/perf-probe.mjs new file mode 100644 index 0000000..22cd9e9 --- /dev/null +++ b/dev-tools/perf-probe.mjs @@ -0,0 +1,189 @@ +// Performance probe for what a wayBetter app injects into its site's tabs. Loads the app's +// document-start scripts (the tab bridge, its observer, its page runtime) as init scripts, like the +// native tab webview does, into headless Chromium and measures: script evaluation time, fetch/XHR +// wrapper layers and their synchronous overhead, Response clones and large JSON.parse calls made by +// the scripts, MutationObserver callbacks / rAF / timer work attributed to them, and main-thread +// long tasks. The app supplies the scripts and its scenarios (fixtures that intercept every request +// locally, or a live page); see wayBetter for X's scripts/perf-probe.mjs. +// +// import { chromium } from 'playwright'; +// import { runPerfProbe } from '/dev-tools/perf-probe.mjs'; +// const results = await runPerfProbe({ chromium, scripts: [{ name: 'runtime', code }], seconds: 8, runs: 3, +// nativeReplies: { some_command: [] }, +// scenarios: [{ name: 'fixture /home', url: 'https://site.test/home', route: async context => { … } }] }); +// +// Numbers are headless Chromium, not WebView2; compare runs on the same machine only. PROFILE=1 +// adds the scripts' self time per function. + +// ------------------------------------------------------------------------------------------ probe +function prelude(names, replies) { + // Work is "ours" when one of the probed scripts is on the stack (they are evaluated as bt-.js). + const pattern = new RegExp('bt-(?:' + names.join('|') + ')\\.js'); + const ours = () => pattern.test(new Error().stack || ''); + const P = window.__probe = { + evals: [], fetchSets: 0, xhrOpenSets: 0, xhrSendSets: 0, fetchCalls: 0, fetchOverheadMs: 0, xhrCalls: 0, + clones: 0, cloneReads: 0, bigParses: 0, bigParseMs: 0, bigParseBytes: 0, + mo: { ours: 0, oursMs: 0, oursObservers: 0, page: 0 }, raf: { ours: 0, oursMs: 0 }, timers: { ours: 0, oursMs: 0, intervals: 0 }, + longtasks: [], outerStart: 0, + }; + const nativeFetch = window.fetch; + let current = function probeInner(...a) { + if (P.outerStart) { P.fetchOverheadMs += performance.now() - P.outerStart; P.outerStart = 0; } + return Reflect.apply(nativeFetch, this, a); + }; + Object.defineProperty(window, 'fetch', { + configurable: true, get: () => current, + set: value => { if (ours()) P.fetchSets++; current = value; }, + }); + const xproto = XMLHttpRequest.prototype; + for (const [key, counter] of [['open', 'xhrOpenSets'], ['send', 'xhrSendSets']]) { + let fn = xproto[key]; + Object.defineProperty(xproto, key, { configurable: true, get: () => fn, set: v => { if (ours()) P[counter]++; fn = v; } }); + } + const clone = Response.prototype.clone; + const cloned = new WeakSet(); + Response.prototype.clone = function () { P.clones++; const c = clone.call(this); cloned.add(c); return c; }; + for (const reader of ['text', 'json', 'arrayBuffer']) { + const orig = Response.prototype[reader]; + Response.prototype[reader] = function () { if (cloned.has(this)) P.cloneReads++; return orig.call(this); }; + } + const parse = JSON.parse; + JSON.parse = function (text, reviver) { + if (typeof text === 'string' && text.length > 20000 && ours()) { + const t = performance.now(); + try { return parse.call(this, text, reviver); } finally { P.bigParses++; P.bigParseMs += performance.now() - t; P.bigParseBytes += text.length; } + } + return parse.call(this, text, reviver); + }; + const MO = window.MutationObserver; + window.MutationObserver = class extends MO { + constructor(cb) { + const mine = ours(); + super((records, obs) => { + if (!mine) { P.mo.page++; return cb(records, obs); } + const t = performance.now(); + try { return cb(records, obs); } finally { P.mo.ours++; P.mo.oursMs += performance.now() - t; } + }); + if (mine) P.mo.oursObservers++; + } + }; + const raf = window.requestAnimationFrame.bind(window); + window.requestAnimationFrame = cb => { + if (!ours()) return raf(cb); + return raf(ts => { const t = performance.now(); try { cb(ts); } finally { P.raf.ours++; P.raf.oursMs += performance.now() - t; } }); + }; + for (const name of ['setTimeout', 'setInterval']) { + const orig = window[name].bind(window); + window[name] = (cb, ms, ...rest) => { + if (typeof cb !== 'function' || !ours()) return orig(cb, ms, ...rest); + if (name === 'setInterval') P.timers.intervals++; + return orig((...a) => { const t = performance.now(); try { cb(...a); } finally { P.timers.ours++; P.timers.oursMs += performance.now() - t; } }, ms, ...rest); + }; + } + try { + new PerformanceObserver(list => { for (const e of list.getEntries()) P.longtasks.push(e.duration); }) + .observe({ type: 'longtask', buffered: true }); + } catch { /* unsupported */ } + // What the native app provides to site tabs: every command answers null unless `replies` names it. + const invoke = (cmd) => Promise.resolve(cmd in replies ? replies[cmd] : null); + window.__TAURI_INTERNALS__ = { invoke }; + window.__TAURI__ = { core: { invoke } }; +} +function postlude() { + const P = window.__probe; + const inner = window.fetch; + // The outermost layer: the site's own calls start here. + const outer = function probeOuter(...a) { P.fetchCalls++; P.outerStart = performance.now(); return Reflect.apply(inner, this, a); }; + const set = Object.getOwnPropertyDescriptor(window, 'fetch').set; + Object.defineProperty(window, 'fetch', { configurable: true, get: () => outer, set }); + const open = XMLHttpRequest.prototype.open; + XMLHttpRequest.prototype.open = function (...a) { P.xhrCalls++; return open.apply(this, a); }; +} +const wrap = ({ name, code }) => + `window.__probe.evals.push(['${name}', performance.now()]);\n${code}\n;window.__probe.evals.push(['${name}:end', performance.now()]);\n//# sourceURL=bt-${name}.js`; + +async function run(browser, options, { name, url, route, scroll }) { + const { scripts, seconds, nativeReplies = {} } = options; + const userAgent = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${browser.version().split('.')[0]}.0.0.0 Safari/537.36`; + const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, userAgent }); + if (route) await route(context); + await context.addInitScript({ content: `(${prelude})(${JSON.stringify(scripts.map(script => script.name))}, ${JSON.stringify(nativeReplies)});\n//# sourceURL=bt-probe-prelude.js` }); + for (const script of scripts) await context.addInitScript({ content: wrap(script) }); + await context.addInitScript({ content: `(${postlude})();\n//# sourceURL=bt-probe-postlude.js` }); + const page = await context.newPage(); + const cdp = await context.newCDPSession(page); + await cdp.send('Performance.enable'); + if (process.env.PROFILE) { await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 50 }); await cdp.send('Profiler.start'); } + const started = Date.now(); + await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 }); + const deadline = started + seconds * 1000; + while (Date.now() < deadline) { + if (scroll) await page.mouse.wheel(0, 700).catch(() => {}); + await page.waitForTimeout(500); + } + const result = await page.evaluate(() => { + const P = window.__probe; + const nav = performance.getEntriesByType('navigation')[0]; + const paint = Object.fromEntries(performance.getEntriesByType('paint').map(e => [e.name, e.startTime])); + const evals = {}; + for (let i = 0; i < P.evals.length; i += 2) evals[P.evals[i][0]] = +(P.evals[i + 1][1] - P.evals[i][1]).toFixed(2); + return { + evalMs: evals, fetchWrapperLayers: P.fetchSets, xhrOpenLayers: P.xhrOpenSets, xhrSendLayers: P.xhrSendSets, + fetchCalls: P.fetchCalls, fetchOverheadMsTotal: +P.fetchOverheadMs.toFixed(2), xhrCalls: P.xhrCalls, + responseClones: P.clones, cloneReads: P.cloneReads, bigJsonParses: P.bigParses, bigJsonParseMs: +P.bigParseMs.toFixed(1), + bigJsonParseMB: +(P.bigParseBytes / 1e6).toFixed(1), + observers: P.mo.oursObservers, observerCallbacks: P.mo.ours, observerMs: +P.mo.oursMs.toFixed(1), pageObserverCallbacks: P.mo.page, + rafCallbacks: P.raf.ours, rafMs: +P.raf.oursMs.toFixed(1), timerCallbacks: P.timers.ours, timerMs: +P.timers.oursMs.toFixed(1), intervals: P.timers.intervals, + longTasks: P.longtasks.length, longTaskMs: Math.round(P.longtasks.reduce((a, b) => a + b, 0)), + domContentLoadedMs: nav ? Math.round(nav.domContentLoadedEventEnd) : null, fcpMs: paint['first-contentful-paint'] != null ? Math.round(paint['first-contentful-paint']) : null, + }; + }); + const secs = (Date.now() - started) / 1000; + if (process.env.PROFILE) { + const { profile } = await cdp.send('Profiler.stop'); + const dt = new Map(); const byId = new Map(profile.nodes.map(n => [n.id, n])); + const counts = new Map(); profile.samples.forEach((id, i) => counts.set(id, (counts.get(id) ?? 0) + (profile.timeDeltas[i] ?? 0))); + for (const [id, us] of counts) { const n = byId.get(id); const f = n.callFrame; if (!/bt-/.test(f.url)) continue; const k = f.url.replace(/.*bt-/, '') + ':' + (f.functionName || '(anon)') + ':' + f.lineNumber; dt.set(k, (dt.get(k) ?? 0) + us / 1000); } + result.selfMs = Object.fromEntries([...dt].sort((a, b) => b[1] - a[1]).slice(0, 25).map(([k, v]) => [k, +v.toFixed(1)])); + } + // Whole-page main-thread totals (the site or fixture + ours), from Chromium's own counters. + const metrics = Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(m => [m.name, m.value])); + result.pageScriptMs = Math.round(metrics.ScriptDuration * 1000); + result.pageTaskMs = Math.round(metrics.TaskDuration * 1000); + result.pageLayoutMs = Math.round(metrics.LayoutDuration * 1000); + result.pageStyleMs = Math.round(metrics.RecalcStyleDuration * 1000); + result.layoutCount = metrics.LayoutCount; + result.styleRecalcCount = metrics.RecalcStyleCount; + result.observerCallbacksPerSec = +(result.observerCallbacks / secs).toFixed(1); + result.ourMainThreadMsPerSec = +((result.observerMs + result.rafMs + result.timerMs + result.fetchOverheadMsTotal + result.bigJsonParseMs) / secs).toFixed(2); + await context.close(); + return { scenario: name, ...result }; +} + +/** + * Runs every scenario `runs` times and returns the median of each numeric field per scenario. + * `scripts`: `{ name, code }` in injection order (none: the page alone, for a baseline). + * `scenarios`: `{ name, url, route?(context), scroll? }`. + */ +export async function runPerfProbe(options) { + const { chromium, scenarios, runs = 3 } = options; + const settings = { scripts: options.scripts ?? [], seconds: options.seconds ?? 8, nativeReplies: options.nativeReplies ?? {} }; + const browser = await chromium.launch({ headless: true }); + const results = []; + try { + for (const scenario of scenarios) { + const all = []; + for (let i = 0; i < runs; i++) all.push(await run(browser, settings, scenario)); + const out = { ...all[0] }; + for (const [key, value] of Object.entries(out)) { + if (typeof value !== 'number') continue; + const sorted = all.map(result => result[key]).sort((a, b) => a - b); + out[key] = sorted[Math.floor(sorted.length / 2)]; + } + results.push(out); + } + } finally { + await browser.close(); + } + return results; +} diff --git a/dev-tools/resize-perf.mjs b/dev-tools/resize-perf.mjs new file mode 100644 index 0000000..6df515a --- /dev/null +++ b/dev-tools/resize-perf.mjs @@ -0,0 +1,266 @@ +// Layout/theme performance probe for a running wayBetter app (release build started with +// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=). Plain CDP. Site pages are +// only read and reloaded, never clicked. Shell input is synthesized with CDP (no OS input, no focus +// change). +// +// SITE_ORIGIN=https://x.com node dev-tools/resize-perf.mjs +// theme reload the first site tab 3x: first paint vs. theme applied, unthemed frames +// (needs THEME_GET and THEME_SET: the app's theme commands; THEME_PRESET= measures +// with that theme and gives the owner's back) +// drag drag the first split divider for 2 s: shell frames, tabs_sync calls, native lag +// switch click between two tabs of one group 10x: click -> tab visible latency +// window (driven by window-resize.ps1 in parallel) shell resize -> native resize lag +// +// Lag is measured across processes with epoch timestamps (performance.timeOrigin + now) taken in +// the shell (when a layout was sent) and in the site tab (its own `resize` event, i.e. when the +// native bounds reached the page). SKIP_PATH=/compose leaves pages under that path out of `theme`. +const [port = '9333', ...cases] = process.argv.slice(2); +const origin = process.env.SITE_ORIGIN; +if (!origin) throw new Error('SITE_ORIGIN is required (the site\'s origin, e.g. https://x.com)'); +const skipPath = process.env.SKIP_PATH ?? ''; +const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); + +async function targets() { return (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); } +function connect(target) { + const ws = new WebSocket(target.webSocketDebuggerUrl); + let id = 0; + const pending = new Map(); + ws.onmessage = event => { const msg = JSON.parse(event.data); if (msg.id) { pending.get(msg.id)?.(msg); pending.delete(msg.id); } }; + const ready = new Promise(resolve => { ws.onopen = resolve; }); + const send = async (method, params = {}) => { await ready; return new Promise(resolve => { const n = ++id; pending.set(n, resolve); ws.send(JSON.stringify({ id: n, method, params })); }); }; + // A frozen page (a parked, hidden tab) never answers: give up after 5 s. + const evaluate = async expression => { + const result = await Promise.race([ + send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }), + wait(5000).then(() => { throw new Error(`${target.url}: no answer`); }), + ]); + if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails).slice(0, 400)); + return result.result?.result?.value; + }; + return { send, evaluate, close: () => ws.close(), url: target.url, id: target.id }; +} +const pct = (values, p) => { if (!values.length) return null; const s = [...values].sort((a, b) => a - b); return +s[Math.min(s.length - 1, Math.floor(p * s.length))].toFixed(1); }; +const stats = values => ({ n: values.length, p50: pct(values, 0.5), p95: pct(values, 0.95), max: values.length ? +Math.max(...values).toFixed(1) : null }); + +const list = await targets(); +const shell = connect(list.find(t => t.type === 'page' && t.url.startsWith('http://tauri.localhost'))); +const xTargets = list.filter(t => t.type === 'page' && t.url.startsWith(`${origin}/`)); +const xs = []; +for (const x of xTargets.map(connect)) { + try { await x.evaluate('1'); xs.push(x); } catch { x.close(); } +} +const results = {}; + +/** Shell recorder: frame times and every tabs_sync (send epoch, round trip, rects). */ +const SHELL_PROBE = `(() => { + if (window.__perf) return; + const P = window.__perf = { frames: [], syncs: [], on: false }; + const now = () => performance.timeOrigin + performance.now(); + const loop = t => { if (P.on) P.frames.push(t); requestAnimationFrame(loop); }; + requestAnimationFrame(loop); + // __TAURI_INTERNALS__.invoke is read-only; its IPC goes through fetch (http://ipc.localhost/). + const original = window.fetch.bind(window); + window.fetch = (input, init) => { + const url = String(input && input.url || input); + if (!P.on || !url.includes('/tabs_sync')) return original(input, init); + let items = []; + try { items = JSON.parse(init.body).items; } catch {} + const entry = { at: now(), items: items.map(i => [i.id, i.x, i.y, i.width, i.height, i.visible]) }; + P.syncs.push(entry); + return original(input, init).finally(() => { entry.rtt = now() - entry.at; }); + }; +})()`; +/** Site tab recorder: its own resize and visibility events, epoch timestamps. */ +const X_PROBE = `(() => { + if (window.__perf) return; + const P = window.__perf = { resizes: [], vis: [] }; + const now = () => performance.timeOrigin + performance.now(); + addEventListener('resize', () => P.resizes.push([now(), innerWidth, innerHeight])); + document.addEventListener('visibilitychange', () => P.vis.push([now(), document.visibilityState])); +})()`; + +async function arm() { + await shell.evaluate(SHELL_PROBE); + for (const x of xs) await x.evaluate(X_PROBE); + await shell.evaluate('(__perf.frames = [], __perf.syncs = [], __perf.on = true)'); + for (const x of xs) await x.evaluate('(__perf.resizes = [], __perf.vis = [])'); +} +async function collect() { + const shellData = await shell.evaluate('(__perf.on = false, { frames: __perf.frames, syncs: __perf.syncs })'); + const xData = []; + for (const x of xs) xData.push({ id: await x.evaluate('(window.__wbTabId ?? null)'), ...(await x.evaluate('({ resizes: __perf.resizes, vis: __perf.vis, w: innerWidth, h: innerHeight })')) }); + return { shellData, xData }; +} +/** For every site tab resize: the latest earlier sync that carried that width for some tab = its cause. */ +function lagOf(shellData, xData) { + const lags = []; + let unmatched = 0; + for (const x of xData) { + for (const [at, w, h] of x.resizes) { + const cause = [...shellData.syncs].reverse().find(s => s.at <= at && s.items.some(i => Math.abs(i[3] - w) <= 1)); + if (cause) lags.push(at - cause.at); else unmatched++; + } + } + return { lag: stats(lags), unmatched }; +} +const frameStats = frames => stats(frames.slice(1).map((t, i) => t - frames[i])); + +if (cases.includes('theme')) { + // A visible site page (a hidden one gets no animation frames to sample). + let x = null; + for (const candidate of xs) if (!x && await candidate.evaluate(`document.visibilityState === 'visible' && !(${JSON.stringify(skipPath)} && location.pathname.startsWith(${JSON.stringify(skipPath)}))`)) x = candidate; + if (!x) throw new Error('no visible site tab'); + const themeGet = process.env.THEME_GET; + const themeSet = process.env.THEME_SET; + if (!themeGet || !themeSet) throw new Error('the theme case needs THEME_GET and THEME_SET (the app\'s theme commands)'); + results.themeTarget = x.url; + // THEME_PRESET=nord: measure with that theme, then give the owner's theme back. + const invoke = (cmd, args) => shell.evaluate(`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(cmd)}, ${JSON.stringify(args)})`); + const original = await invoke(themeGet, {}); + if (process.env.THEME_PRESET) { await invoke(themeSet, { theme: { preset: process.env.THEME_PRESET } }); await wait(1500); } + await x.send('Page.enable'); + // Before every other document script: record paints, theme style arrival and each frame's body color. + const probe = `(() => { + const t0 = performance.now(); + const P = window.__themeProbe = { style: null, vars: null, frames: [], dcl: null }; + const seen = () => { + const s = document.getElementById('bt-theme'); + if (P.style === null && s && s.textContent) P.style = performance.now(); + const v = document.getElementById('wb-theme-vars') || document.getElementById('bt-theme-snapshot'); + if (P.vars === null && v) P.vars = performance.now(); + }; + new MutationObserver(seen).observe(document, { childList: true, subtree: true, characterData: true }); + document.addEventListener('DOMContentLoaded', () => { P.dcl = performance.now(); }); + const frame = t => { + seen(); + // The color the page shows: 's (themes paint the canvas there, stays transparent), + // else 's (X's own inline color before a theme). + const shown = () => { const h = document.documentElement && getComputedStyle(document.documentElement).backgroundColor; const b = document.body && getComputedStyle(document.body).backgroundColor; return h && h !== 'rgba(0, 0, 0, 0)' ? h : b || h || ''; }; + const bg = shown(); + P.frames.push([Math.round(t), bg, !!(document.getElementById('bt-theme')?.textContent), !!document.body]); + if (t - t0 < 6000) requestAnimationFrame(frame); + }; + requestAnimationFrame(frame); + })()`; + const { result } = await x.send('Page.addScriptToEvaluateOnNewDocument', { source: probe }); + const runs = []; + for (let run = 0; run < 3; run++) { + await x.send('Page.reload', {}); + await wait(7000); + const data = await x.evaluate(`(() => { + const P = window.__themeProbe; + const paint = Object.fromEntries(performance.getEntriesByType('paint').map(e => [e.name, Math.round(e.startTime)])); + const h = getComputedStyle(document.documentElement).backgroundColor; + const themedBg = h !== 'rgba(0, 0, 0, 0)' ? h : getComputedStyle(document.body).backgroundColor; + // Frames once there is a body to paint (paint timing entries are not exposed in every run). + const painted = P.frames.filter(f => f[3]); + const unthemed = painted.filter(f => f[1] !== themedBg); + return { paint, firstBody: painted[0]?.[0] ?? null, firstThemedFrame: P.frames.find(f => f[3] && f[1] === themedBg)?.[0] ?? null, style: P.style && Math.round(P.style), vars: P.vars && Math.round(P.vars), dcl: P.dcl && Math.round(P.dcl), themedBg, + framesAfterFirstPaint: painted.length, unthemedFrames: unthemed.length, lastUnthemedAt: unthemed.length ? unthemed[unthemed.length - 1][0] : null, + firstBg: painted[0]?.[1] ?? null }; + })()`); + runs.push(data); + } + await x.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: result.identifier }); + if (process.env.THEME_PRESET) await invoke(themeSet, { theme: original }); + results.theme = runs; +} + +if (cases.includes('drag')) { + await arm(); + const sash = await shell.evaluate(`(() => { const s = document.querySelector('.dv-split-view-container.dv-horizontal > .dv-sash-container > .dv-sash'); const b = s.getBoundingClientRect(); return [b.left + b.width / 2, b.top + b.height / 2]; })()`); + const [sx, sy] = sash; + const mouse = (type, x, buttons = 1) => shell.send('Input.dispatchMouseEvent', { type, x, y: sy, button: 'left', buttons, clickCount: 1 }); + await mouse('mousePressed', sx); + const start = Date.now(); + let steps = 0; + while (Date.now() - start < 2000) { + const phase = (Date.now() - start) / 2000; + await mouse('mouseMoved', sx - 200 * Math.sin(phase * Math.PI * 2)); + steps++; + await wait(8); + } + await mouse('mouseMoved', sx); + const release = await shell.evaluate('performance.timeOrigin + performance.now()'); + await mouse('mouseReleased', sx, 0); + await wait(1000); + const { shellData, xData } = await collect(); + const lastX = Math.max(0, ...xData.flatMap(x => x.resizes.map(r => r[0]))); + results.drag = { + moves: steps, + shellFrames: frameStats(shellData.frames.filter(t => true)), + syncs: shellData.syncs.length, + syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)), + xResizes: xData.map(x => x.resizes.length), + ...lagOf(shellData, xData), + settleAfterRelease: +(lastX - release).toFixed(1), + }; +} + +if (cases.includes('window')) { + // window-resize.ps1 resizes the (non-foreground) window for ~2 s while this records. + await arm(); + await shell.evaluate(`(() => { __perf.win = []; addEventListener('resize', () => __perf.win.push([performance.timeOrigin + performance.now(), innerWidth])); })()`); + await wait(Number(process.env.WINDOW_MS ?? 3500)); + const { shellData, xData } = await collect(); + const win = await shell.evaluate('__perf.win'); + const shellLag = []; + // Native first (the site tab resized before the shell even saw the window change) counts as <= 0. + for (const x of xData) for (const [at] of x.resizes) { + const cause = [...win].reverse().find(w => w[0] <= at); + const after = win.find(w => w[0] > at); + if (cause) shellLag.push(at - cause[0]); else if (after) shellLag.push(-(after[0] - at)); + } + results.window = { + shellResizes: win.length, + shellFrames: frameStats(shellData.frames), + syncs: shellData.syncs.length, + syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)), + xResizes: xData.map(x => x.resizes.length), + xAfterShellResize: stats(shellLag), + // With window-resize.ps1's printed restore time: how long the site tab keeps resizing after the window stopped. + lastXResize: Math.round(Math.max(0, ...xData.flatMap(x => x.resizes.map(r => r[0])))), + lastShellResize: Math.round(Math.max(0, ...win.map(w => w[0]))), + ...lagOf(shellData, xData), + }; +} + +if (cases.includes('switch')) { + await arm(); + // Two web tabs in one group: click the inactive one, wait, click back. Latency = click -> the + // clicked tab's page becomes visible. + const group = await shell.evaluate(`(() => { + const g = [...document.querySelectorAll('.dv-groupview')].map(g => g.closest('.dv-view')).find(v => v && v.querySelectorAll('.dv-tab').length >= 2); + return !!g; + })()`); + const latencies = []; + if (group) { + for (let i = 0; i < 20; i++) { + const clicked = await shell.evaluate(`(() => { + const tabs = [...document.querySelectorAll('.dv-tab')]; + const next = tabs.find(t => t.classList.contains('dv-inactive-tab')); + const at = performance.timeOrigin + performance.now(); + next.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 })); + next.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 })); + next.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, button: 0 })); + next.click(); + return at; + })()`); + await wait(600); + const shown = []; + for (const x of xs) { + const vis = await x.evaluate('__perf.vis'); + const hit = vis.find(v => v[1] === 'visible' && v[0] >= clicked); + if (hit) shown.push(hit[0] - clicked); + await x.evaluate('(__perf.vis = [])'); + } + if (shown.length) latencies.push(Math.min(...shown)); + } + } + const { shellData } = await collect(); + results.switch = { group, latency: stats(latencies), syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)) }; +} + +console.log(JSON.stringify(results, null, 1)); +shell.close(); +for (const x of xs) x.close(); diff --git a/dev-tools/runtime-start-check.mjs b/dev-tools/runtime-start-check.mjs new file mode 100644 index 0000000..8db9ad2 --- /dev/null +++ b/dev-tools/runtime-start-check.mjs @@ -0,0 +1,57 @@ +// Document-start check for an app's page runtime: the built runtime injected the way the app does +// it, as an init script that runs before the parser has created , into static fixtures of the +// site. Every feature flag is switched on, then off, then back to its default; any console error, +// any message with the app's `[label]` prefix or any page error fails the check. Not a live test. +// +// import { chromium } from 'playwright'; +// import { runtimeStartCheck } from '/dev-tools/runtime-start-check.mjs'; +// const { problems, checked } = await runtimeStartCheck({ +// chromium, runtime: code, global: 'MyApp', label: 'wayBetter for Site', origin: 'https://site.test', +// queued: 'window.__btPane={redundantNav:true};', // what native code queues before the runtime exists +// featureDefaults: { someFlag: true }, +// pages: [{ name: 'home', path: '/home', html: '…' }], +// verify: { expression: '({ … })', check: (result, page) => 'a problem' | null }, +// }); + +/** Runs the check; resolves to `{ problems, checked }`. */ +export async function runtimeStartCheck(options) { + const { chromium, runtime, global, label, origin, pages, featureDefaults = {}, queued = '', verify } = options; + const browser = await chromium.launch(); + const context = await browser.newContext({ viewport: { width: 1100, height: 800 } }); + if (queued) await context.addInitScript({ content: queued }); + await context.addInitScript({ content: runtime }); + const problems = []; + let checked = 0; + try { + for (const item of pages) { + const page = await context.newPage(); + page.on('console', message => { if (message.type() === 'error' || message.text().includes(`[${label}]`)) problems.push(`${item.name}: ${message.text().slice(0, 240)}`); }); + page.on('pageerror', error => problems.push(`${item.name}: page error ${String(error).slice(0, 240)}`)); + await page.route(`${origin}/**`, route => route.fulfill({ contentType: 'text/html', body: item.html })); + await page.goto(`${origin}${item.path}`); + const result = await page.evaluate(async ({ name, defaults, expression }) => { + const runtime = window[name]; + if (!runtime) return { runtime: false }; + const all = value => Object.fromEntries(Object.keys(defaults).map(key => [key, value])); + runtime.features.apply(all(true)); + await new Promise(resolve => setTimeout(resolve, 200)); + runtime.features.apply(all(false)); + await new Promise(resolve => setTimeout(resolve, 100)); + runtime.features.apply(defaults); + await new Promise(resolve => setTimeout(resolve, 300)); + // The app's own expression over the page (what it expects to be there after the toggles). + return { runtime: true, details: expression ? (0, eval)(expression) : null }; + }, { name: global, defaults: featureDefaults, expression: verify?.expression ?? '' }); + if (!result.runtime) problems.push(`${item.name}: runtime did not install`); + else { + const problem = verify?.check?.(result.details, item); + if (problem) problems.push(`${item.name}: ${problem}`); + } + checked += 1; + await page.close(); + } + } finally { + await browser.close(); + } + return { problems, checked }; +} diff --git a/dev-tools/window-resize.ps1 b/dev-tools/window-resize.ps1 new file mode 100644 index 0000000..a390249 --- /dev/null +++ b/dev-tools/window-resize.ps1 @@ -0,0 +1,48 @@ +# Resizes a wayBetter app's window (never activated, never while it is the foreground window) for +# ~2 s, then puts it back: a repeatable window-resize workload for resize-perf.mjs `window`. +# powershell -ExecutionPolicy Bypass -File dev-tools/window-resize.ps1 -Process [-Ms 2000] [-Amplitude 200] +param([Parameter(Mandatory = $true)][string]$Process, [int]$Ms = 2000, [int]$Amplitude = 200) +Add-Type @" +using System; using System.Runtime.InteropServices; +public static class WinResize { + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr h); + [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h); + public delegate bool EnumProc(IntPtr h, IntPtr l); + [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc p, IntPtr l); + [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint p); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n); + // The app window itself: MainWindowHandle may be the single-instance or event-loop helper window. + public static IntPtr AppWindow(uint pid) { + IntPtr found = IntPtr.Zero; + EnumWindows((h, l) => { uint p; GetWindowThreadProcessId(h, out p); var c = new System.Text.StringBuilder(64); GetClassName(h, c, 64); + if (p == pid && c.ToString() == "Tauri Window") { found = h; return false; } return true; }, IntPtr.Zero); + return found; + } +} +"@ +$proc = Get-Process $Process -ErrorAction Stop | Select-Object -First 1 +$hwnd = [WinResize]::AppWindow([uint32]$proc.Id) +if ($hwnd -eq [IntPtr]::Zero) { 'skipped: no app window'; exit 2 } +if ([WinResize]::IsIconic($hwnd)) { 'skipped: minimized'; exit 2 } +if ([WinResize]::GetForegroundWindow() -eq $hwnd) { 'skipped: the app is the foreground window'; exit 2 } +if ([WinResize]::IsZoomed($hwnd)) { 'skipped: maximized'; exit 2 } +$r = New-Object WinResize+RECT +[void][WinResize]::GetWindowRect($hwnd, [ref]$r) +$w = $r.Right - $r.Left; $h = $r.Bottom - $r.Top +# SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER +$flags = 0x0002 -bor 0x0004 -bor 0x0010 -bor 0x0200 +$sw = [Diagnostics.Stopwatch]::StartNew() +$steps = 0 +while ($sw.ElapsedMilliseconds -lt $Ms) { + $phase = $sw.ElapsedMilliseconds / $Ms + $dw = [int]($Amplitude * [Math]::Sin($phase * [Math]::PI * 2)) + [void][WinResize]::SetWindowPos($hwnd, [IntPtr]::Zero, 0, 0, $w - [Math]::Abs($dw), $h - [int]([Math]::Abs($dw) / 2), $flags) + $steps++ + Start-Sleep -Milliseconds 8 +} +[void][WinResize]::SetWindowPos($hwnd, [IntPtr]::Zero, 0, 0, $w, $h, $flags) +"resized $steps times, restored ${w}x${h} at $([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds())" diff --git a/packages/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js index a9346b6..b1651a4 100644 --- a/packages/create-waybetter/src/app.js +++ b/packages/create-waybetter/src/app.js @@ -131,21 +131,32 @@ export function normalizeAppOptions(input) { /** 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' }; -/** 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 = { - shell: ['plugins_list', 'plugin_set_enabled', 'plugins_open_folder'], + shell: [], tab: ['tab_report'], site: ['site_ready'], }; /** - * The commands waybetter-host serves for every app (`waybetter_host::commands::SHELL` / `TAB`: - * tab layout and actions, shell raise, external links, window menu, profiles, language; tab - * shortcuts and link drags). The capability files grant them; a test keeps this list in step. + * The commands waybetter-host serves for every app (`waybetter_host::commands::SHELL` / `TAB` / `SITE`: + * tab layout and actions, the shell's focus, first paint and raise, external links, the window + * 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 = { - 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'], + site: ['open_panel'], }; const permission = command => `allow-${command.replace(/_/g, '-')}`; @@ -357,10 +368,11 @@ function siteRs(o) { function pluginsRs(o) { return lines( '//! 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, PluginStore};', + 'use waybetter_host::plugins::PluginHost;', '', 'pub static HOST: PluginHost = PluginHost {', ` runtime_global: ${rustStr(o.runtimeGlobal)},`, @@ -374,11 +386,6 @@ function pluginsRs(o) { ' bundled: &[],', '};', '', - '/// The plugin store in `dir` (the app-data `plugins` folder).', - 'pub fn store(dir: PathBuf) -> PluginStore {', - ' PluginStore::new(dir, &HOST)', - '}', - '', '#[cfg(test)]', 'mod tests {', ' use super::*;', @@ -434,83 +441,24 @@ function desktopRs(o) { '//! 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', '//! 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', - '//! the app\'s own commands. Every command re-checks its caller: the capability files are not the', - '//! boundary.', + '//! (tab layout and actions, shell raise, profiles, language, the plugins folder and custom CSS,', + '//! the page\'s feature flags, the shell\'s settings, opening the panel from a site page). This', + '//! 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 serde::{Deserialize, Serialize};', - 'use std::sync::{Mutex, MutexGuard};', - 'use tauri::{AppHandle, Manager, State, Webview};', + 'use tauri::{AppHandle, Webview};', '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::host;', - 'use waybetter_host::plugins::{PluginStore, ScriptPlugin};', 'use waybetter_host::profiles::Account;', 'use waybetter_host::tabs::TabState;', '', '/// The page runtime (src/runtime/main.ts), written by `npm run build`.', 'const RUNTIME: &str = include_str!("../runtime/runtime.js");', '', - 'struct AppState {', - ' plugins: Mutex,', - '}', - '', - 'fn store<\'a>(state: &\'a State<\'_, AppState>) -> Result, 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, 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, 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', '', @@ -572,28 +520,23 @@ function desktopRs(o) { 'struct Site;', '', 'impl SiteHooks for Site {', - ' fn init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec {', + ' fn init_scripts(&self, app: &AppHandle, _tab: &NewTab) -> Vec {', ' vec![', ' // 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).', ' 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.', ' 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) {', - ' let scripts = app', - ' .state::()', - ' .plugins', - ' .lock()', - ' .map(|store| {', - ' let mut scripts: Vec = waybetter_host::plugins::css_script(&plugins::HOST, &store.css()).into_iter().collect();', - ' scripts.extend(store.start_scripts());', - ' scripts', - ' })', - ' .unwrap_or_default();', + ' let mut scripts = vec![app::i18n_page_script(app)];', + ' scripts.extend(app::page_scripts(app).map(app::PageScripts::all).unwrap_or_default());', ' for script in scripts {', ' let _ = tab.eval(&script);', ' }', @@ -609,16 +552,10 @@ function desktopRs(o) { ' min_window_size: (720.0, 480.0),', ' // The shell frame draws the titlebar (tabs in it, caption buttons on Windows).', ' 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)', - ' .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(', ')}]);`, + ` App::new(config, Site).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`, '//! 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};', '', 'fn capabilities() -> Capabilities {', @@ -638,21 +576,31 @@ function securityRs(o) { '', '#[test]', 'fn host_commands_keep_their_callers() {', - ' capabilities().assert_host_commands();', + ' let caps = capabilities();', + ' caps.assert_host_commands();', ' 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]', 'fn app_commands_keep_their_callers() {', ' let caps = capabilities();', ' let source = include_str!("../src/desktop.rs");', - ` for command in [${quote(COMMANDS.shell)}] {`, - ' caps.assert_shell_only(command);', - ' assert_guarded(source, command, "host::shell_only(&webview)?");', - ' }', - ` for command in [${quote([...COMMANDS.tab, ...COMMANDS.site])}] {`, + ...(COMMANDS.shell.length ? [ + ` for command in [${quote(COMMANDS.shell)}] {`, + ' caps.assert_shell_only(command);', + ' assert_guarded(source, command, "host::shell_only(&webview)?");', + ' }', + ] : []), + ` for command in [${quote(COMMANDS.tab)}] {`, ' 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, "site_ready", "host::site_tab_only(&SITE, &webview)?");', ' // 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', content: cap({ 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'], local: true, 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', content: cap({ 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-*'], local: false, 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( '// The page runtime, injected into every tab and active only on the site\'s origin (top frame).', - '// It sets `window.` (and the `window.wayBetter` alias plugins use) with the', - '// plugin API; native code then evaluates the enabled `*.plugin.js` files against it.', + '// It is composed with the framework\'s helpers (waybetter/runtime/siteRuntime): the runtime', + '// object under `window.` (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 { createCorePluginApi, type CorePluginApi } from 'waybetter/runtime/pluginApi';", - "import { installAccountReport, type Invoke } from 'waybetter/runtime/accountReport';", + "import { installAccountReport } from 'waybetter/runtime/accountReport';", "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';", '', - 'type Runtime = {', - ' api: CorePluginApi;', - ' /** Running plugins by file (native start/stop scripts manage this). */', - ' plugins: Record;', - ' /** Load errors by plugin file. */', - ' errors: Record;', - '};', + '/**', + ' * PLACEHOLDER: the app\'s page tweaks. Each flag is a boolean the owner toggles in the panel', + ' * (waybetter/shell/panel `useFeatures` + `FeatureGroups`; native `features_set` delivers them); a part that', + ' * installs when its flag turns on and disposes when it turns off goes into `INSTALLERS`.', + ' */', + 'const FLAGS: Record = {};', + 'const INSTALLERS: FlagInstaller[] = [];', '', - 'type TauriInternals = { invoke(command: string, args: Record): Promise };', + '/** 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(``)}`)};`, '', 'function install(): void {', ' if (window.top !== window || !isSiteUrl(SITE, location.href)) return;', - ' const globals = window as unknown as Record;', - ' if (globals[SITE.runtimeGlobal]) return;', + ' if ((window as unknown as Record)[SITE.runtimeGlobal]) return;', ' 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 }`', ' // (a ThemeSource from waybetter/runtime/themeApi) once the app has themes.', - ' const api = createCorePluginApi(window, SITE.plugins);', - ' const runtime: Runtime = { api, plugins: {}, errors: {} };', - ' globals[SITE.runtimeGlobal] = runtime;', - ' globals.wayBetter = runtime;', - '', - ' const ipc = (globals.__TAURI_INTERNALS__ ?? null) as TauriInternals | null;', - ' const invoke: Invoke | undefined = ipc ? (command, args) => ipc.invoke(command, args) : undefined;', + ' const api = createCorePluginApi(window, SITE.plugins, { i18n: strings.source });', + ' // Each plugin gets an API view for its declared @permissions, with its own strings.', + ' const plugins = createPluginContext(api, undefined, (full, id) => ({ i18n: full.i18n.namespace(strings.pluginNamespace(id)) }));', + ' const links = SITE.links ? installLinkRouting(window, SITE.links) : undefined;', ' if (SITE.account) installAccountReport(window, SITE.account, invoke);', - ' // "same" until native code configures it: in-page clicks are left alone.', - ' if (SITE.links) installLinkRouting(window, SITE.links);', + ' 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.', + ' 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(() => {});", '}', '', @@ -905,9 +869,9 @@ function shellTs(o) { const handleChars = handle.extra.replace(/[\\\]^-]/g, ch => `\\${ch}`); return lines( '// 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', - '// palette (Ctrl+K) and the account switcher are the framework\'s; native code places each tab\'s', - '// webview over its pane (tabs_sync).', + '// app\'s panel (Panel.tsx: waybetter/shell/panel). Tabs in the titlebar, splits, the address bar,', + '// the new-tab page, the command palette (Ctrl+K) and the account switcher are the framework\'s;', + '// native code places each tab\'s webview over its pane (tabs_sync).', '', "import { createRoot } from 'react-dom/client';", "import { createI18n } from 'waybetter/i18n';", @@ -946,7 +910,12 @@ function shellTs(o) { ' },', ' palette: {', " 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,', ' // 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( - '// The app\'s own tab (Ctrl+Shift+W, the brand button, Ctrl+K "Plugins"): its settings. Here: the', - '// plugins in the plugins folder, each switched on or off live in every site tab.', + '// The app\'s own tab (Ctrl+Shift+W, the brand button, the floating button in the site\'s page,', + '// 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 function Panel(_props: { section?: { name: string; nonce: number } }) {', - ' const [plugins, setPlugins] = useState([]);', - " const [error, setError] = useState('');", - ' const { invoke } = window.__TAURI__.core;', - " const run = (promise: Promise) => promise.then(list => { if (list) setPlugins(list); setError(''); }, failure => setError(String(failure)));", - " useEffect(() => { void run(invoke('plugins_list')); }, []);", - ' return
', - '

Plugins

', - ' {error &&

{error}

}', - ' {plugins.map(plugin => )}', - " ", - '
;', - '}', + 'export const Panel = createPanel({', + " brand: { name: SITE.product, logo: './icon.png' },", + ' home: {', + ` kicker: { name: 'wayBetter', rest: ${str(` for ${o.label}`)} },`, + ` title: () => [${str(`${o.label}, `)}, 'extended', '.'],`, + ` 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.`)},`, + " actions: [{ section: 'plugins', label: () => 'Plugins' }, { section: 'settings', label: () => 'Settings' }],", + ' highlights: [', + " { section: 'plugins', title: () => 'Plugins', text: () => 'One file each, switched on and off live.' },", + " { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },", + ' ],', + ' },', + ' // Placeholder CSS in the custom CSS editor, written with this site\'s own selectors.', + ` cssExamples: { custom: ${str(`/* Example */\n${o.site.selectors.item} { outline: 1px dashed; }`)} },`, + '});', ); } @@ -1037,16 +1007,10 @@ function indexHtml(o) { /** @param {AppOptions} o */ function appCss(o) { return lines( - "/* The app's own panel. The shell frame's styles come with it (dockview and the frame's CSS,", - ' bundled into dist/shell.css); its colors are the --wb-c-* tokens (Night Ink by default). */', + "/* The app's own styles. The shell frame's and the panel's styles come with them (dockview, the", + " 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}; }`, - '.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,18 +1095,26 @@ function readme(o) { '```', 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', '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/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', '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/capabilities/ shell / tab-chrome / site-tab, keyed by webview label', 'src-tauri/tests/security.rs who may call what (waybetter_host::testkit)', 'waybetter.release.json `npm run release`: signed builds and the update manifest (PLACEHOLDER URLs)', '```', '', + 'Build with `npm run desktop:build` (or `npm run release`), not a bare `tauri build`: a Rust binary', + 'embeds the paths it was built from, and those hold your account name. `waybetter build-env` maps', + 'them to `/home`, `/src`, `/cargo` and `/rustup`; `npm run privacy:scan` and the release check the', + 'result (`waybetter privacy-scan --help`).', + '', + '```text', + '```', + '', '## Make it yours', '', `1. Open ${o.origin} in a browser's devtools and replace every PLACEHOLDER in \`src/site.ts\``, @@ -1150,7 +1122,9 @@ function readme(o) { '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,', ' 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/runtime/themeApi`, `theme.schema.json`), signed updates (`updater: true` in the', ' `AppConfig`, `plugins.updater` and `bundle.createUpdaterArtifacts` in tauri.conf.json, then', @@ -1183,11 +1157,13 @@ export function appFiles(o) { build: 'node scripts/build.mjs', typecheck: 'tsc -p tsconfig.json', tauri: 'tauri', + 'desktop:build': 'waybetter build-env -- tauri build', + 'privacy:scan': 'waybetter privacy-scan --tracked .', 'test:rust': 'cargo test --manifest-path src-tauri/Cargo.toml --no-default-features', release: 'waybetter release windows', 'release:macos': 'waybetter release macos', }, - dependencies: { dockview: '^4.0.0', react: '^19.0.0', 'react-dom': '^19.0.0', waybetter: '^0.4.0' }, + dependencies: { dockview: '^4.0.0', react: '^19.0.0', 'react-dom': '^19.0.0', waybetter: '^0.6.0' }, devDependencies: { '@tauri-apps/cli': '^2.0.0', '@types/react': '^19.0.0', '@types/react-dom': '^19.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, }; const tsconfig = { @@ -1217,9 +1193,9 @@ export function appFiles(o) { { path: 'scripts/build.mjs', content: buildMjs() }, { path: 'src/site.ts', content: siteTs(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/Panel.tsx', content: panelTsx() }, + { path: 'src/shell/Panel.tsx', content: panelTsx(o) }, { path: 'src/shell/index.html', content: indexHtml(o) }, { path: 'src/shell/app.css', content: appCss(o) }, { path: 'src/tauri.d.ts', content: tauriTypes() }, diff --git a/packages/create-waybetter/tests/create.test.mjs b/packages/create-waybetter/tests/create.test.mjs index b0fa145..0c95ad7 100644 --- a/packages/create-waybetter/tests/create.test.mjs +++ b/packages/create-waybetter/tests/create.test.mjs @@ -312,7 +312,10 @@ test('app: every site skeleton is consistent across its native and page halves', assert.deepEqual(handler, manifest); 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(); - 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'); 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\(\)/); @@ -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`); // 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, /); + // 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'); // Icons Tauri decodes at compile time. 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)); assert.deepEqual(HOST_COMMANDS.shell, list('SHELL')); assert.deepEqual(HOST_COMMANDS.tab, list('TAB')); + assert.deepEqual(HOST_COMMANDS.site, list('SITE')); }); test('app: host crate sources (submodule default, git)', async () => { diff --git a/packages/runtime/src/commandReport.ts b/packages/runtime/src/commandReport.ts new file mode 100644 index 0000000..c078a1f --- /dev/null +++ b/packages/runtime/src/commandReport.ts @@ -0,0 +1,47 @@ +// Plugin palette commands: a site tab tells the shell which commands its plugins registered, so the +// command palette can list them under each plugin's name. Only `{ id, title, keywords }` strings +// travel (capped in the registry and again natively, waybetter-host `plugins::commands`), only +// about this tab, only when the list changes (`tab_report.commands`). Running one is the shell +// asking native code to call `api.commands.run(id)` in this page; `run` never leaves it. +// +// Developer mode's start failures are reported here too: a toast in the page with file and line. + +import type { CommandInfo } from './commands.ts'; +import { devErrorLocation, formatDevError } from './devErrors.ts'; + +export type Invoke = (command: string, args: Record) => Promise; +type Commands = { list(): CommandInfo[]; onChange(callback: (list: CommandInfo[]) => void): () => void }; + +/** Reports the command list after it changes (batched, only real changes). Returns the disposer. */ +export function installCommandReport(commands: Commands, invoke: Invoke | undefined, delay = 80): () => void { + if (!invoke) return () => {}; + let last = '[]'; + let timer: ReturnType | undefined; + const send = () => { + timer = undefined; + const list = commands.list(); + const json = JSON.stringify(list); + if (json === last) return; + last = json; + invoke('tab_report', { report: { commands: list } }).catch(() => {}); + }; + const off = commands.onChange(() => { + if (timer === undefined) timer = setTimeout(send, delay); + }); + return () => { off(); if (timer !== undefined) clearTimeout(timer); }; +} + +type Toast = (message: string, options: { tone: 'danger'; duration: number }) => void; + +/** + * Developer mode (live reload): a plugin whose start failed shows `file:line — message` as a toast + * in this page. The host evaluates reloaded plugins with a `sourceURL`, so the line is the file's. + * `text` wraps the location in the app's words ("Plugin failed: {error}"). + */ +export function devErrorReporter(toast: () => Toast | undefined, text: (error: string) => string) { + return (file: unknown, error: unknown) => { + if (typeof file !== 'string') return; + const location = formatDevError(devErrorLocation(error, file)); + try { toast()?.(text(location), { tone: 'danger', duration: 12000 }); } catch { /* the page keeps working */ } + }; +} diff --git a/packages/runtime/src/pageStrings.ts b/packages/runtime/src/pageStrings.ts new file mode 100644 index 0000000..6f0bcc7 --- /dev/null +++ b/packages/runtime/src/pageStrings.ts @@ -0,0 +1,100 @@ +// The page runtime's language. Native code hands site tabs the owner's language and exactly the +// strings the page needs (the app's own page strings, the plugin UI kit's `kit.*` and the bundled +// plugins' `plugin.*`; waybetter-host `i18n::page_script`) as `.i18n.set({ locale, dir, +// messages })`, queued in `__wbI18n` until the runtime exists. The messages arrive already resolved +// along the language's fallback chain by the shell; English is built into the runtime (the build +// keeps only those prefixes of the app's catalog). A switch applies live: `onChange` listeners +// re-render. Everything delivered is data: checked, bounded and inserted as text. + +import { formatMessage, normalizeLocale, type Params } from './i18n.ts'; +import { pluginNamespace, type I18nSource } from './pluginI18n.ts'; + +export type PageStringsOptions = { + /** English for every string the page shows (the app's page strings and the framework's kit words). */ + english: Readonly>; + /** Key prefixes a delivery may carry (`['x.', 'kit.', 'plugin.']`); other keys are dropped. */ + prefixes: readonly string[]; + /** Console label (the app's name). */ + label: string; + /** + * The file-name prefix the app installs its bundled plugins with (`bt-` for `bt-.plugin.js`) + * when their strings are keyed by the source name (`plugin..*`). + */ + bundledPrefix?: string; +}; + +export type PageStrings = { + /** The active language's message for `key`, else English. */ + message(key: string): string | undefined; + /** A runtime string: `t('x.media.download')`. Placeholder values are inserted as text. */ + t(key: string, params?: Params): string; + locale(): string; + /** Native code delivers `{ locale, dir, messages }`; anything malformed is ignored (English stays). */ + set(value: unknown): void; + onChange(listener: () => void): () => void; + /** The plugin API's view of the language (pluginI18n.ts): `api.i18n` and the UI kit's words. */ + source: I18nSource; + /** A plugin file's catalog namespace (`plugin..*`). */ + pluginNamespace(id: string): string; +}; + +/** A delivery holds at most this many messages, each at most this long. */ +export const PAGE_STRING_LIMITS = Object.freeze({ keys: 4000, value: 2000 }); + +export function createPageStrings(options: PageStringsOptions): PageStrings { + const { english, prefixes, label, bundledPrefix } = options; + let delivered: Record = {}; + let active = 'en'; + const listeners = new Set<() => void>(); + + const message = (key: string) => delivered[key] ?? english[key]; + const t = (key: string, params?: Params) => { + const text = message(key); + return text === undefined ? key : formatMessage(text, params ?? {}, active); + }; + + function set(value: unknown) { + if (!value || typeof value !== 'object') return; + const input = value as { locale?: unknown; messages?: unknown }; + const tag = normalizeLocale(input.locale); + if (!tag || !input.messages || typeof input.messages !== 'object') return; + const next: Record = {}; + let count = 0; + for (const [key, text] of Object.entries(input.messages as Record)) { + if (count >= PAGE_STRING_LIMITS.keys) break; + if (typeof text !== 'string' || text.length > PAGE_STRING_LIMITS.value || !prefixes.some(prefix => key.startsWith(prefix))) continue; + next[key] = text; + count += 1; + } + const changed = tag !== active || JSON.stringify(next) !== JSON.stringify(delivered); + delivered = next; + active = tag; + if (!changed) return; + for (const listener of [...listeners]) { + try { listener(); } catch (error) { console.error(`[${label}] language listener failed`, error); } + } + } + + const onChange = (listener: () => void) => { + listeners.add(listener); + return () => { listeners.delete(listener); }; + }; + + return { + message, + t, + locale: () => active, + set, + onChange, + source: { locale: () => active, message, onChange }, + // Bundled plugins are installed as `.plugin.js`, but their strings are keyed + // by their source name: without this, every bundled plugin would stay English. + pluginNamespace(id) { + const namespace = pluginNamespace(id); + if (!bundledPrefix || !namespace.startsWith(bundledPrefix)) return namespace; + const bare = namespace.slice(bundledPrefix.length); + const prefix = `plugin.${bare}.`; + return Object.keys(english).some(key => key.startsWith(prefix)) ? bare : namespace; + }, + }; +} diff --git a/packages/runtime/src/panelButton.ts b/packages/runtime/src/panelButton.ts new file mode 100644 index 0000000..6485357 --- /dev/null +++ b/packages/runtime/src/panelButton.ts @@ -0,0 +1,97 @@ +// The way from a site page into the app's panel. The site adapter puts an entry into the site's own +// navigation when it has one (`mountNav`: X clones its "More" item); where the page draws no +// navigation (a full-pane viewer opened by URL, signed-out pages, a mobile layout) a small floating +// button stands in. The button must never cover the site's own UI: it hides while the site layers +// something over the page and sits above the site's bottom bar. Both are re-checked on every DOM +// change through the shared DOM hub. + +import { watchDom, type DomWindow } from './domHub.ts'; + +/** Gap between the button and the pane edge or the site's bottom bar. */ +export const BUTTON_GAP = 16; + +/** + * Pure: the button's `bottom` offset. `barTop` is the top edge of the site's bottom bar, null when + * it has none; a zero-height or implausibly tall bar (a desktop layout may keep an empty one at the + * bottom edge) adds nothing. + */ +export function buttonBottom(barTop: number | null, viewportHeight: number, gap = BUTTON_GAP): number { + if (barTop === null) return gap; + const bar = viewportHeight - barTop; + return bar > 0 && bar < viewportHeight / 3 ? Math.round(bar) + gap : gap; +} + +export type PanelButtonSite = { + /** The floating button's DOM id. */ + id: string; + /** The app's logo (an image URL, usually a data URI: the site's CSP may block others). */ + logo: string; + /** The button's tooltip and accessible name, in the owner's language. */ + title(): string; + /** Puts the entry into the site's own navigation (re-attaching it when the site re-renders); true while it is there. */ + mountNav?(open: () => void): boolean; + /** Pages where the button stays hidden (a full-pane photo or video viewer whose actions sit at the bottom). */ + hiddenOn?(pathname: string): boolean; + /** The site is showing a modal sheet or a dialog layer: the button hides under it. */ + overlaySelector?: string; + /** The site's bottom bar (a mobile layout): the button sits above it. */ + bottomBarSelector?: string; +}; + +/** Pure: whether the button stays hidden on this route / with a site overlay open. */ +export function buttonHidden(site: Pick, pathname: string, overlayOpen: boolean): boolean { + return overlayOpen || !!site.hiddenOn?.(pathname); +} + +/** + * Keeps the panel entry on the page: the site's navigation item when `mountNav` places one, else + * the floating button. `open` opens the panel (the runtime's `open()`). + */ +export function installPanelButton(win: Window & typeof globalThis, site: PanelButtonSite, open: () => void): { sync(): void } { + const doc = win.document; + + const create = (): HTMLButtonElement => { + const button = doc.createElement('button'); + button.id = site.id; + button.type = 'button'; + button.title = site.title(); + button.setAttribute('aria-label', button.title); + const img = doc.createElement('img'); + img.src = site.logo; + img.alt = ''; + Object.assign(img.style, { width: '100%', height: '100%', borderRadius: '22%', display: 'block' }); + button.appendChild(img); + Object.assign(button.style, { + position: 'fixed', left: '16px', bottom: '16px', zIndex: '2147483646', width: '40px', height: '40px', + padding: '0', border: '0', background: 'transparent', cursor: 'pointer', boxShadow: '0 4px 14px rgba(0,0,0,.35)', borderRadius: '22%', + }); + button.addEventListener('click', () => open()); + return button; + }; + + const syncButton = (navMounted: boolean) => { + const existing = doc.getElementById(site.id); + if (navMounted) { existing?.remove(); return; } + const button = existing ?? create(); + const overlay = site.overlaySelector ? !!doc.querySelector(site.overlaySelector) : false; + const barTop = site.bottomBarSelector ? doc.querySelector(site.bottomBarSelector)?.getBoundingClientRect().top ?? null : null; + const display = buttonHidden(site, win.location.pathname, overlay) ? 'none' : 'block'; + const bottom = `${buttonBottom(barTop, win.innerHeight)}px`; + if (button.style.display !== display) button.style.display = display; + if (button.style.bottom !== bottom) button.style.bottom = bottom; + if (!existing) doc.body.appendChild(button); + }; + + const sync = () => { + if (!doc.body) return; + syncButton(site.mountNav?.(open) ?? false); + }; + const start = () => { + sync(); + // Sites re-render their navigation on route and layout changes; re-attach when the entry disappears. + watchDom(win as unknown as DomWindow, sync); + }; + if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', start, { once: true }); + else start(); + return { sync }; +} diff --git a/packages/runtime/src/siteRuntime.ts b/packages/runtime/src/siteRuntime.ts new file mode 100644 index 0000000..c8b9152 --- /dev/null +++ b/packages/runtime/src/siteRuntime.ts @@ -0,0 +1,259 @@ +// The page runtime's composition helpers: what every app's runtime entry does the same way. An +// app's entry (injected at document start into its site's tabs) installs its features and then: +// +// const invoke = pageInvoke(window, SITE.product); +// const flags = createFeatureFlags({ defaults, label: SITE.product, installers, apply }); +// const runtime = installSiteRuntime({ win: window, site: SITE, version, invoke, plugins, strings, features: flags, ... }); +// installPanelButton(window, button, () => runtime.open()); // panelButton.ts +// +// - `pageInvoke`: the IPC bridge, read at call time. +// - `createFeatureFlags`: flag-controlled parts that install on enable and dispose on disable, the +// flags native code delivers (`features_set`) and a deck column's overrides on top of them. +// - `installSiteRuntime`: the runtime object under its window names (`window.wayBetter` and the +// app's own), the members native code calls (features, theme, fonts, pane, links, i18n, column), +// the plugin API views, developer-mode errors, the palette command report, and whatever native +// code delivered before the runtime existed (the `__bt*` / `__wb*` queues). + +import { installCommandReport, devErrorReporter } from './commandReport.ts'; +import type { CommandInfo } from './commands.ts'; +import type { PageStrings } from './pageStrings.ts'; +import type { PluginContext } from './permissions.ts'; +import type { Params } from './i18n.ts'; +import type { SiteAdapter } from './site.ts'; + +export type PageInvoke = (command: string, args: Record) => Promise; + +type BridgeWindow = { __TAURI_INTERNALS__?: { invoke(cmd: string, args?: Record): Promise }; navigator: { webdriver?: boolean } }; + +/** + * Native commands from the page. The IPC bridge is read at call time: a runtime installed at + * document start can run before Tauri has put `__TAURI_INTERNALS__` on the page. A runtime only + * ships inside the app's site tabs; automated test browsers (`navigator.webdriver`) have no + * bridge, and the features that need it stay off there (undefined). + */ +export function pageInvoke(win: Window, product: string): PageInvoke | undefined { + const target = win as unknown as BridgeWindow; + const inApp = !!target.__TAURI_INTERNALS__ || !target.navigator.webdriver; + if (!inApp) return undefined; + return (command, args) => { + const ipc = target.__TAURI_INTERNALS__; + return ipc ? ipc.invoke(command, args) : Promise.reject(new Error(`${product}: IPC bridge not ready`)); + }; +} + +// --------------------------------------------------------------------------------------------- +// Feature flags + +/** A flag-controlled part of the runtime, while it is installed. */ +export type Installed = { dispose(): void }; +export type FlagInstaller = readonly [flag: keyof Flags & string, install: () => Installed]; + +export type FeatureFlagsOptions> = { + /** Every flag with its default; a flag not in here is ignored. */ + defaults: Flags; + /** Console label (the app's name). */ + label: string; + /** Parts that install when their flag turns on and dispose when it turns off, in install order. */ + installers: ReadonlyArray>; + /** Every applied config, before the installers (flags that are CSS, or that another part reads). */ + apply?(config: Partial): void; + /** The page's document: a column's flags delivered at document start wait for `` to exist. */ + document?: Document; +}; + +export type FeatureFlags> = { + /** The flags native code delivers (the owner's tweaks); a deck column's overrides stay on top. */ + apply(config: Partial): void; + /** + * A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are + * dropped here too). Flags a column stops overriding go back to the global value, or the default + * when the global config never named them. Recorded at once; applied now, or once the document + * has its `` (a new column webview gets its config at document start). + */ + setColumnFlags(flags: unknown): void; + /** Turns one installer on or off directly (a kill switch). */ + set(flag: keyof Flags & string, enabled: boolean): void; + /** Whether a flag's installer is installed right now. */ + installed(flag: keyof Flags & string): boolean; +}; + +export function createFeatureFlags>(options: FeatureFlagsOptions): FeatureFlags { + const { defaults, label, installers } = options; + const active = new Map(); + const installerOf = new Map(installers.map(([flag, install]) => [flag as string, install])); + + const set = (flag: string, enabled: boolean) => { + const install = installerOf.get(flag); + if (!install) return; + const current = active.get(flag); + if (enabled && !current) { + try { active.set(flag, install()); } + catch (error) { console.error(`[${label}] ${flag} failed`, error); } + } else if (!enabled && current) { + current.dispose(); + active.delete(flag); + } + }; + // Installed at document start, before the site's bundle runs (request gates wrap its fetch). + for (const [flag] of installers) set(flag, defaults[flag]); + + let globalFlags: Partial = {}; + let columnFlags: Partial = {}; + const merged = (previous: Partial = {}): Partial => { + const restore = Object.fromEntries(Object.keys(previous).map(key => [key, defaults[key]])) as Partial; + return { ...restore, ...globalFlags, ...columnFlags }; + }; + const applyAll = (config: Partial) => { + options.apply?.(config); + for (const [flag] of installers) { + const enabled = config[flag]; + if (typeof enabled === 'boolean') set(flag, enabled); + } + }; + + return { + apply(config) { + globalFlags = { ...globalFlags, ...config }; + applyAll(Object.keys(columnFlags).length ? merged() : config); + }, + setColumnFlags(flags) { + const next: Partial = {}; + if (flags && typeof flags === 'object') { + for (const [key, value] of Object.entries(flags)) if (key in defaults && typeof value === 'boolean') (next as Record)[key] = value; + } + const previous = columnFlags; + columnFlags = next; + if (!Object.keys(previous).length && !Object.keys(next).length) return; + const apply = () => { try { applyAll(merged(previous)); } catch (error) { console.error(`[${label}] column flags failed`, error); } }; + const doc = options.document; + if (!doc || doc.documentElement) apply(); + else doc.addEventListener('DOMContentLoaded', apply, { once: true }); + }, + set, + installed: flag => active.has(flag), + }; +} + +// --------------------------------------------------------------------------------------------- +// The runtime object + +/** What native code and plugins reach through `window.`. */ +export type SiteRuntime = { + version: string; + /** Running plugins by file (native start/stop scripts manage this). */ + plugins: Record void; stop?: () => void }>; + /** Load errors by plugin file. */ + errors: Record; + /** Native code hands over the feature flags (`features_set`). */ + features: { apply(config: unknown): void }; + /** Native code hands over the owner's language: `{ locale, dir, messages }` (pageStrings.ts). */ + i18n: { set(strings: unknown): void; locale(): string; t(key: string, params?: Params): string }; + /** Native code hands over where clicked site pages open (`{ site: 'same' | 'pane' | 'tab' | 'browser' }`). */ + links: { configure(value: unknown): void }; + /** Native code says whether this pane's navigation repeats another pane's (`{ redundantNav }`). */ + pane: { set(state: unknown): void }; + /** Native code hands over downloaded Google Fonts (validated woff2 bytes) that this tab's theme uses. */ + fonts: { provide(fonts: unknown): void }; + /** Power User Mode: native code hands a deck column its config (null = an ordinary tab again). */ + column: { set(config: unknown): void; markRead(): void; jumpToUnread(): void; unread(): number }; + /** Opens the app's panel in the shell (at a section). */ + open(section?: string): void; + /** + * Helpers for `*.plugin.js` files. Read while a plugin's code runs (its module body, constructor, + * start() and stop()), this is that plugin's view for its declared `@permissions`; elsewhere it + * is the full API. + */ + readonly api: Api; + /** Runs `fn` as plugin `id` with `grants` (null = legacy, full API; undefined = as registered). Native start/stop scripts call it. */ + withPlugin(id: string, grants: readonly string[] | null | undefined, fn: () => R): R; + /** Developer mode: a reloaded plugin failed to start (native `dev_start_script`); shown as a toast. */ + devError(file: unknown, error: unknown): void; +}; + +type ApiWithUi = { ui?: { toast(message: string, options: { tone: 'danger'; duration: number }): unknown }; commands?: { list(): CommandInfo[]; onChange(callback: (list: CommandInfo[]) => void): () => void } }; + +export type SiteRuntimeOptions = { + win: Window & typeof globalThis; + site: Pick; + version: string; + /** Other window names for the runtime, besides `wayBetter` and `site.runtimeGlobal` (names older plugins use). */ + aliases?: readonly string[]; + invoke?: PageInvoke; + /** Per-plugin API views (permissions.ts `createPluginContext`). */ + plugins: PluginContext; + strings: PageStrings; + /** The toast for a plugin that failed to start in developer mode ("Plugin failed: {error}"). */ + pluginFailed(error: string): string; + features?: { apply(config: never): void }; + /** The theme handle (themeRuntime.ts), exposed as `theme`. */ + theme?: { apply(choice: unknown): void }; + fonts?(fonts: unknown): void; + pane?: { set(state: unknown): void }; + links?: { configure(value: unknown): void }; + column?: SiteRuntime['column']; + /** The app's own members (X: alerts, fixes). */ + extra?: Extra; + /** Values native code may have delivered for the app's own members before the runtime existed: queue global and receiver. */ + queues?: ReadonlyArray void]>; +}; + +/** + * Builds the runtime object, publishes it under its window names (not writable, not configurable), + * takes over what native code queued before it existed, and starts the palette command report. + */ +export function installSiteRuntime>(options: SiteRuntimeOptions): SiteRuntime & Extra { + const { win, site, plugins, strings } = options; + const label = site.product; + // A failure in one member never breaks native code's other deliveries (or the page). + const guarded = (what: string, fn: (value: T) => void) => (value: T) => { + try { fn(value); } catch (error) { console.error(`[${label}] ${what} failed`, error); } + }; + const runtime = { + ...(options.extra ?? {}), + version: options.version, + plugins: {}, + errors: {}, + features: { apply: (config: unknown) => (options.features as { apply(config: unknown): void } | undefined)?.apply(config) }, + ...(options.theme ? { theme: options.theme } : {}), + fonts: { provide: guarded('fonts', (list: unknown) => options.fonts?.(list)) }, + pane: { set: guarded('split navigation', (state: unknown) => options.pane?.set(state)) }, + links: { configure: (value: unknown) => options.links?.configure(value) }, + i18n: { set: guarded('language', (value: unknown) => strings.set(value)), locale: strings.locale, t: strings.t }, + column: { + set: guarded('deck column', (config: unknown) => options.column?.set(config)), + markRead: () => options.column?.markRead(), + jumpToUnread: () => options.column?.jumpToUnread(), + unread: () => options.column?.unread() ?? 0, + }, + open(section?: string) { + (win as unknown as BridgeWindow).__TAURI_INTERNALS__?.invoke('open_panel', { section: section ?? null }).catch(() => {}); + }, + withPlugin: (id: string, grants: readonly string[] | null | undefined, fn: () => R) => plugins.run(id, grants, fn), + get api() { return plugins.current(); }, + devError: devErrorReporter(() => { + const ui = (plugins.current() as ApiWithUi).ui; + return ui ? (message, toastOptions) => { ui.toast(message, toastOptions); } : undefined; + }, options.pluginFailed), + } as unknown as SiteRuntime & Extra & { theme?: { apply(choice: unknown): void } }; + + // `wayBetter` is the documented name; the app's own names stay for existing plugins. + const names = [...new Set(['wayBetter', site.runtimeGlobal, ...(options.aliases ?? [])])]; + for (const name of names) Object.defineProperty(win, name, { value: runtime, configurable: false, writable: false }); + + // Native code may deliver before this runtime exists. + const queued = win as unknown as Record; + const take = (queue: string, deliver: (value: unknown) => void) => { if (queued[queue]) deliver(queued[queue]); }; + take('__wbI18n', runtime.i18n.set); + take('__btFeatures', runtime.features.apply); + take('__wbFonts', runtime.fonts.provide); + take('__btTheme', value => runtime.theme?.apply(value)); + take('__btPane', runtime.pane.set); + take('__btLinks', runtime.links.configure); + take('__btColumn', runtime.column.set); + for (const [queue, deliver] of options.queues ?? []) take(queue, deliver); + + // Plugin commands for the shell's command palette: ids, titles and keywords about this tab only. + const commands = (plugins.current() as ApiWithUi).commands; + if (commands) installCommandReport(commands, options.invoke); + return runtime; +} diff --git a/packages/runtime/tests/i18n.test.ts b/packages/runtime/tests/i18n.test.ts index 76fc10b..6318ebc 100644 --- a/packages/runtime/tests/i18n.test.ts +++ b/packages/runtime/tests/i18n.test.ts @@ -7,12 +7,14 @@ import { argumentShapes, createI18n, direction, fallbackChain, formatMessage, matchLocale, normalizeLocale, parseMessage, placeholders, pluralCategories, relativeParts, type Catalog, } from '../src/i18n.ts'; -import { checkCatalog, checkMessageSafety, checkShape, checkSource, coverage, generateKeyTypes, type CatalogIssue } from '../src/i18nCheck.ts'; +import { checkCatalog, checkMessageSafety, checkShape, checkSource, coverage, generateKeyTypes, type CatalogIssue, type Meta } from '../src/i18nCheck.ts'; import { createPluginI18n, pluginNamespace } from '../src/pluginI18n.ts'; import { KIT_MESSAGES } from '../src/ui.ts'; import { SHELL_MESSAGES, shellText } from '../../shell/src/messages.ts'; import { STORE_MESSAGES } from '../../shell/src/storeMessages.ts'; import { FRAME_MESSAGES } from '../../shell/src/frame/frameMessages.ts'; +import { PANEL_MESSAGES } from '../../shell/src/panel/panelMessages.ts'; +import { INSTALLER_MESSAGES } from '../../shell/src/installerMessages.ts'; const here = dirname(fileURLToPath(import.meta.url)); @@ -212,15 +214,18 @@ test('plugin strings: own translations, then the app catalog, then own English', test('framework catalogs: kit words for every locale pass the checks', () => { const dir = join(here, '../../waybetter/locales'); const en = JSON.parse(readFileSync(join(dir, 'en.json'), 'utf8')) as Catalog; - assert.deepEqual(en.messages, { ...KIT_MESSAGES, ...SHELL_MESSAGES, ...STORE_MESSAGES, ...FRAME_MESSAGES }, 'en.json is the kit, shell-model, store and shell-frame source'); + assert.deepEqual(en.messages, { ...KIT_MESSAGES, ...SHELL_MESSAGES, ...STORE_MESSAGES, ...FRAME_MESSAGES, ...PANEL_MESSAGES, ...INSTALLER_MESSAGES }, 'en.json is the kit, shell-model, store, shell-frame, panel and installer source'); assert.equal(shellText('wb.account.signedOut', { handle: '@a' }), '@a · signed out'); assert.equal(shellText('wb.account.signedOut', { handle: '@a' }, () => '{handle} · oturum kapalı'), '@a · oturum kapalı'); - const files = readdirSync(dir).filter(file => file.endsWith('.json')); + // Translator notes (en.meta.json): where a message appears, and fragments a language may leave empty. + const meta = JSON.parse(readFileSync(join(dir, 'en.meta.json'), 'utf8')) as Meta & { $schema?: string }; + delete meta.$schema; + const files = readdirSync(dir).filter(file => file.endsWith('.json') && !file.endsWith('.meta.json')); assert.ok(files.length >= 50, `${files.length} locales`); for (const file of files) { const catalog = JSON.parse(readFileSync(join(dir, file), 'utf8')) as Catalog; assert.equal(`${catalog.locale}.json`, file); - const errors: CatalogIssue[] = [...checkShape(catalog, file), ...(file === 'en.json' ? checkSource(catalog) : checkCatalog(catalog, en.messages))].filter(issue => issue.level === 'error'); + const errors: CatalogIssue[] = [...checkShape(catalog, file), ...(file === 'en.json' ? checkSource(catalog, meta) : checkCatalog(catalog, en.messages, meta))].filter(issue => issue.level === 'error'); assert.deepEqual(errors, [], file); } }); diff --git a/packages/runtime/tests/siteRuntime.test.ts b/packages/runtime/tests/siteRuntime.test.ts new file mode 100644 index 0000000..f48028a --- /dev/null +++ b/packages/runtime/tests/siteRuntime.test.ts @@ -0,0 +1,185 @@ +// The runtime composition helpers: the IPC bridge read at call time, flag-controlled parts with a +// deck column's overrides, the runtime object under its window names with what native code queued, +// the page strings native code delivers, the palette command report and the panel button's placement. +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { devErrorReporter, installCommandReport } from '../src/commandReport.ts'; +import { createPageStrings, PAGE_STRING_LIMITS } from '../src/pageStrings.ts'; +import { BUTTON_GAP, buttonBottom, buttonHidden } from '../src/panelButton.ts'; +import { createPluginContext } from '../src/permissions.ts'; +import { createFeatureFlags, installSiteRuntime, pageInvoke } from '../src/siteRuntime.ts'; + +const tick = (ms = 15) => new Promise(resolve => setTimeout(resolve, ms)); +const SITE = { product: 'wayBetter for Test', runtimeGlobal: 'Demo' }; + +test('pageInvoke: the bridge is read at call time; a test browser without one has no invoke', async () => { + const win = { navigator: { webdriver: false } } as unknown as Window & { __TAURI_INTERNALS__?: unknown }; + const invoke = pageInvoke(win, 'Demo')!; + await assert.rejects(invoke('ping', {}), /Demo: IPC bridge not ready/); + win.__TAURI_INTERNALS__ = { invoke: async (command: string, args: unknown) => ({ command, args }) }; + assert.deepEqual(await invoke('ping', { a: 1 }), { command: 'ping', args: { a: 1 } }); + assert.equal(pageInvoke({ navigator: { webdriver: true } } as unknown as Window, 'Demo'), undefined); +}); + +type Flags = { gate: boolean; pill: boolean; css: boolean }; + +test('feature flags: parts install on enable and dispose on disable, in order, and a failing part is contained', () => { + const log: string[] = []; + const part = (name: string) => () => { log.push(`+${name}`); return { dispose: () => { log.push(`-${name}`); } }; }; + const applied: Array> = []; + const errors: unknown[] = []; + const original = console.error; + console.error = (...args: unknown[]) => { errors.push(args[0]); }; + try { + const flags = createFeatureFlags({ + defaults: { gate: true, pill: false, css: true }, + label: 'Demo', + installers: [['gate', part('gate')], ['pill', () => { throw new Error('no pill'); }]], + apply: config => applied.push(config), + }); + assert.deepEqual(log, ['+gate'], 'default-on parts install at once'); + assert.ok(flags.installed('gate') && !flags.installed('pill')); + flags.apply({ gate: false, css: false }); + assert.deepEqual(log, ['+gate', '-gate']); + assert.deepEqual(applied, [{ gate: false, css: false }]); + flags.apply({ gate: true, pill: true }); + assert.deepEqual(log, ['+gate', '-gate', '+gate']); + assert.equal(flags.installed('pill'), false); + assert.match(String(errors[0]), /\[Demo\] pill failed/); + flags.set('gate', false); + assert.equal(flags.installed('gate'), false, 'a kill switch'); + flags.set('css', true); + } finally { console.error = original; } +}); + +test('feature flags: a deck column overrides global flags; dropped overrides go back to the global value or the default', () => { + const applied: Array> = []; + const flags = createFeatureFlags({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => applied.push(config) }); + flags.apply({ pill: true }); + flags.setColumnFlags({ pill: false, css: false, unknown: true, gate: 'yes' }); + assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'only known booleans; the column wins'); + flags.apply({ css: true }); + assert.deepEqual(applied.at(-1), { pill: false, css: false }, 'a global change does not undo the column'); + flags.setColumnFlags({ pill: false }); + assert.deepEqual(applied.at(-1), { pill: false, css: true }, 'css is the global value again'); + flags.setColumnFlags(null); + assert.deepEqual(applied.at(-1), { pill: true, css: true }, 'an ordinary tab again: the global flags'); + const before = applied.length; + flags.setColumnFlags(undefined); + assert.equal(applied.length, before, 'nothing to change'); + // Delivered at document start, a column's flags wait for . + const listeners: Array<() => void> = []; + const doc = { documentElement: null as unknown, addEventListener: (_: string, listener: () => void) => { listeners.push(listener); } }; + const late: Array> = []; + const waiting = createFeatureFlags({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => late.push(config), document: doc as unknown as Document }); + waiting.setColumnFlags({ css: false }); + assert.deepEqual(late, []); + waiting.apply({ pill: true }); + assert.deepEqual(late.at(-1), { pill: true, css: false }, 'recorded at once: a global delivery already respects it'); + listeners[0]!(); + assert.deepEqual(late.at(-1), { pill: true, css: false }); +}); + +function runtimeWindow(queued: Record = {}) { + return { navigator: { webdriver: false }, ...queued } as unknown as Window & typeof globalThis & Record; +} + +test('the runtime is published under its names, takes what native code queued and reports commands', async () => { + const seen: Record = {}; + const sent: unknown[] = []; + const commandListeners: Array<(list: unknown[]) => void> = []; + let list = [{ id: 'a.plugin.js:go', title: 'Go', keywords: '' }]; + const toasts: string[] = []; + const api = { ui: { toast: (message: string) => { toasts.push(message); } }, commands: { list: () => list, onChange: (callback: (next: unknown[]) => void) => { commandListeners.push(callback); return () => {}; } }, i18n: {} }; + const strings = createPageStrings({ english: { 'demo.hello': 'Hello {name}' }, prefixes: ['demo.'], label: 'Demo' }); + const win = runtimeWindow({ + __wbI18n: { locale: 'tr', messages: { 'demo.hello': 'Merhaba {name}', 'other.key': 'dropped' } }, + __btFeatures: { gate: false }, + __btLinks: { site: 'tab' }, + __btColumn: { source: 'home' }, + __demoExtra: ['x'], + }); + const runtime = installSiteRuntime({ + win, site: SITE, version: '1.2.3', aliases: ['OldName'], + invoke: async (command, args) => { sent.push([command, args]); }, + plugins: createPluginContext(api), + strings, + pluginFailed: error => `Plugin failed: ${error}`, + features: { apply: (config: unknown) => { seen.features = config; } }, + links: { configure: value => { seen.links = value; } }, + column: { set: config => { seen.column = config; }, markRead() {}, jumpToUnread() {}, unread: () => 3 }, + extra: { demo: { set: (value: unknown) => { seen.extra = value; } } }, + queues: [['__demoExtra', value => { seen.extra = value; }]], + }); + for (const name of ['wayBetter', 'Demo', 'OldName']) { + assert.equal(win[name], runtime, name); + assert.deepEqual([Object.getOwnPropertyDescriptor(win, name)!.writable, Object.getOwnPropertyDescriptor(win, name)!.configurable], [false, false]); + } + assert.equal(runtime.version, '1.2.3'); + assert.deepEqual(seen, { features: { gate: false }, links: { site: 'tab' }, column: { source: 'home' }, extra: ['x'] }); + assert.equal(runtime.i18n.locale(), 'tr'); + assert.equal(runtime.i18n.t('demo.hello', { name: 'Ada' }), 'Merhaba Ada'); + assert.equal(strings.message('other.key'), undefined, 'only the runtime\'s prefixes are taken'); + assert.equal(runtime.column.unread(), 3); + assert.equal(runtime.api, api, 'outside a plugin: the full API'); + assert.equal(runtime.withPlugin('a.plugin.js', null, () => runtime.api), api, 'a legacy plugin: the full API'); + // A member that throws never breaks the others. + const errors: unknown[] = []; + const original = console.error; + console.error = (...args: unknown[]) => { errors.push(args[0]); }; + try { + const broken = installSiteRuntime({ win: runtimeWindow(), site: { product: 'Demo', runtimeGlobal: 'Broken' }, version: '1', plugins: createPluginContext(api), strings, pluginFailed: String, fonts: () => { throw new Error('bad fonts'); } }); + broken.fonts.provide([]); + assert.match(String(errors[0]), /\[Demo\] fonts failed/); + } finally { console.error = original; } + // Developer mode: a plugin that failed to start shows file:line in a toast. + runtime.devError('a.plugin.js', Object.assign(new Error('boom'), { stack: 'Error: boom\n at start (wb-dev/a.plugin.js:12:5)' })); + assert.match(toasts[0] ?? '', /^Plugin failed: a\.plugin\.js:\d+/); + // The palette hears about commands only when they change. + list = [...list, { id: 'a.plugin.js:stop', title: 'Stop', keywords: 'halt' }]; + commandListeners.forEach(listener => listener(list)); + await tick(120); + assert.deepEqual(sent, [['tab_report', { report: { commands: list } }]]); +}); + +test('page strings: deliveries are data (prefix, type and length checked), English is the fallback', () => { + const strings = createPageStrings({ english: { 'x.a': 'A', 'kit.ok': 'OK', 'plugin.clean-links.name': 'Clean links' }, prefixes: ['x.', 'kit.', 'plugin.'], label: 'Demo', bundledPrefix: 'bt-' }); + let changes = 0; + const off = strings.onChange(() => { changes += 1; }); + strings.set(null); + strings.set({ locale: 'not a tag!', messages: {} }); + strings.set({ locale: 'de' }); + assert.equal(strings.locale(), 'en'); + strings.set({ locale: 'de', messages: { 'x.a': 'Ä', 'x.long': 'l'.repeat(PAGE_STRING_LIMITS.value + 1), 'x.n': 5, 'native.secret': 'no' } }); + assert.equal(changes, 1); + assert.deepEqual([strings.locale(), strings.t('x.a'), strings.t('kit.ok'), strings.message('x.long'), strings.message('native.secret'), strings.t('x.unknown')], ['de', 'Ä', 'OK', undefined, undefined, 'x.unknown']); + strings.set({ locale: 'de', messages: { 'x.a': 'Ä' } }); + assert.equal(changes, 1, 'the same delivery changes nothing'); + assert.equal(strings.source.message('x.a'), 'Ä'); + // Bundled plugins are installed with a prefix; their strings are keyed by the source name. + assert.equal(strings.pluginNamespace('bt-clean-links.plugin.js'), 'clean-links'); + assert.equal(strings.pluginNamespace('bt-mine.plugin.js'), 'bt-mine', 'an owner\'s file that only looks bundled keeps its name'); + assert.equal(strings.pluginNamespace('other.plugin.js'), 'other'); + off(); + strings.set({ locale: 'fr', messages: {} }); + assert.equal(changes, 1); +}); + +test('command report and developer errors without a bridge or a toast do nothing', () => { + assert.doesNotThrow(() => installCommandReport({ list: () => [], onChange: () => () => {} }, undefined)()); + assert.doesNotThrow(() => devErrorReporter(() => undefined, String)('a.plugin.js', new Error('x'))); + assert.doesNotThrow(() => devErrorReporter(() => () => { throw new Error('toast broke'); }, String)('a.plugin.js', new Error('x'))); + assert.doesNotThrow(() => devErrorReporter(() => () => {}, String)(42, new Error('x'))); +}); + +test('the panel button sits above a bottom bar, never over a viewer or under an overlay', () => { + assert.equal(buttonBottom(null, 800), BUTTON_GAP); + assert.equal(buttonBottom(747, 800), 53 + BUTTON_GAP, 'above a 53px bottom bar'); + assert.equal(buttonBottom(800, 800), BUTTON_GAP, 'an empty bar at the bottom edge adds nothing'); + assert.equal(buttonBottom(100, 800), BUTTON_GAP, 'an implausibly tall bar adds nothing'); + const site = { hiddenOn: (pathname: string) => /\/photo\/\d+$/.test(pathname) }; + assert.equal(buttonHidden(site, '/a/status/1/photo/1', false), true); + assert.equal(buttonHidden(site, '/home', true), true); + assert.equal(buttonHidden(site, '/home', false), false); + assert.equal(buttonHidden({}, '/a/status/1/photo/1', false), false); +}); diff --git a/packages/shell/README.md b/packages/shell/README.md index 699bca0..5605e57 100644 --- a/packages/shell/README.md +++ b/packages/shell/README.md @@ -1,6 +1,14 @@ # shell (internal) -Sources of `waybetter/shell/*`: the shell models, the Store screens and the shell frame -(`src/frame`, `createShell`). Published as part of the [`waybetter`](../waybetter/README.md) package; -not published on its own. The repository README's "The shell frame" section describes what an app -supplies. +Sources of `waybetter/shell/*`: the shell models, the Store screens, the shell frame (`src/frame`, +`createShell`) and the panel (`src/panel`, `createPanel`: the app's own tab). Published as part of +the [`waybetter`](../waybetter/README.md) package; not published on its own. The repository README's +"The shell frame" and "The panel" sections describe what an app supplies. + +The panel is here rather than in a package of its own because it is drawn inside the frame and +shares its state: the frame's profile, deck, theme, sync and developer-mode stores, its native +bridge and its language. It imports the theme document model from `../runtime` by source path; +the package build (`packages/waybetter/scripts/build.mjs`) points those imports at `dist/runtime`. + +`scripts/google-fonts-catalog.mjs` regenerates the font browser's offline Google Fonts list +(`src/panel/fonts/googleFontsCatalog.json`). diff --git a/packages/shell/scripts/google-fonts-catalog.mjs b/packages/shell/scripts/google-fonts-catalog.mjs new file mode 100644 index 0000000..9351471 --- /dev/null +++ b/packages/shell/scripts/google-fonts-catalog.mjs @@ -0,0 +1,34 @@ +// Regenerates src/panel/fonts/googleFontsCatalog.json, the font browser's offline list of Google +// Fonts families (name, category, weight axis or static weights, popularity rank). Development-time +// only: an app never fetches this list; it downloads font files natively when the owner installs +// one (fonts.googleapis.com / fonts.gstatic.com, see waybetter-host gfonts.rs and fonts.rs). +// +// node packages/shell/scripts/google-fonts-catalog.mjs [metadata.json] +// +// Without an argument it reads https://fonts.google.com/metadata/fonts. Only families with a Latin +// subset and a name the native side accepts (letters, digits, single spaces) are kept. +import { readFileSync, writeFileSync } from 'node:fs'; + +const CATEGORY = { 'Sans Serif': 'sans', Serif: 'serif', Display: 'display', Handwriting: 'handwriting', Monospace: 'mono' }; +const NAME = /^[A-Za-z0-9]+( [A-Za-z0-9]+)*$/; + +const text = process.argv[2] + ? readFileSync(process.argv[2], 'utf8') + : await (await fetch('https://fonts.google.com/metadata/fonts')).text(); +const metadata = JSON.parse(text.replace(/^\)\]\}'\s*/, '')); +const families = metadata.familyMetadataList + .filter(font => font.subsets?.includes('latin') && NAME.test(font.family) && font.family.length <= 48 && CATEGORY[font.category]) + .sort((a, b) => a.popularity - b.popularity) + .map((font, rank) => { + const axis = font.axes?.find(item => item.tag === 'wght'); + const weights = Object.keys(font.fonts ?? {}).filter(key => /^\d+$/.test(key)).map(Number).sort((a, b) => a - b); + return [font.family, CATEGORY[font.category], axis ? [axis.min, axis.max] : null, weights, rank + 1]; + }); +const out = { + source: 'https://fonts.google.com/metadata/fonts', + generated: new Date().toISOString().slice(0, 10), + fields: ['family', 'category', 'wghtAxis', 'weights', 'rank'], + families, +}; +writeFileSync(new URL('../src/panel/fonts/googleFontsCatalog.json', import.meta.url), `${JSON.stringify(out)}\n`); +console.log(`${families.length} families`); diff --git a/packages/shell/src/frame/appI18n.ts b/packages/shell/src/frame/appI18n.ts new file mode 100644 index 0000000..8f5f155 --- /dev/null +++ b/packages/shell/src/frame/appI18n.ts @@ -0,0 +1,103 @@ +// An app's i18n instance for its shell webview (the shell frame, the panel, its own windows): +// English (the app's catalog over the framework's) is always loaded, other catalogs load on +// demand through the loader the app registers (its bundler's lazy imports), and components call +// `useT()` so a language switch re-renders them in place. The frame is bound to the instance. +// +// export const { i18n, t, tx, useT, setCatalogLoader } = createAppI18n({ +// source: { ...frameworkEn.messages, ...appEn.messages }, languages, useSyncExternalStore, dev: import.meta.env.DEV, +// }); +// +// Keys are typed by the app (`MessageKey`: its English catalog's keys and the framework's). The +// app passes React's `useSyncExternalStore`, so this module has no dependency of its own and the +// app's pure modules that use `t` stay testable under node. + +import { createI18n, type I18n, type Messages, type Params } from '../../../runtime/src/i18n.ts'; +import { setShellI18n } from './i18n.ts'; + +/** One language the app has a catalog for (a row of the app's generated `languages.json`). */ +export type AppLanguage = { + code: string; + name: string; + englishName: string; + dir: 'ltr' | 'rtl'; + status: 'source' | 'machine' | 'reviewed'; + /** `supported`: automatic language choices may resolve to it. `community`: only when picked explicitly. */ + tier: 'supported' | 'community'; + reviewers: string[]; + fallback?: string; + /** Share of English messages this catalog translates (its fallback's included), 0..1. */ + coverage: number; +}; + +export type AppI18nOptions = { + /** English: the framework's messages with the app's over them. */ + source: Messages; + /** Every language with a catalog, English first. */ + languages: readonly AppLanguage[]; + /** React's hook (`import { useSyncExternalStore } from 'react'`), for `useT` and `useLocale`. */ + useSyncExternalStore(subscribe: (listener: () => void) => () => void, getSnapshot: () => Snapshot, getServerSnapshot?: () => Snapshot): Snapshot; + /** A development build: untranslated and malformed messages are logged. */ + dev?: boolean; +}; + +export type AppI18n = { + i18n: I18n; + /** Registers how catalogs load (the app's lazy imports; tests may pass a map). */ + setCatalogLoader(load: (locale: string) => Promise): void; + /** The message for `key` in the active language. */ + t(key: Key, params?: Params): string; + /** For keys assembled at runtime (feature ids, section names): `fallback` when the key is unknown. */ + tx(key: string, params?: Params, fallback?: string): string; + /** Re-renders the calling component when the language changes; returns `t`. */ + useT(): (key: Key, params?: Params) => string; + /** The active locale (re-renders on change). */ + useLocale(): string; + /** "3 minutes ago" style text for a timestamp in the active language. */ + relativeTime(then: number, now?: number): string; + /** A date (and time) in the active language: `formatDate(iso, { dateStyle: 'medium' })`. */ + formatDate(value: string | number | Date, options?: Intl.DateTimeFormatOptions): string; + formatNumber(value: number, options?: Intl.NumberFormatOptions): string; +}; + +export function createAppI18n(options: AppI18nOptions): AppI18n { + let loader: ((locale: string) => Promise) | null = null; + const i18n = createI18n({ + source: options.source, + available: options.languages.map(language => language.code), + fallbacks: Object.fromEntries(options.languages.filter(language => language.fallback).map(language => [language.code, language.fallback!])), + load: locale => loader?.(locale) ?? null, + onMissing: options.dev + ? (key, locale, reason) => { if (reason !== 'key' || locale === 'en') console.warn(`[i18n] ${reason} ${locale}: ${key}`); else console.debug(`[i18n] untranslated ${locale}: ${key}`); } + : undefined, + }); + // The wayBetter shell frame and panel speak through this instance. + setShellI18n(i18n); + + const { useSyncExternalStore } = options; + const t = (key: Key, params?: Params) => i18n.t(key, params); + const subscribe = (listener: () => void) => i18n.onChange(listener); + const snapshot = () => i18n.locale; + return { + i18n, + setCatalogLoader(load) { loader = load; }, + t, + tx: (key, params, fallback) => i18n.tx(key, params, fallback), + useT() { + useSyncExternalStore(subscribe, snapshot, snapshot); + return t; + }, + useLocale: () => useSyncExternalStore(subscribe, snapshot, snapshot), + relativeTime(then, now = Date.now()) { + const seconds = Math.round((then - now) / 1000); + const abs = Math.abs(seconds); + if (abs < 45) return i18n.relative(0, 'second'); + if (abs < 3600) return i18n.relative(Math.round(seconds / 60), 'minute'); + if (abs < 86400) return i18n.relative(Math.round(seconds / 3600), 'hour'); + if (abs < 86400 * 30) return i18n.relative(Math.round(seconds / 86400), 'day'); + if (abs < 86400 * 365) return i18n.relative(Math.round(seconds / (86400 * 30)), 'month'); + return i18n.relative(Math.round(seconds / (86400 * 365)), 'year'); + }, + formatDate: (value, formatOptions = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) => i18n.date(value, formatOptions), + formatNumber: (value, formatOptions) => i18n.number(value, formatOptions), + }; +} diff --git a/packages/shell/src/frame/backupModel.ts b/packages/shell/src/frame/backupModel.ts index 62f4caf..0f6e733 100644 --- a/packages/shell/src/frame/backupModel.ts +++ b/packages/shell/src/frame/backupModel.ts @@ -153,13 +153,24 @@ function details(section: string, current: Json, incoming: Json): string[] { } } +/** + * A section as it is compared. A `settings` section written before the host kept the settings + * names the site links `xLinks` (native code reads both); it is the same setting as `siteLinks`. + */ +function comparable(section: string, value: Json): Json { + if (section !== 'settings' || !('xLinks' in value) || 'siteLinks' in value) return value; + const { xLinks, ...rest } = value; + return { ...rest, siteLinks: xLinks }; +} + /** One preview row per section present in `incoming`, in display order. */ export function diffSections(current: Json, incoming: Json): SectionRow[] { const rows: SectionRow[] = []; for (const section of SECTION_ORDER) { - const next = incoming[section]; - if (!isObject(next)) continue; - const now = isObject(current[section]) ? current[section] as Json : null; + const given = incoming[section]; + if (!isObject(given)) continue; + const next = comparable(section, given); + const now = isObject(current[section]) ? comparable(section, current[section] as Json) : null; const same = !!now && canonical(now) === canonical(next); const status: SectionRow['status'] = same ? 'same' : now && Object.keys(now).length ? 'changed' : 'new'; const lines = same ? [t('wb.backup.detail.same')] : details(section, now ?? {}, next); diff --git a/packages/shell/src/frame/i18n.ts b/packages/shell/src/frame/i18n.ts index 67781bc..a0561f1 100644 --- a/packages/shell/src/frame/i18n.ts +++ b/packages/shell/src/frame/i18n.ts @@ -15,6 +15,7 @@ export type ShellI18n = { onChange(listener: (locale: string) => void): () => void; number(value: number, options?: Intl.NumberFormatOptions): string; relative(value: number, unit: Intl.RelativeTimeFormatUnit): string; + date(value: string | number | Date, options?: Intl.DateTimeFormatOptions): string; }; let current: ShellI18n | null = null; @@ -58,6 +59,11 @@ export function formatNumber(value: number, options?: Intl.NumberFormatOptions): return current ? current.number(value, options) : String(value); } +/** A date (and time) in the active language: `formatDate(iso, { dateStyle: 'medium' })`. */ +export function formatDate(value: string | number | Date, options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }): string { + return current ? current.date(value, options) : new Date(value).toISOString(); +} + /** "3 minutes ago" style text for a timestamp in the active language. */ export function relativeTime(then: number, now = Date.now()): string { if (!current) return new Date(then).toISOString(); diff --git a/packages/shell/src/frame/index.ts b/packages/shell/src/frame/index.ts index 6ca09c8..b724124 100644 --- a/packages/shell/src/frame/index.ts +++ b/packages/shell/src/frame/index.ts @@ -53,3 +53,5 @@ export { chromeVars, CHROME_VAR_NAMES, SHELL_UI_FONT, SHELL_MONO_FONT, type Chro export { shell, setOverlay, scheduleSync, flushSync, isWeb, tabAction, setProfiles, type TabParams, type WebParams } from './state.ts'; export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.ts'; export { Icon, Avatar, ICONS, type IconName } from './icons.tsx'; +export { createLanguage, resolveLocale, type Language, type LanguageOptions, type LanguagePreference } from './language.ts'; +export { createAppI18n, type AppI18n, type AppI18nOptions, type AppLanguage } from './appI18n.ts'; diff --git a/packages/shell/src/frame/language.ts b/packages/shell/src/frame/language.ts new file mode 100644 index 0000000..7de33a9 --- /dev/null +++ b/packages/shell/src/frame/language.ts @@ -0,0 +1,196 @@ +// Which language the app speaks. The owner picks "Follow the site" (default: the language the site +// itself is set to, as its tabs report their ``), "Follow system" (the OS preference, +// read natively) or a language. The shell resolves that to a catalog, switches every window live, +// and hands native code (dialogs, notifications) and site tabs (the page runtime, plugins) exactly +// the strings they need through the shell-only `i18n_set`. Other local windows (a popover) follow +// through localStorage (same origin as the shell). +// +// export const language = createLanguage({ i18n, nativePrefixes: ['x.', 'kit.', 'plugin.', 'native.'], native: { invoke, listen } }); +// await language.initShell(isNative()); +// +// The panel's language picker takes the same object (`PanelSite.languages`). + +import { direction, matchLocale, normalizeLocale } from '../../../runtime/src/i18n.ts'; +import type { Invoke, Listen } from './bridge.ts'; + +/** `site`: follow the site's own language. `system`: follow the OS. Otherwise a catalog tag. */ +export type LanguagePreference = 'site' | 'system' | string; + +/** The part of a waybetter/i18n instance the language state drives. */ +export type LanguageI18n = { + readonly locale: string; + readonly available: readonly string[]; + setLocale(locale: string): Promise; + resolved(prefixes?: readonly string[]): Record; +}; + +export type LanguageOptions = { + i18n: LanguageI18n; + /** Key prefixes native code and site tabs need; the shell hands exactly these over (`i18n_set`). */ + nativePrefixes: readonly string[]; + /** The app's Tauri `invoke` and `listen` (the language is set up before the shell frame is). */ + native: { invoke: Invoke; listen: Listen }; + /** Where the choice is kept for the app's other local windows (default `wb.language`). */ + storageKey?: string; + /** + * The supported tier: automatic choices ("Follow the site", "Follow system") resolve only to + * these (English is always one). Any other catalog is a community language: it applies only + * when picked explicitly. Default: every catalog is supported. + */ + supported?: readonly string[]; +}; + +type NativeLanguage = { preference?: string; locale?: string; system?: string[] }; +type Stored = { preference: LanguagePreference; locale: string; siteLang?: string | null }; + +/** Where the shell keeps its choice for the app's other local windows (localStorage). */ +export const DEFAULT_STORAGE_KEY = `wb.language`; + +/** + * The catalog to use for a preference, the site's reported language and the OS preferences. + * Automatic choices ("site", "system") only resolve to `supported` languages (default: all of + * `available`), through the normal fallback chain (pt-BR -> pt, zh-TW -> zh-Hant); a language + * picked explicitly applies whatever its tier. + */ +export function resolveLocale(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[], supported: readonly string[] = available): string { + if (preference === 'site') { + if (!siteLang) return matchLocale(system, supported, 'en'); + const site = matchLocale([siteLang], supported, ''); + if (site) return site; + // The site's language is a community translation: English (it is offered as a switch), not the system language. + return matchLocale([siteLang], available, '') ? 'en' : matchLocale(system, supported); + } + if (preference === 'system') return matchLocale(system, supported); + return matchLocale([preference], available, matchLocale(system, supported)); +} + +/** + * The community language an automatic choice would have used had it been supported (the site's or + * the system's), or null: the panel offers it as a one-click switch. + */ +export function communitySuggestion(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[], supported: readonly string[] = available): string | null { + if (preference !== 'site' && preference !== 'system') return null; + const wanted = resolveLocale(preference, siteLang, system, available, available); + return supported.includes(wanted) ? null : wanted; +} + +export type Language = ReturnType; + +export function createLanguage(options: LanguageOptions) { + const { i18n, nativePrefixes, native } = options; + const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY; + const available = i18n.available; + const supported = options.supported ? ['en', ...options.supported.filter(code => available.includes(code))] : available; + const current = { + preference: 'site' as LanguagePreference, + siteLang: null as string | null, + system: [] as string[], + native: false, + }; + const listeners = new Set<() => void>(); + + function readStored(): Stored | null { + try { + const value = JSON.parse(localStorage.getItem(storageKey) ?? 'null') as Stored | null; + return value && typeof value.locale === 'string' ? value : null; + } catch { + return null; + } + } + + function writeStored(value: Stored) { + try { localStorage.setItem(storageKey, JSON.stringify(value)); } catch { /* the choice still applies this session */ } + } + + function browserLanguages(): string[] { + const list = typeof navigator === 'undefined' ? [] : [...(navigator.languages ?? []), navigator.language]; + return list.filter((tag): tag is string => typeof tag === 'string' && !!normalizeLocale(tag)); + } + + function paint(locale: string) { + const root = document.documentElement; + root.lang = locale; + root.dir = direction(locale); + } + + let syncing: Promise = Promise.resolve(); + + async function apply() { + const locale = resolveLocale(current.preference, current.siteLang, current.system, available, supported); + await i18n.setLocale(locale); + paint(i18n.locale); + writeStored({ preference: current.preference, locale: i18n.locale, siteLang: current.siteLang }); + if (current.native) { + // Serialized: a quick switch must not let an older set of strings land last. + const strings = { locale: i18n.locale, preference: current.preference, messages: i18n.resolved(nativePrefixes) }; + syncing = syncing.then(() => native.invoke('i18n_set', { strings })).catch(error => console.error('[i18n] native strings were not updated', error)); + } + for (const listener of [...listeners]) listener(); + } + + /** + * Shell start: the saved preference (native), the OS languages, the last language the site + * reported, then the catalog; resolves once the first paint can be in the right language. + */ + async function initShell(isNative: boolean): Promise { + current.native = isNative; + const stored = readStored(); + current.siteLang = stored?.siteLang ?? null; + let fromNative: NativeLanguage | null = null; + if (isNative) { + try { fromNative = await native.invoke('i18n_get'); } catch (error) { console.error('[i18n] i18n_get failed', error); } + } + current.preference = fromNative?.preference || stored?.preference || 'site'; + current.system = [...(fromNative?.system ?? []), ...browserLanguages()]; + if (isNative) { + // Site tabs say which language the site is in; "Follow the site" switches with it. + void native.listen<{ lang?: string }>('tab-state', ({ payload }) => { + const lang = normalizeLocale(payload.lang); + if (!lang || lang === current.siteLang) return; + current.siteLang = lang; + if (current.preference === 'site') void apply(); + else writeStored({ preference: current.preference, locale: i18n.locale, siteLang: lang }); + }); + } + await apply(); + } + + /** Another local window (a popover) and previews: the shell's last choice, kept current through storage events. */ + async function initFollower(forced?: string | null): Promise { + const pick = async () => { + const locale = forced ? matchLocale([forced], available) : readStored()?.locale ?? matchLocale(browserLanguages(), supported); + await i18n.setLocale(locale); + paint(i18n.locale); + }; + if (!forced) { + window.addEventListener('storage', event => { if (event.key === storageKey) void pick(); }); + } + await pick(); + } + + function state() { + return { + preference: current.preference, siteLang: current.siteLang, system: current.system, locale: i18n.locale, + community: communitySuggestion(current.preference, current.siteLang, current.system, available, supported), + }; + } + + async function set(preference: LanguagePreference): Promise { + if (preference !== 'site' && preference !== 'system' && !available.includes(preference)) return; + current.preference = preference; + await apply(); + } + + function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { listeners.delete(listener); }; + } + + /** Development previews (`?lang=tr`): a fixed language without native code. */ + async function forcePreview(tag: string): Promise { + current.preference = matchLocale([tag], available); + await apply(); + } + + return { initShell, initFollower, state, set, subscribe, forcePreview, storageKey }; +} diff --git a/packages/shell/src/frame/site.ts b/packages/shell/src/frame/site.ts index 689c25c..4a826ca 100644 --- a/packages/shell/src/frame/site.ts +++ b/packages/shell/src/frame/site.ts @@ -41,6 +41,10 @@ export type ColumnFlag = { key: string; label: string; hint: string }; export type DeckPreset = { id: string; label(): string; + /** The new deck's name and the preset's row in settings (default: `label`). */ + name?(): string; + /** What the preset's columns are, for settings. */ + hint?(): string; /** Disabled (with this hint) when only one account exists. */ needsTwoAccounts?: () => string; columns(profiles: readonly string[]): Array>; diff --git a/packages/shell/src/installerMessages.ts b/packages/shell/src/installerMessages.ts new file mode 100644 index 0000000..c8b265d --- /dev/null +++ b/packages/shell/src/installerMessages.ts @@ -0,0 +1,38 @@ +// The Windows installer's words in English (`wb.installer.*`), the source of the framework +// catalogs (`waybetter/locales/.json`). They are Tauri's NSIS installer messages for the +// languages Tauri does not ship itself; `packages/waybetter/scripts/installer-languages.mjs` writes +// them as `windows/languages/.nsh`, which an app lists under `customLanguageFiles`. +// Placeholders: `{product}` the app's name, `{version}` its version, `{installed}` the installed +// version, `{error}` and `{code}` what the WebView2 setup reported. + +export const INSTALLER_MESSAGES = { + 'wb.installer.addOrReinstall': 'Add/Reinstall components', + 'wb.installer.alreadyInstalled': 'Already Installed', + 'wb.installer.alreadyInstalledLong': '{product} {version} is already installed. Select the operation you want to perform and click Next to continue.', + 'wb.installer.appRunning': '{product} is running! Please close it first then try again.', + 'wb.installer.appRunningOkKill': '{product} is running!\nClick OK to kill it', + 'wb.installer.chooseMaintenanceOption': 'Choose the maintenance option to perform.', + 'wb.installer.choowHowToInstall': 'Choose how you want to install {product}.', + 'wb.installer.createDesktop': 'Create desktop shortcut', + 'wb.installer.dontUninstall': 'Do not uninstall', + 'wb.installer.dontUninstallDowngrade': 'Do not uninstall (Downgrading without uninstall is disabled for this installer)', + 'wb.installer.failedToKillApp': 'Failed to kill {product}. Please close it first then try again', + 'wb.installer.installingWebview2': 'Installing WebView2...', + 'wb.installer.newerVersionInstalled': 'A newer version of {product} is already installed! It is not recommended that you install an older version. If you really want to install this older version, it\'s better to uninstall the current version first. Select the operation you want to perform and click Next to continue.', + 'wb.installer.older': 'older', + 'wb.installer.olderOrUnknownVersionInstalled': 'An {installed} version of {product} is installed on your system. It\'s recommended that you uninstall the current version before installing. Select the operation you want to perform and click Next to continue.', + 'wb.installer.silentDowngrades': 'Downgrades are disabled for this installer, can\'t proceed with the silent installer, please use the graphical interface installer instead.\n', + 'wb.installer.unableToUninstall': 'Unable to uninstall!', + 'wb.installer.uninstallApp': 'Uninstall {product}', + 'wb.installer.uninstallBeforeInstalling': 'Uninstall before installing', + 'wb.installer.unknown': 'unknown', + 'wb.installer.webview2AbortError': 'Failed to install WebView2! The app can\'t run without it. Try restarting the installer.', + 'wb.installer.webview2DownloadError': 'Error: Downloading WebView2 Failed - {error}', + 'wb.installer.webview2DownloadSuccess': 'WebView2 bootstrapper downloaded successfully', + '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', +} as const; + +export type InstallerKey = keyof typeof INSTALLER_MESSAGES; diff --git a/packages/shell/src/panel/Appearance.tsx b/packages/shell/src/panel/Appearance.tsx new file mode 100644 index 0000000..c586f18 --- /dev/null +++ b/packages/shell/src/panel/Appearance.tsx @@ -0,0 +1,412 @@ +// Appearance: the theme gallery (live previews rendered from each theme document), per-group +// customization on top of the selected theme (fonts per role with the Google Fonts browser), +// account and pane themes, downloaded fonts, import/export of theme JSON and Custom CSS. The theme +// documents, the store and the miniature are the app's (`PanelSite.themes`). +import { useEffect, useRef, useState } from 'react'; +import { THEME_SCHEMA_URL } from '../../../runtime/src/themeApi.ts'; +import type { ThemeChoice } from '../../../runtime/src/themeChoice.ts'; +import { + FONT_CHOICES, MAX_IMAGE_CHARS, fontChoiceOf, googleFontsUsed, parseThemeJson, slug, + type Background, type FontRole, type FontRoleName, type Pattern, type ThemeOverrides, type ThemeSpec, +} from '../../../runtime/src/themeSpec.ts'; +import { AccountAvatar, accountName, useProfiles } from '../frame/AccountSwitcher.tsx'; +import { useT } from '../frame/hooks.ts'; +import { formatDate, t, tx } from '../frame/i18n.ts'; +import { ThemeDots } from '../frame/PaneTheme.tsx'; +import { shell, type WebParams } from '../frame/state.ts'; +import { assign } from '../frame/themeScopes.ts'; +import { tabProfile } from '../profileModel.ts'; +import { Button, ColorField, Row, Section, Segmented, Select, Slider, Toggle, useSettingsQuery, type Option } from './controls.tsx'; +import { bytesLabel, defaultWeights, loadCatalog, weightsLabel } from './fonts/catalog.ts'; +import { FontRoles } from './fonts/FontRoles.tsx'; +import { CustomCssEditor } from './Plugins.tsx'; +import { panelSite, panelThemes, type Notify } from './site.ts'; +import { useThemeState } from './themes.ts'; +import './builder.css'; + +const getError = (error: unknown) => error instanceof Error ? error.message : String(error); + +const CORNERS = [ + { value: 'square', label: 'wb.appearance.corners.square', radius: 0, button: 0 }, + { value: 'crisp', label: 'wb.appearance.corners.crisp', radius: 5, button: 5 }, + { value: 'soft', label: 'wb.appearance.corners.soft', radius: 12, button: 10 }, + { value: 'round', label: 'wb.appearance.corners.round', radius: 16, button: 9999 }, +] as const; +type BackgroundChoice = 'none' | 'glow' | Pattern | 'image'; +const backgrounds = (): Array> => [ + { value: 'none', label: t('wb.appearance.bg.none') }, { value: 'glow', label: t('wb.appearance.bg.glow') }, { value: 'dots', label: t('wb.appearance.bg.dots') }, { value: 'grid', label: t('wb.appearance.bg.grid') }, + { value: 'diagonal', label: t('wb.appearance.bg.diagonal') }, { value: 'scanlines', label: t('wb.appearance.bg.scanlines') }, { value: 'paper', label: t('wb.appearance.bg.paper') }, + { value: 'clouds', label: t('wb.appearance.bg.clouds') }, { value: 'image', label: t('wb.appearance.bg.image'), hint: t('wb.appearance.bg.imageHint') }, +]; + +const modeLabel = (theme: ThemeSpec) => theme.mode === 'auto' ? t('wb.appearance.mode.auto') : theme.mode === 'light' ? t('wb.appearance.mode.light') : t('wb.appearance.mode.dark'); +const fontLabel = (theme: ThemeSpec) => { + const family = theme.font.family; + const choices = panelThemes().fontChoices ?? FONT_CHOICES; + const choice = choices.find(item => item.id === fontChoiceOf(family, choices)); + return (choice?.key ? tx(choice.key, undefined, choice.label) : choice?.label) ?? family[0] ?? panelThemes().siteFont; +}; +/** Built-in themes have translated descriptions (`theme..description` in the app's catalog); imported ones keep their own. */ +export const themeDescription = (theme: ThemeSpec) => tx(`theme.${theme.id}.description`, undefined, theme.description); +const formatPercent = (value: number) => t('wb.appearance.percent', { value: value / 100 }); +const hasOverrides = (choice: ThemeChoice) => !!choice.accent || Object.keys(choice.overrides).length > 0; + +function download(name: string, text: string) { + const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); + const anchor = document.createElement('a'); + anchor.href = url; anchor.download = name; anchor.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +function backgroundFor(kind: BackgroundChoice, theme: ThemeSpec, image?: string): Background { + const base = panelThemes().draftColors; + const text = theme.colors?.text ?? '#8b98a5'; + const light = theme.mode === 'light'; + switch (kind) { + case 'none': return { kind: 'none' }; + case 'glow': return { kind: 'gradient', from: theme.colors?.page ?? theme.colors?.bg ?? base.bg, to: theme.colors?.page ?? theme.colors?.bg ?? base.bg, angle: 180, glow: theme.colors?.accent ?? base.accent }; + case 'image': return { kind: 'image', url: image ?? '', fit: 'cover', dim: light ? 0.55 : 0.6 }; + case 'clouds': return { kind: 'pattern', pattern: 'clouds', ink: light ? '#ffffff' : text, opacity: light ? 0.55 : 0.07, size: 220 }; + case 'dots': return { kind: 'pattern', pattern: 'dots', ink: text, opacity: 0.16, size: 18 }; + case 'grid': return { kind: 'pattern', pattern: 'grid', ink: text, opacity: 0.06, size: 28 }; + case 'diagonal': return { kind: 'pattern', pattern: 'diagonal', ink: text, opacity: 0.06, size: 10 }; + case 'scanlines': return { kind: 'pattern', pattern: 'scanlines', ink: theme.colors?.accent ?? text, opacity: 0.05, size: 4 }; + case 'paper': return { kind: 'pattern', pattern: 'paper', ink: light ? '#7a6a50' : text, opacity: 0.1, size: 180 }; + } +} +const backgroundChoice = (background: Background): BackgroundChoice => + background.kind === 'none' ? 'none' : background.kind === 'gradient' ? 'glow' : background.kind === 'image' ? 'image' : background.pattern; + +/** Asks the panel to show another section (the Theme Builder). */ +const openSection = (section: string) => window.dispatchEvent(new CustomEvent('bt-panel-section', { detail: section })); + +export function Appearance({ notify }: { notify: Notify }) { + const t = useT(); + const themes = panelThemes(); + const { allThemes, installFont, missingFonts, setChoice, setScopes } = themes.store; + const ThemePreview = themes.Preview; + const { ready, choice, scopes } = useThemeState(); + const [importing, setImporting] = useState(false); + const [asking, setAsking] = useState<{ theme: ThemeSpec; families: string[] } | null>(null); + const query = useSettingsQuery(); + + if (!ready) return null; + const effective = themes.catalog.resolve(choice); + const base = themes.catalog.base(choice); + const all = allThemes(choice); + const siteTheme = themes.catalog.defaultChoice.preset; + const suffix = themes.fileSuffix ?? '.theme.json'; + + const update = (next: ThemeChoice, commit = true) => setChoice(next, commit).catch(error => notify(getError(error), true)); + const override = (patch: ThemeOverrides, commit = true) => { + const overrides: ThemeOverrides = { ...choice.overrides }; + for (const [key, value] of Object.entries(patch) as Array<[keyof ThemeOverrides, unknown]>) { + (overrides as Record)[key] = key === 'background' ? value : { ...(choice.overrides[key] as object | undefined), ...(value as object) }; + } + return update({ ...choice, overrides }, commit); + }; + const setRole = (role: FontRoleName, next: FontRole, commit = true) => + override({ font: { roles: { ...(choice.overrides.font?.roles ?? {}), [role]: next } } }, commit); + + function select(id: string) { + if (id === choice.preset) return; + // Customizations belong to the theme they were made on; switching starts clean. + void update({ ...choice, preset: id, overrides: {}, accent: null }); + } + function remove(theme: ThemeSpec) { + const themes = choice.themes.filter(item => item.id !== theme.id); + void update({ ...choice, themes, ...(choice.preset === theme.id ? { preset: siteTheme, overrides: {}, accent: null } : {}) }).then(() => notify(t('wb.appearance.removedTheme', { name: theme.name }))); + } + function add(theme: ThemeSpec, message: string) { + let id = theme.id; + for (let n = 2; all.some(item => item.id === id); n++) id = `${theme.id.slice(0, 36)}-${n}`; + void update({ ...choice, themes: [...choice.themes, { ...theme, id }], preset: id, overrides: {}, accent: null }).then(() => notify(message)); + } + function exportTheme() { + const custom = hasOverrides(choice); + const doc: ThemeSpec = { ...effective, ...(custom ? { id: slug(`${effective.name} custom`), name: t('wb.appearance.customName', { name: effective.name }) } : {}) }; + // `$schema` lets editors validate and complete the file; imports ignore it. + download(`${doc.id}${suffix}`, JSON.stringify({ $schema: THEME_SCHEMA_URL, ...doc }, null, 2)); + } + function saveAsNew() { + const name = t('wb.appearance.savedName', { name: base.name }); + add({ ...effective, id: slug(`${base.name} custom`), name, author: t('wb.appearance.you'), description: t('wb.appearance.basedOn', { name: base.name }) }, t('wb.appearance.saved', { name })); + } + /** An imported theme that names Google fonts asks before anything is downloaded. */ + function imported(theme: ThemeSpec, warnings: string[]) { + setImporting(false); + add(theme, `${t('wb.appearance.imported', { name: theme.name })}${warnings.length ? ` ${warnings.join(' ')}` : ''}`); + const families = missingFonts(theme); + if (families.length) setAsking({ theme, families }); + } + async function downloadFonts(families: string[]) { + setAsking(null); + const catalog = await loadCatalog(); + for (const family of families) { + const font = catalog.find(item => item.family === family); + try { + await installFont(family, font ? defaultWeights(font) : { kind: 'list', values: [400, 700] }); + notify(t('wb.appearance.downloadedFont', { family })); + } catch (error) { notify(`${family}: ${getError(error)}`, true); } + } + } + + const cornerValue = CORNERS.find(corner => corner.radius === effective.shape.radius && corner.button === effective.shape.button)?.value ?? null; + const timeline = effective.layout.cards ? 'cards' : effective.layout.frame ? 'framed' : 'flat'; + + async function pickImage(file: File | undefined) { + if (!file) return; + if (!/^image\/(png|jpeg|webp|gif|avif)$/.test(file.type)) { notify(t('wb.appearance.imageType'), true); return; } + const url = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(reader.error); reader.readAsDataURL(file); }); + if (url.length > MAX_IMAGE_CHARS) { notify(t('wb.appearance.imageTooLarge'), true); return; } + void override({ background: backgroundFor('image', effective, url) }); + } + + const searching = !!query; + return <> + {!searching &&
+ + + + }> + {importing && setImporting(false)} onImport={imported}/>} + {asking &&
+
+ {t('wb.appearance.askFontsTitle', { name: asking.theme.name, fonts: asking.families.join(', ') })} +

{t('wb.appearance.askFontsText', { count: asking.families.length })}

+
+
+
} +
+ {all.map(theme => { + const on = theme.id === choice.preset; + const isImported = choice.themes.some(item => item.id === theme.id); + return
+ + {isImported && } +
; + })} +
+
} + +
+ + + : undefined}> + + void update({ ...choice, accent })}/> + + + + + + formatPercent(v)} + onChange={v => void override({ font: { scale: v / 100 } }, false)} onCommit={v => void override({ font: { scale: v / 100 } })}/> + + + = 750 ? 800 : effective.font.bold >= 675 ? 700 : 600} + onChange={bold => void override({ font: { bold } })} options={[{ value: 600, label: t('wb.appearance.bold.medium') }, { value: 700, label: t('wb.appearance.bold.bold') }, { value: 800, label: t('wb.appearance.bold.heavy') }]}/> + + + { const corner = CORNERS.find(item => item.value === value)!; void override({ shape: { radius: corner.radius, button: corner.button } }); }} + options={CORNERS.map(corner => ({ value: corner.value, label: t(corner.label) }))}/> + + + void override({ shape: { avatar } })} + options={[{ value: 'circle', label: t('wb.appearance.avatars.circle') }, { value: 'rounded', label: t('wb.appearance.avatars.rounded') }, { value: 'square', label: t('wb.appearance.corners.square') }]}/> + + + void override({ layout: { density } })} + options={[{ value: 'compact', label: t('wb.appearance.density.compact') }, { value: 'default', label: t('wb.appearance.density.default') }, { value: 'comfortable', label: t('wb.appearance.density.roomy') }]}/> + + + void override({ layout: { cards: value === 'cards', frame: value === 'framed' } })} + options={[{ value: 'flat', label: t('wb.appearance.timeline.flat') }, { value: 'framed', label: t('wb.appearance.timeline.framed') }, { value: 'cards', label: t('wb.appearance.timeline.cards') }]}/> + + + t('wb.appearance.px', { value: v })} + onChange={column => void override({ layout: { column } }, false)} onCommit={column => void override({ layout: { column } })}/> + + + t('wb.appearance.px', { value: v })} + onChange={sidebar => void override({ layout: { sidebar } }, false)} onCommit={sidebar => void override({ layout: { sidebar } })}/> + + +
+ { void pickImage(event.target.files?.[0]); event.target.value = ''; }}/> +
+
+ {effective.background.kind === 'image' && + formatPercent(v)} + onChange={v => void override({ background: { ...(effective.background as Extract), dim: v / 100 } }, false)} + onCommit={v => void override({ background: { ...(effective.background as Extract), dim: v / 100 } })}/> + } + + void override({ effects: { motion } })} + options={[{ value: 0, label: t('wb.common.off') }, { value: 140, label: t('wb.appearance.motion.subtle') }, { value: 260, label: t('wb.appearance.motion.lively') }]}/> + + + void override({ effects: { hover } })} + options={[{ value: 'none', label: t('wb.appearance.hover.none') }, { value: 'tint', label: t('wb.appearance.hover.tint') }, { value: 'lift', label: t('wb.appearance.hover.lift') }, { value: 'glow', label: t('wb.appearance.bg.glow') }]}/> + + + void override({ effects: { crt } })}/> + + { void override({ css: { text } }); notify(t('wb.appearance.cssApplied', { name: base.name })); }}/> +
+ +
+ + void setScopes({ ...scopes, chrome: on ? 'theme' : 'own' }).catch(error => notify(getError(error), true))}/> + + + +
+ + + + ; +} + +/** Theme choices for a scope row: follow (the level above) plus every theme with its swatch. */ +function scopeOptions(follow: string): Array> { + // Called during render of components that use useT(), so the labels follow the language. + return [{ value: '', label: follow }, ...panelThemes().store.allThemes().map(theme => ({ value: theme.id, label: theme.name, icon: }))]; +} + +function AccountThemes({ notify }: { notify: Notify }) { + const t = useT(); + const { setScopes, themeName, themeState } = panelThemes().store; + const profiles = useProfiles(); + const { scopes, choice } = useThemeState(); + return +
+ {profiles.profiles.map(profile =>
+ {accountName(profile)}{scopes.profiles[profile.id] ? t('wb.appearance.ownTheme') : t('wb.appearance.followsApp', { name: themeName(choice.preset) })} + void setScopes(assign(themeState().scopes, 'panes', panel.id, id || null)).catch(error => notify(getError(error), true))}/> +
; + })} +
} +
; +} + +function DownloadedFonts({ notify }: { notify: Notify }) { + const t = useT(); + const { removeFont } = panelThemes().store; + const { fonts } = useThemeState(); + const query = useSettingsQuery(); + const title = t('wb.appearance.downloaded'); + if (query && !`downloaded fonts google fonts typeface remove storage ${title}`.toLowerCase().includes(query.toLowerCase().trim())) return null; + const total = fonts.reduce((sum, font) => sum + font.bytes, 0); + return
+ + {fonts.length > 0 &&
    + {fonts.map(font =>
  • + {font.family}
    {weightsLabel(font.weights)} · {bytesLabel(font.bytes)}
    + {formatDate(font.installedAt, { dateStyle: 'medium' })} + +
  • )} +
} +
+
; +} + +/** The selected theme's own CSS: travels with the theme (export, Save as theme); switching themes starts clean, like every customization. */ +function ThemeCssEditor({ css, onApply }: { css: string; onApply(text: string): void }) { + const t = useT(); + const [text, setText] = useState(css); + const query = useSettingsQuery(); + useEffect(() => setText(css), [css]); + const label = t('wb.appearance.themeCss'); + if (query && !`theme css stylesheet style code custom ${label}`.toLowerCase().includes(query.toLowerCase().trim())) return null; + const dirty = text !== css; + return +
+