Compare commits

..

72 commits

Author SHA1 Message Date
CRT
f6deac4145 DOM hub: open shadow roots of hosts a site names are part of the page
X renders its chat inside an open shadow root since 2026-10-01 (the XChatEmbed
host [data-testid=xchatEmbedRoute]); the hub's document observer saw nothing
of it, selector observers found nothing, feature sheets in <head> did not
reach it and probes could not see it.

A site adapter may name shadowHosts. The hub's one MutationObserver then also
observes each such root (picked up on the next page mutation, or a few timed
retries while a host has no root yet; dropped with the observer), selector
observers search the roots too, domRoots(win) gives features the roots, a
feature's ctx.css sheet is also adopted by each root (CSP-proof, updated in
place, taken off on stop), and probes count matches inside the roots.
Tests: hub observes and searches a root that appears later with one
observer; registry adopts and removes the sheet and a probe inside a root is
never a miss.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 05:02:01 +07:00
CRT
046994f804 Last words of the night in every catalog: Share my setup (wb.setup.*), icon pack import (wb.appearance.icons.*), translate mode (wb.strings.translate*) and the menu's Languages row
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 05:00:31 +07:00
CRT
7e7105b54c Theme doctor: advice on imported themes, never a block
themeDoctor(theme) names the lighter mechanism for what a theme's CSS does
(radius, bevel, hiding, literal colors, fonts), its performance costs (:has,
universal selectors, blur, size) and accessibility costs (outline removed,
unguarded motion, small post text, moved navigation), plus contrast fixes.
Theme import adds the count and the first hint to its message. Tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:56:33 +07:00
CRT
cd9917aad3 Icon pack import: the install screen gets the row's full width
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:54:37 +07:00
CRT
a890dd506f create-waybetter: a TypeScript plugin project depends on waybetter ^0.6.0 like the app scaffold (^0.2.0 could not resolve to the current package)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:52:37 +07:00
CRT
10d86ef55c App menu: a Languages… row (after Store) opens the panel's Languages section; it shows only when the app says its panel has one (features.strings); English word wb.menu.strings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:52:27 +07:00
CRT
fe7f60cd8d Share my setup, links: a waybetter://setup link opened from outside reaches the shell as text on the install-link event (shape and size checked natively, never decoded or applied there); the install controller hands it to the app's onSetupLink and stages nothing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:49:57 +07:00
CRT
a8710dfe02 Theme v2: import icon packs (install screen, packs in the theme choice)
Appearance > Icons gets Import icon pack: a *.icons.json file is parsed by the
runtime sanitizer and shown on an install screen (name, author, licence,
source, credits, every glyph, size, data only) before it joins the persisted
theme choice (packs, at most 8, validated natively for shape and size) and
the Icons picker. Imported packs can be removed again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:48:26 +07:00
CRT
d902d3f65a App menu: with no menu button in the titlebar, the tab strip reserves no room for it
With the logo as the menu's only titlebar trigger (`<AppMenu trigger={false}/>`), `--bt-tb-menu` still kept 38px free at the end of the titlebar-hosted tab strip. It is 0 when there is no `.bt-app-button`, so the right side is back to its layout before the menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:45:26 +07:00
CRT
1c7a842d09 Languages section: a pack's name and its badges on one line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:44:14 +07:00
CRT
44ea2d2060 Share my setup, panel: Backup & sync gets "Share my setup" (Copy link, Save file) and "Use a setup" (paste a waybetter://setup link or open a file, then What will change with Apply and Cancel); shown only for an app that sets PanelSite.setup; English words
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:43:24 +07:00
CRT
8005b2f047 README: the optional command groups the host serves and what the app supplies for each
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:42:07 +07:00
CRT
409949edb9 Host: the settings backup commands (collect, export, open, apply) are served for every app; SiteHooks::backup_drafts and backup_apply carry what only the app knows; commands::BACKUP, testkit::assert_backup_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:41:12 +07:00
CRT
198b1160f2 String packs: the site tab's delivery layer lives in app.rs, so a host without the net feature builds again (a generated app's cargo check failed on the net-gated store_commands module)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:40:25 +07:00
CRT
38b877f03a Share my setup, model: one file or one waybetter://setup link with the look (theme id, accent, icon pack), the mode and the non-default flags, nothing personal; reading drops what the app does not know and refuses another app's setup; the plan lists exactly what would change and applying it changes nothing else (not in the UI yet)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:38:30 +07:00
CRT
3402c1d85d Host: developer mode (dev_* commands and the watcher) is served for every app that sets AppConfig::with_dev; SiteHooks::dev_theme_apply and dev_theme_end carry the app's theme file; commands::DEV, testkit::assert_dev_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:32:54 +07:00
CRT
c83f541006 String packs, icon packs and install words in every catalog: wb.strings.*, wb.install.strings.*, license/credits, the strings install and error words, wb.appearance.icons*; dropHint and the two kind errors translated again for their new English
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:31:43 +07:00
CRT
311f5d9e20 App menu: one home in the titlebar, the logo
The top-right ⋮ and the logo opened the same menu: one of them was redundant.
The logo stays as the only titlebar trigger (the app's own mark, where an app
menu lives); the right side is back to workspaces, accounts and the window
buttons. Alt+F, F10, the palette and the account menu's last row open the
menu under the logo. Apps that want a separate button keep <AppMenu/>'s
default trigger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:26:40 +07:00
CRT
48ff509b15 Host: workspaces (always) and encrypted folder sync (AppConfig::with_sync) commands; SiteHooks::backup_sections and backup_section_names say what a backup and sync carry; commands::WORKSPACES, commands::SYNC, testkit::assert_sync_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:26:03 +07:00
CRT
385ca189da Docs: string packs as a Store kind (licence and credits on every item), the delivery to site tabs, the Languages section and translate mode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:26:02 +07:00
CRT
b4157d7eac String packs: translate mode. Strings carry an invisible key marker, a click on a word opens an editor that checks the edit with the pack rules, edits collect in the tab as a draft pack that applies after a reload, and "Copy pack file" gives the pack; the Languages section switches it on (the delivery then carries the whole inventory, packs or not); native code accepts such a delivery without packs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:25:04 +07:00
CRT
8a0ab6d3a1 Icon packs are the owner's pick: the theme choice carries it, Appearance offers it
- ThemeChoice gains an optional icons field (absent: follow the theme's pack; site: the site's
  own icons; else a pack id), validated natively as a slug (waybetter-host theme.rs, with a
  test) and kept by per-theme choices; variants is an override group natively too.
- Appearance: an Icons row (Follow the theme / the site's own icons / the site's packs) when the
  site lists packs; English words in the catalog.
- The chrome's glyphs follow the owner's pick as well as the theme's suggestion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:19:55 +07:00
CRT
e88339bda6 Host: native update commands (update_status, update_check, apply_update, app_ready) and the update loop are served for every app that sets AppConfig::with_updates; commands::UPDATE, testkit::assert_update_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:18:34 +07:00
CRT
1904031e6f String packs in the shell: the install screen shows a pack's language, coverage against the site's inventory (and what is ignored or cannot be replaced yet), a sample, that it is data only, and any item's licence and credits; the Store lists string packs under Languages and removes them; the Languages section turns packs on and off, orders and removes them and hands the site tabs the new delivery; English words (wb.strings.*, wb.install.strings.*, wb.install.license/credits and the strings variants)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:14:41 +07:00
CRT
825742b964 Repair: the Google Fonts host commands as 7f9e172 meant them (a staging race split them from 43fc8a1)
Two agents staged the same host files at once: 7f9e172 went in with the diagnostics' hunks of app.rs, commands.rs and lib.rs instead of its own, and 43fc8a1 then dropped fonts_commands.rs. This puts back exactly the Google Fonts wiring from the working tree (AppConfig::with_fonts, SiteHooks::fonts_changed, commands::GFONTS, the fonts handler, fonts_commands.rs); the diagnostics stay as committed. theme.rs, still in progress, is not included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:12:43 +07:00
CRT
43fc8a15f5 Diagnostics for focus and layering (--diag / WAYBETTER_DIAG=1): one timestamped line per event in the app's log folder
For the macOS reports (the menu never shows and the window goes inactive on a click; the find field gets no keyboard): off unless the app is started with `--diag` or WAYBETTER_DIAG=1. Then native code and the shell append to `diag.log` in the app's log folder (truncated at launch): menu open requests and every close with its reason, overlay counts, raise/lower and `shell_raise` results, native `shell_focus` calls and their result, the shell document's focus/blur/visibility, and where the find bar's focus is right after it opens and 300 ms later. A line is an event and a few words in plain ASCII (capped); never a URL, a query or page text. `diag_get` / `diag_log` are shell-only (in commands::SHELL and the template's list).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:11:53 +07:00
CRT
7f9e172196 Host: Google Fonts commands (gfonts_*) are served for every app that sets AppConfig::with_fonts; SiteHooks::fonts_changed; commands::GFONTS, testkit::assert_fonts_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:11:46 +07:00
CRT
da9ac11b24 Shell: the chrome's own glyphs follow the theme's icon pack
A site's theme adapter may name the pack of the global theme (iconPack); the frame's Icon draws
that pack's glyph for the same meaning (home, search, bell, mail, bookmark, user, ...) from its
validated path data, and its own line glyph where the pack has none. Rendered as React SVG
elements, never markup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:07:49 +07:00
CRT
873f8561ca Host: the media panel's commands (gallery folders, previews, the clipboard history and its watcher) are served for every app that sets AppConfig::with_media; commands::MEDIA, media_commands::gallery_file/clip_image for an app's attach command, testkit::assert_media_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 04:02:35 +07:00
CRT
419f60b5b1 Store kind "strings": string packs install like themes and plugins (dropped .strings.json, links, the signed Store), validated as plain data on this side (envelope, plain text, size caps, the app's own site), kept in app data strings/ with their order and which are on (at most 8); licence and credits are optional fields of every catalog item; five shell-only commands (strings_list, strings_read, strings_set, strings_remove, strings_apply); the shell's delivery (packs + the inventory slice) goes into site tabs' session storage by revision, as the first document-start layer of a site tab and never in safe mode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:56:54 +07:00
CRT
8e9442c2fc Report a problem: the webview's full version (the user agent carries a reduced one)
Seen live: the report said "WebView2 154.0.0.0", Chromium's reduced user agent version. The engine's brand list (`fullVersionList`) gives the full one, which the report now uses when it is a plain version (tested).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:56:18 +07:00
CRT
8eb9dba4d7 App menu and mode words in every catalog: find in page, update check, safe mode, report a problem, Custom/Re-apply
menuMessages.en.json stays the English source of the menu's words; en.json now carries them too
(the i18n test takes them into the source union) and 48 catalogs translate all 51 menu words and
the seven new mode words (plural forms per language for the match count).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:50:45 +07:00
CRT
92b9d1d9fc Remote builds: list the output with numeric owners, so a build log never shows the machine's account name
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:48:16 +07:00
CRT
5211995694 Find in page: WebView2 counts its active match from 1; the shell's index is 0-based
Seen live on the shared app: "domain" on example.com showed "2/2" for the first of two matches, and "2 matches" after Next. `ICoreWebView2Find::ActiveMatchIndex` starts at 1 (-1: none); `FindState::from_webview2` converts it (tested), so the bar reads 1/2, then 2/2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:47:23 +07:00
CRT
3450eac09a Host: the store's commands (install links, dropped files, the signed Store, the install screen) are served for every app that sets AppConfig::with_store; commands::STORE, testkit::assert_shell_only_group and assert_store_guards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:40:37 +07:00
CRT
06e830b132 Startup cover never outlasts a page that does not say it painted; menu clicks ask nothing native; mode cards show their picture
Release blocker (macOS 1.0.0: both panes stayed on the shell's loading shape). After `shell_ready` the startup cover waited, with no limit, for every visible site tab to report that it painted. A page whose report never comes (its paint check is frame-driven and gives up after 10 s, and an engine may hold a hidden window's frames back) kept the shell raised over the panes, showing the skeleton, for good. The wait is now bounded (8 s after the window is shown); the page then shows as it is.

The app menu asked for the keyboard natively (`shell_focus`) on every open. It now does so only when the shell does not have it (keys pressed in a tab); a click on the shell already gave it the keyboard.

The mode cards' default picture was shrunk to 16px by the shell's base glyph rule ("a few dots"); it keeps its size.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:40:02 +07:00
CRT
2e3babd2f5 Plugin API: a style injected at document start waits for the document root
WebView2 runs document-start scripts before the document has an element, so
injectCSS threw ("reading 'appendChild'") for every CSS feature that was on at
start, e.g. hiding promoted posts, until the next flags delivery restarted it.
Such styles now wait (one MutationObserver for all of them), are attached as
soon as the document has a root, and get their CSP check then; a style cleared
while waiting is never attached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:39:16 +07:00
CRT
26658e14ae Modes: a mode that no longer matches the features reads "Custom (based on <mode>)" and offers "Re-apply <mode>"
A mode is a starting point, never a lock and never applied again on its own. modeStatus() (runtime)
compares the flags with the mode's preset: custom, what re-applying turns on and off, and which of
those the preset gained in an update since it was applied. mode_set keeps the preset of that moment
(modes.json "preset", flag names only, bounded; forgotten when the mode changes). Settings, the
first-run screen and the app menu's Mode row show Custom; Re-apply lists what it turns on and off
before it writes anything; a preset that grew is mentioned once on the mode row (Review), never applied.
Tests: exact match, changed by the owner, preset grew, choice made before the preset was kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:33:41 +07:00
CRT
b75246bef8 String packs: a page gets only the slice of the inventory its packs' keys need (sliceInventory, isPageInventory); a slice does not call other keys new
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 03:30:21 +07:00
CRT
eb2bc62ad4 Find in a deck column; the app menu no longer closes on a passing blur
Ctrl+F pressed in a deck column (or in the shell while a deck is in front, for its focused column) opens that column's own find bar, laid over the column's header; F3 and Shift+F3 step through it. Same bar, same `tab_find`.

The app menu closed on any window blur. Taking the keyboard from a focused tab (Alt+F / F10 forwarded by the tab, then `shell_focus`) can pass through a blur on its way to the shell, which closed the menu a few milliseconds after it opened. It now closes on blur only if the focus is still away a moment later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:35:58 +07:00
CRT
1356d9364a release macos|linux: --commit <ref> builds an exact commit (its submodule pointers included), the artifact version comes from that commit
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:33:11 +07:00
CRT
0c6b1454d9 Remote builds: the updater tarball carries no account name in its entry headers (owner 0/root); the scan caught it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:31:26 +07:00
CRT
006a7d160c Theme runtime: a static sheet for what does not depend on the site's stylesheet (components, variants, decoration, icons); refresh()
The site adapter's staticCss(choice, mode) is written to its own <style> (wb-theme-static), rebuilt
only when the theme or the site's mode changes or on refresh(); the palette pass never reads it back
as the site's rules, and the first-frame snapshot carries it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:30:34 +07:00
CRT
7469f0e4af waybetter manifests: winget, Chocolatey, Homebrew cask and AUR files from one JSON description
Generic (publisher, id, name, version, installer URLs and sha256 or local files, silent switches, licence, homepage). winget: version, installer and locale manifests (validated with the installed winget), Chocolatey: nuspec + install script with checksum (choco pack), Homebrew: a cask for our own tap, AUR: PKGBUILD and .SRCINFO from the .deb or AppImage. waybetter release windows|macos|linux writes them to <outDir>/distribution/<version> once the public download URL is given (--download-base); nothing is submitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:28:44 +07:00
CRT
5a7aae7adb Remote builds: unpack with the current time (cargo must not reuse stale objects from a cached target), export blobs as committed, build at low priority
git archive stamps files with the commit time, older than the cached build in the shared target dir: a changed source looked unchanged and the build reused stale objects (seen as a missing module after a pointer bump).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:26:19 +07:00
CRT
7c683598a4 Report a problem: a diagnostic summary with no personal data, shown as it would be shared, with Copy and the issue page
The app menu's "Report a problem…" opens a small dialog with the summary (reportModel.ts, English on purpose: the people who read reports do): the app and framework versions, the system and webview (coarse, from the user agent), the language and how it was chosen, the mode, the theme and icon pack ids, the file names of the plugins that are on, what paused itself (the panel's `reportDetails`), and safe mode. The model has no field for an account, a handle, an address, a tab or a path, and a value that is not made of id characters is left out rather than trimmed into shape, so nothing of that kind can ride along (tested with hostile input). The dialog sends nothing: Copy puts the text on the clipboard, and "Open the issue page" opens `ShellSite.menu.report.issueUrl` bare in the system browser (the summary is never put in a URL). Without an issue page the button is off and the dialog says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:25:13 +07:00
CRT
1b0a489b36 waybetter release: builds of the committed state on a Mac over SSH and in WSL
release macos --remote and release linux --wsl export HEAD plus each submodule at its recorded commit (git archive, never the working tree, nothing fetched from origin), build it path-free through build-env with unsigned bundles, bring the artifacts back and scan them here. release linux --appimage/--deb signs the AppImage (the Linux update payload) on the release machine and adds linux-x86_64 to latest.json. The remote script is low priority, never installs, quits or replaces an app on the Mac. Config: prepareCommand, exportExclude.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:24:04 +07:00
CRT
f8144a3bff Windows installer: an install made under the app's old name is older than any setup of the renamed app, whatever its version number (upgrade in place, data kept)
The renamed app may start its numbering again. Told apart by DisplayName in the uninstall key
(the old app wrote its old name there; this template writes the new one). Also exempt from the
silent-downgrade abort. Compiled with and without a legacy name and run on the test variant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:23:43 +07:00
CRT
16957f4ea7 Theme engine v2, the document side: component tokens, layout variants, decoration, icon packs
A theme may now say how each piece of a site is built, not only one radius and one density:
- components (themeComponents.ts): 36 generic parts with clamped tokens (radius, border incl.
  98.css-style bevels, fill by color role / glass / gradient, padding, sizes, type, shadow, shape,
  hover/active/focus), presets and parents; compiled over a site's part map as soft values
  (--wb-part-*) and rigid rules; text on a chosen fill keeps its contrast.
- variants (themeVariants.ts): fixed words on six axes; the owner holds an axis or switches layout
  changes off; the look of a variant is the site's skin.
- decoration (themeDecor.ts): dividers, chrome (title bar, masthead, prompt), a focus ring that is
  always visible, selection, scrollbars, links, motion under reduced-motion.
- icon packs (themeIcons.ts): a standalone document of glyphs by semantic name (path data, colored
  layers or a small PNG, never an SVG document), with license, source and credits; a theme only
  names a pack; the owner's icon choice is separate; drawn as CSS masks of the current color over
  the site's own svg boxes, behind forced-colors and mask-support guards, per group.
- a theme document gains the optional groups components, variants, decor, icons and
  colors.actions; a theme without them is sanitized to exactly what it was.
- theme.schema.json and the new icons.schema.json are generated from the same tables
  (scripts/theme-schema.mjs; a test fails when they are stale).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:22:36 +07:00
CRT
593ce46bd7 READMEs for strangers: overview, three layers, a real minimal adapter, security model; the long reference moves to docs/ARCHITECTURE.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:20:58 +07:00
CRT
ca46210e53 Safe mode: one run with only the shell working (the app menu, --safe-mode, Shift at launch on Windows)
Host: `safe.rs` is a flag in this process's memory, never written to disk, so the next normal start is back to the owner's setup. While it is on a site tab gets the tab bridge and nothing of the app's page layers: its document-start scripts are `SiteHooks::safe_init_scripts` (default: the bridge alone) instead of `init_scripts`; `site_page_loaded`, `tab_placed` and `tab_background` are not called; `page_scripts` is empty; `eval_in_site_tabs` does nothing. So no page runtime, plugins, theme, custom CSS, feature flags, fixes, hotfix data or words reach a page: the site runs as in a browser, and only the shell is the app's. It starts from the launch argument `--safe-mode` (for when the interface itself is broken), from Shift held while the app starts (Windows), or from the shell: `safe_mode_get` / `safe_mode_set {on}` (shell-only), where a switch rebuilds every tab webview (profiles marked stale, `tabs-rebuild` asks the shell for its layout) so document-start scripts change too. Tests: the argument, the flag, and that app.rs and host.rs gate every layer.

Frame: the app menu's "Restart in safe mode…" says what it does before anything reloads; while on, the titlebar shows an amber "Safe mode | Leave" chip (one click leaves) and the row reads "Leave safe mode"; the chrome drops its theme (and pane themes) and takes it back on leaving, without touching the first-frame cache. `features.safeMode` (on by default).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:13:03 +07:00
CRT
d24b1d2234 Words: the deck is "Deck" (it was "Power User Mode", which collided with the Power User mode); the three feature-health words in all 48 translated languages (machine)
Keys and saved data unchanged. Each language reuses its own word for a deck; only "Deck settings"
is newly translated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 23:05:23 +07:00
CRT
16d89de712 Theme color model: a foreground the site paints dimmer than its secondary text becomes the theme's secondary text
A site may color an icon or text with one of its border grays (X's composer toolbar: 1.7:1 on its
own black). Placed by axis position it landed between a theme's background and its secondary
text, under every contrast a theme guarantees. In text usage that stretch of the axis (above the
most raised surface, below secondary text) now maps to the theme's secondary text; surface-dark
foregrounds (labels on a filled surface), borders and backgrounds are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:58:48 +07:00
CRT
2f126659f9 App menu: "Check for updates" is a real check, once, now, and says what came of it calmly
Host: `updater::check_now` runs the same check the timer runs (the same updater endpoint, nothing else) for the app's shell-only `update_check`. It never queues or retries: while a check is in flight (the timer's or an earlier request's), or within 10 seconds of the last request, it only answers with the current status (`update::may_check_now`, tested). The timer's loop uses the same single-flight guard.

Frame: the menu's Updates row is that check (`updateRow`, tested): "Checking…", "Up to date · <version>", "Downloading <version>…", "Restart to update" when an update is ready (the row then installs it), and "Could not check" with a plain sentence as its tooltip when the server does not answer. The updater's error text is never shown there, and a failure is only mentioned when the owner asked for the check in this menu; the timer's own failures stay quiet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:54:51 +07:00
CRT
c7437ac504 String packs, phase 1: data-only packs that replace the wrapped site's own UI strings. Pack and inventory formats, validator (only inventory keys, parameter names, plural and select kinds, no markup), ordered idempotent engine that keeps what a restore needs, coverage and drift report; the per-site catalog hook adapter with a self-check (ok, hook not matched, no catalog seen), a fail-open webpack chunk array hook, a small DOM text net; waybetter strings check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:38:07 +07:00
CRT
b31fa6b1d2 Find in page: the shell's find bar per pane (Ctrl+F, the app menu, the palette) over the engine's own find
Host: `tab_find {id, action, query}` (shell-only; start, next, previous, stop). On Windows it drives WebView2's own find (`ICoreWebView2Find` from `ICoreWebView2_28`, find options from `ICoreWebView2Environment15`; its built-in find bar suppressed, all matches highlighted) and reports the engine's match count and active match to the shell as `tab-find` events. On macOS, Linux and an older WebView2 Runtime native code evaluates the engine's `window.find` in the tab instead (next and previous work, no count); WKWebView's and WebKitGTK's native find are not wired here because this tree cannot be compiled or run for them on this machine. The query is one typed line (1..=256 characters, no control characters), goes to the engine and is kept nowhere. Tabs gain no command: a tab forwards the existing key name `find` (Ctrl+F) through tab_shortcut.

Frame: FindBar.tsx takes the address field's place in its pane's toolbar while open, so the page does not move and in split view the bar is the searched pane's. "3/17" where the engine counts, "No matches" for none; Enter / F3 next, Shift+Enter / Shift+F3 previous, Esc closes, clears the highlights and gives the page the keyboard. `features.find` (on by default) gates the menu row, the palette entry and the keys. Only what the page has rendered can be found, as in a browser.

Also: this makes `pub mod find` in lib.rs (already in HEAD) resolve again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:34:48 +07:00
CRT
832396801c README: Dev loop section
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:32:38 +07:00
CRT
098b985bce devloop guard test: skip its own module
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:21:41 +07:00
CRT
e84470a95d Dev loop: debug-only page scripts from disk + tab rebuild on change (waybetter-host devloop, page_script!), generic devmode watcher, waybetter dev, buildRuntime watch, template scripts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:20:22 +07:00
CRT
9d9f0ab10a App menu: the titlebar logo opens it too, hung under the logo on its side of the window
The logo at the start of the titlebar is now a button (aria-haspopup, keyboard reachable, tooltip) and a second trigger of the same menu: same component and model, only the anchor differs (`openAppMenu({ anchor: 'logo' })`). A submenu opens toward the middle of the window, else on the other side, else over the menu (`submenuLeft`, tested). A click on the logo never starts a window drag; a press that moves more than 5px does (the window's `startDragging`), so the logo still moves the window like the titlebar around it. A right-click shows the window's system menu. Clear of the macOS traffic lights: the logo sits after the titlebar's 78px inset and the menu hangs below it. The button at the end and the account menu's row stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:15:09 +07:00
CRT
632ba863c9 Feature health on the area cards: a feature that paused itself is named by its area's "health" palette entry, and the panel reads it for the row and the card (no new report to the host)
The entry opens the notes in the page; its keywords carry the paused flags of that area. English
for the three new words; the other catalogs follow with the words step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 22:00:04 +07:00
CRT
e5d43afffc App menu: the titlebar's "Settings and more" (Alt+F, F10, the palette, the account menu's last row) with rows from the site config; page zoom per tab in the host
Frame: AppMenu.tsx is a menu at the end of the titlebar cluster (before the caption buttons; macOS has none there). Its rows are `ShellSite.menu`: ordered groups of built-in rows by name and the app's own ({id, label, icon, shortcut, hint, when, checked, run | submenu}); `DEFAULT_MENU`, `menuWith` and `menuWithout` order, add and remove. A built-in row shows only when the app serves it (decks, `menu.languages`, themes, `menu.modes`, and `features`: zoom, store, workspaces, developer, updates), so no app gets a dead row. Language, Theme, Mode, Workspaces and Developer are submenus; Language and Theme apply live and keep the menu open, Mode asks the same keep-my-changes question as Settings (panel `menuModes()`). Keyboard: arrows, Home/End, type-ahead, the arrow along the reading direction opens a submenu, Esc closes one level; ARIA menu roles; submenus stay inside the window; one highlight for pointer and keys. It is an overlay like the other shell menus (the shell is raised, panes stay visible, nothing is dimmed).

Words: menuMessages.en.json (`wb.menu.*`), read through the framework i18n with that English as the fallback until the catalogs have them; words the panel already has are reused.

Host: `tab_zoom {id, factor}` (shell-only) sets a tab's page zoom with the engine's own zoom, clamped to 25%..500% and remembered per tab id in app data `zoom.json` (a number per tab id, nothing else; a closed tab's entry goes); without a factor it reads. A tab may forward four more shortcut names: `app-menu`, `zoom-in`, `zoom-out`, `zoom-reset`. The titlebar shows a zoom chip only while the pane in front is not at 100%.

create-waybetter: `tab_zoom` in the shell capability list; the template says which panel sections it lacks (store, updates) and how to add menu rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:52:51 +07:00
CRT
eed6bdd8f4 Route listeners: one removed by an earlier listener in the same round is not called (a feature stopped by the route re-added its stylesheet); the route poll never keeps a test process alive
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:19:02 +07:00
CRT
86eacd173e Panel: a long section name wraps left-aligned in the side rail instead of centring
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:19:00 +07:00
CRT
30a004b93b Theme engine: a rule is read as it takes effect (a Tailwind opacity utility's nested @supports value, not its solid fallback); unsupported @supports groups are left out; reach() is exported for site adapters
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:04:12 +07:00
CRT
046f409d23 Feature modules: a feature ported from a plugin keeps that plugin's words (words), so nothing is retranslated; the keep-my-changes question takes its own line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:53:11 +07:00
CRT
2d596c9771 Locales: the area cards, the Fixes list, modes and the feature settings words in all 48 translated languages (machine)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:37:56 +07:00
CRT
381d55466b Feature modules in a new app, i18n rename, and what the first area port needed
- create-waybetter: the generated app has a feature table (one area, one feature, three modes), a feature module, the registry in its runtime, the cards and the first-run screen in its panel
- waybetter i18n rename --map <file> [--copy]: keys move or are copied in every catalog with each language's own value
- feature context: win (no globals in a module), text() for a feature's words (t('...') is read as a whole catalog key by the i18n tools)
- probes: `when` (only counts while the part of the page it lives in is there)
- cards: a caret, an empty area says its features come later; the first-run screen takes the whole panel

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:25:15 +07:00
CRT
dc7d6f815a Panel: area plugin cards with per-feature toggles, the Fixes list, modes (first-run screen and Settings)
- PanelSite.features: the app's feature table; AreaPlugins draws one card per area (switch, count, grouped features, Settings button that runs the area's command in the site tab) and the core flags as Fixes
- a feature still backed by an old plugin file is switched through plugin_set_enabled from its card and left out of the JavaScript plugins list
- Modes: Onboarding (three cards, recommended preselected; an existing setup may be kept) and ModeSettings with the keep-my-changes question; openOnboardingWhenDue for ShellSite.start
- flags are saved sparsely (only what differs from the table's defaults)
- PanelSite.appearance.extra; palette commands of an area are listed under its name
- the kit's words for feature settings and health notes; English in the framework catalog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:34:14 +07:00
CRT
e7e744f66d Host: 256 feature flags, the onboarding mode (mode_get/mode_set, shell-only), and the one-time move of replaced plugin files to feature flags
- settings: MAX_FEATURES 64 -> 256 (an older app's whole-map backup still validates)
- modes: ModeState {mode, onboarded, existing} in modes.json; existing is decided natively on the first start
- plugins::migrate: PluginHost.superseded (file -> flag); enabled and as shipped -> flag on and the file goes; edited -> kept, flag left off; marker written last, every step repeatable; map_backup for imported enabled lists
- a superseded file is never written again by install_bundled
- create-waybetter: the host command list and PluginHost.superseded

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:34:13 +07:00
CRT
ca9eec05ab Feature modules: a feature table (areas, flags, modes), a registry that runs a module only on its surfaces, one shared observer for every feature and plugin, settings from a schema, selector health with self-pause
- featureTable.ts: areas, per-feature flags, core flags, modes as presets; sparse storage, ownership (an area that is off turns off what it owns), mode switching that keeps or drops manual changes, table validation
- featureModules.ts: createFeatureRegistry (flag + surface gating, scoped context, palette commands under the area with a budget of 5, settings dialog, probes, hotfix selector overrides and kill flags)
- settingsForm.ts: a settings schema normalizes stored values and draws the controls from the UI kit
- domHub observeSelector; api.observe goes through the shared hub (a root of the caller's own keeps its observer)
- createFeatureFlags: a delivery is the whole state (a flag it does not name is at its default), resolve() for ownership, current()

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 18:11:42 +07:00
CRT
748be340a8 build-env: MSVC C and C++ lose the build paths too (/d1trimfile in CL, /PDBALTPATH in LINK)
A library a build script compiles with MSVC (CMake, the cc crate) kept its
absolute source paths through __FILE__: -ffile-prefix-map exists only on gcc
and clang. cl.exe and link.exe read CL and LINK themselves, so the roots are
trimmed whatever runs the compiler. Longest root first: the first match wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:48:27 +07:00
208 changed files with 31298 additions and 1307 deletions

631
README.md
View file

@ -1,290 +1,56 @@
# waybetter
The framework behind the wayBetter apps: apps that extend the apps you already use in place, the
way BetterDiscord extends Discord. The first app is **wayBetter for X**; more are being built on
the same core.
```sh
npm install waybetter
```
[npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi)
A wayBetter app is one native window (Tauri 2, multiwebview) with:
- a trusted local **shell** webview: tab strip, split panes (dockview), address bar, titlebar and
window controls, command palette, account switcher, the app's own settings;
- one native child webview per browser **tab**, positioned over the pane rectangles the shell
reports (`tabs_sync`), each in an account **profile** with its own WebView data directory;
- a **page runtime** injected into tabs that are on the app's site: shared DOM/request hubs,
plugins, themes, split-view rail hiding, link routing and account reporting.
This repository holds the parts that do not depend on which site the app extends. An app is mostly
a **site adapter** plus its own features.
## One system for every app
Every wayBetter app is the same system: the Tauri window above (shell + page runtime) plus one
small adapter. That holds for websites like x.com and just as much for services that ship their
own Electron desktop client, such as WhatsApp or Discord: wayBetter runs their web app in its own
light Tauri window instead of the heavy client, and gives it the same tabs, split panes, real
accounts side by side, themes, plugins and signed updates. There is no second kind of host.
A framework for desktop apps that run one website (or a web app you would otherwise use through a
heavy Electron client) in a small native window and extend it in place, the way BetterDiscord
extends Discord. You get tabs, split panes, several signed-in accounts side by side, themes,
plugins, a signed store for them, backups and updates. You write a small adapter that says what
the site is.
The first app built on it is [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x).
License: GPL-3.0-or-later.
## Projects using wayBetter
| Project | Target | What it is |
| --- | --- | --- |
| [wayBetter for X](https://waybetter.fyi/x/) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. |
Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does.
## Build your own
```sh
npm create waybetter plugin # a *.plugin.js (or --ts: a TypeScript project) on the real plugin API
npm create waybetter theme # a theme JSON with "$schema", a derived palette and font roles
npm create waybetter app -- --site kick.com # a whole app: Tauri 2 + waybetter-host + runtime + shell
npm install waybetter # page runtime, shell, CLI tools
npm create waybetter # scaffold a plugin, a theme or a whole app
```
`create-waybetter` (in `packages/create-waybetter`) asks for what it needs in a terminal, and
takes every answer as a flag (`--help`). The app skeleton is this README in code: the native
`SiteSpec`, the page `SiteAdapter`, the app on `waybetter_host::app` (its config, site hooks and
its own commands), the three capability files and a `tests/security.rs` on `waybetter_host::testkit`,
the shell (the framework's shell frame through `createShell`, with the site's pages and a plugins
panel), the plugin store, one site-only command, the
runtime bundled with `waybetter/build` and a `waybetter.release.json` for `waybetter release`, with presets for
youtube.com, kick.com and twitch.tv and every site selector marked as a placeholder. Its tests
generate each kind into a temp folder and check it against the real contracts: plugin headers with
`plugins::parse_meta`, plugin code against `createCorePluginApi`'s members, themes against
`theme.schema.json`, the app's TypeScript with `tsc` against the built package and its Rust with
`cargo check`/`cargo test` against this crate.
Links: [source](https://git.crt.fyi/CRT/waybetter) · [npm](https://www.npmjs.com/package/waybetter) · [waybetter.fyi](https://waybetter.fyi)
## Layout
## The three layers
```
crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads,
and the generic native features every app gets (below)
tab-bridge.js the tab bridge every tab gets (served by src/bridge.rs)
src/site.rs SiteSpec + AccountRules (the native half of the adapter)
src/policy.rs webview labels, origin checks, tab rect clamp
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,
deck ColumnConfig bounds and unread caps
src/bridge.rs the tab bridge script (reports; shortcut/link-drag forwarding opt-in)
src/backup.rs settings backup envelope, secret scrubbing, plugin/account sections
src/sync.rs encrypted folder sync (Argon2id + XChaCha20-Poly1305 snapshots)
src/workspaces.rs saved tab/pane/deck layouts, bounded and well-formed
src/devmode.rs developer mode: debounced file watcher, reload order, error positions
src/alerts.rs keyword alerts: keywords, snippets, rate limits; native notifications
src/media.rs gallery folders (path containment), clipboard history, PNG encoding
src/media/clipboard.rs (feature "tauri") opt-in clipboard polling, private copies skipped
src/gfonts.rs self-hosted Google Fonts: CSS parsing, URL/woff2 checks, cache format
src/fonts.rs (feature "net") font downloads and the font cache
src/updater.rs (features "tauri" + "net") signed native updates and the hotfix channel
src/store/ install links, download allow-list, signed multi-app store catalog, staging
and installs; downloads with feature "net" (docs/STORE.md)
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)
site.ts SiteAdapter (the page half of the adapter) + configureRuntime
domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page
pluginApi.ts core of window.<Runtime>.api for plugins (incl. ui and theme)
ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed)
themeApi.ts the active theme as values + --wb-* CSS variables (api.theme)
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
paneNav.ts split view: park the site's navigation rail in redundant panes
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
deckModel.ts decks of site columns: bounded storage model, paging layout, focus
linkDrop.ts dropping links into the dock
profileModel.ts profiles and account labels
palette.ts command palette scoring/ranking
updateModel.ts titlebar update chip
windowControls.ts caption buttons, resize grips, system menu (Tauri API injected)
chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs)
storeModel.ts storeMessages.ts Store wire types, item states, permission words; wb.store/install/permission.*
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`,
`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)
```
A wayBetter app is one Tauri 2 window with several webviews. The framework has one piece for each
layer and does not need to know which site you wrap.
Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime
dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type
stripping. Anything that needs the Tauri API (window controls, the shell frame) takes it as a
parameter. The React parts (the Store screens, the shell frame) have React, and the frame dockview,
as optional peers: the app's copies are used.
| Layer | Where | What it does |
| --- | --- | --- |
| Native host | `crates/waybetter-host` (Rust) | Builds the window, the trusted `shell` webview and one child webview per tab, keeps profiles (each with its own WebView data folder), the plugin store, settings, backups, encrypted sync, updates, fonts, the store install rules, and decides which webview may call which command. |
| Page runtime | `packages/runtime` (TypeScript, no dependencies) | Injected into tabs that are on the site's exact origin: one DOM hub and one fetch/XHR hub, the plugin API and its themed UI kit, the theme engine, split-view navigation, link routing, account reporting, deck columns, string packs. |
| Shell | `packages/shell` (TypeScript and React) | The local UI around the tabs: `createShell(site)` gives tabs in the titlebar, split panes, address bar, command palette, account switcher, decks and workspaces; `createPanel(site)` gives the app's own settings tab (appearance, theme builder, plugins, store, backup, developer mode). |
## The shell frame
Both TypeScript packages ship as the npm package `waybetter` (plain ESM with `.d.ts`). The Rust
crate is used from source, as a git submodule or a path dependency. Details of every module are in
[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
`packages/shell/src/frame` (`waybetter/shell/frame`) is the whole shell of a wayBetter app. An app
describes its site and gets tabs in the titlebar row, split panes and link drags into the dock, the
smart address bar, the new-tab page, the command palette, the account switcher, decks of site
columns, workspaces, the developer-mode and sync chips, the gallery/clipboard panel, pane themes,
its own panel tab, keyboard shortcuts, overlays that raise the shell above the tab webviews, the
one-layout-in-flight `tabs_sync` and session restore:
## A minimal adapter
```tsx
import { invoke } from '@tauri-apps/api/core'; // or window.__TAURI__ (withGlobalTauri)
import { listen } from '@tauri-apps/api/event';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { createShell, type ShellSite } from 'waybetter/shell/frame';
An adapter is three small things. This is what `npm create waybetter app` writes for `kick.com`
(selectors are placeholders you replace after looking at the real site).
const site: ShellSite = { name: 'Kick', product: 'wayBetter for Kick', homeUrl, loginUrl, logoutUrl,
isSiteUrl, accounts, searchUrl, address, panel: { id, title, component }, newTab, palette,
deck, media, themes, overlays, features, start };
const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n });
createRoot(root).render(<Shell/>);
```
What the site supplies (`frame/site.ts`, every field documented there):
- names and pages: `name` (in messages as `{site}`), `product`, `logo`, `homeUrl`, `loginUrl`,
`logoutUrl`, `isSiteUrl`, the account rules, `searchUrl` for typed text;
- the address bar: `address(url)` (chips, usually `parseAddress` with an `AddressSite`) and an
optional `addressCompleter` (inline completions, e.g. search operators);
- slots: `panel` (the app's own tab and its sections), `newTab` (search label, quick links),
`palette` (placeholder, the literal search, completions, the panel's sections, the site's pages),
`deck` (column kinds with labels and icons, the page each loads, titles, value parsing and
completions, column flags and presets, an optional compose dock), `media` (which pages have a
composer), `themes` (a `createThemeStore(adapter)`: the app's theme documents, chrome colors via
`chromeVars`, pane themes), `overlays` (the app's own dialogs), `start()` (read site settings,
call `siteChanged()` when site text changes);
- `features`: the native features the app wires up (workspaces, sync, developer mode, plugin
palette commands); an app without them shows nothing of them.
The frame's words are `wb.*` messages in the framework catalogs (51 languages; English source in
`frame/frameMessages.ts`): the app passes its i18n instance with the framework catalogs merged in.
Styles come with the components (dockview's, then `shell.css`, `deck.css`, `workspaces.css`,
`accountSwitcher.css`, `paneTheme.css`); colors are `--wb-c-*` tokens with Night Ink fallbacks,
set by the theme store (the chrome and each pane group) and cached for the first frame:
`bootScript()` (`frame/boot.ts`) is the `boot.js` an app serves before its modules (a Vite plugin or
a build step writes it). `installPreviewMocks(handlers)` answers native commands from memory, so
the real shell renders in a plain browser for development previews and screenshots.
Native commands the frame calls: the host's (`tabs_sync`, `tab_navigate`, `tab_action`,
`shell_focus`, `shell_raise`, `open_external_url`, `window_system_menu`, `profiles_*`), and for the
features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sync_*`, `dev_*`,
`plugins_list`, `tab_run_command`, `media_get`/`gallery_*`/`clip_*`/`tab_attach_image`/
`tab_insert_text`, `theme_scopes_*` and `gfonts_*`, `app_ready`/`update_status`/`apply_update`. It
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.<flag>.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.<file>.name|description` (its bundled plugins),
`theme.<id>.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.
### 1. Native: `SiteSpec` (Rust)
**1. Native: which webviews are site tabs, and what an account looks like** (`src-tauri/src/site.rs`)
```rust
use waybetter_host::site::{AccountRules, SiteSpec};
fn kick_handle(value: &str) -> bool {
(3..=25).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
pub fn valid_handle(handle: &str) -> bool {
(3..=25).contains(&handle.len()) && handle.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
pub static SITE: SiteSpec = SiteSpec {
product: "wayBetter for Kick",
hosts: &["kick.com"], // exact https origin(s) of site tabs
runtime_global: "WayBetterKick", // window.<global> of the page runtime
hosts: &["kick.com"], // exact https origin(s): the only definition of a site tab
runtime_global: "WayBetterForKick", // window.<global> of the page runtime
accounts: AccountRules {
valid_handle: kick_handle,
valid_handle,
avatar_prefixes: &["https://files.kick.com/"],
max_name_chars: 50,
max_avatar_len: 512,
@ -292,240 +58,149 @@ pub static SITE: SiteSpec = SiteSpec {
};
```
`SiteSpec::is_origin` is the only definition of "a site tab". Site-only commands check
`policy::require_site_tab(&SITE, label, url)` (or `host::site_tab_only`), which also requires a
`tab-*` label.
### 2. Page: `SiteAdapter` (TypeScript)
**2. Page: what the runtime needs to know about the markup** (`src/site.ts`, shortened)
```ts
import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts';
import type { SiteAdapter } from 'waybetter/runtime/site';
export const KICK: SiteAdapter = {
export const SITE: SiteAdapter = {
product: 'wayBetter for Kick',
hosts: ['kick.com'],
runtimeGlobal: 'WayBetterKick',
heavyPath: null, // pages where offOnHeavy DOM features pause
apiMarks: ['/api/'], // request URLs the net hub stages may see
runtimeGlobal: 'WayBetterForKick',
heavyPath: null,
apiMarks: ['/api/'], // request URLs the net hub may inspect
xhrMarks: [],
plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:',
styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18',
plugins: { name: 'WayBetterForKick', product: 'wayBetter for Kick', storagePrefix: 'wb-kick-plugin:',
styleDataKey: 'wbKickPlugin', toastId: 'wb-kick-ui', toastBackground: '#53fc18',
itemSelector: '[data-chat-entry]', chordKeys: [] },
rail: { prefix: 'wbk', rail: '#sidebar-wrapper', anchor: 'a[href="/"]', main: 'main',
modalOpen: '[role="dialog"]', menuOpen: '[role="menu"]',
paint: { width: 64, background: '#0b0e0f', line: 'rgba(255,255,255,.12)', accent: '#53fc18', rtl: false } },
account: { read: readKickAccount, signedOut: root => !!root.querySelector('[data-test="login"]') },
links: { configKey: 'site', clickedUrl: kickClickedUrl },
themeSources: { dark: KICK_DARK_AXIS },
account: { read: readAccount, signedOut: root => !!root.querySelector('button[data-testid="login"]') },
links: { configKey: 'site', clickedUrl },
};
configureRuntime(KICK);
```
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) | 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, and the host's `commands::SITE` (`open_panel`) |
| other local webviews (`popover-*`, ...) | their own narrow capability |
```json
{ "identifier": "tab-chrome", "webviews": ["tab-*"], "local": false,
"remote": { "urls": ["https://*/*", "http://*/*"] },
"permissions": ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"] }
```
**3. Capabilities: who may call what** (`src-tauri/capabilities/*.json`, keyed by webview label).
The scaffold writes `shell`, `tab-chrome` and `site-tab`; the last one is granted only on the
site's own URLs:
```json
{ "identifier": "site-tab", "webviews": ["tab-*"], "local": false,
"remote": { "urls": ["https://kick.com/*"] },
"permissions": ["allow-open-panel"] }
"permissions": ["allow-site-ready", "allow-open-panel"] }
```
Native code re-checks every one of these (the capability file alone is not the boundary): the
caller's label, the webview's own URL (never the page's claim), payload bounds. A tab can speak only
about itself; the account it reports is recorded only for its own profile, only while it is on the
site, and a shell save can never change it (`ProfileSettings::keep_accounts_from`).
The app itself is `waybetter_host::app` configured with an `AppConfig` and a `SiteHooks`
implementation (what only your site knows: page scripts, legacy domains, link routing). Anything
else the app needs is an ordinary `#[tauri::command]` in your crate.
`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_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.
## What the host gives an app
- `app` (feature `app`): the whole app. `App::new(AppConfig, hooks).setup(..).run(context,
handler)` (or `run_app`) registers single-instance, deep-link (opt-in), window-state, opener,
updater (opt-in), process, notification and dialog; makes the app-data folder (0700 on Unix),
loads the profiles and the language, runs the app's setup, then builds the window (frameless
with the shell's titlebar, or the OS frame), restores its geometry (lost geometry reset),
routes helper-window closes (Windows), follows window resizes natively and adds the shell
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`, `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:
`profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`,
`open_external`.
To show the first window only after restored panes are placed, opt in on both sides:
`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 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).
- `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be
removed), `data_dir` (ids cannot escape `profiles/`), `orphan_dirs`, `store_identifier` (macOS).
- `plugins`: `PluginStore` with a `PluginHost` (runtime global, origin, product, bundled plugins).
Bundled plugins are written disabled and upgraded only while untouched.
- `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data.
- `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots).
- `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it.
- `bridge`: the tab bridge (`SOURCE`, or `script(BridgeOptions)` to leave shortcut and link-drag
forwarding off when the shell does not handle them).
- `backup` + `sync`: the `.waybetter` settings backup (the app registers its sections and files;
secret-looking keys are scrubbed both ways) and encrypted snapshots in a folder the owner syncs.
- `workspaces`: validation of saved layouts (slug ids, known tab kinds, http(s) URLs, size caps).
- `devmode`: the live-reload watcher (plugins, `custom.css`, one theme file; the app turns the theme
document into its own state through a callback).
- `alerts`: keyword settings, snippets, `Throttle`, `AlertGate` over any `KeywordMatch`;
`alerts::notify` (feature `tauri`) shows a native notification.
- `media`: gallery folders and the opt-in clipboard history; `media::clipboard::watch` (feature
`tauri`) polls the OS clipboard and never reads a copy a password manager marked private.
- `gfonts` + `fonts` (feature `net`): Google Fonts downloaded natively from the two Google hosts
only, cached with a sha256 manifest and handed to site pages as bytes (`page_script(&SITE, ..)`).
- `updater` (features `tauri` + `net`): the update loop, the signed hotfix channel and
`status`/`apply`/`ready` for the app's commands, configured by an `UpdaterConfig`.
- `plugins::commands`: palette commands a site tab reports, and `run_script(&SITE, id)`.
- `store`: the wayBetter Store for any app from a `StoreConfig` (app id, link scheme, store URL,
public keys with rotation, download hosts): `waybetter://install` link parsing, the allow-list,
size caps, catalog verification (Ed25519, strict schema, each app sees only its items), `Store`
(pending links, staged installs, commit of exactly the staged bytes, records, offline catalog),
and with feature `net` no-redirect/no-cookie downloads. The shell half is `waybetter/shell`'s
`InstallHost`, `StoreView` and install controller; the tooling is `waybetter store`
(docs/STORE.md).
- `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`,
`eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`,
`read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`,
`system_menu`.
The app keeps its own `#[tauri::command]` wrappers for everything else, and its capability files;
its `build.rs` lists its commands through `commands::manifest`, which adds the host's.
The npm package adds the app-side tooling:
- `waybetter/build`: `buildRuntime({ entry, outfile, catalog, prefixes, ... })` bundles a page
runtime into one IIFE with the app's esbuild (`?inline` CSS as text, other CSS dropped, only the
runtime's own catalog prefixes compiled in).
- `waybetter release windows|macos`: signed native releases and the update manifest from the
app's `waybetter.release.json` (product and file names, key folder, CDN and API URLs, an optional
manifest validator). Windows: the signed NSIS build, the installer and `.sig` in
`<outDir>/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 -- <command>` 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/<Language>.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
it is newer than what is installed (an upgrade in place, app data untouched); otherwise it opens
the installed app and exits 0, so an old setup left in Downloads never replaces or downgrades an
install the updater has moved on. `/FORCE` reinstalls the same version (repair), `/NORUN` does
not open the app, `/UPDATE` is the updater's path and always installs. An app renamed after its
first release keeps its registry keys by defining `WAYBETTER_LEGACY_NAME` in its installer hooks
(`bundle.windows.nsis.installerHooks`).
## Consuming it
wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source:
- Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`,
with `features = ["app", "net", "macos-private-api"]` enabled by the app's desktop feature (and
as a build-dependency for `commands::manifest`).
- TypeScript: relative imports of `waybetter/packages/*/src/*.ts`: the X site for the shell frame
(`src/shell/site.tsx`), the page runtime's adapter and a few X modules. Its Vite config dedupes
React, dockview and the Tauri API (the frame's imports use the app's copies) and serves
`bootScript()` as `/boot.js`. The
packages are not Bun workspace members of the app on purpose: the app's server CI clones without
submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's
type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's
isolated linker on Windows.
## Scripts (no CI)
## Start a project
```sh
bun install # typescript + @types/node for the checks
bun run typecheck # tsc over both packages and their tests, and create-waybetter (checkJs)
bun run test # node --test (runtime + shell), cargo test (headless host), create-waybetter
bun run test:ts
bun run test:rust
bun run test:create # scaffolds into temp dirs; its cargo check of an app is ~1 min cold
# (WAYBETTER_SKIP_CARGO_CHECK=1 skips it; needs the local crate cache)
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
npm create waybetter plugin -- --name "Hide Trends"
npm create waybetter theme -- --name "Midnight Mint" --accent "#3ddc97"
npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes
```
`dev-tools/` has the harnesses for a running or built app (perf probes, the graceful-close check,
tab and webview stress); see its README.
The app scaffold adds the framework as a git submodule at `waybetter/` by default (`--host-source
path` and `--host-source git` are the alternatives). Its next steps, as the tool prints them:
`git init && git submodule add https://git.crt.fyi/CRT/waybetter.git waybetter`, then
`npm install`, `npm run build`, `npm run tauri dev`, then replace the placeholder selectors in
`src/site.ts` and `src-tauri/src/site.rs`. Flags: `npm create waybetter -- --help`.
See [packages/create-waybetter](packages/create-waybetter/README.md).
Requires Bun 1.4.2+, Node 24+ and Rust 1.88+.
## The dev loop
In a scaffolded app, `npm run dev` runs `waybetter dev --watch "node scripts/build.mjs --watch"`:
it starts your watchers, waits for their first build and runs `tauri dev`. In debug builds the page
runtime file is read from disk and watched; when it changes, every tab webview is rebuilt on its
current URL (about a second from save to visible, the route is kept, the scroll position is not).
The shell reloads through the frontend dev server. Rust, `tauri.conf.json`, capabilities and
bundled plugin sources need a restart. `npm run dev:stable` adds `--no-watch` so a Rust file saved
elsewhere does not restart the app. Release builds contain none of this. There is also a developer
mode in the panel (Settings, Developer) that reloads installed plugins, custom CSS and one theme
file in every tab as you save.
## Security model
The site's page is not trusted, and neither is a plugin. The rules:
- Capabilities are keyed by webview label and each command re-checks its caller in Rust: the
capability file is not the boundary. A `tab-*` webview may only report about itself
(`tab_report`, `tab_shortcut`, `tab_link_drag`); on the site's exact origin it also gets the
app's short, reviewed list of site commands and `open_panel`. Everything else (tab layout,
settings, plugins, backup, install) is callable from the local `shell` webview only.
- `SiteSpec::is_origin` is the single definition of "a site tab": exact https origin, no
credentials in the URL.
- The account a tab reports is recorded only for that tab's own profile, only while it is on the
site, validated by your `AccountRules`, and a settings save can never change it.
- Installs (themes, plugins) come from a dropped file, a `waybetter://install` link or the signed
store, and are written only after the owner confirms in the shell. The store catalog is verified
with Ed25519; downloads use an allow-list, no redirects, no cookies and size caps. Plugins may
declare `@permissions`; the runtime gives each an API view that throws on undeclared members.
That is a guard rail, not a sandbox. A plugin without the line is labelled legacy and gets the
full API.
- Backups and sync snapshots never contain cookies, WebView profile folders, tokens or signing
keys. Sync is encrypted with the owner's passphrase (Argon2id and XChaCha20-Poly1305).
- `waybetter_host::testkit` lets your `tests/security.rs` read every capability file and assert
that host commands stay shell-only or tab-only, that site commands are granted only on the
site's URLs, and that each command's first statement checks its caller. The scaffold includes
such a test.
- `waybetter privacy-scan` and `waybetter build-env` keep a build free of the builder's paths and
names; `waybetter release` refuses to release an artifact with a hit.
## Optional command groups
Beyond the commands every app gets, the host serves groups of shell-only commands that an app turns
on in its `AppConfig` (or, for the state-free ones, simply grants in its shell capability). Each
group is a list in `waybetter_host::commands`, each wrapper checks its caller first, and
`waybetter_host::testkit` asserts both in your `tests/security.rs`.
| Group | Turn on with | What it serves | What the app supplies |
| --- | --- | --- | --- |
| `STORE` | `AppConfig::with_store(&STORE)` | install links, dropped files, the signed Store, the install screen | its `StoreConfig` (app id, hosts, public keys) |
| `MEDIA` | `with_media()` | gallery folders, previews, the opt-in clipboard history and its watcher | attaching an image to the site's composer, if it has one (`media_commands::gallery_file` and `clip_image` give it the checked bytes) |
| `GFONTS` | `with_fonts()` | Google Fonts install, remove, preview (needs the `net` feature) | `SiteHooks::fonts_changed` (give the tabs their theme again) |
| `UPDATE` | `with_updates(&UpdaterConfig)` | update status, check now, apply, the update loop and the hotfix channel | the channel, its key and the download page |
| `SYNC` | `with_sync()` | encrypted folder sync | `SiteHooks::backup_sections` and `backup_section_names` |
| `DEV` | `with_dev()` | developer mode: live reload of plugins, custom CSS and a theme file | `SiteHooks::dev_theme_apply` and `dev_theme_end` |
| `WORKSPACES`, `BACKUP` | always served | saved layouts; settings backup (collect, export, open, apply) | for backup: `backup_drafts` and `backup_apply` (how each imported section is applied) |
What is still the app's to write today: keyword alerts' commands around `waybetter_host::alerts`,
the theme commands around `waybetter_host::theme` (wayBetter for X names them `x_*`), a
popover webview and anything else that is specific to the site. They are on the list to move.
## Repository layout
```
crates/waybetter-host/ Rust host crate (features: tauri, net, app)
packages/runtime/ page runtime (published inside `waybetter`)
packages/shell/ shell models, shell frame, panel, store screens (published inside `waybetter`)
packages/waybetter/ the npm package: built runtime and shell, JSON Schemas, locales,
and the `waybetter` command (store, release, i18n, strings, privacy-scan,
build-env, dev)
packages/create-waybetter/ `npm create waybetter`
docs/ ARCHITECTURE.md, STORE.md, STRING-PACKS.md
dev-tools/ harnesses for a running or built app (not published)
```
## Tests
```sh
bun install
bun run typecheck # tsc over both packages, their tests and create-waybetter
bun run test:ts # node --test: runtime and shell
bun run test:rust # cargo test of the host crate (headless, feature net)
bun run test:create # scaffolds each kind into temp folders and checks them against the real contracts
```
`test:create` also runs `cargo check` on a generated app (about a minute cold);
`WAYBETTER_SKIP_CARGO_CHECK=1` skips that step. Requires Bun 1.4.2+, Node 24+ and Rust 1.88+.
## Contributing
Issues and pull requests go to [git.crt.fyi/CRT/waybetter](https://git.crt.fyi/CRT/waybetter).
Keep the split: generic mechanisms belong here, site-specific ones in the app. If you built
something on wayBetter, add it to the list below with a pull request.
| Project | Target | What it is |
| --- | --- | --- |
| [wayBetter for X](https://git.crt.fyi/CRT/waybetter-for-x) | x.com | Tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. |

View file

@ -64,7 +64,7 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
rustls = { version = "0.23", default-features = false, features = ["ring"], optional = true }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true }
windows = { version = "0.62", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging"], optional = true }
# The WebView2 COM interfaces wry already links (hidden tabs: low memory target).
webview2-com = { version = "0.39", optional = true }
# Clipboard sequence number (skip unchanged polls) and password-manager exclusion formats.

View file

@ -22,6 +22,7 @@ use crate::{
host::{self, emit_shell, emit_tab_state, read_json, shell_only, site_tab_only, tab_only, tab_webview, write_json},
i18n::{self, NativeStrings},
layout,
modes::{ModeState, MODES_FILE},
plugins::{self, PluginHost, PluginStore, ScriptPlugin},
policy,
profiles::{self, AccountSeen, ProfileSettings},
@ -79,6 +80,26 @@ pub struct AppConfig {
pub plugins: &'static PluginHost,
/// The home page before the owner sets one (default: the site's first origin).
pub home_url: Option<&'static str>,
/// The store this app installs themes and plugins from (`waybetter://install` links, dropped
/// files, the signed catalog): serves [`commands::STORE`]. Needs `deep_link` for the links and
/// the `net` feature for downloads.
pub store: Option<&'static crate::store::StoreConfig>,
/// The shell's media panel (gallery folders, the clipboard history): serves [`commands::MEDIA`].
pub media: bool,
/// Google Fonts (install, remove, preview; the cache in app data): serves [`commands::GFONTS`]
/// and calls [`SiteHooks::fonts_changed`]. Needs the `net` feature.
pub fonts: bool,
/// Encrypted folder sync of the settings backup: serves [`commands::SYNC`] and needs
/// [`SiteHooks::backup_sections`]. ([`commands::WORKSPACES`] is served for every app.)
pub sync: bool,
/// Developer mode (live reload of plugins, custom CSS and a theme file): serves
/// [`commands::DEV`] and runs the watcher while it is on; the theme file is the app's
/// ([`SiteHooks::dev_theme_apply`]).
pub dev: bool,
/// Native updates and the hotfix channel: serves [`commands::UPDATE`] and runs the update loop.
/// Needs `updater` (the plugin) and the `net` feature.
#[cfg(feature = "net")]
pub updates: Option<&'static crate::updater::UpdaterConfig>,
}
impl AppConfig {
@ -100,9 +121,53 @@ impl AppConfig {
page_string_prefixes: &["kit.", "plugin."],
plugins,
home_url: None,
store: None,
media: false,
fonts: false,
sync: false,
dev: false,
#[cfg(feature = "net")]
updates: None,
}
}
/// Serves the update commands ([`commands::UPDATE`]) and runs the update loop.
#[cfg(feature = "net")]
pub const fn with_updates(mut self, updates: &'static crate::updater::UpdaterConfig) -> Self {
self.updates = Some(updates);
self
}
/// Serves the developer-mode commands ([`commands::DEV`]).
pub const fn with_dev(mut self) -> Self {
self.dev = true;
self
}
/// Serves the sync commands ([`commands::SYNC`]).
pub const fn with_sync(mut self) -> Self {
self.sync = true;
self
}
/// Serves the Google Fonts commands ([`commands::GFONTS`]).
pub const fn with_fonts(mut self) -> Self {
self.fonts = true;
self
}
/// Serves the media panel's commands ([`commands::MEDIA`]).
pub const fn with_media(mut self) -> Self {
self.media = true;
self
}
/// Serves the store's commands ([`commands::STORE`]) with this configuration.
pub const fn with_store(mut self, store: &'static crate::store::StoreConfig) -> Self {
self.store = Some(store);
self
}
/// 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()))
@ -136,6 +201,13 @@ pub trait SiteHooks: Send + Sync + 'static {
/// (`waybetter_host::bridge`), then the app's page runtime.
fn init_scripts(&self, app: &AppHandle, tab: &NewTab) -> Vec<String>;
/// The document-start scripts of a tab in safe mode ([`crate::safe`]) instead of
/// [`Self::init_scripts`]: by default the host's tab bridge alone, so nothing of the app's page
/// layers runs. An app returns more here only for a layer it wants to survive safe mode.
fn safe_init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec<String> {
vec![crate::bridge::SOURCE.to_owned()]
}
/// The new tab webview's background until the page paints.
fn tab_background(&self, _app: &AppHandle, _label: &str) -> Option<tauri::window::Color> {
None
@ -174,6 +246,44 @@ pub trait SiteHooks: Send + Sync + 'static {
/// A tab webview was created.
fn tab_created(&self, _app: &AppHandle) {}
/// A Google font was installed or removed ([`commands::GFONTS`]): give the site tabs their
/// theme, and the font bytes, again.
fn fonts_changed(&self, _app: &AppHandle) {}
/// The app's native settings as backup sections (themes, plugins, tweaks, ... keyed by section
/// name, from app data): what a backup and [`commands::SYNC`] carry besides the shell's own
/// storage. By default none.
fn backup_sections(&self, _app: &AppHandle) -> Result<serde_json::Map<String, serde_json::Value>, String> {
Ok(serde_json::Map::new())
}
/// The names of the sections an import may carry (others are dropped). By default none.
fn backup_section_names(&self) -> &'static [&'static str] {
&[]
}
/// The `drafts` backup section (only when the owner ticks "include drafts"), or none. By default none.
fn backup_drafts(&self, _app: &AppHandle) -> Result<Option<serde_json::Value>, String> {
Ok(None)
}
/// Applies the sections of an import the owner chose ([`commands::BACKUP`]): check each the way
/// its own setter does, write nothing if any is bad, and return what was applied and notes for
/// the owner (`{ applied: [..], notes: [..] }`). By default importing is not supported.
fn backup_apply(&self, _app: &AppHandle, _sections: &serde_json::Map<String, serde_json::Value>) -> Result<serde_json::Value, String> {
Err("UNAVAILABLE: this app cannot import a backup".into())
}
/// Developer mode: show the theme file the owner picked (read `path`, make it the theme preview
/// in every site tab). An error is shown with its file and line. By default themes are not
/// supported and this does nothing.
fn dev_theme_apply(&self, _app: &AppHandle, _path: &std::path::Path) -> Result<(), crate::devmode::DevError> {
Ok(())
}
/// Developer mode ended (or the theme file was cleared): end the preview [`Self::dev_theme_apply`] made.
fn dev_theme_end(&self, _app: &AppHandle) {}
/// `tab` was laid out for `item` (existing or new), before it is placed.
fn tab_placed(&self, _app: &AppHandle, _tab: &Webview, _item: &TabLayout) {}
@ -203,6 +313,8 @@ pub struct PageState {
/// A JSON object of booleans ([`settings::validate_features`]).
pub features: serde_json::Value,
pub settings: ShellSettings,
/// The onboarding mode the owner started from and whether the first-run screen was answered.
pub modes: ModeState,
}
struct Profiles(Mutex<ProfileState>);
@ -218,7 +330,20 @@ fn host_state(app: &AppHandle) -> tauri::State<'_, Host> {
app.state::<Host>()
}
/// The app's site hooks ([`run_app`] must be running).
pub(crate) fn hooks(app: &AppHandle) -> Arc<dyn SiteHooks> {
host_state(app).hooks.clone()
}
/// The app's config ([`run_app`] must be running).
/// The document-start script that gives a new site tab the current string packs (none when the
/// shell never applied any, or the app has no store). Part of the normal page layers, so safe mode
/// leaves it out.
fn strings_layer(app: &AppHandle) -> Option<String> {
let stored = app.try_state::<crate::store::Store>()?.strings().delivery()?;
Some(crate::store::delivery_script(config(app).site.hosts, &stored, false))
}
pub fn config(app: &AppHandle) -> AppConfig {
host_state(app).config
}
@ -269,6 +394,10 @@ impl PageScripts {
/// 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<PageScripts, String> {
// Safe mode: a site page gets none of them.
if crate::safe::active() {
return Ok(PageScripts { features: String::new(), links: String::new(), css: None, plugins: Vec::new() });
}
let site = config(app).site;
let page = page(app)?;
let css = page.plugins.css();
@ -401,8 +530,10 @@ fn in_site(site: &SiteSpec, hooks: &dyn SiteHooks, url: &Url) -> bool {
/// Reconciles native tab webviews with the shell's panes: creates missing ones, positions and
/// shows/hides all of them, and closes webviews whose tab no longer exists.
#[tauri::command]
async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, viewport: Option<[f64; 2]>) -> Result<(), String> {
pub(crate) async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, viewport: Option<[f64; 2]>) -> Result<(), String> {
shell_only(&webview)?;
#[cfg(debug_assertions)]
crate::devloop::remember_layout(&items, viewport);
let hooks = host_state(&app).hooks.clone();
let window = webview.window();
// Kept current by the window's resize events (host::follow_window_resizes): no blocking
@ -479,7 +610,7 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
let new_tab = NewTab { id: &item.id, label: &label, profile: &item.profile, item: &item };
let builder = tab_builder(&app, &hooks, &new_tab, url, data_dir);
// The site's page color until it paints (never the WebView's white).
let builder = match hooks.tab_background(&app, &label) {
let builder = match crate::safe::layer(crate::safe::active(), || hooks.tab_background(&app, &label), || None) {
Some(color) => builder.background_color(color),
None => builder,
};
@ -490,6 +621,8 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
if shell_is_raised() {
host::raise_shell(&webview, true);
}
// A new webview starts at 100%: this tab's remembered page zoom.
host::restore_tab_zoom(&app, &tab);
tab
}
Err(error) => {
@ -499,7 +632,9 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
}
}
};
hooks.tab_placed(&app, &tab, &item);
if !crate::safe::active() {
hooks.tab_placed(&app, &tab, &item);
}
host::place_tab(&tab, (x, y, width, height), visible, item.parked || rect.is_none());
placed.push((item.id.clone(), (x, y, width, height), visible));
}
@ -514,6 +649,7 @@ async fn tabs_sync(webview: Webview, app: AppHandle, items: Vec<TabLayout>, view
if let Ok(mut data) = profiles(&app) {
data.tab_profiles.remove(&label);
}
host::forget_tab_zoom(&app, id);
hooks.tab_closed(&app, &label, TabClosed::Removed);
}
}
@ -542,11 +678,63 @@ async fn tab_action(webview: Webview, app: AppHandle, id: String, action: String
host::tab_action(&app, &id, &action)
}
/// The page zoom of tab `id` (the app menu's zoom row, Ctrl with + / - / 0): sets it to `factor`
/// (clamped to 25%..500%, remembered per tab in app data `zoom.json`), or only reads it without
/// one. Returns the factor in effect. The engine's own page zoom; nothing is injected into the page.
#[tauri::command]
async fn tab_zoom(webview: Webview, app: AppHandle, id: String, factor: Option<f64>) -> Result<f64, String> {
shell_only(&webview)?;
host::tab_zoom(&app, &id, factor)
}
/// Find in page for tab `id` (the shell's find bar): `start` with a query, `next`, `previous`, `stop`.
/// The engine's own find where this build can drive it (counts arrive as `tab-find` events), else the
/// evaluated `window.find`. The query is one typed line (validated) and is kept nowhere.
#[tauri::command]
async fn tab_find(webview: Webview, app: AppHandle, id: String, action: String, query: Option<String>) -> Result<(), String> {
shell_only(&webview)?;
host::tab_find(&app, &id, &action, query.as_deref())
}
/// Whether safe mode is on ([`crate::safe`]): the shell shows it in the titlebar and drops its chrome theme.
#[tauri::command]
async fn safe_mode_get(webview: Webview) -> Result<crate::safe::SafeState, String> {
shell_only(&webview)?;
Ok(crate::safe::state())
}
/// Switches safe mode for this run (memory only, never saved) and rebuilds every tab webview, so
/// each page starts again with or without the app's page layers. The app menu's "Restart in safe
/// mode" and the titlebar's "Leave".
#[tauri::command]
async fn safe_mode_set(webview: Webview, app: AppHandle, on: bool) -> Result<crate::safe::SafeState, String> {
shell_only(&webview)?;
if crate::safe::set(on) {
emit_shell(&app, crate::safe::EVENT, crate::safe::state());
rebuild_tabs(&app);
}
Ok(crate::safe::state())
}
/// Every tab webview is built again on the shell's next layout: their recorded profiles are marked
/// stale (`tabs_sync` then closes and recreates each one with the document-start scripts of the
/// moment) and the shell is asked to send its layout.
pub fn rebuild_tabs(app: &AppHandle) {
if let Ok(mut data) = profiles(app) {
for profile in data.tab_profiles.values_mut() {
*profile = crate::safe::STALE_PROFILE.to_owned();
}
}
emit_shell(app, crate::safe::EVENT_REBUILD, ());
}
/// Gives keyboard focus back to the shell (e.g. Ctrl+L pressed inside a tab).
#[tauri::command]
async fn shell_focus(webview: Webview) -> Result<(), String> {
shell_only(&webview)?;
webview.set_focus().map_err(|error| format!("FOCUS: {error}"))
let result = webview.set_focus().map_err(|error| format!("FOCUS: {error}"));
crate::diag::log("host", &format!("shell_focus -> {}", if result.is_ok() { "ok" } else { "error" }));
result
}
/// The shell calls this after its first DOM commit, so startup never exposes an empty webview.
@ -578,7 +766,24 @@ async fn shell_raise(webview: Webview, app: AppHandle, on: bool) -> Result<bool,
host_state(&app).hooks.shell_raised(&app, on);
}
SHELL_RAISED.store(on, Ordering::SeqCst);
Ok(host::raise_shell(&webview, on))
let supported = host::raise_shell(&webview, on);
crate::diag::log("host", &format!("shell_raise on={on} -> supported={supported}"));
Ok(supported)
}
/// Whether focus and layering diagnostics are on for this run ([`crate::diag`]).
#[tauri::command]
async fn diag_get(webview: Webview) -> Result<bool, String> {
shell_only(&webview)?;
Ok(crate::diag::active())
}
/// One diagnostic line from the shell (plain short text; nothing is written unless diagnostics are on).
#[tauri::command]
async fn diag_log(webview: Webview, line: String) -> Result<(), String> {
shell_only(&webview)?;
crate::diag::log("shell", &line);
Ok(())
}
#[tauri::command]
@ -715,6 +920,27 @@ async fn features_set(webview: Webview, app: AppHandle, features: serde_json::Ma
set_features(&app, features)
}
/// The onboarding mode: what was chosen, whether the first-run screen was answered, and whether
/// this app was set up before modes existed.
#[tauri::command]
async fn mode_get(webview: Webview, app: AppHandle) -> Result<ModeState, String> {
shell_only(&webview)?;
Ok(page(&app)?.modes.clone())
}
/// Remembers the chosen mode (or none), that the first-run screen was answered, and what the
/// mode's preset was when it was applied (`preset`, flag names to on/off: data for the shell's
/// "custom" and "this mode has new features" notes). The preset's flags are the shell's to apply
/// (`features_set`); this only records the choice.
#[tauri::command]
async fn mode_set(webview: Webview, app: AppHandle, mode: Option<String>, onboarded: bool, preset: Option<std::collections::BTreeMap<String, bool>>) -> Result<ModeState, String> {
shell_only(&webview)?;
let next = page(&app)?.modes.chosen(mode, onboarded, preset)?;
write_json(&app, MODES_FILE, &next)?;
page(&app)?.modes = next.clone();
Ok(next)
}
#[tauri::command]
async fn settings_get(webview: Webview, app: AppHandle) -> Result<ShellSettings, String> {
shell_only(&webview)?;
@ -803,7 +1029,10 @@ fn tab_builder(app: &AppHandle, hooks: &Arc<dyn SiteHooks>, tab: &NewTab, url: U
builder = builder.data_store_identifier(profiles::store_identifier(tab.profile));
}
}
for script in hooks.init_scripts(app, tab) {
// Safe mode: the safe set (the tab bridge) instead of the app's page layers.
// The string packs' delivery goes first, before the page runtime reads it (not in safe mode).
let layers = || strings_layer(app).into_iter().chain(hooks.init_scripts(app, tab)).collect::<Vec<_>>();
for script in crate::safe::layer(crate::safe::active(), layers, || hooks.safe_init_scripts(app, tab)) {
builder = builder.initialization_script(script);
}
builder
@ -878,9 +1107,11 @@ fn tab_builder(app: &AppHandle, hooks: &Arc<dyn SiteHooks>, tab: &NewTab, url: U
let finished = matches!(payload.event(), PageLoadEvent::Finished);
if !finished {
load_hooks.page_started(app, &tab);
// An engine that resets page zoom on navigation still shows this tab's.
host::restore_tab_zoom(app, &tab);
}
emit_tab_state(app, TabState { id: load_id.clone(), url: Some(payload.url().to_string()), loading: Some(!finished), ..Default::default() });
if finished && site.is_origin(payload.url()) {
if finished && site.is_origin(payload.url()) && !crate::safe::active() {
load_hooks.site_page_loaded(app, &tab, payload.url());
}
})
@ -935,6 +1166,12 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
tabs_sync,
tab_navigate,
tab_action,
tab_zoom,
tab_find,
safe_mode_get,
safe_mode_set,
diag_get,
diag_log,
open_external_url,
shell_focus,
shell_ready,
@ -952,6 +1189,8 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
custom_css_set,
features_get,
features_set,
mode_get,
mode_set,
settings_get,
settings_set,
tab_shortcut,
@ -960,6 +1199,59 @@ fn host_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 's
]
}
/// The store's commands ([`commands::STORE`]): with the `net` feature (downloads) only.
#[cfg(feature = "net")]
fn store_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::store_commands::handler()
}
#[cfg(not(feature = "net"))]
fn store_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
|_| false
}
/// The backup commands ([`commands::BACKUP`]).
fn backup_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::backup_commands::handler()
}
/// The developer-mode commands ([`commands::DEV`]).
fn dev_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::dev_commands::handler()
}
/// The workspaces and sync commands ([`commands::WORKSPACES`], [`commands::SYNC`]).
fn sync_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::sync_commands::handler()
}
/// The update commands ([`commands::UPDATE`]): with the `net` feature only.
#[cfg(feature = "net")]
fn update_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::update_commands::handler()
}
#[cfg(not(feature = "net"))]
fn update_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
|_| false
}
/// The Google Fonts commands ([`commands::GFONTS`]): with the `net` feature (downloads) only.
#[cfg(feature = "net")]
fn fonts_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::fonts_commands::handler()
}
#[cfg(not(feature = "net"))]
fn fonts_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
|_| false
}
/// The media panel's commands ([`commands::MEDIA`]).
fn media_handler() -> impl Fn(tauri::ipc::Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::media_commands::handler()
}
type Setup = Box<dyn FnOnce(&AppHandle) -> Result<(), Box<dyn std::error::Error>> + Send>;
/// The app builder: config, site hooks, the app's own setup, then [`App::run`].
@ -990,6 +1282,13 @@ impl App {
{
let App { config, hooks, setup } = self;
let host_handler = host_handler();
let store_handler = store_handler();
let media_handler = media_handler();
let fonts_handler = fonts_handler();
let update_handler = update_handler();
let sync_handler = sync_handler();
let dev_handler = dev_handler();
let backup_handler = backup_handler();
let builder = tauri::Builder::<Wry>::default()
// Must be first: a second launch focuses the running window instead of fighting over
// the app's data and WebView profile (and hands over its link).
@ -1019,6 +1318,8 @@ impl App {
}
let directory = tauri_app.path().app_data_dir()?;
std::fs::create_dir_all(&directory)?;
// Someone set this app up before (read before anything below writes a file).
let existing = [PROFILES_FILE, SETTINGS_FILE, FEATURES_FILE, PLUGINS_DIR].iter().any(|name| directory.join(name).exists());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
@ -1042,18 +1343,67 @@ impl App {
let settings = read_json::<serde_json::Value>(&handle, SETTINGS_FILE)
.and_then(|value| ShellSettings::from_value(value, &home).ok())
.unwrap_or_else(|| ShellSettings::defaults(&home));
let features = read_json::<serde_json::Value>(&handle, FEATURES_FILE)
let mut features = read_json::<serde_json::Value>(&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 })));
// Plugin files the app turned into features: what was enabled becomes its flag, once
// (plugins::migrate). The flags are saved before any file is touched.
let migrated = plugins.migrate_superseded(config.plugins.superseded, |flags| {
let Some(map) = features.as_object_mut().filter(|_| !flags.is_empty()) else { return Ok(()) };
for flag in flags {
map.insert(flag.clone(), serde_json::Value::Bool(true));
}
settings::validate_features(map)?;
write_json(&handle, FEATURES_FILE, &*map)
});
if let Err(error) = migrated {
eprintln!("{}: {error}", config.title);
}
let modes = read_json::<ModeState>(&handle, MODES_FILE).and_then(|state| state.validated().ok()).unwrap_or_else(|| {
let state = ModeState::first_run(existing);
let _ = write_json(&handle, MODES_FILE, &state);
state
});
tauri_app.manage(Page(Mutex::new(PageState { plugins, features, settings, modes })));
tauri_app.manage(Host { config, hooks });
#[cfg(feature = "net")]
crate::store_commands::init(&handle, &config);
crate::media_commands::init(&handle);
crate::sync_commands::init(&handle);
crate::dev_commands::init(&handle);
#[cfg(feature = "net")]
crate::fonts_commands::init(&handle);
#[cfg(feature = "net")]
crate::update_commands::init(&handle);
// Safe mode for this run: the launch argument, or Shift held while starting (Windows).
crate::safe::set(crate::safe::at_launch(std::env::args(), host::shift_held()));
// Focus and layering diagnostics for this run: `--diag` or WAYBETTER_DIAG=1 (app log folder, diag.log).
if crate::diag::asked(std::env::args(), std::env::var(crate::diag::ENV).ok().as_deref()) {
crate::diag::start(handle.path().app_log_dir().ok());
}
#[cfg(debug_assertions)]
crate::devloop::start(&handle);
if let Some(setup) = setup {
setup(&handle)?;
}
open_window(tauri_app, &config)
})
.invoke_handler(move |invoke| {
if commands::is_host(invoke.message.command()) {
if commands::STORE.contains(&invoke.message.command()) {
store_handler(invoke)
} else if commands::MEDIA.contains(&invoke.message.command()) {
media_handler(invoke)
} else if commands::GFONTS.contains(&invoke.message.command()) {
fonts_handler(invoke)
} else if commands::UPDATE.contains(&invoke.message.command()) {
update_handler(invoke)
} else if commands::WORKSPACES.contains(&invoke.message.command()) || commands::SYNC.contains(&invoke.message.command()) {
sync_handler(invoke)
} else if commands::DEV.contains(&invoke.message.command()) {
dev_handler(invoke)
} else if commands::BACKUP.contains(&invoke.message.command()) {
backup_handler(invoke)
} else if commands::is_host(invoke.message.command()) {
host_handler(invoke)
} else {
handler(invoke)

View file

@ -0,0 +1,147 @@
//! Settings backup, native side ([`crate::commands::BACKUP`], served for every app; an app that
//! does not use them grants them to no one): everything the owner set up in one versioned `.waybetter` file.
//! Every command is shell-only. The envelope, the secret scrubbing and the validation are
//! [`crate::backup`]'s; this module asks for what to save and writes the file.
//!
//! What a backup carries is the app's: its native sections
//! ([`crate::app::SiteHooks::backup_sections`]), its drafts only when the owner ticks "include
//! drafts" ([`crate::app::SiteHooks::backup_drafts`]) and the shell's own storage (`decks`,
//! `shell`). Importing shows the sections for a preview first (nothing is applied); the app applies
//! the ones the owner chose ([`crate::app::SiteHooks::backup_apply`]), each checked as its own
//! setter checks it. Never included: cookies, WebView profile folders, the session database,
//! tokens, signing keys, the sync key, update state, font files, gallery and clipboard data.
use crate::app::{config, hooks, tr};
use crate::backup;
use crate::host::shell_only;
use serde::Serialize;
use serde_json::{json, Map, Value};
use tauri::{AppHandle, Webview};
use tauri_plugin_dialog::DialogExt;
/// The app's native sections (plus drafts when asked) and `extra` sections from the shell
/// (`decks`), secret-looking keys removed.
fn collect(app: &AppHandle, include_drafts: bool, extra: Option<Map<String, Value>>) -> Result<Map<String, Value>, String> {
let hooks = hooks(app);
let mut sections = hooks.backup_sections(app)?;
if include_drafts {
if let Some(drafts) = hooks.backup_drafts(app)? {
sections.insert("drafts".into(), drafts);
}
}
for (key, value) in extra.unwrap_or_default() {
// The shell only adds its own storage; it cannot replace a native section or add drafts.
if (key == "decks" || key == "shell") && value.is_object() {
sections.insert(key, value);
}
}
let mut value = Value::Object(sections);
backup::strip_secrets(&mut value);
Ok(match value {
Value::Object(map) => map,
_ => Map::new(),
})
}
fn envelope(app: &AppHandle, sections: Map<String, Value>) -> Value {
json!({
"format": backup::FORMAT,
"version": backup::VERSION,
"app": config(app).title,
"appVersion": app.package_info().version.to_string(),
"createdAt": chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
"includesDrafts": sections.contains_key("drafts"),
"sections": sections,
})
}
/// The current settings as a backup would carry them (for the import preview's diff).
#[tauri::command]
pub(crate) async fn backup_collect(webview: Webview, app: AppHandle, include_drafts: bool) -> Result<Map<String, Value>, String> {
shell_only(&webview)?;
collect(&app, include_drafts, None)
}
/// Asks where to save and writes the `.waybetter` file. Returns the path, or None when cancelled.
#[tauri::command]
pub(crate) async fn backup_export_file(
webview: Webview,
app: AppHandle,
include_drafts: bool,
extra: Option<Map<String, Value>>,
) -> Result<Option<String>, String> {
shell_only(&webview)?;
let sections = collect(&app, include_drafts, extra)?;
let bytes = serde_json::to_vec_pretty(&envelope(&app, sections)).map_err(|_| "BACKUP: serialization failed")?;
let today = chrono::Utc::now().format("%Y-%m-%d");
let name = format!("wayBetter-settings-{today}.{}", backup::EXTENSION);
let picked = app
.dialog()
.file()
.set_parent(&webview.window())
.set_title(tr(&app, "native.dialog.saveBackup", "Save wayBetter settings"))
.set_file_name(&name)
.add_filter(tr(&app, "native.dialog.backupFilter", "wayBetter settings"), &[backup::EXTENSION])
.blocking_save_file();
let Some(picked) = picked else { return Ok(None) };
let mut path = picked.into_path().map_err(|_| "BACKUP: not a local file")?;
if path.extension().and_then(|ext| ext.to_str()) != Some(backup::EXTENSION) {
path.set_extension(backup::EXTENSION);
}
backup::write_atomic(&path, &bytes)?;
Ok(Some(path.to_string_lossy().into_owned()))
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct OpenedBackup {
file: String,
created_at: Option<String>,
app_version: Option<String>,
sections: Map<String, Value>,
}
/// Asks for a `.waybetter` file and returns its sections for the preview (nothing applied yet).
#[tauri::command]
pub(crate) async fn backup_open_file(webview: Webview, app: AppHandle) -> Result<Option<OpenedBackup>, String> {
shell_only(&webview)?;
let picked = app
.dialog()
.file()
.set_parent(&webview.window())
.set_title(tr(&app, "native.dialog.importBackup", "Import wayBetter settings"))
.add_filter(tr(&app, "native.dialog.backupFilter", "wayBetter settings"), &[backup::EXTENSION, "json"])
.blocking_pick_file();
let Some(picked) = picked else { return Ok(None) };
let path = picked.into_path().map_err(|_| "BACKUP: not a local file")?;
let meta = std::fs::metadata(&path).map_err(|_| "BACKUP: file not found")?;
if meta.len() as usize > backup::MAX_BACKUP_BYTES {
return Err("BACKUP: the file is larger than 32 MB".into());
}
let bytes = std::fs::read(&path).map_err(|error| format!("BACKUP: {error}"))?;
let sections = backup::parse_backup(&bytes, hooks(&app).backup_section_names())?;
let head: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
Ok(Some(OpenedBackup {
file: path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(),
created_at: head.get("createdAt").and_then(Value::as_str).map(str::to_owned),
app_version: head.get("appVersion").and_then(Value::as_str).map(str::to_owned),
sections,
}))
}
/// Applies the sections the owner chose (the shell applies `decks` itself): secret-looking keys
/// are removed first, then the app checks and applies each section
/// ([`crate::app::SiteHooks::backup_apply`]). Returns what was applied and notes for the owner.
#[tauri::command]
pub(crate) async fn backup_apply(webview: Webview, app: AppHandle, sections: Map<String, Value>) -> Result<Value, String> {
shell_only(&webview)?;
let mut sections = Value::Object(sections);
backup::strip_secrets(&mut sections);
let sections = sections.as_object().cloned().unwrap_or_default();
hooks(&app).backup_apply(&app, &sections)
}
/// The backup commands ([`crate::commands::BACKUP`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![backup_collect, backup_export_file, backup_open_file, backup_apply]
}

View file

@ -12,7 +12,7 @@ const DEFAULT_OPTIONS: &str = "const options = { shortcuts: true, linkDrags: tru
/// not handle it: a forwarded shortcut is taken from the page (`preventDefault`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BridgeOptions {
/// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, deck keys).
/// Browser shortcuts (new/close/reopen tab, reload, back/forward, split, palette, the app menu, zoom, deck keys).
pub shortcuts: bool,
/// Link drags out of (or into) the page, for the shell's split/tab drop zones.
pub link_drags: bool,
@ -58,7 +58,7 @@ mod tests {
fn forwarded_shortcuts_are_ones_the_host_accepts() {
for name in ["deck-toggle", "deck-compose", "column-page-prev", "column-page-next", "column-prev", "column-next", "reopen-tab", "new-tab",
"open-panel", "close-tab", "focus-address", "command-palette", "prev-tab", "next-tab", "hard-reload", "reload", "split-down",
"split-right", "back", "forward"] {
"split-right", "back", "forward", "app-menu", "zoom-in", "zoom-out", "zoom-reset", "find"] {
assert!(SOURCE.contains(&format!("'{name}'")), "{name} is not in the bridge");
assert!(crate::tabs::valid_shortcut(name), "{name} would be refused");
}

View file

@ -11,6 +11,12 @@ pub const SHELL: &[&str] = &[
"tabs_sync",
"tab_navigate",
"tab_action",
"tab_zoom",
"tab_find",
"safe_mode_get",
"safe_mode_set",
"diag_get",
"diag_log",
"open_external_url",
"shell_focus",
"shell_ready",
@ -28,6 +34,8 @@ pub const SHELL: &[&str] = &[
"custom_css_set",
"features_get",
"features_set",
"mode_get",
"mode_set",
"settings_get",
"settings_set",
];
@ -39,9 +47,80 @@ pub const TAB: &[&str] = &["tab_shortcut", "tab_link_drag"];
/// 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"];
/// Shell-only, optional: the store's commands (install links, dropped files, the signed Store and
/// the install screen), served when the app sets `AppConfig::store`. An app that uses the store
/// grants these to the shell (`testkit::Capabilities::assert_shell_only_group`).
pub const STORE: &[&str] = &[
"install_pending",
"install_stage_link",
"install_stage_file",
"install_cancel",
"install_commit",
"plugin_remove",
"install_records",
"install_forget",
"store_catalog",
"store_stage",
"strings_list",
"strings_read",
"strings_set",
"strings_remove",
"strings_apply",
];
/// Shell-only, optional: the media panel's commands (gallery folders, previews, the clipboard
/// history), served when the app sets `AppConfig::media`. An app that uses them grants these to the
/// shell (`testkit::Capabilities::assert_shell_only_group`).
pub const MEDIA: &[&str] = &[
"media_get",
"media_set",
"gallery_add_folder",
"gallery_list",
"gallery_thumb",
"clip_list",
"clip_thumb",
"clip_remove",
];
/// Shell-only, optional: Google Fonts (what is installed, install, remove, the faces of a family and
/// a preview), served when the app sets `AppConfig::fonts`; needs the `net` feature.
pub const GFONTS: &[&str] = &["gfonts_installed", "gfonts_install", "gfonts_remove", "gfonts_faces", "gfonts_preview"];
/// Shell-only, optional: native updates (status, check now, apply, the shell reached a working
/// state), served when the app sets `AppConfig::updates`; needs the `net` feature.
pub const UPDATE: &[&str] = &["update_status", "update_check", "apply_update", "app_ready"];
/// Shell-only, optional: saved workspaces (named tab, pane and deck layouts). State-free: served
/// for every app; an app that uses them grants them to the shell.
pub const WORKSPACES: &[&str] = &["workspaces_get", "workspaces_set"];
/// Shell-only, optional: encrypted folder sync of the settings backup, served when the app sets
/// `AppConfig::sync`.
pub const SYNC: &[&str] = &[
"sync_status",
"sync_choose_folder",
"sync_unlock",
"sync_lock",
"sync_disable",
"sync_configure",
"sync_push",
"sync_check",
"sync_open",
"sync_mark_pulled",
];
/// Shell-only, optional: developer mode (live reload of plugins, custom CSS and one theme file),
/// served when the app sets `AppConfig::dev`.
pub const DEV: &[&str] = &["dev_get", "dev_set", "dev_pick_theme", "dev_clear_theme", "dev_reload_plugin", "dev_report_error"];
/// Shell-only, optional: the settings backup (collect, export to a file, open a file for the preview,
/// apply chosen sections). State-free: served for every app; what a backup carries is the app's
/// (`SiteHooks::backup_sections`, `backup_drafts`, `backup_apply`).
pub const BACKUP: &[&str] = &["backup_collect", "backup_export_file", "backup_open_file", "backup_apply"];
/// 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) || SITE.contains(&command)
SHELL.contains(&command) || TAB.contains(&command) || SITE.contains(&command) || STORE.contains(&command) || MEDIA.contains(&command) || GFONTS.contains(&command) || UPDATE.contains(&command) || WORKSPACES.contains(&command) || SYNC.contains(&command) || DEV.contains(&command) || BACKUP.contains(&command)
}
/// The capability permission tauri-build generates for `command` (`tabs_sync` → `allow-tabs-sync`).
@ -56,8 +135,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() + SITE.len());
for command in app.iter().chain(SHELL).chain(TAB).chain(SITE) {
let mut all: Vec<&'static str> = Vec::with_capacity(app.len() + SHELL.len() + TAB.len() + SITE.len() + STORE.len() + MEDIA.len() + GFONTS.len() + UPDATE.len() + WORKSPACES.len() + SYNC.len() + DEV.len() + BACKUP.len());
for command in app.iter().chain(SHELL).chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) {
if !all.contains(command) {
all.push(command);
}
@ -74,7 +153,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).chain(SITE) {
for command in SHELL.iter().chain(TAB).chain(SITE).chain(STORE).chain(MEDIA).chain(GFONTS).chain(UPDATE).chain(WORKSPACES).chain(SYNC).chain(DEV).chain(BACKUP) {
assert!(all.contains(command), "{command}");
assert!(is_host(command));
}
@ -84,7 +163,7 @@ mod tests {
#[test]
fn shell_and_tab_commands_do_not_overlap() {
assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command)));
assert!(!SHELL.iter().any(|command| TAB.contains(command) || SITE.contains(command) || STORE.contains(command) || MEDIA.contains(command) || GFONTS.contains(command) || UPDATE.contains(command) || WORKSPACES.contains(command) || SYNC.contains(command) || DEV.contains(command) || BACKUP.contains(command)));
assert!(!TAB.iter().any(|command| SITE.contains(command)));
}
}

View file

@ -0,0 +1,346 @@
//! Developer mode (live reload), native side, for every app that sets
//! [`crate::app::AppConfig::dev`] ([`crate::commands::DEV`]). Off by default. While on, a polling
//! watcher ([`crate::devmode`]) sees the plugins folder, `custom.css` and one theme file the owner
//! picked, and reloads what changed in every site tab: the same plugin start and stop scripts, the
//! same custom-CSS script and the app's own theme preview the settings use. Syntax and start
//! errors are kept (and shown as a toast in the site tabs) with the file and line.
//!
//! Every command is shell-only; site tabs gain no command, they only receive scripts native code
//! already evaluates. The theme file is the app's ([`crate::app::SiteHooks::dev_theme_apply`]).
use crate::app::{config, hooks, page, tr};
use crate::devmode::{self, DevError};
use crate::host::{emit_shell, eval_in_site_tabs, read_json, shell_only, write_json};
use crate::plugins;
use serde::Serialize;
use std::collections::VecDeque;
use std::path::Path;
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Webview};
use tauri_plugin_dialog::DialogExt;
const MAX_DEV_ERRORS: usize = 20;
#[derive(Default)]
pub(crate) struct DevState {
inner: Mutex<DevInner>,
}
#[derive(Default)]
struct DevInner {
settings: devmode::DevSettings,
errors: VecDeque<DevErrorEntry>,
/// The theme preview in every site tab is developer mode's (so turning it off ends it).
owns_preview: bool,
/// Bumped when what is watched changes; the watcher then takes a new baseline.
generation: u64,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct DevErrorEntry {
#[serde(flatten)]
error: DevError,
at: String,
}
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
enum DevEvent {
/// A plugin file changed; the shell checks its syntax, then asks `dev_reload_plugin`.
Check { file: String, source: String },
Reloaded { target: String, file: Option<String> },
Error { error: DevError },
Changed,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DevStatus {
enabled: bool,
theme_file: Option<String>,
plugins_folder: String,
errors: Vec<DevErrorEntry>,
}
fn dev_state(app: &AppHandle) -> Result<tauri::State<'_, DevState>, String> {
app.try_state::<DevState>().ok_or_else(|| "UNAVAILABLE: this app has no developer mode".to_owned())
}
fn now() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
}
fn eval_in_site(app: &AppHandle, script: &str) {
eval_in_site_tabs(app, config(app).site, script);
}
fn dev_status(app: &AppHandle) -> Result<DevStatus, String> {
let dev = dev_state(app)?;
let inner = dev.inner.lock().map_err(|_| "DEV: busy")?;
let folder = page(app)?.plugins.dir().to_string_lossy().into_owned();
Ok(DevStatus { enabled: inner.settings.enabled, theme_file: inner.settings.theme_file.clone(), plugins_folder: folder, errors: inner.errors.iter().cloned().collect() })
}
/// A danger toast through the plugin UI kit of the page runtime, in the top frame of a site tab.
fn toast_script(app: &AppHandle, message: &str) -> String {
let site = config(app).site;
let message = serde_json::to_string(message).unwrap_or_else(|_| "\"\"".into());
let origin = serde_json::to_string(&site.primary_origin()).unwrap_or_else(|_| "\"\"".into());
format!(
"(()=>{{if(window.top!==window||location.origin!=={origin})return;const W=window.{};\
try{{W&&W.api&&W.api.ui&&W.api.ui.toast({message},{{tone:'danger',duration:12000}});}}catch(e){{}}}})();",
site.runtime_global
)
}
fn record_error(app: &AppHandle, error: DevError) {
let where_ = match (error.line, error.column) {
(Some(line), Some(column)) => format!("{}:{line}:{column}", error.file),
(Some(line), None) => format!("{}:{line}", error.file),
_ => error.file.clone(),
};
eval_in_site(app, &toast_script(app, &format!("{where_} — {}", error.message)));
if let Ok(dev) = dev_state(app) {
if let Ok(mut inner) = dev.inner.lock() {
inner.errors.push_front(DevErrorEntry { error: error.clone(), at: now() });
inner.errors.truncate(MAX_DEV_ERRORS);
}
}
emit_shell(app, devmode::EVENT, DevEvent::Error { error });
}
fn clear_errors_for(app: &AppHandle, file: &str) {
if let Ok(dev) = dev_state(app) {
if let Ok(mut inner) = dev.inner.lock() {
inner.errors.retain(|entry| entry.error.file != file);
}
}
}
/// Loads the saved settings and starts the watcher (idle until developer mode is turned on). Does
/// nothing unless the app set [`crate::app::AppConfig::dev`].
pub(crate) fn init(app: &AppHandle) {
if !config(app).dev {
return;
}
let settings = read_json::<devmode::DevSettings>(app, devmode::FILE).and_then(|settings| settings.validated().ok()).unwrap_or_default();
app.manage(DevState { inner: Mutex::new(DevInner { settings, ..Default::default() }) });
let handle = app.clone();
std::thread::Builder::new().name("wb-dev-watch".into()).spawn(move || watch_loop(handle)).ok();
}
fn watch_loop(app: AppHandle) {
let mut watcher = devmode::Watcher::new();
let mut generation = u64::MAX;
loop {
std::thread::sleep(devmode::POLL);
let Ok(dev) = dev_state(&app) else { return };
let (enabled, theme_file, current) = match dev.inner.lock() {
Ok(inner) => (inner.settings.enabled, inner.settings.theme_file.clone(), inner.generation),
Err(_) => continue,
};
drop(dev);
if !enabled {
generation = u64::MAX;
std::thread::sleep(std::time::Duration::from_millis(800));
continue;
}
if current != generation {
watcher.reset();
generation = current;
}
let Ok(plugins_dir) = page(&app).map(|page| page.plugins.dir().to_path_buf()) else { continue };
let scan = devmode::scan(&plugins_dir, theme_file.as_deref().map(Path::new));
for change in watcher.observe(std::time::Instant::now(), scan) {
handle_change(&app, &change, theme_file.as_deref());
}
}
}
fn apply_dev_theme(app: &AppHandle, path: &str) {
match hooks(app).dev_theme_apply(app, Path::new(path)) {
Ok(()) => {
if let Ok(dev) = dev_state(app) {
if let Ok(mut inner) = dev.inner.lock() {
inner.owns_preview = true;
}
}
let file = Path::new(path).file_name().map(|name| name.to_string_lossy().into_owned());
if let Some(file) = &file {
clear_errors_for(app, file);
}
emit_shell(app, devmode::EVENT, DevEvent::Reloaded { target: "theme".into(), file });
}
Err(error) => record_error(app, error),
}
}
fn handle_change(app: &AppHandle, change: &devmode::Change, theme_file: Option<&str>) {
use devmode::{Change, Target};
let plugins = config(app).plugins;
match change {
Change::Changed(Target::Theme) => {
if let Some(path) = theme_file {
apply_dev_theme(app, path);
}
}
Change::Removed(Target::Theme) => {
let file = theme_file.and_then(|path| Path::new(path).file_name()).map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
record_error(app, DevError { file, line: None, column: None, message: "The theme file was deleted or renamed.".into() });
}
Change::Changed(Target::Css) | Change::Removed(Target::Css) => {
let css = page(app).map(|page| page.plugins.css()).unwrap_or_default();
if let Ok(script) = plugins::css_script(plugins, &css) {
eval_in_site(app, &script);
}
emit_shell(app, devmode::EVENT, DevEvent::Reloaded { target: "css".into(), file: Some("custom.css".into()) });
}
Change::Changed(Target::Plugin(file)) => {
let (enabled, source) = match page(app) {
Ok(page) => {
let enabled = page.plugins.list().map(|list| list.iter().any(|plugin| &plugin.file == file && plugin.enabled)).unwrap_or(false);
(enabled, std::fs::read_to_string(page.plugins.dir().join(file)).ok())
}
Err(_) => return,
};
match (enabled, source) {
(true, Some(source)) if source.len() as u64 <= plugins::MAX_PLUGIN_BYTES => {
emit_shell(app, devmode::EVENT, DevEvent::Check { file: file.clone(), source });
}
(true, _) => record_error(app, DevError { file: file.clone(), line: None, column: None, message: "Not readable as UTF-8 text under 2 MiB.".into() }),
(false, _) => emit_shell(app, devmode::EVENT, DevEvent::Changed),
}
}
Change::Removed(Target::Plugin(file)) => {
if let Ok(script) = plugins::stop_script(plugins, file) {
eval_in_site(app, &script);
}
emit_shell(app, devmode::EVENT, DevEvent::Changed);
}
}
}
fn save_dev(app: &AppHandle, settings: &devmode::DevSettings) -> Result<(), String> {
write_json(app, devmode::FILE, settings)
}
fn end_dev_preview(app: &AppHandle) {
let owned = dev_state(app).ok().and_then(|dev| dev.inner.lock().ok().map(|mut inner| std::mem::take(&mut inner.owns_preview))).unwrap_or(false);
if owned {
hooks(app).dev_theme_end(app);
}
}
#[tauri::command]
pub(crate) async fn dev_get(webview: Webview, app: AppHandle) -> Result<DevStatus, String> {
shell_only(&webview)?;
dev_status(&app)
}
/// Turns developer mode on or off. Off ends the watched theme's preview.
#[tauri::command]
pub(crate) async fn dev_set(webview: Webview, app: AppHandle, enabled: bool) -> Result<DevStatus, String> {
shell_only(&webview)?;
let (settings, theme_file) = {
let dev = dev_state(&app)?;
let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?;
inner.settings.enabled = enabled;
inner.generation = inner.generation.wrapping_add(1);
(inner.settings.clone(), inner.settings.theme_file.clone())
};
save_dev(&app, &settings)?;
emit_shell(&app, devmode::EVENT, DevEvent::Changed);
if enabled {
if let Some(path) = theme_file {
apply_dev_theme(&app, &path);
}
} else {
end_dev_preview(&app);
}
dev_status(&app)
}
/// Picks the theme JSON file to live-apply (shown in every site tab while developer mode is on).
#[tauri::command]
pub(crate) async fn dev_pick_theme(webview: Webview, app: AppHandle) -> Result<DevStatus, String> {
shell_only(&webview)?;
let title = tr(&app, "native.dialog.themeFile", "Choose a theme file to live-reload");
let filter = tr(&app, "native.dialog.themeFilter", "Theme");
let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).add_filter(filter, &["json"]).blocking_pick_file();
let Some(picked) = picked else { return dev_status(&app) };
let path = picked.into_path().map_err(|_| "DEV: not a local file")?;
let settings = {
let dev = dev_state(&app)?;
let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?;
let next = devmode::DevSettings { theme_file: Some(path.to_string_lossy().into_owned()), ..inner.settings.clone() }.validated()?;
inner.settings = next.clone();
inner.generation = inner.generation.wrapping_add(1);
next
};
save_dev(&app, &settings)?;
if settings.enabled {
apply_dev_theme(&app, settings.theme_file.as_deref().unwrap_or_default());
}
dev_status(&app)
}
#[tauri::command]
pub(crate) async fn dev_clear_theme(webview: Webview, app: AppHandle) -> Result<DevStatus, String> {
shell_only(&webview)?;
let settings = {
let dev = dev_state(&app)?;
let mut inner = dev.inner.lock().map_err(|_| "DEV: busy")?;
inner.settings.theme_file = None;
inner.generation = inner.generation.wrapping_add(1);
inner.settings.clone()
};
save_dev(&app, &settings)?;
end_dev_preview(&app);
dev_status(&app)
}
/// Reloads plugin `file` in every site tab after the shell checked its syntax: stop, then start the
/// new version (evaluated with a sourceURL so errors name the file and line). Developer mode only.
#[tauri::command]
pub(crate) async fn dev_reload_plugin(webview: Webview, app: AppHandle, file: String) -> Result<(), String> {
shell_only(&webview)?;
if !dev_state(&app)?.inner.lock().map(|inner| inner.settings.enabled).unwrap_or(false) {
return Err("DEV: developer mode is off".into());
}
let host = config(&app).plugins;
let (stop, start) = {
let page = page(&app)?;
let enabled = page.plugins.list()?.iter().any(|plugin| plugin.file == file && plugin.enabled);
if !enabled {
return Err("DEV: that plugin is not enabled".into());
}
let source = std::fs::read_to_string(page.plugins.dir().join(&file)).map_err(|_| "DEV: plugin file not readable")?;
(plugins::stop_script(host, &file)?, plugins::dev_start_script(host, &file, &source, devmode::SOURCE_PREFIX)?)
};
// The old version is stopped, then the new one starts, evaluated on its own so its sourceURL
// line numbers are the file's. Scripts run in order in each tab.
eval_in_site(&app, &stop);
eval_in_site(&app, &start);
clear_errors_for(&app, &file);
emit_shell(&app, devmode::EVENT, DevEvent::Reloaded { target: "plugin".into(), file: Some(file) });
Ok(())
}
/// The shell found a syntax error in a changed plugin (it was not reloaded): recorded, and shown
/// as a toast in the site tabs.
#[tauri::command]
pub(crate) async fn dev_report_error(webview: Webview, app: AppHandle, file: String, line: Option<usize>, column: Option<usize>, message: String) -> Result<(), String> {
shell_only(&webview)?;
if !plugins::valid_file_name(&file) {
return Err("VALIDATION: invalid plugin file name".into());
}
let message: String = message.chars().filter(|ch| !ch.is_control()).take(300).collect();
record_error(&app, DevError { file, line, column, message });
Ok(())
}
/// The developer-mode commands ([`crate::commands::DEV`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![dev_get, dev_set, dev_pick_theme, dev_clear_theme, dev_reload_plugin, dev_report_error]
}

View file

@ -0,0 +1,116 @@
//! The debug dev loop: an app's page scripts are read from disk whenever a tab's init scripts are
//! built, and when one of those files changes every tab webview is rebuilt on its current URL, so
//! the new script is injected within a second or two without restarting the app.
//!
//! This module exists only in debug builds (`cfg(debug_assertions)`, see `lib.rs`); release builds
//! contain no file read, no path string and no watcher. An app names its files with
//! [`page_script!`](crate::page_script) in `SiteHooks::init_scripts`; the files it names are the ones
//! watched. Change detection is `devmode`'s debounced signature watcher (a file must keep its
//! size and modification time for `DEBOUNCE`, so a half-written bundle never loads).
//!
//! Why the tabs are rebuilt rather than reloaded: a webview's document-start scripts are fixed at
//! creation, so a plain reload would run the old copy. The rebuild reuses `tabs_sync`'s
//! profile-change path (close, then create with the current init scripts) on the shell's last
//! layout, with each tab's live URL, so route and layout are kept (scroll position is not).
use crate::app::{self, tabs_sync};
use crate::devmode::{self, Watcher};
use crate::{host, policy, tabs::TabLayout};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Mutex;
use std::time::Instant;
use tauri::{AppHandle, Manager};
/// Marks a tab's recorded profile as stale so `tabs_sync` rebuilds its webview.
const STALE: &str = "\u{0}dev-reload";
static FILES: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
static LAYOUT: Mutex<Option<(Vec<TabLayout>, Option<[f64; 2]>)>> = Mutex::new(None);
/// `path` read from disk (and watched from now on), or `embedded` when it is missing or empty.
pub fn from_disk(path: &str, embedded: &str) -> String {
let path = PathBuf::from(path);
let read = std::fs::read_to_string(&path).ok().filter(|text| !text.trim().is_empty());
if let Ok(mut files) = FILES.lock() {
files.insert(path);
}
read.unwrap_or_else(|| embedded.to_owned())
}
/// The shell's latest layout (from `tabs_sync`), to rebuild the tabs from.
pub(crate) fn remember_layout(items: &[TabLayout], viewport: Option<[f64; 2]>) {
if let Ok(mut layout) = LAYOUT.lock() {
*layout = Some((items.to_vec(), viewport));
}
}
/// Starts the watcher thread (debug builds, from the host's setup).
pub(crate) fn start(app: &AppHandle) {
let app = app.clone();
std::thread::Builder::new().name("wb-dev-loop".into()).spawn(move || watch_loop(app)).ok();
}
fn scan() -> BTreeMap<PathBuf, devmode::Signature> {
let files = FILES.lock().map(|files| files.clone()).unwrap_or_default();
files.into_iter().filter_map(|path| devmode::signature(&path).map(|sig| (path, sig))).collect()
}
fn watch_loop(app: AppHandle) {
let mut watcher: Watcher<PathBuf> = Watcher::new();
let mut known = 0;
loop {
std::thread::sleep(devmode::POLL);
let current = scan();
// A newly named file (the first tab just built its scripts) becomes part of the baseline.
if current.len() != known {
known = current.len();
watcher.reset();
}
let changes = watcher.observe(Instant::now(), current);
if !changes.is_empty() {
let names: Vec<String> = changes.iter().filter_map(|change| change.target().file_name()).map(|name| name.to_string_lossy().into_owned()).collect();
let started = Instant::now();
reload_tabs(&app);
eprintln!("[wayBetter dev] {} changed: tabs rebuilt in {} ms", names.join(", "), started.elapsed().as_millis());
}
}
}
/// Rebuilds every tab webview (fresh init scripts) on its current URL.
fn reload_tabs(app: &AppHandle) {
let Some((mut items, viewport)) = LAYOUT.lock().ok().and_then(|layout| layout.clone()) else { return };
let Some(shell) = app.get_webview(policy::SHELL_LABEL) else { return };
for item in &mut items {
let Some(tab) = host::tab_webview(app, &item.id) else { continue };
if let Ok(url) = tab.url() {
if matches!(url.scheme(), "http" | "https") {
item.url = url.to_string();
}
}
if let Ok(mut data) = app::profiles(app) {
data.tab_profiles.insert(policy::tab_label(&item.id), STALE.to_owned());
}
}
if let Err(error) = tauri::async_runtime::block_on(tabs_sync(shell, app.clone(), items, viewport)) {
eprintln!("[wayBetter dev] tab rebuild failed: {error}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_disk_reads_the_file_and_falls_back_to_the_embedded_copy() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("runtime.js");
let path = file.to_str().unwrap();
assert_eq!(from_disk(path, "embedded"), "embedded", "missing file");
std::fs::write(&file, " \n").unwrap();
assert_eq!(from_disk(path, "embedded"), "embedded", "empty file");
std::fs::write(&file, "fresh();").unwrap();
assert_eq!(from_disk(path, "embedded"), "fresh();");
assert!(scan().contains_key(&file), "a named file is watched");
}
}

View file

@ -61,21 +61,23 @@ pub struct Signature {
pub modified: Option<SystemTime>,
}
/// A stable change of one watched key (a [`Target`] for developer mode; the debug page-script
/// reload keys its files by path).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Change {
Changed(Target),
Removed(Target),
pub enum Change<K = Target> {
Changed(K),
Removed(K),
}
impl Change {
pub fn target(&self) -> &Target {
impl<K> Change<K> {
pub fn target(&self) -> &K {
match self {
Change::Changed(target) | Change::Removed(target) => target,
}
}
}
fn signature(path: &Path) -> Option<Signature> {
pub fn signature(path: &Path) -> Option<Signature> {
let meta = fs::metadata(path).ok()?;
meta.is_file().then(|| Signature { len: meta.len(), modified: meta.modified().ok() })
}
@ -103,25 +105,30 @@ pub fn scan(plugins_dir: &Path, theme_file: Option<&Path>) -> BTreeMap<Target, S
}
/// The debounced change detector. The first scan is the baseline (nothing is "changed" at start).
#[derive(Default)]
pub struct Watcher {
known: Option<BTreeMap<Target, Signature>>,
pub struct Watcher<K: Ord + Clone = Target> {
known: Option<BTreeMap<K, Signature>>,
/// Target → (signature seen, since when), for changes not yet stable.
pending: BTreeMap<Target, (Option<Signature>, Instant)>,
pending: BTreeMap<K, (Option<Signature>, Instant)>,
}
impl Watcher {
impl<K: Ord + Clone> Default for Watcher<K> {
fn default() -> Self {
Self { known: None, pending: BTreeMap::new() }
}
}
impl<K: Ord + Clone> Watcher<K> {
pub fn new() -> Self {
Self::default()
}
/// Feeds one scan; returns the changes that became stable, in reload order.
pub fn observe(&mut self, now: Instant, scan: BTreeMap<Target, Signature>) -> Vec<Change> {
pub fn observe(&mut self, now: Instant, scan: BTreeMap<K, Signature>) -> Vec<Change<K>> {
let Some(known) = self.known.as_mut() else {
self.known = Some(scan);
return Vec::new();
};
let mut targets: Vec<Target> = known.keys().cloned().collect();
let mut targets: Vec<K> = known.keys().cloned().collect();
for target in scan.keys() {
if !known.contains_key(target) {
targets.push(target.clone());
@ -141,7 +148,7 @@ impl Watcher {
}
}
let mut ready = Vec::new();
let stable: Vec<Target> = self
let stable: Vec<K> = self
.pending
.iter()
.filter(|(_, (_, since))| now.duration_since(*since) >= DEBOUNCE)
@ -171,7 +178,7 @@ impl Watcher {
}
/// Theme first (so plugins read the new `--wb-*` values), then custom CSS, then plugins by name.
pub fn reload_order(mut changes: Vec<Change>) -> Vec<Change> {
pub fn reload_order<K: Ord>(mut changes: Vec<Change<K>>) -> Vec<Change<K>> {
changes.sort_by(|a, b| a.target().cmp(b.target()));
changes
}

View file

@ -0,0 +1,89 @@
//! Focus and layering diagnostics, off unless asked for at launch (`--diag` or the environment
//! variable `WAYBETTER_DIAG=1`). While on, native code and the shell append one timestamped line per
//! event to `diag.log` in the app's log folder: menu open requests and every close with its reason,
//! overlays and `shell_raise` calls with their results, native focus calls, and the shell document's
//! focus, blur and visibility changes. A line is an event name and a few words: never a URL, a
//! query, page text or anything about an account ([`clean`] keeps plain printable ASCII only and
//! caps the length). The file is truncated at each launch with diagnostics on.
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
use std::time::Instant;
pub const ARG: &str = "--diag";
pub const ENV: &str = "WAYBETTER_DIAG";
pub const FILE: &str = "diag.log";
const MAX_LINE: usize = 300;
static ON: AtomicBool = AtomicBool::new(false);
static SINK: Mutex<Option<(std::fs::File, Instant)>> = Mutex::new(None);
/// Whether this launch asks for diagnostics (the first argument is the program itself).
pub fn asked<I, S>(args: I, env: Option<&str>) -> bool
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
env.is_some_and(|value| value == "1") || args.into_iter().skip(1).any(|arg| arg.as_ref() == ARG)
}
/// A line as it is written: printable ASCII only (anything else becomes `?`), one line, capped.
pub fn clean(line: &str) -> String {
line.chars().take(MAX_LINE).map(|ch| if (' '..='~').contains(&ch) { ch } else { '?' }).collect()
}
/// Starts writing to `dir/diag.log` (created, truncated). Nothing happens without a folder.
pub fn start(dir: Option<PathBuf>) {
let Some(dir) = dir else { return };
let _ = std::fs::create_dir_all(&dir);
if let Ok(file) = std::fs::File::create(dir.join(FILE)) {
if let Ok(mut sink) = SINK.lock() {
*sink = Some((file, Instant::now()));
ON.store(true, Ordering::SeqCst);
}
}
log("host", "diagnostics on");
}
pub fn active() -> bool {
ON.load(Ordering::SeqCst)
}
/// One event from `source` (`host` or `shell`), with milliseconds since the start.
pub fn log(source: &str, line: &str) {
if !active() {
return;
}
if let Ok(mut sink) = SINK.lock() {
if let Some((file, started)) = sink.as_mut() {
let _ = writeln!(file, "{:>9} {:<5} {}", started.elapsed().as_millis(), clean(source), clean(line));
let _ = file.flush();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn asked_by_the_argument_or_the_environment_only() {
assert!(asked(["app", "--diag"], None));
assert!(asked(["app"], Some("1")));
assert!(!asked(["app"], Some("yes")));
assert!(!asked(["--diag"], None), "the first argument is the program");
assert!(!asked(["app", "--diag=1", "diag"], None));
}
#[test]
fn a_line_is_plain_short_ascii() {
assert_eq!(clean("menu close: blur (hasFocus=false)"), "menu close: blur (hasFocus=false)");
assert_eq!(clean("two\nlines\ttab é"), "two?lines?tab ?");
assert_eq!(clean(&"x".repeat(1000)).len(), MAX_LINE);
// Off by default: nothing is written.
assert!(!active());
log("shell", "ignored");
}
}

View file

@ -0,0 +1,160 @@
//! Find in page. The shell owns the find bar; a tab's page is searched natively through the
//! shell-only `tab_find {id, action, query}`: `start` (a new query), `next`, `previous`, `stop`
//! (the bar closed: highlights go).
//!
//! The engine's own find is used where this build can drive it: WebView2's `ICoreWebView2Find`
//! (Windows, WebView2 Runtime with `ICoreWebView2_28`; its own find bar suppressed), which also
//! reports the match count and the active match (`tab-find` events to the shell). Everywhere else
//! (macOS, Linux, an older WebView2 Runtime) native code evaluates [`fallback_script`] in the tab:
//! the engine's `window.find`, which selects the next match and scrolls to it but counts nothing.
//!
//! The query is data: it goes from the shell to the engine and is kept nowhere (no file, no log,
//! no state in this crate). Tabs gain no command; a tab may only forward the key name `find`
//! through `tab_shortcut`. Only what the page has rendered can be found, as in a browser.
use serde::Serialize;
/// The shell event with the engine's counts for a tab's find session.
pub const EVENT_TAB_FIND: &str = "tab-find";
/// A query is one line of text a person typed.
pub const MAX_QUERY: usize = 256;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FindAction {
Start,
Next,
Previous,
Stop,
}
impl FindAction {
pub fn parse(action: &str) -> Result<Self, String> {
match action {
"start" => Ok(Self::Start),
"next" => Ok(Self::Next),
"previous" => Ok(Self::Previous),
"stop" => Ok(Self::Stop),
_ => Err("VALIDATION: unknown find action".into()),
}
}
}
/// What the engine reported for a tab's find session: how many matches and which one is active
/// (0-based; -1 for none).
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct FindState {
pub id: String,
pub count: i32,
pub index: i32,
}
impl FindState {
/// From WebView2's counts: its `ActiveMatchIndex` starts at 1 (and is -1 without an active match);
/// the shell's is 0-based. A negative count is none.
pub fn from_webview2(id: &str, count: i32, active_one_based: i32) -> Self {
let count = count.max(0);
let index = if (1..=count).contains(&active_one_based) { active_one_based - 1 } else { -1 };
Self { id: id.to_owned(), count, index }
}
}
/// A request as native code runs it: `start` carries the query, the others none.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FindRequest {
pub action: FindAction,
pub query: Option<String>,
}
/// Validates a `tab_find` call: a known action; for `start` a query of 1..=256 characters with no
/// control characters (one typed line). `next`/`previous` repeat the last query the shell sent for
/// the fallback (the engine's own find keeps its session), so they may carry it too.
pub fn request(action: &str, query: Option<&str>) -> Result<FindRequest, String> {
let action = FindAction::parse(action)?;
let query = match query {
Some(text) => {
let count = text.chars().count();
if count == 0 || count > MAX_QUERY || text.chars().any(char::is_control) {
return Err("VALIDATION: invalid find query".into());
}
Some(text.to_owned())
}
None => None,
};
if action == FindAction::Start && query.is_none() {
return Err("VALIDATION: find needs a query".into());
}
Ok(FindRequest { action, query: if action == FindAction::Stop { None } else { query } })
}
/// The script native code evaluates where the engine's find cannot be driven natively: the
/// engine's `window.find` (case-insensitive, wrapping), or clearing the selection for `stop`.
/// The query appears only as a JSON string literal; nothing is sent anywhere or stored in the page.
pub fn fallback_script(request: &FindRequest) -> String {
match (&request.action, &request.query) {
(FindAction::Stop, _) | (_, None) => {
"(()=>{try{const s=getSelection();if(s)s.removeAllRanges();}catch(e){}})();".to_owned()
}
(action, Some(query)) => {
let text = serde_json::to_string(query).unwrap_or_else(|_| "\"\"".into());
// A new query starts from the top of the page; next/previous continue from the selection.
let restart = if *action == FindAction::Start { "const s=getSelection();if(s)s.removeAllRanges();" } else { "" };
let backwards = *action == FindAction::Previous;
format!("(()=>{{try{{{restart}if(typeof window.find==='function')window.find({text},false,{backwards},true,false,false,false);}}catch(e){{}}}})();")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_request_is_a_known_action_and_one_typed_line() {
assert_eq!(request("start", Some("tauri")).unwrap(), FindRequest { action: FindAction::Start, query: Some("tauri".into()) });
assert_eq!(request("next", None).unwrap().action, FindAction::Next);
assert_eq!(request("previous", Some("x")).unwrap().query.as_deref(), Some("x"));
assert_eq!(request("stop", Some("left over")).unwrap(), FindRequest { action: FindAction::Stop, query: None }, "stop carries nothing");
assert!(request("start", None).is_err(), "start needs a query");
assert!(request("start", Some("")).is_err());
assert!(request("eval", Some("x")).is_err());
assert!(request("start", Some("two\nlines")).is_err());
assert!(request("start", Some("nul\0")).is_err());
assert!(request("start", Some(&"a".repeat(MAX_QUERY))).is_ok());
assert!(request("start", Some(&"a".repeat(MAX_QUERY + 1))).is_err());
assert!(request("start", Some(&"ş".repeat(MAX_QUERY))).is_ok(), "characters, not bytes");
}
#[test]
fn the_fallback_script_carries_the_query_only_as_a_string_literal() {
let script = fallback_script(&request("start", Some("it's \"quoted\" </script> \\ ${x} `y`")).unwrap());
assert!(script.contains(r#"window.find("it's \"quoted\" </script> \\ ${x} `y`",false,false,true"#), "{script}");
assert!(script.contains("removeAllRanges"), "a new query starts from the top");
let next = fallback_script(&request("next", Some("a")).unwrap());
assert!(next.contains(r#"window.find("a",false,false,true"#) && !next.contains("removeAllRanges"));
assert!(fallback_script(&request("previous", Some("a")).unwrap()).contains(r#"window.find("a",false,true,true"#));
// Stop (and a step without a query) only clears the selection.
for request in [request("stop", None).unwrap(), request("next", None).unwrap()] {
let script = fallback_script(&request);
assert!(script.contains("removeAllRanges") && !script.contains("window.find"), "{script}");
}
// Nothing leaves the page or stays in it: no network, storage, invoke or DOM writes.
for script in [script, next] {
for forbidden in ["fetch", "XMLHttpRequest", "localStorage", "sessionStorage", "invoke", "postMessage", "innerHTML", "document.cookie", "eval("] {
assert!(!script.contains(forbidden), "{forbidden} in {script}");
}
}
}
#[test]
fn counts_are_numbers_about_the_tab() {
let state = FindState { id: "t1".into(), count: 17, index: 2 };
assert_eq!(serde_json::to_string(&state).unwrap(), r#"{"id":"t1","count":17,"index":2}"#);
// WebView2 counts its active match from 1 (seen live: "2/2" for the first of two).
assert_eq!(FindState::from_webview2("t1", 2, 1), FindState { id: "t1".into(), count: 2, index: 0 });
assert_eq!(FindState::from_webview2("t1", 2, 2).index, 1);
assert_eq!(FindState::from_webview2("t1", 2, -1).index, -1, "no active match");
assert_eq!(FindState::from_webview2("t1", 2, 3).index, -1, "out of range");
assert_eq!(FindState::from_webview2("t1", 0, 0), FindState { id: "t1".into(), count: 0, index: -1 });
assert_eq!(FindState::from_webview2("t1", -5, 1).count, 0);
}
}

View file

@ -0,0 +1,66 @@
//! Google Fonts, native side, for every app that sets [`crate::app::AppConfig::fonts`]: the
//! shell-only `gfonts_*` commands ([`crate::commands::GFONTS`]) over [`crate::fonts`]'s downloads
//! and cache (`fonts.googleapis.com` and `fonts.gstatic.com` only, app-data `fonts/`). Site tabs
//! never request fonts and gain no command: native code hands them cached bytes
//! ([`crate::fonts::page_script_for`]).
//!
//! When a font is installed or removed the app's [`crate::app::SiteHooks::fonts_changed`] runs, so
//! it can give every site tab its theme (and the font bytes) again.
use crate::fonts::{self, InstalledFont};
use crate::gfonts::Weights;
use crate::host::shell_only;
use tauri::{AppHandle, Manager, Webview};
/// Opens the font cache in app data. Does nothing unless the app set [`crate::app::AppConfig::fonts`].
pub(crate) fn init(app: &AppHandle) {
if !crate::app::config(app).fonts {
return;
}
if let Ok(dir) = app.path().app_data_dir() {
fonts::init(&dir);
}
}
fn changed(app: &AppHandle) {
crate::app::hooks(app).fonts_changed(app);
}
#[tauri::command]
pub(crate) async fn gfonts_installed(webview: Webview) -> Result<Vec<InstalledFont>, String> {
shell_only(&webview)?;
fonts::installed()
}
#[tauri::command]
pub(crate) async fn gfonts_install(webview: Webview, app: AppHandle, family: String, weights: Weights) -> Result<InstalledFont, String> {
shell_only(&webview)?;
let installed = fonts::install(family, weights).await?;
changed(&app);
Ok(installed)
}
#[tauri::command]
pub(crate) async fn gfonts_remove(webview: Webview, app: AppHandle, family: String) -> Result<(), String> {
shell_only(&webview)?;
fonts::remove(&family)?;
changed(&app);
Ok(())
}
#[tauri::command]
pub(crate) async fn gfonts_faces(webview: Webview, family: String) -> Result<serde_json::Value, String> {
shell_only(&webview)?;
fonts::faces(&family)
}
#[tauri::command]
pub(crate) async fn gfonts_preview(webview: Webview, family: String, weights: Weights, text: String) -> Result<Vec<serde_json::Value>, String> {
shell_only(&webview)?;
fonts::preview(family, weights, text).await
}
/// The fonts commands ([`crate::commands::GFONTS`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![gfonts_installed, gfonts_install, gfonts_remove, gfonts_faces, gfonts_preview]
}

View file

@ -48,6 +48,10 @@ pub fn tab_webview<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<Webview<R
/// Evaluates `script` in every tab that is on the site right now.
pub fn eval_in_site_tabs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, script: &str) {
// Safe mode: site pages run none of the app's layers, so nothing is pushed into them either.
if crate::safe::active() {
return;
}
for (label, webview) in app.webviews() {
if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) {
let _ = webview.eval(script);
@ -89,6 +93,186 @@ pub fn tab_action<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str) -> Res
result.map_err(|error| format!("TAB: {error}"))
}
/// Whether Shift is held right now (asked once while the app starts: safe mode). Windows only;
/// elsewhere the launch argument is the way in.
pub fn shift_held() -> bool {
#[cfg(windows)]
{
use windows::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_SHIFT};
// SAFETY: a plain Win32 key-state read. The high bit means the key is down.
unsafe { GetAsyncKeyState(i32::from(VK_SHIFT.0)) < 0 }
}
#[cfg(not(windows))]
{
false
}
}
/// The remembered page zoom per tab ([`crate::zoom`], app data `zoom.json`), read once.
fn zooms<R: Runtime>(app: &AppHandle<R>) -> std::sync::MutexGuard<'static, crate::zoom::ZoomMap> {
use std::sync::{Mutex, OnceLock};
static ZOOMS: OnceLock<Mutex<crate::zoom::ZoomMap>> = OnceLock::new();
ZOOMS
.get_or_init(|| Mutex::new(read_json::<crate::zoom::ZoomMap>(app, crate::zoom::ZOOM_FILE).unwrap_or_default().validated()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// `tab_zoom`: sets tab `id`'s page zoom to `factor` (clamped to 25%..500%, the engine's own page
/// zoom) and remembers it for that tab; without a factor only reads it. Returns the factor in effect.
pub fn tab_zoom<R: Runtime>(app: &AppHandle<R>, id: &str, factor: Option<f64>) -> Result<f64, String> {
if !policy::valid_tab_id(id) {
return Err("VALIDATION: invalid tab id".into());
}
let Some(factor) = factor else { return Ok(zooms(app).get(id)) };
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
let (before, factor, saved) = {
let mut map = zooms(app);
let before = map.get(id);
let factor = map.set(id, factor)?;
(before, factor, map.clone())
};
if let Err(error) = tab.set_zoom(factor) {
// Not applied: what is remembered stays what the tab shows.
let _ = zooms(app).set(id, before);
return Err(format!("TAB: {error}"));
}
if factor != before {
write_json(app, crate::zoom::ZOOM_FILE, &saved)?;
}
Ok(factor)
}
/// A tab webview that was just created, or loads a page: it shows its remembered zoom (a new
/// webview starts at 100%). Tabs at 100% are left alone.
pub fn restore_tab_zoom<R: Runtime>(app: &AppHandle<R>, tab: &Webview<R>) {
let Some(id) = policy::tab_id(tab.label()) else { return };
let factor = zooms(app).get(id);
if factor != crate::zoom::DEFAULT {
let _ = tab.set_zoom(factor);
}
}
/// A closed tab's zoom is forgotten (a tab that comes back under the same id starts at 100%).
pub fn forget_tab_zoom<R: Runtime>(app: &AppHandle<R>, id: &str) {
let saved = {
let mut map = zooms(app);
map.forget(id).then(|| map.clone())
};
if let Some(map) = saved {
let _ = write_json(app, crate::zoom::ZOOM_FILE, &map);
}
}
/// `tab_find`: searches tab `id`'s page ([`crate::find`]). The engine's own find where this build
/// can drive it (WebView2's `ICoreWebView2Find`, which reports counts through `tab-find` events);
/// otherwise the evaluated `window.find` fallback. The query is kept nowhere.
pub fn tab_find<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str, query: Option<&str>) -> Result<(), String> {
if !policy::valid_tab_id(id) {
return Err("VALIDATION: invalid tab id".into());
}
let request = crate::find::request(action, query)?;
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
#[cfg(windows)]
{
let fallback = tab.clone();
let (app, id) = (app.clone(), id.to_owned());
tab.with_webview(move |platform| {
// The engine has no find interface (an older WebView2 Runtime): the evaluated fallback.
if !find_windows::run(&app, &platform, &id, &request) {
let _ = fallback.eval(crate::find::fallback_script(&request));
}
})
.map_err(|error| format!("TAB: {error}"))
}
#[cfg(not(windows))]
{
tab.eval(crate::find::fallback_script(&request)).map_err(|error| format!("TAB: {error}"))
}
}
/// WebView2's own find (`ICoreWebView2Find`, WebView2 Runtime with `ICoreWebView2_28`): the find
/// session, its highlights and its counts are the engine's; its own find bar stays hidden.
#[cfg(windows)]
mod find_windows {
use super::{emit_shell, AppHandle, Runtime};
use crate::find::{FindAction, FindRequest, FindState, EVENT_TAB_FIND};
use std::collections::HashSet;
use std::sync::{Mutex, OnceLock};
use webview2_com::Microsoft::Web::WebView2::Win32::{ICoreWebView2Environment15, ICoreWebView2Find, ICoreWebView2_28};
use webview2_com::{FindActiveMatchIndexChangedEventHandler, FindMatchCountChangedEventHandler, FindStartCompletedHandler};
use windows::core::{Interface, HSTRING};
/// Tab webviews whose find object already reports its counts (one pair of handlers each).
fn watched() -> std::sync::MutexGuard<'static, HashSet<String>> {
static WATCHED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
WATCHED.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
/// The tab's webview is gone: a new one under the same id registers its own handlers.
pub(super) fn forget(id: &str) {
watched().remove(id);
}
fn report<R: Runtime>(app: &AppHandle<R>, id: &str, find: &ICoreWebView2Find) {
let (mut count, mut index) = (0i32, -1i32);
// SAFETY: COM property reads on the live find object, on the main thread.
unsafe {
let _ = find.MatchCount(&mut count);
let _ = find.ActiveMatchIndex(&mut index);
}
emit_shell(app, EVENT_TAB_FIND, FindState::from_webview2(id, count, index));
}
/// Runs `request` with the engine's find on the main thread; false when this runtime has none.
pub(super) fn run<R: Runtime>(app: &AppHandle<R>, platform: &tauri::webview::PlatformWebview, id: &str, request: &FindRequest) -> bool {
// SAFETY: COM calls on this webview's live controller and environment, on the main thread
// (with_webview runs the closure there; the handlers run there too).
unsafe {
let Ok(core) = platform.controller().CoreWebView2() else { return false };
let (Ok(core), Ok(environment)) = (core.cast::<ICoreWebView2_28>(), platform.environment().cast::<ICoreWebView2Environment15>()) else { return false };
let Ok(find) = core.Find() else { return false };
if watched().insert(id.to_owned()) {
let mut token = 0i64;
let (count_app, count_id) = (app.clone(), id.to_owned());
let counted = FindMatchCountChangedEventHandler::create(Box::new(move |sender, _| {
if let Some(find) = sender { report(&count_app, &count_id, &find); }
Ok(())
}));
let _ = find.add_MatchCountChanged(&counted, &mut token);
let (index_app, index_id) = (app.clone(), id.to_owned());
let moved = FindActiveMatchIndexChangedEventHandler::create(Box::new(move |sender, _| {
if let Some(find) = sender { report(&index_app, &index_id, &find); }
Ok(())
}));
let _ = find.add_ActiveMatchIndexChanged(&moved, &mut token);
}
match (request.action, request.query.as_deref()) {
(FindAction::Start, Some(query)) => {
let Ok(options) = environment.CreateFindOptions() else { return false };
let _ = options.SetFindTerm(&HSTRING::from(query));
let _ = options.SetSuppressDefaultFindDialog(true);
let _ = options.SetShouldHighlightAllMatches(true);
let _ = options.SetIsCaseSensitive(false);
let _ = options.SetShouldMatchWord(false);
// A new query is a new session, from the first match.
let _ = find.Stop();
let (done_app, done_id, done_find) = (app.clone(), id.to_owned(), find.clone());
let started = FindStartCompletedHandler::create(Box::new(move |_| {
report(&done_app, &done_id, &done_find);
Ok(())
}));
let _ = find.Start(&options, &started);
}
(FindAction::Next, _) => { let _ = find.FindNext(); }
(FindAction::Previous, _) => { let _ = find.FindPrevious(); }
(FindAction::Stop, _) | (FindAction::Start, None) => { let _ = find.Stop(); }
}
}
true
}
}
/// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`).
pub fn forward_shortcut<R: Runtime>(app: &AppHandle<R>, id: String, shortcut: String) -> Result<(), String> {
if !tabs::valid_shortcut(&shortcut) {
@ -747,6 +931,11 @@ pub fn forget_tab<R: Runtime>(app: &AppHandle<R>, label: &str) {
}
#[cfg(not(windows))]
let _ = app;
// Its find session went with the webview: a new one under the same id registers its own handlers.
#[cfg(windows)]
if let Some(id) = policy::tab_id(label) {
find_windows::forget(id);
}
placements().forget(label);
}

View file

@ -10,6 +10,7 @@
//! - [`policy`]: webview labels, origin checks and the tab rectangle clamp (security boundary).
//! - [`profiles`]: account profiles, one WebView data directory each, with the account seen inside.
//! - [`plugins`]: owner-installed `*.plugin.js` files, custom CSS and bundled-plugin upgrades;
//! [`plugins::migrate`]: the one-time move of replaced plugin files to feature flags;
//! [`plugins::commands`]: the palette commands site tabs report and the script that runs one.
//! - [`hotfix`]: the signed, data-only hotfix channel.
//! - [`update`]: silent-update scheduling and the crash handshake.
@ -23,8 +24,14 @@
//! 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.
//! - `devloop` (debug builds with `app` only): page scripts read from disk and every tab rebuilt when
//! one changes; an app names its files with [`page_script!`].
//! - [`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.
//! - [`modes`]: the onboarding mode the owner started from (the presets are the app's feature table).
//! - [`zoom`]: page zoom per tab (a clamped factor the shell sets, remembered in `zoom.json`).
//! - [`safe`]: safe mode for one run (a flag in memory: site tabs get the tab bridge and nothing else).
//! - [`find`]: find in page (the request the shell sends, the fallback script; the query is kept nowhere).
//! - [`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;
@ -47,6 +54,8 @@ pub mod backup;
pub mod bridge;
pub mod commands;
pub mod devmode;
pub mod diag;
pub mod find;
#[cfg(feature = "net")]
pub mod fonts;
pub mod gfonts;
@ -54,9 +63,11 @@ pub mod hotfix;
pub mod i18n;
pub mod layout;
pub mod media;
pub mod modes;
pub mod plugins;
pub mod policy;
pub mod profiles;
pub mod safe;
pub mod settings;
pub mod site;
pub mod store;
@ -66,10 +77,74 @@ pub mod testkit;
pub mod theme;
pub mod update;
pub mod workspaces;
pub mod zoom;
#[cfg(feature = "app")]
pub mod app;
#[cfg(all(feature = "app", feature = "net"))]
mod store_commands;
#[cfg(feature = "app")]
pub mod media_commands;
#[cfg(feature = "app")]
mod sync_commands;
#[cfg(feature = "app")]
mod dev_commands;
#[cfg(feature = "app")]
mod backup_commands;
#[cfg(all(feature = "app", feature = "net"))]
mod fonts_commands;
#[cfg(all(feature = "app", feature = "net"))]
mod update_commands;
#[cfg(all(feature = "app", debug_assertions))]
pub mod devloop;
#[cfg(feature = "tauri")]
pub mod host;
#[cfg(all(feature = "tauri", feature = "net"))]
pub mod updater;
/// An app's page script for `SiteHooks::init_scripts`: `$embedded` (an `include_str!`) in every
/// build, except that a debug build reads `$file` (relative to the app crate's manifest directory)
/// from disk each time and falls back to the embedded copy when it is missing. The files named
/// this way are watched: a change rebuilds every tab (`devloop`). In a release build the disk arm
/// is not compiled at all: the expansion is `$embedded.to_owned()`, `$file` appears nowhere.
#[macro_export]
macro_rules! page_script {
($embedded:expr, $file:literal) => {{
#[cfg(debug_assertions)]
{
$crate::devloop::from_disk(concat!(env!("CARGO_MANIFEST_DIR"), "/", $file), $embedded)
}
#[cfg(not(debug_assertions))]
{
($embedded).to_owned()
}
}};
}
#[cfg(test)]
mod release_guard {
/// Release builds must not contain the dev loop: every mention of it in this crate is behind
/// `cfg(debug_assertions)` (checked on the source, so it also holds when only debug is built).
#[test]
fn every_devloop_mention_is_debug_only() {
for (file, source) in [("lib.rs", include_str!("lib.rs")), ("app.rs", include_str!("app.rs"))] {
// This test module itself talks about the dev loop; only the code before it counts.
let lines: Vec<&str> = source.split("mod release_guard").next().unwrap_or(source).lines().collect();
for (index, line) in lines.iter().enumerate() {
let code = line.trim_start();
if code.starts_with("//") || !(code.contains("devloop::") || code.starts_with("pub mod devloop")) || code.contains("$crate::devloop") {
continue;
}
let gated = (index.saturating_sub(2)..index).any(|before| lines[before].contains("debug_assertions"));
assert!(gated, "{file}:{}: devloop used outside cfg(debug_assertions)", index + 1);
}
}
}
/// `cargo test --release`: the macro is just the embedded text.
#[cfg(not(debug_assertions))]
#[test]
fn release_page_script_is_the_embedded_copy() {
assert_eq!(crate::page_script!("embedded", "no/such/file.js"), "embedded");
}
}

View file

@ -0,0 +1,264 @@
//! The shell's Media panel, native side, for every app that sets [`crate::app::AppConfig::media`]:
//! gallery folders picked through the native dialog, image previews read only from inside those
//! folders, and the opt-in local clipboard history ([`crate::commands::MEDIA`]). Every command is
//! shell-only; site tabs get nothing. The rules (path containment, size caps, the private-copy
//! rule of the clipboard watcher) are [`crate::media`]'s; this module keeps the state, the files
//! and the polling thread.
//!
//! Attaching an image to a site's composer is the app's (it knows the site's composer); it reads
//! the bytes through [`gallery_file`] and [`clip_image`], which apply the same checks.
use crate::app::{config, tr};
use crate::host::{data_file, emit_shell, read_json, shell_only, write_json};
use crate::media::clipboard::{self, Seen};
use crate::media::{self, ClipHistory, ClipItem, ImageEntry, MediaSettings};
use sha2::{Digest, Sha256};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use tauri::{AppHandle, Manager, State, Webview};
use tauri_plugin_dialog::DialogExt;
const MEDIA_FILE: &str = "media.json";
const CLIP_DIR: &str = "clipboard";
const POLL: Duration = Duration::from_millis(1_000);
struct MediaData {
settings: MediaSettings,
history: ClipHistory,
}
pub(crate) struct MediaState(Mutex<MediaData>);
fn lock(state: &MediaState) -> Result<MutexGuard<'_, MediaData>, String> {
state.0.lock().map_err(|_| "STATE: media state poisoned".to_string())
}
fn media_state(app: &AppHandle) -> Result<State<'_, MediaState>, String> {
app.try_state::<MediaState>().ok_or_else(|| "UNAVAILABLE: this app has no media panel".to_owned())
}
fn clip_dir(app: &AppHandle) -> Option<PathBuf> {
data_file(app, CLIP_DIR)
}
fn load_history(app: &AppHandle) -> ClipHistory {
clip_dir(app).map(|dir| media::load_history(&dir)).unwrap_or_default()
}
fn save_history(app: &AppHandle, history: &ClipHistory) -> Result<(), String> {
media::save_history(&clip_dir(app).ok_or("STORAGE: no application data directory")?, history)
}
fn delete_files(app: &AppHandle, items: &[ClipItem]) {
if let Some(dir) = clip_dir(app) {
media::delete_files(&dir, items);
}
}
/// Loads the settings and the history and starts the clipboard watcher (idle until the owner turns
/// the history on). Does nothing unless the app set [`crate::app::AppConfig::media`].
pub(crate) fn init(app: &AppHandle) {
if !config(app).media {
return;
}
let settings = read_json::<MediaSettings>(app, MEDIA_FILE)
.and_then(|settings| settings.validated().ok())
.unwrap_or_default();
let history = load_history(app);
app.manage(MediaState(Mutex::new(MediaData { settings, history })));
let handle = app.clone();
std::thread::spawn(move || poll_clipboard(handle));
}
// ---------------------------------------------------------------------------------------------
// Clipboard polling (opt-in; the watcher never reads a copy marked private)
fn poll_clipboard(app: AppHandle) {
let enabled = || {
app.try_state::<MediaState>()
.and_then(|state| lock(&state).ok().map(|data| data.settings.clipboard_enabled))
.unwrap_or(false)
};
let title = config(&app).title;
clipboard::watch(POLL, enabled, |seen| {
if let Err(error) = record(&app, seen) {
eprintln!("{title}: clipboard history: {error}");
}
});
}
/// 32 hex characters (what [`media::valid_clip_id`] accepts): not a secret, only unique.
fn new_clip_id(hash: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
let digest = Sha256::digest(format!("{nanos}:{}:{hash}", COUNTER.fetch_add(1, Ordering::Relaxed)));
digest.iter().take(16).map(|byte| format!("{byte:02x}")).collect()
}
fn record(app: &AppHandle, seen: Seen) -> Result<(), String> {
let at = chrono::Utc::now().timestamp_millis();
let item = match seen {
Seen::Text(hash, text) => ClipItem { id: new_clip_id(&hash), kind: "text".into(), text: Some(text), file: None, hash, at },
Seen::Image(hash, width, height, rgba) => {
let id = new_clip_id(&hash);
let state = media_state(app)?;
if lock(&state)?.history.has_hash(&hash) {
// Already stored: just move it to the front, no new file.
ClipItem { id, kind: "image".into(), text: None, file: None, hash, at }
} else {
let png = media::encode_png(width, height, rgba).ok_or("image encoding failed")?;
let dir = clip_dir(app).ok_or("STORAGE: no application data directory")?;
std::fs::create_dir_all(&dir).map_err(|error| format!("STORAGE: {error}"))?;
let file = format!("{id}.png");
std::fs::write(dir.join(&file), png).map_err(|error| format!("STORAGE: {error}"))?;
ClipItem { id, kind: "image".into(), text: None, file: Some(file), hash, at }
}
}
};
let state = media_state(app)?;
let evicted = {
let mut data = lock(&state)?;
let max = data.settings.clipboard_max;
let evicted = data.history.push(item, max);
save_history(app, &data.history)?;
evicted
};
delete_files(app, &evicted);
emit_shell(app, "clipboard-changed", ());
Ok(())
}
// ---------------------------------------------------------------------------------------------
// What an app needs to attach an image
/// The bytes of a gallery image, only from inside a gallery folder the owner added (symlinks and
/// `..` cannot leave it), with its resolved path (for the name and the type).
pub fn gallery_file(app: &AppHandle, path: &str) -> Result<(PathBuf, Vec<u8>), String> {
let state = media_state(app)?;
let folders = lock(&state)?.settings.folders.clone();
let real = media::resolve_in_folders(&folders, path)?;
let bytes = std::fs::read(&real).map_err(|error| format!("STORAGE: {error}"))?;
Ok((real, bytes))
}
/// The PNG of a clipboard-history image.
pub fn clip_image(app: &AppHandle, id: &str) -> Result<Vec<u8>, String> {
if !media::valid_clip_id(id) {
return Err("VALIDATION: invalid clipboard item".into());
}
let state = media_state(app)?;
let file = lock(&state)?
.history
.items
.iter()
.find(|item| item.id == id)
.and_then(|item| item.file.clone())
.ok_or("CLIPBOARD: image not found")?;
let dir = clip_dir(app).ok_or("STORAGE: no application data directory")?;
std::fs::read(dir.join(file)).map_err(|error| format!("STORAGE: {error}"))
}
// ---------------------------------------------------------------------------------------------
// Commands (shell only)
#[tauri::command]
pub(crate) async fn media_get(webview: Webview, app: AppHandle) -> Result<MediaSettings, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let settings = lock(&state)?.settings.clone();
Ok(settings)
}
/// Changes the clipboard options and removes folders. New folders are only added through the
/// native dialog (`gallery_add_folder`), so the shell cannot widen the file scope by itself.
#[tauri::command]
pub(crate) async fn media_set(webview: Webview, app: AppHandle, settings: MediaSettings) -> Result<MediaSettings, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let settings = settings.validated()?;
let evicted = {
let mut data = lock(&state)?;
if settings.folders.iter().any(|f| !data.settings.folders.contains(f)) {
return Err("FORBIDDEN: add gallery folders with the folder picker".into());
}
write_json(&app, MEDIA_FILE, &settings)?;
data.settings = settings.clone();
let evicted = data.history.trim(settings.clipboard_max);
if !evicted.is_empty() {
save_history(&app, &data.history)?;
}
evicted
};
delete_files(&app, &evicted);
Ok(settings)
}
#[tauri::command]
pub(crate) async fn gallery_add_folder(webview: Webview, app: AppHandle) -> Result<MediaSettings, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let title = tr(&app, "native.dialog.galleryFolder", "Add a gallery folder");
let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).blocking_pick_folder();
let Some(picked) = picked else { return Ok(lock(&state)?.settings.clone()) };
let path = picked.into_path().map_err(|_| "VALIDATION: not a local folder")?;
let mut data = lock(&state)?;
let mut next = data.settings.clone();
if next.add_folder(&path)? {
write_json(&app, MEDIA_FILE, &next)?;
data.settings = next;
}
Ok(data.settings.clone())
}
#[tauri::command]
pub(crate) async fn gallery_list(webview: Webview, app: AppHandle, limit: Option<usize>) -> Result<Vec<ImageEntry>, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let folders = lock(&state)?.settings.folders.clone();
Ok(media::list_recent(&folders, limit.unwrap_or(60)))
}
#[tauri::command]
pub(crate) async fn gallery_thumb(webview: Webview, app: AppHandle, path: String) -> Result<String, String> {
shell_only(&webview)?;
let (real, bytes) = gallery_file(&app, &path)?;
Ok(media::data_url(media::mime_for(&real), &bytes))
}
#[tauri::command]
pub(crate) async fn clip_list(webview: Webview, app: AppHandle) -> Result<Vec<ClipItem>, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let items = lock(&state)?.history.items.clone();
Ok(items)
}
#[tauri::command]
pub(crate) async fn clip_thumb(webview: Webview, app: AppHandle, id: String) -> Result<String, String> {
shell_only(&webview)?;
Ok(media::data_url("image/png", &clip_image(&app, &id)?))
}
#[tauri::command]
pub(crate) async fn clip_remove(webview: Webview, app: AppHandle, id: Option<String>) -> Result<Vec<ClipItem>, String> {
shell_only(&webview)?;
let state = media_state(&app)?;
let (removed, items) = {
let mut data = lock(&state)?;
let removed = match id {
Some(id) => data.history.remove(&id).into_iter().collect(),
None => std::mem::take(&mut data.history.items),
};
save_history(&app, &data.history)?;
(removed, data.history.items.clone())
};
delete_files(&app, &removed);
Ok(items)
}
/// The media commands ([`crate::commands::MEDIA`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![media_get, media_set, gallery_add_folder, gallery_list, gallery_thumb, clip_list, clip_thumb, clip_remove]
}

View file

@ -0,0 +1,132 @@
//! The onboarding mode: which preset (Basic / Advanced / Power User, whatever the app defines) the
//! owner started from, and whether the first-run screen was answered. A mode is a starting point:
//! the presets themselves are the app's (its feature table) and are applied by the shell through
//! `features_set`; native code only remembers the choice (`modes.json`), so the screen shows once.
//! With the choice it keeps what the preset was at that moment (`preset`: flag names and on/off,
//! data the shell hands over), so the shell can tell "the owner changed features" from "an update
//! made the preset larger" later. Native code never reads it and never applies anything.
//!
//! `existing` is decided natively, once, on the first start of a version that has modes: an app
//! data folder that already held settings belongs to someone who set the app up before. They keep
//! exactly what they have, and the screen they see can be dismissed without choosing.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub const MODES_FILE: &str = "modes.json";
const MAX_MODE_ID: usize = 32;
const MAX_PRESET_FLAGS: usize = 512;
const MAX_FLAG_NAME: usize = 64;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ModeState {
/// The mode chosen last; `None` = never chosen (the app's defaults, or an earlier setup).
pub mode: Option<String>,
/// The first-run screen was answered or dismissed.
pub onboarded: bool,
/// The app was set up before modes existed.
pub existing: bool,
/// The chosen mode's preset as it was when it was applied (flag name to on/off). `None`: not
/// known (no mode, or a choice made by a version that did not keep it).
#[serde(skip_serializing_if = "Option::is_none")]
pub preset: Option<BTreeMap<String, bool>>,
}
/// A flag name: letters, digits, `.`, `-` and `_`, at most 64 characters.
fn valid_flag(name: &str) -> bool {
!name.is_empty() && name.len() <= MAX_FLAG_NAME && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
}
/// A mode id: lowercase letters, digits and `-`, starting with a letter, at most 32 characters.
pub fn valid_mode(id: &str) -> bool {
!id.is_empty()
&& id.len() <= MAX_MODE_ID
&& id.as_bytes()[0].is_ascii_lowercase()
&& id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
impl ModeState {
/// The state on the first start: nothing chosen, the screen still to be shown.
pub fn first_run(existing: bool) -> Self {
Self { mode: None, onboarded: false, existing, preset: None }
}
pub fn validated(self) -> Result<Self, String> {
if self.mode.as_deref().is_some_and(|mode| !valid_mode(mode)) {
return Err("VALIDATION: invalid mode".into());
}
if let Some(preset) = &self.preset {
if self.mode.is_none() || preset.len() > MAX_PRESET_FLAGS || !preset.keys().all(|name| valid_flag(name)) {
return Err("VALIDATION: invalid mode preset".into());
}
}
Ok(self)
}
/// What the shell may change: the chosen mode, that the screen was answered, and the preset
/// the mode had when it was applied. Without `preset` the stored one stays while the mode
/// stays, and is forgotten when the mode changes. `existing` stays what native code decided.
pub fn chosen(&self, mode: Option<String>, onboarded: bool, preset: Option<BTreeMap<String, bool>>) -> Result<Self, String> {
let preset = match preset {
Some(preset) => Some(preset),
None if mode == self.mode => self.preset.clone(),
None => None,
};
Self { mode, onboarded, existing: self.existing, preset }.validated()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mode_ids_are_short_plain_words() {
for good in ["basic", "advanced", "power-user", "m2"] {
assert!(valid_mode(good), "{good}");
}
for bad in ["", "Basic", "2fast", "a b", "a/b", "../x", &"a".repeat(33)] {
assert!(!valid_mode(bad), "{bad}");
}
}
#[test]
fn the_shell_chooses_a_mode_but_never_what_kind_of_install_this_is() {
let fresh = ModeState::first_run(false);
assert_eq!(fresh, ModeState { mode: None, onboarded: false, existing: false, preset: None });
let existing = ModeState::first_run(true);
let dismissed = existing.chosen(None, true, None).unwrap();
assert_eq!(dismissed, ModeState { mode: None, onboarded: true, existing: true, preset: None }, "dismissed without choosing: nothing else changes");
let chosen = dismissed.chosen(Some("power".into()), true, None).unwrap();
assert_eq!(chosen.mode.as_deref(), Some("power"));
assert!(chosen.existing);
assert!(existing.chosen(Some("<script>".into()), true, None).is_err());
// The file reads back; missing fields take the defaults; unknown input never panics.
let json = serde_json::to_string(&chosen).unwrap();
assert_eq!(json, r#"{"mode":"power","onboarded":true,"existing":true}"#);
assert_eq!(serde_json::from_str::<ModeState>("{}").unwrap(), ModeState::default());
assert!(serde_json::from_str::<ModeState>(r#"{"mode":"BAD MODE"}"#).unwrap().validated().is_err());
}
#[test]
fn the_preset_of_the_moment_is_kept_with_the_choice() {
let preset = |pairs: &[(&str, bool)]| pairs.iter().map(|(name, on)| (name.to_string(), *on)).collect::<BTreeMap<_, _>>();
let start = ModeState::first_run(false);
let chosen = start.chosen(Some("advanced".into()), true, Some(preset(&[("reader.readMarker", true), ("area.chat", false)]))).unwrap();
assert_eq!(serde_json::to_string(&chosen).unwrap(), r#"{"mode":"advanced","onboarded":true,"existing":false,"preset":{"area.chat":false,"reader.readMarker":true}}"#);
// The same mode again without a preset: what is stored stays. Another mode without one: forgotten.
assert_eq!(chosen.chosen(Some("advanced".into()), true, None).unwrap().preset, chosen.preset);
assert_eq!(chosen.chosen(Some("basic".into()), true, None).unwrap().preset, None);
assert_eq!(chosen.chosen(Some("advanced".into()), true, Some(preset(&[]))).unwrap().preset, Some(preset(&[])));
// Flag names only, a bounded number of them, and never without a mode.
assert!(start.chosen(Some("advanced".into()), true, Some(preset(&[("<b>", true)]))).is_err());
assert!(start.chosen(Some("advanced".into()), true, Some(preset(&[(&"a".repeat(65), true)]))).is_err());
assert!(start.chosen(None, true, Some(preset(&[("hideAds", true)]))).is_err());
let many = (0..=MAX_PRESET_FLAGS).map(|index| (format!("flag{index}"), true)).collect::<BTreeMap<_, _>>();
assert!(start.chosen(Some("advanced".into()), true, Some(many)).is_err());
// A file written before the preset was kept reads as "not known".
assert_eq!(serde_json::from_str::<ModeState>(r#"{"mode":"advanced","onboarded":true,"existing":true}"#).unwrap().preset, None);
}
}

View file

@ -13,6 +13,7 @@
//! it. A plugin without the line is "legacy" (full API, labelled so in the app).
pub mod commands;
pub mod migrate;
use serde::Serialize;
use sha2::{Digest, Sha256};
@ -43,6 +44,9 @@ pub struct PluginHost {
pub example: Option<(&'static str, &'static str)>,
/// First-party plugins, written disabled and upgraded (see [`PluginStore::install_bundled`]).
pub bundled: &'static [(&'static str, &'static str)],
/// First-party plugin files the app replaced with feature flags: never written again, and moved
/// over once (see [`migrate`]).
pub superseded: &'static [migrate::Superseded],
}
fn content_hash(bytes: &[u8]) -> String {
@ -279,7 +283,7 @@ impl PluginStore {
.unwrap_or_default();
let before = manifest.clone();
for (file, source) in bundled {
if !valid_file_name(file) {
if !valid_file_name(file) || self.host.superseded.iter().any(|row| row.file == *file) {
continue;
}
let path = self.dir.join(file);
@ -535,6 +539,7 @@ mod tests {
css_element_id: "demo-css",
example: Some(("example.plugin.js", "/**\n * @name Example\n */\nmodule.exports = class { start(){} stop(){} };")),
bundled: &[("wb-one.plugin.js", "/** @name One */ module.exports = {};")],
superseded: &[],
};
#[test]

View file

@ -0,0 +1,316 @@
//! One-time move of first-party plugin files to feature flags.
//!
//! When an app turns a bundled plugin into a feature of an area plugin (its code now runs from the
//! app's feature registry behind a flag), the old file must not keep running next to it, and the
//! owner must not lose what they had on. The app lists the files it replaced ([`Superseded`]:
//! file -> flag) in its [`super::PluginHost`]; [`PluginStore::migrate_superseded`] runs once per
//! listed file, at startup, and leaves the owner's effective state exactly as it was:
//!
//! | The old file is ... | Result |
//! |--------------------------------------------------------|------------------------------------------------------|
//! | enabled, as shipped (never edited) | its flag is turned on; the file and its entry go |
//! | disabled, as shipped | the flag stays off; the file goes |
//! | edited by the owner (or a file of their own) | kept with its on/off state; the flag is left off |
//! | deleted earlier by the owner | nothing; the flag stays off |
//! | not there at all (a fresh install) | nothing |
//!
//! "As shipped" means byte-identical to what the app last wrote (`bundled.json`). The marker
//! (`migrations.json` in the plugins folder) is written last, so a crash in between repeats the
//! steps, and every step is safe to repeat: flags are only ever turned on, and a file already
//! removed is simply not there. The same table maps the `enabled` list of an imported backup
//! ([`map_backup`]).
use super::{content_hash, valid_file_name, PluginStore, BUNDLED_FILE, STATE_FILE};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
/// Which superseded files were handled already (in the plugins folder).
pub const MARKER_FILE: &str = "migrations.json";
/// An old first-party plugin file and the feature flag that replaces it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Superseded {
pub file: &'static str,
pub flag: &'static str,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
struct Marker {
superseded: BTreeSet<String>,
}
/// What one run did (empty when there was nothing left to do).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Outcome {
/// Flags turned on: their old plugin was enabled and as shipped.
pub flags_on: Vec<String>,
/// Files removed (as shipped).
pub removed: Vec<String>,
/// Files kept because the owner changed them; their replacement flag was left alone.
pub kept: Vec<String>,
}
impl PluginStore {
/// Handles every file of `table` that was not handled before. `turn_on` persists the flags to
/// turn on (it must only ever set them to true and keep every other flag) and runs before any
/// file is touched: when it fails nothing has changed and the next start tries again.
pub fn migrate_superseded(&self, table: &[Superseded], turn_on: impl FnOnce(&[String]) -> Result<(), String>) -> Result<Outcome, String> {
let marker_path = self.dir.join(MARKER_FILE);
let mut marker: Marker = fs::read_to_string(&marker_path).ok().and_then(|raw| serde_json::from_str(&raw).ok()).unwrap_or_default();
let pending: Vec<&Superseded> = table.iter().filter(|row| valid_file_name(row.file) && !marker.superseded.contains(row.file)).collect();
if pending.is_empty() {
return Ok(Outcome::default());
}
fs::create_dir_all(&self.dir).map_err(|error| format!("PLUGINS: {error}"))?;
let manifest_path = self.dir.join(BUNDLED_FILE);
let mut manifest: BTreeMap<String, String> = fs::read_to_string(&manifest_path).ok().and_then(|raw| serde_json::from_str(&raw).ok()).unwrap_or_default();
let mut enabled = self.enabled_set();
let mut outcome = Outcome::default();
let mut gone: Vec<&str> = Vec::new();
for row in &pending {
match fs::read(self.dir.join(row.file)) {
// Deleted earlier (or never installed): nothing to move; a stale enabled entry goes.
Err(_) => gone.push(row.file),
Ok(bytes) => {
if manifest.get(row.file).is_some_and(|installed| *installed == content_hash(&bytes)) {
if enabled.contains(row.file) {
outcome.flags_on.push(row.flag.to_owned());
}
outcome.removed.push(row.file.to_owned());
} else {
outcome.kept.push(row.file.to_owned());
}
}
}
}
turn_on(&outcome.flags_on)?;
let before = enabled.len();
for file in outcome.removed.iter().map(String::as_str).chain(gone.iter().copied()) {
enabled.remove(file);
}
if enabled.len() != before {
let json = serde_json::to_string_pretty(&enabled).map_err(|_| "PLUGINS: serialization failed")?;
fs::write(self.dir.join(STATE_FILE), json).map_err(|error| format!("PLUGINS: {error}"))?;
}
for file in &outcome.removed {
match fs::remove_file(self.dir.join(file)) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("PLUGINS: {error}")),
}
}
// The app no longer ships these files: their "last written" entries go with them. A kept
// (edited) file is an ordinary plugin of the owner's from here on.
let entries = manifest.len();
for row in &pending {
manifest.remove(row.file);
}
if manifest.len() != entries {
let json = serde_json::to_string_pretty(&manifest).map_err(|_| "PLUGINS: serialization failed")?;
fs::write(&manifest_path, json).map_err(|error| format!("PLUGINS: {error}"))?;
}
marker.superseded.extend(pending.iter().map(|row| row.file.to_owned()));
let json = serde_json::to_string_pretty(&marker).map_err(|_| "PLUGINS: serialization failed")?;
fs::write(&marker_path, json).map_err(|error| format!("PLUGINS: {error}"))?;
Ok(outcome)
}
}
/// The `enabled` list of an imported backup, mapped through `table`: a superseded file that the
/// backup only names (it was as shipped, so the backup carries no copy) becomes its flag and leaves
/// the list; one the backup carries a copy of (`files`: the owner's edited version) stays a plugin.
/// Returns the list to enable and the flags to turn on.
pub fn map_backup(enabled: Vec<String>, files: &[String], table: &[Superseded]) -> (Vec<String>, Vec<String>) {
let mut keep = Vec::with_capacity(enabled.len());
let mut flags_on = Vec::new();
for name in enabled {
match table.iter().find(|row| row.file == name) {
Some(row) if !files.contains(&name) => {
if !flags_on.iter().any(|flag| flag == row.flag) {
flags_on.push(row.flag.to_owned());
}
}
_ => keep.push(name),
}
}
(keep, flags_on)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plugins::PluginHost;
use std::cell::RefCell;
use std::path::Path;
static HOST: PluginHost = PluginHost {
runtime_global: "Demo",
origin: "https://site.test",
product: "wayBetter for Test",
css_element_id: "demo-css",
example: None,
bundled: &[("wb-stays.plugin.js", "stays v1")],
superseded: TABLE,
};
/// The previous version of the app: it still shipped the files.
static OLD_HOST: PluginHost = PluginHost { superseded: &[], ..HOST };
const TABLE: &[Superseded] = &[
Superseded { file: "wb-focus.plugin.js", flag: "navigation.focusMode" },
Superseded { file: "wb-keys.plugin.js", flag: "navigation.keyboardPlus" },
Superseded { file: "wb-edited.plugin.js", flag: "navigation.edited" },
Superseded { file: "wb-deleted.plugin.js", flag: "navigation.deleted" },
];
/// What the previous version shipped.
const OLD: &[(&str, &str)] = &[
("wb-stays.plugin.js", "stays v1"),
("wb-focus.plugin.js", "focus v1"),
("wb-keys.plugin.js", "keys v1"),
("wb-edited.plugin.js", "edited v1"),
("wb-deleted.plugin.js", "deleted v1"),
];
/// A plugins folder as the previous version left it: Focus and the edited one enabled, Keys off.
fn upgraded() -> (tempfile::TempDir, PluginStore) {
let root = tempfile::tempdir().unwrap();
let old = PluginStore::new(root.path().join("plugins"), &OLD_HOST);
fs::create_dir_all(old.dir()).unwrap();
old.install_bundled(OLD);
let store = PluginStore::new(root.path().join("plugins"), &HOST);
fs::write(store.dir().join("wb-edited.plugin.js"), "my own version").unwrap();
fs::remove_file(store.dir().join("wb-deleted.plugin.js")).unwrap();
fs::write(store.dir().join("mine.plugin.js"), "mine").unwrap();
for file in ["wb-focus.plugin.js", "wb-edited.plugin.js", "mine.plugin.js", "wb-stays.plugin.js"] {
store.set_enabled(file, true).unwrap();
}
(root, store)
}
fn exists(store: &PluginStore, file: &str) -> bool {
store.dir().join(file).exists()
}
fn marker(dir: &Path) -> Vec<String> {
let marker: Marker = serde_json::from_str(&fs::read_to_string(dir.join(MARKER_FILE)).unwrap()).unwrap();
marker.superseded.into_iter().collect()
}
#[test]
fn every_case_keeps_the_owners_effective_state() {
let (_root, store) = upgraded();
let turned_on = RefCell::new(Vec::new());
let outcome = store.migrate_superseded(TABLE, |flags| { turned_on.borrow_mut().extend(flags.to_vec()); Ok(()) }).unwrap();
// Enabled and as shipped: the flag takes over and the file goes.
assert_eq!(outcome.flags_on, ["navigation.focusMode"]);
assert_eq!(*turned_on.borrow(), ["navigation.focusMode"]);
assert!(!exists(&store, "wb-focus.plugin.js") && !store.is_enabled("wb-focus.plugin.js"));
// Disabled and as shipped: the file goes, its flag stays off.
assert!(!exists(&store, "wb-keys.plugin.js"));
assert_eq!(outcome.removed, ["wb-focus.plugin.js", "wb-keys.plugin.js"]);
// Edited by the owner: kept, still enabled, and the built-in replacement is left off.
assert_eq!(outcome.kept, ["wb-edited.plugin.js"]);
assert_eq!(fs::read_to_string(store.dir().join("wb-edited.plugin.js")).unwrap(), "my own version");
assert!(store.is_enabled("wb-edited.plugin.js"));
// Deleted earlier: still deleted, flag untouched.
assert!(!exists(&store, "wb-deleted.plugin.js"));
// Everything else is as it was.
assert!(store.is_enabled("mine.plugin.js") && store.is_enabled("wb-stays.plugin.js"));
assert_eq!(fs::read_to_string(store.dir().join("wb-stays.plugin.js")).unwrap(), "stays v1");
assert_eq!(marker(store.dir()), ["wb-deleted.plugin.js", "wb-edited.plugin.js", "wb-focus.plugin.js", "wb-keys.plugin.js"]);
// Nothing runs twice: no old file is enabled while its flag is on.
for row in TABLE {
assert!(!(store.is_enabled(row.file) && outcome.flags_on.iter().any(|flag| flag == row.flag)), "{}", row.file);
}
// The removed files are gone from what the app "last wrote"; the next start does not bring them back.
store.ensure().unwrap();
assert!(!exists(&store, "wb-focus.plugin.js") && !exists(&store, "wb-keys.plugin.js"));
let manifest: BTreeMap<String, String> = serde_json::from_str(&fs::read_to_string(store.dir().join(BUNDLED_FILE)).unwrap()).unwrap();
assert_eq!(manifest.keys().collect::<Vec<_>>(), ["wb-stays.plugin.js"]);
// Even an app that still lists a superseded file as bundled never writes it again.
store.install_bundled(OLD);
assert!(!exists(&store, "wb-focus.plugin.js") && !exists(&store, "wb-deleted.plugin.js"));
}
#[test]
fn it_runs_once_and_later_rows_are_handled_when_they_appear() {
let (_root, store) = upgraded();
let first = &TABLE[..1];
let outcome = store.migrate_superseded(first, |_| Ok(())).unwrap();
assert_eq!(outcome.flags_on, ["navigation.focusMode"]);
assert!(exists(&store, "wb-keys.plugin.js"), "a file the table does not list yet is left alone");
// Again: nothing to do, and the closure is not asked for anything.
let again = store.migrate_superseded(first, |_| panic!("already done")).unwrap();
assert_eq!(again, Outcome::default());
// The owner later drops a file of that name in: it is theirs now, not migrated again.
fs::write(store.dir().join("wb-focus.plugin.js"), "mine now").unwrap();
store.set_enabled("wb-focus.plugin.js", true).unwrap();
// A later version supersedes more files: only the new rows are handled.
let later = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
assert_eq!(later.removed, ["wb-keys.plugin.js"]);
assert!(store.is_enabled("wb-focus.plugin.js") && exists(&store, "wb-focus.plugin.js"));
}
#[test]
fn a_failure_or_crash_between_steps_is_repeated_safely() {
// The flags could not be saved: nothing changed, and the next start tries again.
let (_root, store) = upgraded();
assert!(store.migrate_superseded(TABLE, |_| Err("DISK: full".into())).is_err());
assert!(exists(&store, "wb-focus.plugin.js") && store.is_enabled("wb-focus.plugin.js"));
assert!(!store.dir().join(MARKER_FILE).exists());
let retry = store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
assert_eq!(retry.flags_on, ["navigation.focusMode"]);
// A crash after the flags were saved and the enabled list rewritten, before the files went
// and the marker was written: the flag is already on (saved), so the rerun only cleans up.
let (_root, store) = upgraded();
let enabled: BTreeSet<&str> = ["wb-edited.plugin.js", "mine.plugin.js", "wb-stays.plugin.js"].into();
fs::write(store.dir().join(STATE_FILE), serde_json::to_string(&enabled).unwrap()).unwrap();
let rerun = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty(), "flags are only ever turned on, never off"); Ok(()) }).unwrap();
assert_eq!(rerun.removed, ["wb-focus.plugin.js", "wb-keys.plugin.js"]);
assert!(!exists(&store, "wb-focus.plugin.js"));
// A crash after the files went, before the marker: the rerun finds nothing and writes it.
let (_root, store) = upgraded();
store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
fs::remove_file(store.dir().join(MARKER_FILE)).unwrap();
let rerun = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
assert_eq!((rerun.removed.len(), rerun.kept), (0, vec!["wb-edited.plugin.js".to_owned()]));
assert!(store.is_enabled("wb-edited.plugin.js"));
assert_eq!(marker(store.dir()).len(), 4);
}
#[test]
fn a_fresh_install_has_nothing_to_move() {
let root = tempfile::tempdir().unwrap();
let store = PluginStore::new(root.path().join("plugins"), &HOST);
store.ensure().unwrap();
let outcome = store.migrate_superseded(TABLE, |flags| { assert!(flags.is_empty()); Ok(()) }).unwrap();
assert_eq!(outcome, Outcome::default());
assert_eq!(marker(store.dir()).len(), 4);
let listed: Vec<String> = store.list().unwrap().into_iter().map(|plugin| plugin.file).collect();
assert_eq!(listed, ["wb-stays.plugin.js"], "only what the app ships now");
assert!(store.start_scripts().is_empty(), "plugin files stay off until the owner turns them on");
}
#[test]
fn a_stale_enabled_entry_of_a_deleted_file_goes() {
let (_root, store) = upgraded();
let enabled: BTreeSet<&str> = ["wb-deleted.plugin.js", "mine.plugin.js"].into();
fs::write(store.dir().join(STATE_FILE), serde_json::to_string(&enabled).unwrap()).unwrap();
let outcome = store.migrate_superseded(TABLE, |_| Ok(())).unwrap();
assert!(outcome.flags_on.is_empty(), "a file the owner deleted does not turn its flag on");
assert!(!store.is_enabled("wb-deleted.plugin.js") && store.is_enabled("mine.plugin.js"));
}
#[test]
fn a_backup_with_old_names_turns_into_flags_unless_it_carries_an_edited_copy() {
let enabled = vec!["wb-focus.plugin.js".to_owned(), "mine.plugin.js".to_owned(), "wb-edited.plugin.js".to_owned(), "wb-focus.plugin.js".to_owned()];
let files = vec!["mine.plugin.js".to_owned(), "wb-edited.plugin.js".to_owned()];
let (keep, flags_on) = map_backup(enabled, &files, TABLE);
assert_eq!(keep, ["mine.plugin.js", "wb-edited.plugin.js"]);
assert_eq!(flags_on, ["navigation.focusMode"]);
let (keep, flags_on) = map_backup(vec!["other.plugin.js".into()], &[], TABLE);
assert_eq!((keep.len(), flags_on.len()), (1, 0));
}
}

View file

@ -0,0 +1,145 @@
//! Safe mode: the app with only its shell working. While it is on, a site tab gets nothing of the
//! app's page layers: no page runtime, no plugins, no theme, no custom CSS, no feature flags, no
//! hotfix data, no words; only the host's tab bridge (so the shell still shows the tab's address and
//! title and its keys still work). The site is its own, exactly as in a browser.
//!
//! It is a flag in this process's memory and nothing else: it is never written to disk, so the
//! next normal start is back to the owner's setup. It is switched on by the launch argument
//! [`ARG`] (for when the interface itself is broken), by holding Shift while the app starts
//! (Windows), or from the shell (`safe_mode_set`, shell-only: the app menu's "Restart in safe
//! mode" and the titlebar's "Leave"), which rebuilds every tab webview so document-start scripts
//! change too.
//!
//! How the layers go ([`crate::app`]): a tab's document-start scripts are the app's
//! `SiteHooks::safe_init_scripts` (by default the tab bridge alone) instead of `init_scripts`;
//! `SiteHooks::site_page_loaded`, `tab_placed` and `tab_background` are not called;
//! `app::page_scripts` is empty; and `host::eval_in_site_tabs`, the one way the host and an app
//! push state into site pages later (flags, CSS, theme, words, hotfix), does nothing. An app that
//! wants some layer of its own to survive safe mode says so in `safe_init_scripts`; by default
//! nothing survives, fixes included: the point is to rule the app's own code out.
use serde::Serialize;
use std::sync::atomic::{AtomicBool, Ordering};
/// The launch argument that starts the app in safe mode.
pub const ARG: &str = "--safe-mode";
/// Shell event: safe mode was switched (payload [`SafeState`]).
pub const EVENT: &str = "safe-mode";
/// Shell event: every tab webview must be built again; the shell answers with its layout (`tabs_sync`).
pub const EVENT_REBUILD: &str = "tabs-rebuild";
/// Marks a tab's recorded profile as stale, so the next `tabs_sync` closes its webview and creates
/// it again with the document-start scripts of the moment (the profile-change path).
pub const STALE_PROFILE: &str = "\u{0}rebuild";
static ACTIVE: AtomicBool = AtomicBool::new(false);
/// What the shell hears about safe mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct SafeState {
pub active: bool,
}
/// Whether safe mode is on in this process.
pub fn active() -> bool {
ACTIVE.load(Ordering::SeqCst)
}
/// Switches safe mode; true when that changed anything.
pub fn set(on: bool) -> bool {
ACTIVE.swap(on, Ordering::SeqCst) != on
}
pub fn state() -> SafeState {
SafeState { active: active() }
}
/// Whether the launch arguments ask for safe mode (the first is the program itself).
pub fn asked_by_args<I, S>(args: I) -> bool
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
args.into_iter().skip(1).any(|arg| arg.as_ref() == ARG)
}
/// Whether this launch starts in safe mode: the argument, or Shift held while the app starts.
pub fn at_launch<I, S>(args: I, shift_held: bool) -> bool
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
shift_held || asked_by_args(args)
}
/// One of the app's page layers: `normal` normally, `safe` (usually nothing) in safe mode.
pub fn layer<T>(active: bool, normal: impl FnOnce() -> T, safe: impl FnOnce() -> T) -> T {
if active {
safe()
} else {
normal()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_launch_argument_and_shift_ask_for_safe_mode() {
assert!(asked_by_args(["app.exe", "--safe-mode"]));
assert!(asked_by_args(["app.exe", "waybetter://install?kind=theme", "--safe-mode"]));
assert!(!asked_by_args(["app.exe"]));
assert!(!asked_by_args(["--safe-mode"]), "the first argument is the program");
assert!(!asked_by_args(["app.exe", "--safe-mode=1", "safe-mode", "--SAFE-MODE", "https://x.com/?--safe-mode"]), "exactly the argument");
assert!(at_launch(["app.exe"], true));
assert!(at_launch(["app.exe", "--safe-mode"], false));
assert!(!at_launch(["app.exe"], false));
assert!(!at_launch(Vec::<String>::new(), false));
}
#[test]
fn the_flag_lives_in_memory_only_and_gates_every_layer() {
// One test owns the process-wide flag (tests run in parallel).
assert!(!active(), "off unless asked for");
assert!(set(true) && active());
assert!(!set(true), "switching to the same state changes nothing");
assert_eq!(serde_json::to_string(&state()).unwrap(), r#"{"active":true}"#);
assert_eq!(layer(active(), || vec!["runtime.js", "plugins"], Vec::new), Vec::<&str>::new());
assert!(set(false) && !active());
assert_eq!(layer(active(), || vec!["runtime.js"], Vec::new), vec!["runtime.js"]);
// Never persisted: this module touches no file, so the next start is a normal one.
let source = include_str!("safe.rs");
let code = source.split("#[cfg(test)]").next().unwrap();
for forbidden in ["std::fs", "write_json", "read_json", "File::", "app_data_dir"] {
assert!(!code.contains(forbidden), "{forbidden}");
}
}
#[test]
fn the_host_skips_every_page_layer_in_safe_mode() {
let app = include_str!("app.rs");
let host = include_str!("host.rs");
// Document-start scripts: the safe set instead of the app's.
// (the normal layers are the string packs' delivery and then the app's own scripts).
assert!(app.contains("let layers = || strings_layer(app).into_iter().chain(hooks.init_scripts(app, tab)).collect::<Vec<_>>();"));
assert!(app.contains("crate::safe::layer(crate::safe::active(), layers, || hooks.safe_init_scripts(app, tab))"));
// The default safe set is the tab bridge alone.
let default = &app[app.find("fn safe_init_scripts").expect("the hook")..];
let default = &default[..default.find("\n }").unwrap()];
assert!(default.contains("vec![crate::bridge::SOURCE.to_owned()]"), "{default}");
// A loaded site page gets nothing; placement and background hooks stay out; page_scripts is empty.
assert!(app.contains("if finished && site.is_origin(payload.url()) && !crate::safe::active() {"));
assert!(app.contains("if !crate::safe::active() {\n hooks.tab_placed(&app, &tab, &item);"));
assert!(app.contains("crate::safe::layer(crate::safe::active(), || hooks.tab_background(&app, &label), || None)"));
let page_scripts = &app[app.find("pub fn page_scripts").expect("page_scripts")..];
assert!(page_scripts[..page_scripts.find("let site").unwrap()].contains("if crate::safe::active()"), "page_scripts checks the flag first");
// The one way state is pushed into site pages later does nothing.
let eval = &host[host.find("pub fn eval_in_site_tabs").expect("eval_in_site_tabs")..];
assert!(eval[..eval.find("for (label").unwrap()].contains("if crate::safe::active()"), "eval_in_site_tabs checks the flag first");
// Both commands are the shell's.
for command in ["safe_mode_get", "safe_mode_set"] {
assert!(crate::commands::SHELL.contains(&command), "{command}");
crate::testkit::assert_guarded(app, command, "shell_only(&webview)?");
}
}
}

View file

@ -96,9 +96,16 @@ pub fn links_script(site: &SiteSpec, settings: &ShellSettings) -> String {
tabs::deliver_script(site.runtime_global, "links", "configure", "__btLinks", &links.to_string())
}
/// Flags a store may hold. It was 64 while every flag was a page tweak; area plugins carry a flag
/// per feature. The map is stored sparsely (only values that differ from the app's defaults), so a
/// backup written by this version normally still fits an older app's limit of 64.
pub const MAX_FEATURES: usize = 256;
/// Characters in a flag key.
pub const MAX_FEATURE_KEY: usize = 64;
/// Feature flags are booleans only, in a small map; the page normalizes them again before use.
pub fn validate_features(features: &Map<String, Value>) -> Result<(), String> {
if features.len() > 64 || features.iter().any(|(key, value)| key.len() > 64 || !value.is_boolean()) {
if features.len() > MAX_FEATURES || features.iter().any(|(key, value)| key.is_empty() || key.len() > MAX_FEATURE_KEY || !value.is_boolean()) {
return Err("VALIDATION: features must be a small map of booleans".into());
}
Ok(())
@ -175,7 +182,13 @@ mod tests {
assert!(validate_features(&map(json!({ "a": "yes" }))).is_err());
let long: Map<String, Value> = [("x".repeat(65), Value::Bool(true))].into_iter().collect();
assert!(validate_features(&long).is_err());
let many: Map<String, Value> = (0..65).map(|n| (format!("f{n}"), Value::Bool(true))).collect();
// What an older app wrote (at most 64 flags, the whole map) still imports; the cap is 256 now.
let old: Map<String, Value> = (0..64).map(|n| (format!("f{n}"), Value::Bool(n % 2 == 0))).collect();
assert!(validate_features(&old).is_ok());
let full: Map<String, Value> = (0..MAX_FEATURES).map(|n| (format!("area{n}.feature"), Value::Bool(true))).collect();
assert!(validate_features(&full).is_ok());
let many: Map<String, Value> = (0..=MAX_FEATURES).map(|n| (format!("f{n}"), Value::Bool(true))).collect();
assert!(validate_features(&many).is_err());
assert!(validate_features(&map(json!({ "": true }))).is_err());
}
}

View file

@ -59,6 +59,8 @@ pub struct StoreConfig {
pub enum Kind {
Theme,
Plugin,
/// A string pack: data that replaces the site's own UI strings (`store::strings`).
Strings,
}
impl Kind {
@ -66,7 +68,8 @@ impl Kind {
match value {
"theme" => Ok(Kind::Theme),
"plugin" => Ok(Kind::Plugin),
_ => Err("VALIDATION: kind must be \"theme\" or \"plugin\"".into()),
"strings" => Ok(Kind::Strings),
_ => Err("VALIDATION: kind must be \"theme\", \"plugin\" or \"strings\"".into()),
}
}
@ -74,6 +77,7 @@ impl Kind {
match self {
Kind::Theme => "theme",
Kind::Plugin => "plugin",
Kind::Strings => "strings",
}
}
@ -81,6 +85,7 @@ impl Kind {
match self {
Kind::Theme => MAX_THEME_BYTES,
Kind::Plugin => MAX_PLUGIN_BYTES as usize,
Kind::Strings => super::strings::MAX_STRINGS_BYTES,
}
}
}
@ -288,6 +293,15 @@ pub struct CatalogItem {
/// Themes: a few colors for swatches.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub colors: Option<Swatch>,
/// String packs: the language tag of the pack.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
/// String packs: the licence of the text (an SPDX id such as `CC-BY-4.0`, or a short name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub license: Option<String>,
/// String packs: who translated and reviewed it, plain text.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub credits: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@ -360,6 +374,13 @@ impl CatalogItem {
if self.size == 0 || self.size > self.kind.max_bytes() as u64 {
return bad("size");
}
// Any item may name its licence and credit its authors; only a string pack has a language.
if !self.license.as_deref().is_none_or(|v| !v.trim().is_empty() && valid_text(v, 60)) || !self.credits.as_deref().is_none_or(|v| valid_text(v, 600)) {
return bad("license or credits");
}
if self.kind != Kind::Strings && self.language.is_some() {
return bad("language");
}
match self.kind {
Kind::Plugin => {
if !self.file.as_deref().is_some_and(valid_file_name) || self.colors.is_some() {
@ -372,6 +393,14 @@ impl CatalogItem {
}
}
}
Kind::Strings => {
if self.file.is_some() || self.permissions.is_some() || self.colors.is_some() {
return bad("string pack fields");
}
if !self.language.as_deref().is_some_and(super::strings::valid_language) {
return bad("language");
}
}
Kind::Theme => {
if self.file.is_some() || self.permissions.is_some() {
return bad("theme fields");

View file

@ -6,6 +6,7 @@
use super::catalog::{
self as dist, Catalog, CatalogItem, InstallLink, InstallRecord, InstallRecords, Kind, SourceKind, StoreConfig, ThemeInfo,
};
use super::strings::{self as packs, StringsInfo, StringsList, StringsStore};
use crate::plugins::{self, PluginHost, PluginStore, ScriptPlugin, PLUGIN_SUFFIX};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque};
@ -19,8 +20,14 @@ pub const RECORDS_FILE: &str = "store-installed.json";
/// The last verified catalog and its signature (verified again when read back).
pub const CATALOG_CACHE: &str = "store-catalog.json";
pub const CATALOG_SIG_CACHE: &str = "store-catalog.json.sig";
/// Shell event: a validated install link (`{ link: { kind, url } }`) or `{ error }`.
/// Shell event: a validated install link (`{ link: { kind, url } }`), a "Share my setup" link
/// (`{ setup }`: its text, for the shell's preview) or `{ error }`.
pub const EVENT_LINK: &str = "install-link";
/// "Share my setup" links: `waybetter://setup?app=…&d=…`. Native code only checks the shape and
/// hands the text to the shell; it never decodes or applies a setup (the shell shows what would
/// change and asks first).
pub const SETUP_LINK: &str = "waybetter://setup";
const MAX_SETUP_LINK: usize = 24 * 1024;
/// Links received before the shell asked for them (startup, or while the shell reloads).
const MAX_PENDING: usize = 8;
const MAX_STAGED: usize = 8;
@ -37,6 +44,22 @@ pub struct LinkEvent {
pub link: Option<InstallLink>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// A "Share my setup" link, as text (see [`SETUP_LINK`]).
#[serde(skip_serializing_if = "Option::is_none")]
pub setup: Option<String>,
}
/// `Some` when `raw` is a setup link: its text when it has the plain shape (the path, a query of
/// URL-safe characters, bounded), else an error. `None`: not a setup link.
pub fn setup_link(raw: &str) -> Option<Result<String, String>> {
let rest = raw.strip_prefix(SETUP_LINK)?;
let query = rest.strip_prefix("/?").or_else(|| rest.strip_prefix('?'));
let ok = query.is_some_and(|query| {
!query.is_empty()
&& raw.len() <= MAX_SETUP_LINK
&& query.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'=' | b'&' | b'%' | b'.'))
});
Some(if ok { Ok(raw.to_owned()) } else { Err("LINK: this setup link is not valid".to_owned()) })
}
#[derive(Clone, Debug, Serialize)]
@ -72,6 +95,8 @@ pub struct InstallPreview {
pub version: String,
pub plugin: Option<ScriptPlugin>,
pub theme: Option<ThemeInfo>,
/// String packs: what the pack says about itself (the shell adds coverage from the inventory).
pub strings: Option<StringsInfo>,
pub findings: Vec<&'static str>,
pub existing: Option<Existing>,
pub store: Option<CatalogItem>,
@ -85,6 +110,8 @@ pub struct InstallOutcome {
pub plugins: Option<Vec<ScriptPlugin>>,
/// Themes: the exact JSON the owner confirmed; the shell adds it (sanitized) to its themes.
pub theme_text: Option<String>,
/// String packs: the installed packs after installing.
pub strings: Option<StringsList>,
}
#[derive(Clone, Debug, Serialize)]
@ -191,6 +218,11 @@ impl Store {
PluginStore::new(self.data_dir.join("plugins"), self.plugins)
}
/// The installed string packs (`<data>/strings`).
pub fn strings(&self) -> StringsStore {
StringsStore::new(&self.data_dir)
}
fn plugins_dir(&self) -> PathBuf {
self.data_dir.join("plugins")
}
@ -210,9 +242,13 @@ impl Store {
/// A link reached the app (OS deep link, second launch): validate it and queue it for the
/// shell. Returns the event to emit ([`EVENT_LINK`]). Nothing is downloaded or installed here.
pub fn receive_link(&self, raw: &str) -> LinkEvent {
let event = match dist::parse_install_link(self.config, raw) {
Ok(link) => LinkEvent { link: Some(link), error: None },
Err(error) => LinkEvent { link: None, error: Some(error) },
let event = match setup_link(raw) {
Some(Ok(text)) => LinkEvent { link: None, error: None, setup: Some(text) },
Some(Err(error)) => LinkEvent { link: None, error: Some(error), setup: None },
None => match dist::parse_install_link(self.config, raw) {
Ok(link) => LinkEvent { link: Some(link), error: None, setup: None },
Err(error) => LinkEvent { link: None, error: Some(error), setup: None },
},
};
let mut inner = self.lock();
if inner.pending.len() >= MAX_PENDING {
@ -234,7 +270,7 @@ impl Store {
let link = dist::parse_install_link(self.config, &dist::install_link(self.config, kind, url))?;
let file = match kind {
Kind::Plugin => Some(dist::plugin_file_from_url(&Url::parse(&link.url).map_err(|_| "VALIDATION: invalid URL")?)?),
Kind::Theme => None,
Kind::Theme | Kind::Strings => None,
};
Ok((link, file))
}
@ -254,6 +290,7 @@ impl Store {
};
}
let text = String::from_utf8(bytes.clone()).map_err(|_| "VALIDATION: not UTF-8 text")?;
let mut strings = None;
let (plugin, theme, findings, version, existing) = match kind {
Kind::Plugin => {
let file = file.as_deref().ok_or("VALIDATION: missing plugin file name")?;
@ -267,6 +304,22 @@ impl Store {
let version = validated.meta.version.clone();
(Some(validated.meta), None, validated.findings, version, existing)
}
Kind::Strings => {
let info = packs::validate_strings(&bytes)?;
if info.site != self.config.app_id {
return Err(format!("VALIDATION: this string pack is for another app ({})", info.site));
}
let id = packs::pack_id(&info, store.as_ref().map(|item| item.id.as_str()));
let local = self.strings();
let existing = local.read(&id).map(|old| Existing {
version: packs::validate_strings(&old).map(|old| old.version).unwrap_or_default(),
enabled: local.state().enabled.contains(&id),
same: dist::sha256_hex(&old) == dist::sha256_hex(&bytes),
});
let version = if info.version.is_empty() { store.as_ref().map(|item| item.version.clone()).unwrap_or_default() } else { info.version.clone() };
strings = Some(info);
(None, None, Vec::new(), version, existing)
}
Kind::Theme => {
let info = dist::validate_theme(&bytes)?;
let version = store.as_ref().map(|item| item.version.clone()).unwrap_or_default();
@ -291,6 +344,7 @@ impl Store {
version: version.clone(),
plugin,
theme,
strings,
findings,
existing,
store: store.clone(),
@ -316,10 +370,12 @@ impl Store {
let lower = name.to_ascii_lowercase();
let (kind, file) = if lower.ends_with(PLUGIN_SUFFIX) {
(Kind::Plugin, Some(name.to_owned()))
} else if lower.ends_with(".strings.json") {
(Kind::Strings, None)
} else if lower.ends_with(".json") {
(Kind::Theme, None)
} else {
return Err("VALIDATION: drop a theme (.json) or a plugin (.plugin.js)".into());
return Err("VALIDATION: drop a theme (.json), a plugin (.plugin.js) or a string pack (.strings.json)".into());
};
if text.len() > kind.max_bytes() {
return Err("VALIDATION: the file is larger than allowed".into());
@ -393,7 +449,18 @@ impl Store {
store.set_enabled(&file, true)?;
run(&script);
}
Ok(InstallOutcome { kind: Kind::Plugin, plugins: Some(store.list()?), theme_text: None })
Ok(InstallOutcome { kind: Kind::Plugin, plugins: Some(store.list()?), theme_text: None, strings: None })
}
Kind::Strings => {
let info = packs::validate_strings(&staged.bytes)?;
let id = packs::pack_id(&info, staged.store.as_ref().map(|item| item.id.as_str()));
let local = self.strings();
local.install(&id, &staged.bytes, enable)?;
inner.records.insert(InstallRecords::key(Kind::Strings, &id), record(staged.version.clone()));
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
Ok(InstallOutcome { kind: Kind::Strings, plugins: None, theme_text: None, strings: Some(local.list()) })
}
Kind::Theme => {
let id = theme_id.filter(|id| valid_theme_id(id)).ok_or("VALIDATION: invalid theme id")?;
@ -402,7 +469,7 @@ impl Store {
drop(inner);
self.save_records(&records);
let text = String::from_utf8(staged.bytes).map_err(|_| "VALIDATION: not UTF-8")?;
Ok(InstallOutcome { kind: Kind::Theme, plugins: None, theme_text: Some(text) })
Ok(InstallOutcome { kind: Kind::Theme, plugins: None, theme_text: Some(text), strings: None })
}
}
}
@ -421,6 +488,19 @@ impl Store {
store.list()
}
/// Removes an installed string pack and forgets where it came from.
pub fn remove_strings(&self, id: &str) -> Result<StringsList, String> {
let local = self.strings();
local.remove(id)?;
let mut inner = self.lock();
if inner.records.items.remove(&InstallRecords::key(Kind::Strings, id)).is_some() {
let records = inner.records.clone();
drop(inner);
self.save_records(&records);
}
Ok(local.list())
}
/// Where installed plugins and themes came from (for badges and update checks).
pub fn records(&self) -> InstallRecords {
self.lock().records.clone()
@ -515,6 +595,7 @@ mod tests {
css_element_id: "wb-test-css",
example: None,
bundled: &[],
superseded: &[],
};
const THEME: &[u8] = br#"{"name":"Nord","author":"me","css":"a{}"}"#;
@ -543,6 +624,19 @@ mod tests {
assert!(ok.link.is_some() && ok.error.is_none());
let bad = store.receive_link("waybetter://install?kind=theme&url=https://evil.example/a.json");
assert!(bad.link.is_none() && bad.error.unwrap().starts_with("LINK:"));
// A "Share my setup" link is only handed over as text; its data is never read here.
let setup = store.receive_link("waybetter://setup?app=x&d=eyJmb3JtYXQiOiJ3YXliZXR0ZXItc2V0dXAifQ");
assert_eq!(setup.setup.as_deref(), Some("waybetter://setup?app=x&d=eyJmb3JtYXQiOiJ3YXliZXR0ZXItc2V0dXAifQ"));
assert!(setup.link.is_none() && setup.error.is_none());
for bad in ["waybetter://setup", "waybetter://setup?", "waybetter://setup?d=<script>", "waybetter://setup?d=a b", "waybetter://setupx?d=a"] {
let event = store.receive_link(bad);
assert!(event.setup.is_none(), "{bad}");
assert!(event.error.is_some(), "{bad}");
}
let long = format!("waybetter://setup?d={}", "a".repeat(MAX_SETUP_LINK));
assert!(store.receive_link(&long).setup.is_none(), "bounded");
assert_eq!(serde_json::to_string(&setup).unwrap(), r#"{"setup":"waybetter://setup?app=x&d=eyJmb3JtYXQiOiJ3YXliZXR0ZXItc2V0dXAifQ"}"#);
store.take_pending();
for _ in 0..20 {
store.receive_link("waybetter://install?kind=theme&url=https://waybetter.fyi/a.json");
}

View file

@ -27,8 +27,10 @@
pub mod catalog;
pub mod install;
pub mod strings;
#[cfg(feature = "net")]
pub mod net;
pub use catalog::*;
pub use install::*;
pub use strings::*;

View file

@ -0,0 +1,423 @@
//! String packs (waybetter/docs/STRING-PACKS.md) on disk: data-only packs that replace the wrapped
//! site's own UI strings. The shell checks a pack against the site's inventory (coverage, unknown
//! keys); this side only accepts well-formed data and keeps it: `strings/<id>.json`, and
//! `strings/state.json` (which packs are on, in which order). A pack carries text, never code.
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
pub const MAX_STRINGS_BYTES: usize = 2 * 1024 * 1024;
pub const MAX_PACK_STRINGS: usize = 40_000;
pub const MAX_PACK_VALUE_CHARS: usize = 2000;
/// At most this many packs are installed (and at most 8 are on at once).
pub const MAX_PACKS: usize = 64;
pub const MAX_ENABLED: usize = 8;
const STATE_FILE: &str = "state.json";
const DELIVERY_FILE: &str = "delivery.json";
/// A delivery (packs + the inventory slice their keys need) the shell computed; handed to site tabs.
pub const MAX_DELIVERY_BYTES: usize = 8 * 1024 * 1024;
/// What the install screen and the settings list show about a pack.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StringsInfo {
pub site: String,
pub catalog: String,
pub language: String,
pub name: String,
pub authors: Vec<String>,
pub version: String,
pub description: String,
/// Number of strings in the pack.
pub strings: usize,
}
fn plain(value: &str, max: usize) -> bool {
value.chars().count() <= max && !value.chars().any(|ch| ch.is_control() || ch == '<' || ch == '>' || ('\u{202a}'..='\u{202e}').contains(&ch) || ('\u{2066}'..='\u{2069}').contains(&ch))
}
fn ident(value: &str) -> bool {
!value.is_empty() && value.len() <= 32 && value.bytes().next().is_some_and(|b| b.is_ascii_lowercase()) && value.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// A BCP 47-shaped language tag (`eo`, `pt-BR`, `en-x-pirate`).
pub fn valid_language(tag: &str) -> bool {
let mut parts = tag.split('-');
let first = parts.next().unwrap_or_default();
(2..=8).contains(&first.len()) && first.bytes().all(|b| b.is_ascii_alphabetic()) && parts.all(|part| (1..=8).contains(&part.len()) && part.bytes().all(|b| b.is_ascii_alphanumeric()))
}
/// A string pack file: at most [`MAX_STRINGS_BYTES`], UTF-8 JSON with the pack envelope, key ids
/// mapped to plain text (no markup, no control or bidi-override characters). Whether the ids and
/// parameters fit the site is the shell's check against the inventory.
pub fn validate_strings(bytes: &[u8]) -> Result<StringsInfo, String> {
if bytes.is_empty() {
return Err("VALIDATION: the string pack is empty".into());
}
if bytes.len() > MAX_STRINGS_BYTES {
return Err("VALIDATION: string packs are limited to 2 MiB".into());
}
let text = std::str::from_utf8(bytes).map_err(|_| "VALIDATION: a string pack must be UTF-8 JSON")?;
let value: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|_| "VALIDATION: this file is not valid JSON")?;
let object = value.as_object().ok_or("VALIDATION: a string pack is a JSON object")?;
let text_field = |key: &str| object.get(key).and_then(serde_json::Value::as_str);
if object.get("format").and_then(serde_json::Value::as_u64) != Some(1) {
return Err("VALIDATION: a string pack needs \"format\": 1".into());
}
let site = text_field("site").filter(|v| ident(v)).ok_or("VALIDATION: invalid \"site\"")?;
let catalog = text_field("catalog").filter(|v| ident(v)).ok_or("VALIDATION: invalid \"catalog\"")?;
let language = text_field("language").filter(|v| valid_language(v)).ok_or("VALIDATION: invalid \"language\"")?;
if let Some(base) = object.get("base") {
if !base.as_str().is_some_and(valid_language) {
return Err("VALIDATION: invalid \"base\"".into());
}
}
let name = text_field("name").filter(|v| !v.trim().is_empty() && plain(v, 80)).ok_or("VALIDATION: a string pack needs a plain-text \"name\"")?;
let authors: Vec<String> = match object.get("authors").and_then(serde_json::Value::as_array) {
Some(list) if list.len() <= 16 => list
.iter()
.map(|author| author.as_str().filter(|a| !a.trim().is_empty() && plain(a, 80)).map(str::to_owned))
.collect::<Option<Vec<_>>>()
.ok_or("VALIDATION: invalid \"authors\"")?,
_ => return Err("VALIDATION: \"authors\" must be a list of at most 16 names".into()),
};
let version = match object.get("version") {
None => String::new(),
Some(v) => v.as_str().filter(|v| plain(v, 32)).ok_or("VALIDATION: invalid \"version\"")?.to_owned(),
};
let description = match object.get("description") {
None => String::new(),
Some(v) => v.as_str().filter(|v| plain(v, 400)).ok_or("VALIDATION: invalid \"description\"")?.to_owned(),
};
let strings = object.get("strings").and_then(serde_json::Value::as_object).ok_or("VALIDATION: \"strings\" must be an object of key id -> text")?;
if strings.len() > MAX_PACK_STRINGS {
return Err("VALIDATION: too many strings".into());
}
for (id, value) in strings {
let ok_id = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-' || b == b'.' || b == b'$');
let ok_value = value.as_str().is_some_and(|v| !v.is_empty() && plain(v, MAX_PACK_VALUE_CHARS));
if !ok_id || !ok_value {
return Err(format!("VALIDATION: string {} is not plain text", id.chars().take(64).collect::<String>()));
}
}
const KNOWN: &[&str] = &["$schema", "format", "site", "catalog", "language", "base", "name", "authors", "version", "description", "strings"];
if let Some(key) = object.keys().find(|key| !KNOWN.contains(&key.as_str())) {
return Err(format!("VALIDATION: unknown field \"{}\"", key.chars().take(40).collect::<String>()));
}
Ok(StringsInfo {
site: site.to_owned(),
catalog: catalog.to_owned(),
language: language.to_owned(),
name: name.to_owned(),
authors,
version,
description,
strings: strings.len(),
})
}
/// The id a pack is installed under: the store item's id, else derived from its language and name.
pub fn pack_id(info: &StringsInfo, store_id: Option<&str>) -> String {
if let Some(id) = store_id {
return id.to_owned();
}
let mut id = String::new();
for ch in format!("{}-{}", info.language, info.name).chars() {
let ch = ch.to_ascii_lowercase();
if ch.is_ascii_alphanumeric() {
id.push(ch);
} else if !id.ends_with('-') {
id.push('-');
}
}
let id: String = id.trim_matches('-').chars().take(40).collect();
let id = id.trim_end_matches('-').to_owned();
if id.is_empty() { "strings".to_owned() } else { id }
}
fn valid_pack_id(id: &str) -> bool {
!id.is_empty() && id.len() <= 40 && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// Which packs are on, in application order (a later one wins per key).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StringsState {
pub order: Vec<String>,
pub enabled: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledStrings {
pub id: String,
#[serde(flatten)]
pub info: StringsInfo,
pub sha256: String,
pub enabled: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StringsList {
/// In application order.
pub packs: Vec<InstalledStrings>,
}
/// The installed packs of one app: `<data>/strings/`.
pub struct StringsStore {
dir: PathBuf,
}
impl StringsStore {
pub fn new(data_dir: &Path) -> Self {
Self { dir: data_dir.join("strings") }
}
fn file(&self, id: &str) -> PathBuf {
self.dir.join(format!("{id}.json"))
}
pub fn state(&self) -> StringsState {
std::fs::read_to_string(self.dir.join(STATE_FILE)).ok().and_then(|text| serde_json::from_str(&text).ok()).unwrap_or_default()
}
fn save_state(&self, state: &StringsState) -> Result<(), String> {
std::fs::create_dir_all(&self.dir).map_err(|e| format!("STRINGS: {e}"))?;
let text = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?;
write_atomic(&self.dir.join(STATE_FILE), text.as_bytes())
}
/// The installed pack's bytes, if any.
pub fn read(&self, id: &str) -> Option<Vec<u8>> {
if !valid_pack_id(id) {
return None;
}
std::fs::read(self.file(id)).ok()
}
/// Writes a pack (validated again) under `id`; a new pack goes last in the order, on when `enable`.
pub fn install(&self, id: &str, bytes: &[u8], enable: bool) -> Result<StringsInfo, String> {
if !valid_pack_id(id) {
return Err("VALIDATION: invalid string pack id".into());
}
let info = validate_strings(bytes)?;
let mut state = self.state();
let known: HashSet<&String> = state.order.iter().collect();
if !known.contains(&id.to_owned()) && state.order.len() >= MAX_PACKS {
return Err("INSTALL: too many string packs installed".into());
}
std::fs::create_dir_all(&self.dir).map_err(|e| format!("STRINGS: {e}"))?;
write_atomic(&self.file(id), bytes)?;
if !state.order.iter().any(|item| item == id) {
state.order.push(id.to_owned());
}
if enable && !state.enabled.iter().any(|item| item == id) && state.enabled.len() < MAX_ENABLED {
state.enabled.push(id.to_owned());
}
self.save_state(&state)?;
Ok(info)
}
pub fn remove(&self, id: &str) -> Result<(), String> {
if !valid_pack_id(id) {
return Err("VALIDATION: invalid string pack id".into());
}
let _ = std::fs::remove_file(self.file(id));
let mut state = self.state();
state.order.retain(|item| item != id);
state.enabled.retain(|item| item != id);
self.save_state(&state)
}
/// Sets the order and which packs are on. Unknown ids are dropped; installed packs missing
/// from `order` keep their place at the end.
pub fn set(&self, order: &[String], enabled: &[String]) -> Result<StringsList, String> {
let installed = self.installed_ids();
let mut next = StringsState::default();
for id in order.iter().chain(installed.iter()) {
if installed.contains(id) && !next.order.contains(id) {
next.order.push(id.clone());
}
}
for id in &next.order {
if enabled.contains(id) && next.enabled.len() < MAX_ENABLED {
next.enabled.push(id.clone());
}
}
self.save_state(&next)?;
Ok(self.list())
}
fn installed_ids(&self) -> Vec<String> {
let mut ids: Vec<String> = std::fs::read_dir(&self.dir)
.map(|entries| {
entries
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().to_str().and_then(|name| name.strip_suffix(".json")).map(str::to_owned))
.filter(|id| valid_pack_id(id) && id != "state" && id != "delivery")
.collect()
})
.unwrap_or_default();
ids.sort();
ids
}
/// Installed packs in application order (packs the state does not name yet come last).
pub fn list(&self) -> StringsList {
let state = self.state();
let installed = self.installed_ids();
let mut order: Vec<String> = state.order.iter().filter(|id| installed.contains(id)).cloned().collect();
for id in installed {
if !order.contains(&id) {
order.push(id);
}
}
let packs = order
.into_iter()
.filter_map(|id| {
let bytes = self.read(&id)?;
let info = validate_strings(&bytes).ok()?;
Some(InstalledStrings { enabled: state.enabled.contains(&id), sha256: super::catalog::sha256_hex(&bytes), id, info })
})
.collect();
StringsList { packs }
}
/// The enabled packs' JSON texts, in application order.
pub fn enabled_texts(&self) -> Vec<String> {
self.list().packs.into_iter().filter(|pack| pack.enabled).filter_map(|pack| self.read(&pack.id)).filter_map(|bytes| String::from_utf8(bytes).ok()).collect()
}
/// Keeps the delivery the shell computed (JSON: `{ inventory, packs }`; `None`: no pack on)
/// under a new revision, and returns the stored text (`{ rev, inventory?, packs? }`). A site
/// tab keeps the newest revision it was given, so a tab created before a change never goes
/// back to the older delivery it was created with.
pub fn set_delivery(&self, delivery: Option<&str>, rev: u64) -> Result<String, String> {
let mut stored = serde_json::Map::new();
if let Some(text) = delivery {
if text.len() > MAX_DELIVERY_BYTES {
return Err("VALIDATION: the delivery is too large".into());
}
let value: serde_json::Value = serde_json::from_str(text).map_err(|_| "VALIDATION: the delivery is not JSON")?;
let inventory = value.get("inventory").filter(|v| v.is_object()).cloned();
// Translate mode may run without any pack (the author starts from the site's own words).
let translate = value.get("translate").and_then(serde_json::Value::as_bool).unwrap_or(false);
let packs = value.get("packs").filter(|v| v.as_array().is_some_and(|packs| (translate || !packs.is_empty()) && packs.len() <= MAX_ENABLED)).cloned();
let (Some(inventory), Some(packs)) = (inventory, packs) else {
return Err("VALIDATION: a delivery is { inventory, packs } with 1 to 8 packs".into());
};
stored.insert("inventory".into(), inventory);
stored.insert("packs".into(), packs);
if translate {
stored.insert("translate".into(), true.into());
}
}
stored.insert("rev".into(), rev.into());
let text = serde_json::Value::Object(stored).to_string();
std::fs::create_dir_all(&self.dir).map_err(|e| format!("STRINGS: {e}"))?;
write_atomic(&self.dir.join(DELIVERY_FILE), text.as_bytes())?;
Ok(text)
}
/// The stored delivery (`{ rev, inventory?, packs? }`), if the shell ever set one.
pub fn delivery(&self) -> Option<String> {
std::fs::read_to_string(self.dir.join(DELIVERY_FILE)).ok()
}
}
/// The session-storage key a page runtime reads its string packs from at document start.
pub const DELIVERY_KEY: &str = "wayBetter.stringPacks";
/// A script for a site tab: on one of `hosts` (https) only, puts `stored` (a stored delivery with
/// its `rev`) in the tab's session storage unless the tab already holds that revision or a newer
/// one; with `reload`, reloads the page after a change so the runtime applies it from the start.
/// Data only: the delivery is a JSON string literal, never code.
pub fn delivery_script(hosts: &[&str], stored: &str, reload: bool) -> String {
let hosts = serde_json::to_string(hosts).unwrap_or_else(|_| "[]".into());
let key = serde_json::to_string(DELIVERY_KEY).unwrap_or_default();
let rev = serde_json::from_str::<serde_json::Value>(stored).ok().and_then(|v| v.get("rev").and_then(serde_json::Value::as_u64)).unwrap_or(0);
let text = serde_json::to_string(stored).unwrap_or_else(|_| "\"{}\"".into());
format!(
"(() => {{ try {{ if (location.protocol !== 'https:' || !{hosts}.includes(location.host)) return; \
let held = 0; try {{ held = Number(JSON.parse(sessionStorage.getItem({key}) || '{{}}').rev) || 0; }} catch (e) {{}} \
if (held >= {rev}) return; sessionStorage.setItem({key}, {text});{} }} catch (e) {{}} }})();",
if reload { " location.reload();" } else { "" }
)
}
fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes).map_err(|e| format!("STRINGS: {e}"))?;
std::fs::rename(&tmp, path).map_err(|e| format!("STRINGS: {e}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn pack(strings: &str) -> Vec<u8> {
format!(r#"{{"format":1,"site":"x","catalog":"web","language":"eo","name":"Esperanto","authors":["A"],"version":"1.0.0","strings":{strings}}}"#).into_bytes()
}
#[test]
fn packs_are_plain_data_with_the_envelope() {
let info = validate_strings(&pack(r#"{"a0000001":"Hejmo","b0000002":"{count, plural, one {# afiŝo} other {# afiŝoj}}"}"#)).unwrap();
assert_eq!((info.language.as_str(), info.strings, info.name.as_str()), ("eo", 2, "Esperanto"));
for bad in [
pack(r#"{"a":"<b>x</b>"}"#),
pack(r#"{"a":"x > y"}"#),
pack(&format!(r#"{{"a":"{}x"}}"#, char::from_u32(0x202e).unwrap())),
pack(r#"{"a":""}"#),
pack(r#"{"a":1}"#),
pack(r#"{"a b":"x"}"#),
pack(r#"[]"#),
br#"{"format":2,"site":"x","catalog":"web","language":"eo","name":"E","authors":[],"strings":{}}"#.to_vec(),
br#"{"format":1,"site":"X","catalog":"web","language":"eo","name":"E","authors":[],"strings":{}}"#.to_vec(),
br#"{"format":1,"site":"x","catalog":"web","language":"not a tag","name":"E","authors":[],"strings":{}}"#.to_vec(),
br#"{"format":1,"site":"x","catalog":"web","language":"eo","name":"E","authors":[],"strings":{},"code":"x"}"#.to_vec(),
b"not json".to_vec(),
Vec::new(),
] {
assert!(validate_strings(&bad).is_err(), "{}", String::from_utf8_lossy(&bad));
}
assert!(valid_language("en-x-pirate") && valid_language("pt-BR") && !valid_language("e") && !valid_language("en_US"));
}
#[test]
fn install_order_enable_remove_and_delivery() {
let dir = std::env::temp_dir().join(format!("wb-strings-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = StringsStore::new(&dir);
let info = validate_strings(&pack(r#"{"a":"x"}"#)).unwrap();
assert_eq!(pack_id(&info, None), "eo-esperanto");
assert_eq!(pack_id(&info, Some("esperanto")), "esperanto");
store.install("eo-esperanto", &pack(r#"{"a":"x"}"#), true).unwrap();
store.install("second", &pack(r#"{"a":"y"}"#), false).unwrap();
let list = store.list();
assert_eq!(list.packs.iter().map(|p| (p.id.as_str(), p.enabled)).collect::<Vec<_>>(), [("eo-esperanto", true), ("second", false)]);
let list = store.set(&["second".into(), "nope".into()], &["second".into(), "eo-esperanto".into()]).unwrap();
assert_eq!(list.packs.iter().map(|p| (p.id.as_str(), p.enabled)).collect::<Vec<_>>(), [("second", true), ("eo-esperanto", true)]);
assert_eq!(store.enabled_texts().len(), 2);
assert!(store.install("../evil", &pack("{}"), true).is_err());
assert!(store.install("bad", b"{}", true).is_err());
let stored = store.set_delivery(Some(r#"{"inventory":{"site":"x"},"packs":[{"a":1}],"extra":"dropped"}"#), 7).unwrap();
assert_eq!(stored, r#"{"inventory":{"site":"x"},"packs":[{"a":1}],"rev":7}"#);
assert_eq!(store.delivery().as_deref(), Some(stored.as_str()));
assert!(store.set_delivery(Some("[]"), 8).is_err());
assert!(store.set_delivery(Some(r#"{"inventory":{},"packs":[]}"#), 8).is_err(), "no packs is None, not an empty list");
assert_eq!(store.set_delivery(Some(r#"{"inventory":{},"packs":[],"translate":true}"#), 8).unwrap(), r#"{"inventory":{},"packs":[],"rev":8,"translate":true}"#, "translate mode may start without a pack");
assert_eq!(store.list().packs.len(), 2, "the delivery file is not a pack");
assert_eq!(store.set_delivery(None, 9).unwrap(), r#"{"rev":9}"#);
store.remove("second").unwrap();
assert_eq!(store.list().packs.len(), 1);
assert_eq!(store.state().order, ["eo-esperanto"]);
let script = delivery_script(&["x.com"], r#"{"rev":12,"packs":["</script>"]}"#, true);
assert!(script.contains(r#"!["x.com"].includes(location.host)"#), "{script}");
assert!(script.contains("if (held >= 12) return;") && script.contains("sessionStorage.setItem(\"wayBetter.stringPacks\", \"{\\\"rev\\\":12"));
assert!(script.contains("location.reload();"));
assert!(!delivery_script(&["x.com"], r#"{"rev":1}"#, false).contains("reload"));
let _ = std::fs::remove_dir_all(&dir);
}
}

View file

@ -0,0 +1,205 @@
//! The store's Tauri commands for every app that sets [`crate::app::AppConfig::store`]: the
//! `waybetter://install` deep link, dropped files, the signed wayBetter Store and the install
//! screen's commands ([`crate::commands::STORE`]). Every command is shell-only; site tabs and web
//! pages have no way to install anything. A deep link only *proposes* an install: the shell shows
//! the confirmation screen and nothing is written until the owner confirms there.
//!
//! The rules, the catalog format and the install state are [`crate::store`]'s; this module only
//! wraps them. An app without a store configuration registers nothing and every command here
//! answers that it is not available.
use crate::app::AppConfig;
use crate::host::{emit_shell, eval_in_site_tabs, shell_only};
use crate::plugins::ScriptPlugin;
use crate::policy;
use crate::store::{delivery_script, InstallOutcome, InstallPreview, InstallRecords, LinkEvent, Store, StoreItemRef, StoreView, StringsList, EVENT_LINK};
use tauri::{AppHandle, Manager, State, Webview};
use tauri_plugin_deep_link::DeepLinkExt;
/// Makes the [`Store`] for the app's configuration and listens for install links (launch argument,
/// open-URL event, a second launch forwarded by single-instance).
pub(crate) fn init(app: &AppHandle, config: &AppConfig) {
let Some(store) = config.store else { return };
let dir = app.path().app_data_dir().unwrap_or_default();
app.manage(Store::new(store, config.plugins, dir));
// Windows installs register the scheme in the NSIS installer and macOS in Info.plist; a Linux
// AppImage and a Windows development build register it here (HKCU / xdg, current user only).
#[cfg(any(target_os = "linux", all(windows, debug_assertions)))]
if let Err(error) = app.deep_link().register_all() {
eprintln!("{}: deep link registration failed: {error}", config.title);
}
let handle = app.clone();
app.deep_link().on_open_url(move |event| {
for url in event.urls() {
received(&handle, url.as_str());
}
});
// Launched by a link (Windows/Linux pass it as an argument; macOS as an open-URL event).
if let Ok(Some(urls)) = app.deep_link().get_current() {
for url in urls {
received(app, url.as_str());
}
}
}
/// A `waybetter://` link reached the app: validate it, queue it for the shell and bring the window
/// forward. Nothing is downloaded or installed until the shell's screen asks for it.
fn received(app: &AppHandle, raw: &str) {
let Some(store) = app.try_state::<Store>() else { return };
emit_shell(app, EVENT_LINK, store.receive_link(raw));
if let Some(window) = app.get_window(policy::MAIN_LABEL) {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
}
}
fn store(app: &AppHandle) -> Result<State<'_, Store>, String> {
app.try_state::<Store>().ok_or_else(|| "UNAVAILABLE: this app has no store".to_owned())
}
fn eval_in_site(app: &AppHandle, script: &str) {
eval_in_site_tabs(app, crate::app::config(app).site, script);
}
/// Links that arrived before the shell listened (drained).
#[tauri::command]
pub(crate) async fn install_pending(webview: Webview, app: AppHandle) -> Result<Vec<LinkEvent>, String> {
shell_only(&webview)?;
Ok(store(&app)?.take_pending())
}
/// Downloads what a validated install link points at and stages it for the confirmation screen.
#[tauri::command]
pub(crate) async fn install_stage_link(webview: Webview, app: AppHandle, kind: String, url: String) -> Result<InstallPreview, String> {
shell_only(&webview)?;
store(&app)?.stage_link(&kind, &url).await
}
/// A file dropped on the window (the shell read it with the File API; native code validates it).
#[tauri::command]
pub(crate) async fn install_stage_file(webview: Webview, app: AppHandle, name: String, text: String) -> Result<InstallPreview, String> {
shell_only(&webview)?;
store(&app)?.stage_file(&name, text)
}
#[tauri::command]
pub(crate) async fn install_cancel(webview: Webview, app: AppHandle, token: String) -> Result<(), String> {
shell_only(&webview)?;
store(&app)?.cancel(&token);
Ok(())
}
/// The owner confirmed the screen for `token`. Plugins are written (validated again) and, when
/// `enable` (or they were enabled before an update), started in every site tab. Themes are handed
/// back for the shell to add under `theme_id`.
#[tauri::command]
pub(crate) async fn install_commit(
webview: Webview,
app: AppHandle,
token: String,
enable: bool,
theme_id: Option<String>,
) -> Result<InstallOutcome, String> {
shell_only(&webview)?;
store(&app)?.commit(&token, enable, theme_id, |script| eval_in_site(&app, script))
}
/// Deletes a plugin (stopped in every site tab first). Shell-only, like every plugin command.
#[tauri::command]
pub(crate) async fn plugin_remove(webview: Webview, app: AppHandle, file: String) -> Result<Vec<ScriptPlugin>, String> {
shell_only(&webview)?;
store(&app)?.remove_plugin(&file, |script| eval_in_site(&app, script))
}
/// Where installed plugins and themes came from (for badges and update checks).
#[tauri::command]
pub(crate) async fn install_records(webview: Webview, app: AppHandle) -> Result<InstallRecords, String> {
shell_only(&webview)?;
Ok(store(&app)?.records())
}
/// A theme was removed in Appearance: forget where it came from.
#[tauri::command]
pub(crate) async fn install_forget(webview: Webview, app: AppHandle, kind: String, name: String) -> Result<(), String> {
shell_only(&webview)?;
store(&app)?.forget(&kind, &name)
}
/// The signed catalog, this app's items only (fetched at most every 10 minutes unless `refresh`),
/// with what is installed.
#[tauri::command]
pub(crate) async fn store_catalog(webview: Webview, app: AppHandle, refresh: bool) -> Result<StoreView, String> {
shell_only(&webview)?;
Ok(store(&app)?.catalog(refresh).await)
}
/// Downloads a store item, checks it against the signed catalog (size + sha256) and stages it.
#[tauri::command]
pub(crate) async fn store_stage(webview: Webview, app: AppHandle, item: StoreItemRef) -> Result<InstallPreview, String> {
shell_only(&webview)?;
store(&app)?.stage_item(&item).await
}
/// Installed string packs, in application order, with which are on.
#[tauri::command]
pub(crate) async fn strings_list(webview: Webview, app: AppHandle) -> Result<StringsList, String> {
shell_only(&webview)?;
Ok(store(&app)?.strings().list())
}
/// One installed string pack's JSON (the shell checks it against the site's inventory).
#[tauri::command]
pub(crate) async fn strings_read(webview: Webview, app: AppHandle, id: String) -> Result<String, String> {
shell_only(&webview)?;
let bytes = store(&app)?.strings().read(&id).ok_or("STRINGS: no such string pack")?;
String::from_utf8(bytes).map_err(|_| "STRINGS: not UTF-8".to_owned())
}
/// Sets the order of the installed string packs and which are on (at most 8).
#[tauri::command]
pub(crate) async fn strings_set(webview: Webview, app: AppHandle, order: Vec<String>, enabled: Vec<String>) -> Result<StringsList, String> {
shell_only(&webview)?;
store(&app)?.strings().set(&order, &enabled)
}
/// Removes an installed string pack.
#[tauri::command]
pub(crate) async fn strings_remove(webview: Webview, app: AppHandle, id: String) -> Result<StringsList, String> {
shell_only(&webview)?;
store(&app)?.remove_strings(&id)
}
/// The shell computed what site tabs get (the packs that are on, in order, with the slice of the
/// site's inventory their keys need; `None`: no pack on). It is kept for new tabs, and every site
/// tab gets it in its session storage and reloads, so X registers its strings through it from the
/// start. Data only; a site tab gains no command.
#[tauri::command]
pub(crate) async fn strings_apply(webview: Webview, app: AppHandle, delivery: Option<String>) -> Result<(), String> {
shell_only(&webview)?;
let rev = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
let stored = store(&app)?.strings().set_delivery(delivery.as_deref(), rev)?;
eval_in_site(&app, &delivery_script(crate::app::config(&app).site.hosts, &stored, true));
Ok(())
}
/// The store's commands ([`crate::commands::STORE`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
install_pending,
install_stage_link,
install_stage_file,
install_cancel,
install_commit,
plugin_remove,
install_records,
install_forget,
store_catalog,
store_stage,
strings_list,
strings_read,
strings_set,
strings_remove,
strings_apply
]
}

View file

@ -0,0 +1,369 @@
//! Saved workspaces and encrypted folder sync, native side ([`crate::commands::WORKSPACES`],
//! [`crate::commands::SYNC`]). Every command is shell-only. The format, the crypto and the
//! validation are [`crate::workspaces`]' and [`crate::sync`]'s (Argon2id + XChaCha20-Poly1305
//! snapshots of the settings backup in a folder the owner picks); this module keeps the local
//! state (which folder, this device, the remembered key) and the dialogs.
//!
//! The synced settings are the app's own backup sections
//! ([`crate::app::SiteHooks::backup_sections`]) plus the shell's own storage (`decks`, `shell`),
//! never drafts, with secret-looking keys removed. The sync key lives in memory, or in app data
//! `sync-key.json` when the owner ticks "remember on this computer"; it is never part of a backup
//! or a snapshot.
use crate::app::{hooks, tr};
use crate::backup;
use crate::host::{data_file, read_json, shell_only, write_json};
use crate::sync::{self, Key, SnapshotInfo};
use crate::workspaces::{self, WorkspaceStore};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Webview};
use tauri_plugin_dialog::DialogExt;
const SYNC_FILE: &str = "sync.json";
/// The remembered sync key. Never part of a backup or a snapshot.
const SYNC_KEY_FILE: &str = "sync-key.json";
/// The sync state (the unlocked key, and a lock that serializes pushes, pulls and unlocks).
#[derive(Default)]
pub(crate) struct SyncState {
key: Mutex<Option<Key>>,
/// Serializes pushes, pulls and unlocks (file writes in the folder).
busy: Mutex<()>,
}
/// Does nothing unless the app set [`crate::app::AppConfig::sync`].
pub(crate) fn init(app: &AppHandle) {
if crate::app::config(app).sync {
app.manage(SyncState::default());
}
}
fn sync_state(app: &AppHandle) -> Result<tauri::State<'_, SyncState>, String> {
app.try_state::<SyncState>().ok_or_else(|| "UNAVAILABLE: this app has no sync".to_owned())
}
// ---------------------------------------------------------------------------------------------
// Workspaces
#[tauri::command]
pub(crate) async fn workspaces_get(webview: Webview, app: AppHandle) -> Result<WorkspaceStore, String> {
shell_only(&webview)?;
Ok(read_json::<WorkspaceStore>(&app, workspaces::FILE).and_then(|store| store.validated().ok()).unwrap_or_default())
}
#[tauri::command]
pub(crate) async fn workspaces_set(webview: Webview, app: AppHandle, store: WorkspaceStore) -> Result<WorkspaceStore, String> {
shell_only(&webview)?;
let store = store.validated()?;
write_json(&app, workspaces::FILE, &store)?;
Ok(store)
}
// ---------------------------------------------------------------------------------------------
// Sync
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
struct SyncLocal {
/// The folder the owner picked (the snapshots live in `<folder>/wayBetter Sync`).
folder: Option<String>,
device: String,
device_name: String,
/// Push automatically when settings change.
auto_push: bool,
/// Newest snapshot of another device that was pulled (or found equal to ours), ms.
last_pulled: u64,
/// sha256 of the settings last pushed (skip unchanged pushes).
last_pushed_hash: String,
last_pushed_at: u64,
}
fn load_sync(app: &AppHandle) -> Result<SyncLocal, String> {
let mut local = read_json::<SyncLocal>(app, SYNC_FILE).unwrap_or_default();
if !sync::valid_device(&local.device) {
local.device = sync::new_device_id()?;
local.device_name = std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")).unwrap_or_else(|_| "This computer".into());
local.auto_push = true;
write_json(app, SYNC_FILE, &local)?;
}
Ok(local)
}
fn sync_folder(local: &SyncLocal) -> Option<PathBuf> {
local.folder.as_deref().map(|folder| sync::sync_dir(Path::new(folder)))
}
fn current_key(app: &AppHandle, local: &SyncLocal) -> Option<Key> {
let state = sync_state(app).ok()?;
let mut key = state.key.lock().ok()?;
if key.is_none() {
// A remembered key, if it still opens this folder.
let remembered = read_json::<Value>(app, SYNC_KEY_FILE).and_then(|value| value.get("key").and_then(Value::as_str).and_then(Key::from_base64));
if let (Some(remembered), Some(dir)) = (remembered, sync_folder(local)) {
if sync::key_matches(&dir, &remembered) {
*key = Some(remembered);
}
}
}
key.clone()
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SyncStatus {
folder: Option<String>,
device: String,
device_name: String,
auto_push: bool,
/// The folder already holds a sync setup (unlock with its passphrase) or not (choose one).
initialized: bool,
unlocked: bool,
remembered: bool,
last_pushed_at: u64,
last_pulled: u64,
snapshots: Vec<SnapshotInfo>,
error: Option<String>,
}
fn status(app: &AppHandle) -> Result<SyncStatus, String> {
let local = load_sync(app)?;
let dir = sync_folder(&local);
let (initialized, error) = match &dir {
Some(dir) => match sync::read_meta(dir) {
Ok(meta) => (meta.is_some(), None),
Err(error) => (false, Some(error)),
},
None => (false, None),
};
let unlocked = dir.is_some() && current_key(app, &local).is_some();
Ok(SyncStatus {
folder: local.folder.clone(),
device: local.device.clone(),
device_name: local.device_name.clone(),
auto_push: local.auto_push,
initialized,
unlocked,
remembered: data_file(app, SYNC_KEY_FILE).is_some_and(|path| path.exists()),
last_pushed_at: local.last_pushed_at,
last_pulled: local.last_pulled,
snapshots: dir.map(|dir| sync::list(&dir).into_iter().take(20).collect()).unwrap_or_default(),
error,
})
}
fn forget_key(app: &AppHandle) {
if let Ok(state) = sync_state(app) {
if let Ok(mut key) = state.key.lock() {
*key = None;
}
}
if let Some(path) = data_file(app, SYNC_KEY_FILE) {
let _ = std::fs::remove_file(path);
}
}
/// The app's backup sections plus the shell's own storage (`decks`, `shell`), never drafts,
/// secret-looking keys removed: what sync carries.
fn collect(app: &AppHandle, extra: Option<Map<String, Value>>) -> Result<Map<String, Value>, String> {
let mut sections = hooks(app).backup_sections(app)?;
for (key, value) in extra.unwrap_or_default() {
// The shell only adds its own storage; it cannot replace a native section or add drafts.
if (key == "decks" || key == "shell") && value.is_object() {
sections.insert(key, value);
}
}
let mut value = Value::Object(sections);
backup::strip_secrets(&mut value);
Ok(match value {
Value::Object(map) => map,
_ => Map::new(),
})
}
fn hash(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|byte| format!("{byte:02x}")).collect()
}
#[tauri::command]
pub(crate) async fn sync_status(webview: Webview, app: AppHandle) -> Result<SyncStatus, String> {
shell_only(&webview)?;
status(&app)
}
/// Picks the folder to sync through (e.g. a OneDrive/iCloud/Dropbox folder). Locks until unlocked.
#[tauri::command]
pub(crate) async fn sync_choose_folder(webview: Webview, app: AppHandle) -> Result<SyncStatus, String> {
shell_only(&webview)?;
let title = tr(&app, "native.dialog.syncFolder", "Choose a folder to sync wayBetter settings through");
let picked = app.dialog().file().set_parent(&webview.window()).set_title(title).blocking_pick_folder();
let Some(picked) = picked else { return status(&app) };
let path = picked.into_path().map_err(|_| "SYNC: not a local folder")?;
let mut local = load_sync(&app)?;
local.folder = Some(path.to_string_lossy().into_owned());
local.last_pulled = 0;
local.last_pushed_hash.clear();
write_json(&app, SYNC_FILE, &local)?;
forget_key(&app);
status(&app)
}
/// Unlocks the folder with the passphrase (or sets the folder up with it the first time).
#[tauri::command]
pub(crate) async fn sync_unlock(webview: Webview, app: AppHandle, passphrase: String, remember: bool) -> Result<SyncStatus, String> {
shell_only(&webview)?;
let local = load_sync(&app)?;
let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?;
// Argon2id takes a moment on purpose; keep it off the async runtime's threads.
let task_app = app.clone();
let key = tauri::async_runtime::spawn_blocking(move || {
let state = sync_state(&task_app)?;
let _busy = state.busy.lock().map_err(|_| "SYNC: busy".to_string())?;
sync::unlock_or_create(&dir, &passphrase, sync::KdfParams::default())
})
.await
.map_err(|_| "SYNC: unlock failed")??
.0;
if remember {
write_json(&app, SYNC_KEY_FILE, &json!({ "key": key.to_base64() }))?;
#[cfg(unix)]
if let Some(path) = data_file(&app, SYNC_KEY_FILE) {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
} else if let Some(path) = data_file(&app, SYNC_KEY_FILE) {
let _ = std::fs::remove_file(path);
}
*sync_state(&app)?.key.lock().map_err(|_| "SYNC: busy")? = Some(key);
status(&app)
}
#[tauri::command]
pub(crate) async fn sync_lock(webview: Webview, app: AppHandle) -> Result<SyncStatus, String> {
shell_only(&webview)?;
forget_key(&app);
status(&app)
}
/// Stops syncing on this computer (the folder and its snapshots stay).
#[tauri::command]
pub(crate) async fn sync_disable(webview: Webview, app: AppHandle) -> Result<SyncStatus, String> {
shell_only(&webview)?;
let mut local = load_sync(&app)?;
local.folder = None;
write_json(&app, SYNC_FILE, &local)?;
forget_key(&app);
status(&app)
}
#[tauri::command]
pub(crate) async fn sync_configure(webview: Webview, app: AppHandle, auto_push: bool, device_name: String) -> Result<SyncStatus, String> {
shell_only(&webview)?;
let mut local = load_sync(&app)?;
local.auto_push = auto_push;
let name: String = device_name.chars().filter(|ch| !ch.is_control()).take(40).collect();
if !name.trim().is_empty() {
local.device_name = name.trim().to_owned();
}
write_json(&app, SYNC_FILE, &local)?;
status(&app)
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PushResult {
pushed: bool,
name: Option<String>,
}
/// Writes an encrypted snapshot when the settings changed since the last push. `force` writes one
/// even when nothing changed (the "Sync now" button). `extra`: the shell's own sections (decks).
#[tauri::command]
pub(crate) async fn sync_push(webview: Webview, app: AppHandle, extra: Option<Map<String, Value>>, force: bool) -> Result<PushResult, String> {
shell_only(&webview)?;
let mut local = load_sync(&app)?;
let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?;
if !force && !local.auto_push {
return Ok(PushResult { pushed: false, name: None });
}
let key = current_key(&app, &local).ok_or("SYNC: locked; enter the passphrase")?;
let plaintext = sync::settings_plaintext(&collect(&app, extra)?);
let digest = hash(&plaintext);
if !force && digest == local.last_pushed_hash {
return Ok(PushResult { pushed: false, name: None });
}
let state = sync_state(&app)?;
let _busy = state.busy.lock().map_err(|_| "SYNC: busy")?;
let now = chrono::Utc::now().timestamp_millis().max(0) as u64;
let name = sync::write_snapshot(&dir, &key, &local.device, &local.device_name, now, &plaintext)?;
local.last_pushed_hash = digest;
local.last_pushed_at = now;
write_json(&app, SYNC_FILE, &local)?;
Ok(PushResult { pushed: true, name: Some(name) })
}
/// The newest snapshot another computer wrote since the last pull, if its settings differ from
/// ours (one that equals ours is marked as seen). None when locked or nothing is newer.
#[tauri::command]
pub(crate) async fn sync_check(webview: Webview, app: AppHandle, extra: Option<Map<String, Value>>) -> Result<Option<SnapshotInfo>, String> {
shell_only(&webview)?;
let mut local = load_sync(&app)?;
let Some(dir) = sync_folder(&local) else { return Ok(None) };
let Some(key) = current_key(&app, &local) else { return Ok(None) };
let Some(newer) = sync::newer_from_others(&dir, &local.device, local.last_pulled) else { return Ok(None) };
let (_, plaintext) = sync::read_snapshot(&dir, &key, &newer.name)?;
let ours = sync::settings_plaintext(&collect(&app, extra)?);
let theirs: Value = serde_json::from_slice(&plaintext).map_err(|_| "SYNC: damaged snapshot")?;
if serde_json::to_vec(&theirs).unwrap_or_default() == ours {
local.last_pulled = newer.created_at;
write_json(&app, SYNC_FILE, &local)?;
return Ok(None);
}
Ok(Some(newer))
}
/// Opens snapshot `name` for the import preview (nothing applied yet).
#[tauri::command]
pub(crate) async fn sync_open(webview: Webview, app: AppHandle, name: String) -> Result<Map<String, Value>, String> {
shell_only(&webview)?;
let local = load_sync(&app)?;
let dir = sync_folder(&local).ok_or("SYNC: choose a folder first")?;
let key = current_key(&app, &local).ok_or("SYNC: locked; enter the passphrase")?;
let (_, plaintext) = sync::read_snapshot(&dir, &key, &name)?;
let wrapped = json!({ "format": backup::FORMAT, "version": backup::VERSION, "sections": serde_json::from_slice::<Value>(&plaintext).map_err(|_| "SYNC: damaged snapshot")? });
backup::parse_backup(&serde_json::to_vec(&wrapped).map_err(|_| "SYNC: damaged snapshot")?, hooks(&app).backup_section_names())
}
/// Records that snapshot `name` was pulled (or skipped): it is not offered again.
#[tauri::command]
pub(crate) async fn sync_mark_pulled(webview: Webview, app: AppHandle, name: String) -> Result<SyncStatus, String> {
shell_only(&webview)?;
let mut local = load_sync(&app)?;
let created = sync_folder(&local).and_then(|dir| sync::list(&dir).into_iter().find(|info| info.name == name)).map(|info| info.created_at);
if let Some(created) = created {
local.last_pulled = local.last_pulled.max(created);
write_json(&app, SYNC_FILE, &local)?;
}
status(&app)
}
/// The workspaces and sync commands ([`crate::commands::WORKSPACES`], [`crate::commands::SYNC`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
workspaces_get,
workspaces_set,
sync_status,
sync_choose_folder,
sync_unlock,
sync_lock,
sync_disable,
sync_configure,
sync_push,
sync_check,
sync_open,
sync_mark_pulled
]
}

View file

@ -15,7 +15,7 @@ pub const EVENT_PROFILES_CHANGED: &str = "profiles-changed";
pub const EVENT_OPEN_PANEL: &str = "open-panel";
/// One pane as the shell lays it out (`tabs_sync`).
#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TabLayout {
pub id: String,
@ -159,6 +159,7 @@ pub fn new_window_mode<'a>(on_site: bool, site_mode: &'a str, external_mode: &'a
pub const SHORTCUTS: &[&str] = &[
"command-palette", "new-tab", "close-tab", "reopen-tab", "focus-address", "next-tab", "prev-tab", "reload",
"back", "forward", "split-right", "split-down", "open-panel", "find", "hard-reload",
"app-menu", "zoom-in", "zoom-out", "zoom-reset",
"column-prev", "column-next", "column-1", "column-2", "column-3", "column-4", "column-5", "column-6", "column-7",
"column-8", "column-9", "column-page-prev", "column-page-next", "column-mark-read", "deck-compose", "deck-toggle",
];

View file

@ -125,6 +125,14 @@ impl Capabilities {
}
}
/// Every command of an optional group (e.g. [`commands::STORE`]) is granted, and only to the
/// local shell webview.
pub fn assert_shell_only_group(&self, group: &[&str]) {
for command in group {
self.assert_shell_only(command);
}
}
/// `command` is granted to no capability at all.
pub fn assert_not_granted(&self, command: &str) {
let permission = commands::permission(command);
@ -203,10 +211,77 @@ pub fn assert_host_guards() {
}
}
/// The store commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_store_guards() {
let source = include_str!("store_commands.rs");
for command in commands::STORE {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The media commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_media_guards() {
let source = include_str!("media_commands.rs");
for command in commands::MEDIA {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The fonts commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_fonts_guards() {
let source = include_str!("fonts_commands.rs");
for command in commands::GFONTS {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The update commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_update_guards() {
let source = include_str!("update_commands.rs");
for command in commands::UPDATE {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The workspaces and sync commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_sync_guards() {
let source = include_str!("sync_commands.rs");
for command in commands::WORKSPACES.iter().chain(commands::SYNC) {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The developer-mode commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_dev_guards() {
let source = include_str!("dev_commands.rs");
for command in commands::DEV {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
/// The backup commands' wrappers check their caller first. Runs against the host's source.
pub fn assert_backup_guards() {
let source = include_str!("backup_commands.rs");
for command in commands::BACKUP {
assert_guarded(source, command, "shell_only(&webview)?");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_store_commands_check_their_caller_first() {
assert_store_guards();
assert_media_guards();
assert_fonts_guards();
assert_update_guards();
assert_sync_guards();
assert_dev_guards();
assert_backup_guards();
}
fn caps_with(shell_extra: &str, tab_extra: &str, site_extra: &str) -> Capabilities {
let host_shell: Vec<String> = commands::SHELL.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect();
let host_tab: Vec<String> = commands::TAB.iter().map(|c| format!("\"{}\"", commands::permission(c))).collect();

View file

@ -41,8 +41,11 @@ pub const MAX_THEME_BYTES: usize = 1_200_000;
pub const MAX_TOTAL_BYTES: usize = 4_000_000;
/// Theme names: 1-60 characters (`theme.schema.json` `name`).
pub const MAX_NAME_CHARS: usize = 60;
/// Icon packs the owner imported (theme engine v2), each a standalone pack document.
pub const MAX_PACKS: usize = 8;
pub const MAX_PACK_BYTES: usize = 150_000;
/// Override groups the panel may change on top of a theme.
pub const OVERRIDE_KEYS: [&str; 7] = ["font", "shape", "layout", "background", "effects", "colors", "css"];
pub const OVERRIDE_KEYS: [&str; 8] = ["font", "shape", "layout", "background", "effects", "colors", "css", "variants"];
/// The theme applied to the site's tabs: a theme id (built-in or one of `themes`), an optional
/// accent, per-group overrides from the panel and the owner's imported theme documents.
@ -56,6 +59,14 @@ pub struct ThemeChoice {
pub overrides: Map<String, Value>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub themes: Vec<Value>,
/// The owner's icon pack: absent follows the theme's suggestion, `site` keeps the site's own icons,
/// otherwise a pack id (theme engine v2). A slug; an unknown pack falls back to the site's icons in the page.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icons: Option<String>,
/// Icon packs the owner imported: data documents (path data, colored layers, small PNGs), checked
/// again by the page runtime's sanitizer; here only their shape and size.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub packs: Vec<Value>,
}
/// A theme id: a lowercase slug of 1-40 characters (`theme.schema.json` `id`).
@ -75,7 +86,7 @@ fn doc_id(theme: &Value) -> Option<&str> {
impl ThemeChoice {
/// The site's own look, nothing customized.
pub fn default_for(site: &ThemeSite) -> Self {
Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new() }
Self { preset: site.own().into(), accent: None, overrides: Map::new(), themes: Vec::new(), icons: None, packs: Vec::new() }
}
pub fn validate(&self, site: &ThemeSite) -> Result<(), String> {
@ -84,6 +95,27 @@ impl ThemeChoice {
return Err("VALIDATION: accent must use six-digit hex".into());
}
}
if let Some(icons) = &self.icons {
if !valid_id(icons) {
return Err("VALIDATION: an icon pack id is a lowercase slug".into());
}
}
if self.packs.len() > MAX_PACKS {
return Err("VALIDATION: too many icon packs".into());
}
let mut pack_ids: Vec<&str> = Vec::new();
for pack in &self.packs {
let object = pack.as_object().ok_or("VALIDATION: an icon pack must be an object")?;
let id = object.get("id").and_then(Value::as_str).ok_or("VALIDATION: an icon pack needs an id")?;
let name = object.get("name").and_then(Value::as_str).ok_or("VALIDATION: an icon pack needs a name")?;
if !valid_id(id) || pack_ids.contains(&id) || name.trim().is_empty() || name.chars().count() > MAX_NAME_CHARS || !object.get("glyphs").is_some_and(Value::is_object) {
return Err("VALIDATION: icon packs have unique slug ids, a name and glyphs".into());
}
if serde_json::to_vec(pack).map(|bytes| bytes.len()).unwrap_or(usize::MAX) > MAX_PACK_BYTES {
return Err("VALIDATION: icon pack is too large".into());
}
pack_ids.push(id);
}
if self.themes.len() > MAX_THEMES {
return Err("VALIDATION: too many themes".into());
}
@ -120,7 +152,7 @@ impl ThemeChoice {
/// True when the site keeps its own look (nothing to apply). Imported themes are kept in the
/// file even while the site's own look is selected, so this only looks at what is applied.
pub fn is_default(&self, site: &ThemeSite) -> bool {
self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty()
self.preset == site.own() && self.accent.is_none() && self.overrides.is_empty() && self.icons.is_none()
}
/// Nothing worth persisting: the site's own look and no imported themes.
@ -139,7 +171,7 @@ impl ThemeChoice {
let base = if id == self.preset || !self.knows(site, id) {
self.clone()
} else {
ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone() }
ThemeChoice { preset: id.into(), accent: None, overrides: Map::new(), themes: self.themes.clone(), icons: self.icons.clone(), packs: self.packs.clone() }
};
let preset = base.preset.clone();
let themes = base.themes.into_iter().filter(|theme| doc_id(theme) == Some(preset.as_str())).collect();
@ -304,6 +336,24 @@ mod tests {
assert_eq!(imported.page_color(&SITE), Some((0xab, 0xcd, 0xef)), "an invalid page color falls back to bg");
}
#[test]
fn icon_choice_is_a_slug_and_counts_as_a_choice() {
let picked = with(json!({ "preset": "site", "icons": "wb-pixel" })).unwrap();
assert_eq!(picked.icons.as_deref(), Some("wb-pixel"));
assert!(!picked.is_default(&SITE), "an icon pick is applied even on the site's own look");
assert!(with(json!({ "preset": "site", "icons": "Bad Pack!" })).is_err());
assert!(with(json!({ "preset": "site", "overrides": { "variants": { "nav": "top" } } })).is_ok(), "layout variants are an override group");
assert_eq!(picked.for_theme(&SITE, "nord").icons.as_deref(), Some("wb-pixel"), "the icon pick is global");
let pack = json!({ "id": "retro", "name": "Retro", "glyphs": { "home": { "d": "M0 0h1" } } });
let with_pack = with(json!({ "preset": "site", "icons": "retro", "packs": [pack.clone()] })).unwrap();
assert_eq!(with_pack.packs.len(), 1);
assert_eq!(with_pack.for_theme(&SITE, "nord").packs.len(), 1, "imported packs are global");
assert!(with(json!({ "preset": "site", "packs": [pack.clone(), pack] })).is_err(), "pack ids are unique");
assert!(with(json!({ "preset": "site", "packs": [{ "id": "x", "name": "X" }] })).is_err(), "a pack has glyphs");
let big = json!({ "id": "big", "name": "Big", "glyphs": { "home": { "d": "M".repeat(MAX_PACK_BYTES) } } });
assert!(with(json!({ "preset": "site", "packs": [big] })).is_err(), "a pack is bounded");
}
#[test]
fn user_themes_and_overrides_are_bounded() {
let ok = with(json!({ "preset": "mine", "themes": [{ "id": "mine", "name": "Mine", "colors": null }], "overrides": { "font": { "scale": 1.1 } } })).unwrap();

View file

@ -14,6 +14,16 @@ pub const READY_DEADLINE: Duration = Duration::from_secs(30);
/// Launches of an updated version without `app_ready` before automatic apply is disabled.
pub const MAX_FAILED_BOOTS: u32 = 2;
pub const PENDING_FILE: &str = "update-pending.json";
/// Least time between two checks the owner asks for ("Check for updates"): a row clicked again
/// and again asks the server once.
pub const MANUAL_CHECK_GAP: Duration = Duration::from_secs(10);
/// Whether a check the owner asked for may start: never while one is in flight (the timer's or
/// an earlier request's), and not within [`MANUAL_CHECK_GAP`] of the last request. A refused
/// request answers with the current status; nothing is queued and nothing retries.
pub fn may_check_now(in_flight: bool, since_last_request: Option<Duration>) -> bool {
!in_flight && since_last_request.is_none_or(|elapsed| elapsed >= MANUAL_CHECK_GAP)
}
/// Wait before the next check: 30 min +/- 5 min, from any 64-bit entropy value.
pub fn next_check_delay(entropy: u64) -> Duration {
@ -76,6 +86,16 @@ pub fn on_boot(pending: Option<PendingUpdate>, current_version: &str) -> BootDec
mod tests {
use super::*;
#[test]
fn a_requested_check_runs_once_and_never_piles_up() {
assert!(may_check_now(false, None), "the first request checks");
assert!(!may_check_now(true, None), "not while the timer's check is in flight");
assert!(!may_check_now(true, Some(Duration::from_secs(3600))));
assert!(!may_check_now(false, Some(Duration::from_secs(2))), "a row clicked again asks the server once");
assert!(may_check_now(false, Some(MANUAL_CHECK_GAP)));
assert!(may_check_now(false, Some(Duration::from_secs(60))));
}
#[test]
fn delay_stays_within_jitter() {
for entropy in [0, 1, 300, 600, 601, u64::MAX] {

View file

@ -0,0 +1,53 @@
//! Native updates, for every app that sets [`crate::app::AppConfig::updates`]: the shell's four
//! narrow commands ([`crate::commands::UPDATE`]) over [`crate::updater`] (signed native updates and
//! the signed data-only hotfix channel, configured by the app's [`crate::updater::UpdaterConfig`]).
//! Everything runs in Rust; site tabs get no updater IPC at all, only the verified hotfix data the
//! app injects ([`crate::updater::hotfix_script`]).
use crate::app::config;
use crate::host::shell_only;
use crate::update::UpdateStatus;
use crate::updater;
use tauri::{AppHandle, Webview};
/// Runs the launch handshake, loads the cached hotfix and starts the update loop. Does nothing
/// unless the app set [`crate::app::AppConfig::updates`].
pub(crate) fn init(app: &AppHandle) {
if let Some(updates) = config(app).updates {
updater::init(app, updates);
}
}
#[tauri::command]
pub(crate) async fn update_status(webview: Webview, app: AppHandle) -> Result<UpdateStatus, String> {
shell_only(&webview)?;
updater::status(&app)
}
/// "Check for updates" in the app menu: the same check the timer runs, once, now (the same updater
/// endpoint; never queued, never retried). Returns the status when the check has finished.
#[tauri::command]
pub(crate) async fn update_check(webview: Webview, app: AppHandle) -> Result<UpdateStatus, String> {
shell_only(&webview)?;
updater::check_now(&app).await
}
/// Installs the downloaded update and restarts. On Windows the quiet NSIS installer replaces
/// the app and relaunches it (`/UPDATE /R`), and this process exits inside `install`.
#[tauri::command]
pub(crate) async fn apply_update(webview: Webview, app: AppHandle) -> Result<(), String> {
shell_only(&webview)?;
updater::apply(&app)
}
/// The shell reached a working state: confirms a just-installed update and returns the status.
#[tauri::command]
pub(crate) async fn app_ready(webview: Webview, app: AppHandle) -> Result<UpdateStatus, String> {
shell_only(&webview)?;
updater::ready(&app)
}
/// The update commands ([`crate::commands::UPDATE`]).
pub(crate) fn handler() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![update_status, update_check, apply_update, app_ready]
}

View file

@ -4,8 +4,8 @@
//! its verification are [`crate::hotfix`].
//!
//! The app registers the updater plugin, calls [`init`] from `setup` with its [`UpdaterConfig`],
//! and wraps [`status`], [`apply`] and [`ready`] in its own shell-only commands; its shell gets an
//! `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data
//! and wraps [`status`], [`apply`], [`ready`] and [`check_now`] in its own shell-only commands; its
//! shell gets an `update-status` event. Site tabs get no updater IPC at all, only verified hotfix data
//! ([`hotfix_script`]).
use crate::hotfix::{self, Hotfix, Outcome};
@ -23,6 +23,7 @@ const HOTFIX_SIG_FILE: &str = "hotfix.json.sig";
/// What differs between apps: the hotfix channel, the page names hotfix data is delivered under,
/// the manual download page and what to do when an update is ready.
#[derive(Debug)]
pub struct UpdaterConfig {
/// Hotfix data goes to this site's tabs.
pub site: &'static SiteSpec,
@ -49,6 +50,10 @@ struct Inner {
hotfix: Option<Hotfix>,
/// Automatic apply is off after repeated failed starts of an update.
problem: bool,
/// A check is running (the timer's or one the owner asked for): a second one never starts beside it.
checking: bool,
/// When the owner last asked for a check ([`check_now`]).
asked: Option<std::time::Instant>,
}
struct UpdateState {
@ -111,13 +116,48 @@ pub fn init(app: &AppHandle, config: &'static UpdaterConfig) {
tauri::async_runtime::spawn(async move {
tokio::time::sleep(update::FIRST_CHECK).await;
loop {
check_native(&app).await;
check_once(&app).await;
check_hotfix(&app).await;
tokio::time::sleep(update::next_check_delay(entropy())).await;
}
});
}
/// One native check, unless one is already running.
async fn check_once(app: &AppHandle) {
{
let state = app.state::<UpdateState>();
let Ok(mut inner) = state.inner.lock() else { return };
if inner.checking {
return;
}
inner.checking = true;
}
check_native(app).await;
if let Ok(mut inner) = app.state::<UpdateState>().inner.lock() {
inner.checking = false;
}
}
/// A check the owner asked for (the app's shell-only `update_check`, the app menu's "Check for
/// updates"): the same check the timer runs, once, now, against the same updater endpoint (no
/// other network destination). It never queues or retries: while a check is in flight, or within
/// [`update::MANUAL_CHECK_GAP`] of the last request, it only answers with the current status.
/// Returns the status once the check has finished (the shell also hears each step as events).
pub async fn check_now(app: &AppHandle) -> Result<UpdateStatus, String> {
{
let state = app.try_state::<UpdateState>().ok_or("UPDATE: state unavailable")?;
let mut inner = state.inner.lock().map_err(|_| "UPDATE: state unavailable")?;
let now = std::time::Instant::now();
if !update::may_check_now(inner.checking, inner.asked.map(|asked| now.duration_since(asked))) {
return Ok(status_of(state.config, &inner));
}
inner.asked = Some(now);
}
check_once(app).await;
status(app)
}
async fn check_native(app: &AppHandle) {
{
let state = app.state::<UpdateState>();

View file

@ -0,0 +1,139 @@
//! Page zoom per tab. The shell alone sets it (`tab_zoom {id, factor}`, shell-only): the factor is
//! a plain number, clamped to 25%..500% and rounded to whole percent, applied natively to that
//! tab's webview (the engine's own page zoom, never CSS) and remembered per tab id in app data
//! `zoom.json`, so a tab keeps its zoom when its webview is created again (a restart with session
//! restore, a profile change). A tab at 100% has no entry; a closed tab's entry goes with it.
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const ZOOM_FILE: &str = "zoom.json";
/// 25%: below this a page is unreadable and engines start refusing.
pub const MIN: f64 = 0.25;
/// 500%: the most the engines accept.
pub const MAX: f64 = 5.0;
pub const DEFAULT: f64 = 1.0;
/// Remembered tabs at most; past this the file is of no use and only grows.
pub const MAX_TABS: usize = 512;
/// The factor the host applies for a requested one: a finite number, clamped to [`MIN`]..[`MAX`]
/// and rounded to whole percent (so 110% is 1.1, not 1.1000000000000001).
pub fn normalize(factor: f64) -> Result<f64, String> {
if !factor.is_finite() {
return Err("VALIDATION: zoom is not a number".into());
}
Ok((factor.clamp(MIN, MAX) * 100.0).round() / 100.0)
}
/// The remembered factors by tab id (`zoom.json`). Only tabs away from 100% are kept.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ZoomMap(BTreeMap<String, f64>);
impl ZoomMap {
/// What was read from disk, made safe: valid tab ids only, every factor normalized, bounded.
pub fn validated(self) -> Self {
let mut out = BTreeMap::new();
for (id, factor) in self.0 {
if out.len() >= MAX_TABS {
break;
}
if let (true, Ok(factor)) = (crate::policy::valid_tab_id(&id), normalize(factor)) {
if factor != DEFAULT {
out.insert(id, factor);
}
}
}
Self(out)
}
/// The factor tab `id` shows (100% when nothing is remembered).
pub fn get(&self, id: &str) -> f64 {
self.0.get(id).copied().unwrap_or(DEFAULT)
}
/// Remembers `factor` for tab `id` and returns the factor in effect. 100% forgets the tab.
pub fn set(&mut self, id: &str, factor: f64) -> Result<f64, String> {
if !crate::policy::valid_tab_id(id) {
return Err("VALIDATION: invalid tab id".into());
}
let factor = normalize(factor)?;
if factor == DEFAULT {
self.0.remove(id);
} else {
if !self.0.contains_key(id) && self.0.len() >= MAX_TABS {
return Err("VALIDATION: too many zoomed tabs".into());
}
self.0.insert(id.to_owned(), factor);
}
Ok(factor)
}
/// A closed tab: true when something was remembered for it (the file changes).
pub fn forget(&mut self, id: &str) -> bool {
self.0.remove(id).is_some()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn factors_are_clamped_and_rounded_and_must_be_numbers() {
assert_eq!(normalize(1.0).unwrap(), 1.0);
assert_eq!(normalize(1.1000000000000001).unwrap(), 1.1);
assert_eq!(normalize(0.666).unwrap(), 0.67);
assert_eq!(normalize(0.01).unwrap(), MIN, "never below 25%");
assert_eq!(normalize(-3.0).unwrap(), MIN);
assert_eq!(normalize(40.0).unwrap(), MAX, "never above 500%");
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(normalize(bad).is_err(), "{bad}");
}
}
#[test]
fn a_tab_keeps_its_zoom_until_it_is_reset_or_closed() {
let mut map = ZoomMap::default();
assert_eq!(map.get("t1"), 1.0);
assert_eq!(map.set("t1", 1.25).unwrap(), 1.25);
assert_eq!(map.set("t2", 9.0).unwrap(), 5.0);
assert_eq!((map.get("t1"), map.get("t2"), map.len()), (1.25, 5.0, 2));
// 100% is the absence of an entry.
assert_eq!(map.set("t1", 1.0).unwrap(), 1.0);
assert_eq!(map.len(), 1);
assert!(map.forget("t2") && !map.forget("t2"));
assert!(map.is_empty());
// Only tab ids the host itself accepts.
assert!(map.set("../x", 1.5).is_err());
assert!(map.set("t1", f64::NAN).is_err());
assert!(map.is_empty());
}
#[test]
fn the_file_is_data_and_is_bounded() {
let mut map = ZoomMap::default();
map.set("t1", 1.5).unwrap();
let json = serde_json::to_string(&map).unwrap();
assert_eq!(json, r#"{"t1":1.5}"#);
assert_eq!(serde_json::from_str::<ZoomMap>(&json).unwrap().validated(), map);
// A hand-edited file: bad ids and neutral entries are dropped, factors are clamped.
let read = serde_json::from_str::<ZoomMap>(r#"{"t1":99,"t2":1,"bad id!":2,"t3":0.001}"#).unwrap().validated();
assert_eq!((read.get("t1"), read.get("t2"), read.get("t3"), read.len()), (5.0, 1.0, 0.25, 2));
assert!(serde_json::from_str::<ZoomMap>(r#"{"t1":"big"}"#).is_err());
for n in 0..MAX_TABS {
map.set(&format!("x{n}"), 2.0).unwrap_or(0.0);
}
assert_eq!(map.len(), MAX_TABS);
assert!(map.set("one-more", 2.0).is_err(), "bounded");
assert_eq!(map.set("t1", 3.0).unwrap(), 3.0, "a remembered tab can still change");
}
}

View file

@ -85,12 +85,21 @@
if (key === 'w') return 'close-tab';
if (key === 'l') return 'focus-address';
if (key === 'k' && !event.shiftKey) return 'command-palette';
// Find in page is the shell's bar (`tab_find`): this tab only says the keys were pressed.
if (key === 'f' && !event.shiftKey) return 'find';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return event.shiftKey ? 'hard-reload' : 'reload';
// Physical key: layouts like Turkish-Q produce other characters on this key.
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
// Page zoom is the shell's (`tab_zoom`): this tab only says which key was pressed.
if (key === '=' || key === '+' || event.code === 'NumpadAdd') return 'zoom-in';
if (key === '-' || event.code === 'NumpadSubtract') return 'zoom-out';
if (key === '0' || event.code === 'Numpad0') return 'zoom-reset';
}
if (key === 'f5') return 'reload';
// The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS).
if (key === 'f10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu';
if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && !/Mac/i.test(navigator.platform)) return 'app-menu';
if (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;

564
docs/ARCHITECTURE.md Normal file
View file

@ -0,0 +1,564 @@
# Architecture reference
Every module of the host, the runtime and the shell, and what an app supplies. The overview is in
the [README](../README.md); this is the long form.
A wayBetter app is one native window (Tauri 2, multiwebview) with:
- a trusted local **shell** webview: tab strip, split panes (dockview), address bar, titlebar and
window controls, command palette, account switcher, the app's own settings;
- one native child webview per browser **tab**, positioned over the pane rectangles the shell
reports (`tabs_sync`), each in an account **profile** with its own WebView data directory;
- a **page runtime** injected into tabs that are on the app's site: shared DOM/request hubs,
plugins, themes, split-view rail hiding, link routing and account reporting.
This repository holds the parts that do not depend on which site the app extends. An app is mostly
a **site adapter** plus its own features.
## One system for every app
Every wayBetter app is the same system: the Tauri window above (shell + page runtime) plus one
small adapter. That holds for websites like x.com and just as much for services that ship their
own Electron desktop client, such as WhatsApp or Discord: wayBetter runs their web app in its own
light Tauri window instead of the heavy client, and gives it the same tabs, split panes, real
accounts side by side, themes, plugins and signed updates. There is no second kind of host.
License: GPL-3.0-or-later.
## Projects using wayBetter
| Project | Target | What it is |
| --- | --- | --- |
| [wayBetter for X](https://waybetter.fyi/x/) | x.com (website) | Desktop app around the live X: tabs, split panes, real accounts side by side, themes, plugins, drafts and fixes for X's own bugs. The first wayBetter app. |
Built something on wayBetter? Add it to this list with a pull request: name and link, what it extends, one line on what it does.
## Build your own
```sh
npm create waybetter plugin # a *.plugin.js (or --ts: a TypeScript project) on the real plugin API
npm create waybetter theme # a theme JSON with "$schema", a derived palette and font roles
npm create waybetter app -- --site kick.com # a whole app: Tauri 2 + waybetter-host + runtime + shell
```
`create-waybetter` (in `packages/create-waybetter`) asks for what it needs in a terminal, and
takes every answer as a flag (`--help`). The app skeleton is this README in code: the native
`SiteSpec`, the page `SiteAdapter`, the app on `waybetter_host::app` (its config, site hooks and
its own commands), the three capability files and a `tests/security.rs` on `waybetter_host::testkit`,
the shell (the framework's shell frame through `createShell`, with the site's pages and a plugins
panel), the plugin store, one site-only command, the
runtime bundled with `waybetter/build` and a `waybetter.release.json` for `waybetter release`, with presets for
youtube.com, kick.com and twitch.tv and every site selector marked as a placeholder. Its tests
generate each kind into a temp folder and check it against the real contracts: plugin headers with
`plugins::parse_meta`, plugin code against `createCorePluginApi`'s members, themes against
`theme.schema.json`, the app's TypeScript with `tsc` against the built package and its Rust with
`cargo check`/`cargo test` against this crate.
## Layout
```
crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfix, updates, tab payloads,
and the generic native features every app gets (below)
tab-bridge.js the tab bridge every tab gets (served by src/bridge.rs)
src/site.rs SiteSpec + AccountRules (the native half of the adapter)
src/policy.rs webview labels, origin checks, tab rect clamp
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,
deck ColumnConfig bounds and unread caps
src/bridge.rs the tab bridge script (reports; shortcut/link-drag forwarding opt-in)
src/backup.rs settings backup envelope, secret scrubbing, plugin/account sections
src/sync.rs encrypted folder sync (Argon2id + XChaCha20-Poly1305 snapshots)
src/workspaces.rs saved tab/pane/deck layouts, bounded and well-formed
src/devmode.rs developer mode: debounced file watcher, reload order, error positions
src/alerts.rs keyword alerts: keywords, snippets, rate limits; native notifications
src/media.rs gallery folders (path containment), clipboard history, PNG encoding
src/media/clipboard.rs (feature "tauri") opt-in clipboard polling, private copies skipped
src/gfonts.rs self-hosted Google Fonts: CSS parsing, URL/woff2 checks, cache format
src/fonts.rs (feature "net") font downloads and the font cache
src/updater.rs (features "tauri" + "net") signed native updates and the hotfix channel
src/store/ install links, download allow-list, signed multi-app store catalog, staging
and installs; downloads with feature "net" (docs/STORE.md)
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)
site.ts SiteAdapter (the page half of the adapter) + configureRuntime
domHub.ts netHub.ts one MutationObserver/frame, one fetch/XHR hook per page
pluginApi.ts core of window.<Runtime>.api for plugins (incl. ui and theme)
ui.ts plugin UI kit: toasts, alert/confirm/prompt, dialogs (shadow DOM, themed)
themeApi.ts the active theme as values + --wb-* CSS variables (api.theme)
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
paneNav.ts split view: park the site's navigation rail in redundant panes
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
stringPacks.ts string packs (docs/STRING-PACKS.md): pack and inventory formats, validator,
ordered engine, coverage, drift report
stringPackHook.ts the per-site catalog hook adapter, its self-check, a webpack chunk array hook
textNet.ts DOM safety net for labels no catalog hook reaches
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
deckModel.ts decks of site columns: bounded storage model, paging layout, focus
linkDrop.ts dropping links into the dock
profileModel.ts profiles and account labels
palette.ts command palette scoring/ranking
updateModel.ts titlebar update chip
windowControls.ts caption buttons, resize grips, system menu (Tauri API injected)
chrome.ts titlebar/toolbar/resize-border sizes (match policy.rs)
storeModel.ts storeMessages.ts Store wire types, item states, permission words; wb.store/install/permission.*
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`,
`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)
```
Both TypeScript packages are plain source (`.ts`, ESM, `type: module`) with no runtime
dependencies, so an app can bundle them with esbuild/Vite and run their tests with Node's type
stripping. Anything that needs the Tauri API (window controls, the shell frame) takes it as a
parameter. The React parts (the Store screens, the shell frame) have React, and the frame dockview,
as optional peers: the app's copies are used.
## The shell frame
`packages/shell/src/frame` (`waybetter/shell/frame`) is the whole shell of a wayBetter app. An app
describes its site and gets tabs in the titlebar row, split panes and link drags into the dock, the
smart address bar, the new-tab page, the command palette, the account switcher, decks of site
columns, workspaces, the developer-mode and sync chips, the gallery/clipboard panel, pane themes,
its own panel tab, keyboard shortcuts, overlays that raise the shell above the tab webviews, the
one-layout-in-flight `tabs_sync` and session restore:
```tsx
import { invoke } from '@tauri-apps/api/core'; // or window.__TAURI__ (withGlobalTauri)
import { listen } from '@tauri-apps/api/event';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { createShell, type ShellSite } from 'waybetter/shell/frame';
const site: ShellSite = { name: 'Kick', product: 'wayBetter for Kick', homeUrl, loginUrl, logoutUrl,
isSiteUrl, accounts, searchUrl, address, panel: { id, title, component }, newTab, palette,
deck, media, themes, overlays, features, start };
const Shell = createShell(site, { native: { invoke, listen, currentWindow: getCurrentWindow }, i18n });
createRoot(root).render(<Shell/>);
```
What the site supplies (`frame/site.ts`, every field documented there):
- names and pages: `name` (in messages as `{site}`), `product`, `logo`, `homeUrl`, `loginUrl`,
`logoutUrl`, `isSiteUrl`, the account rules, `searchUrl` for typed text;
- the address bar: `address(url)` (chips, usually `parseAddress` with an `AddressSite`) and an
optional `addressCompleter` (inline completions, e.g. search operators);
- slots: `panel` (the app's own tab and its sections), `newTab` (search label, quick links),
`palette` (placeholder, the literal search, completions, the panel's sections, the site's pages),
`deck` (column kinds with labels and icons, the page each loads, titles, value parsing and
completions, column flags and presets, an optional compose dock), `media` (which pages have a
composer), `themes` (a `createThemeStore(adapter)`: the app's theme documents, chrome colors via
`chromeVars`, pane themes), `overlays` (the app's own dialogs), `start()` (read site settings,
call `siteChanged()` when site text changes);
- `features`: the native features the app wires up (workspaces, sync, developer mode, plugin
palette commands); an app without them shows nothing of them.
The frame's words are `wb.*` messages in the framework catalogs (51 languages; English source in
`frame/frameMessages.ts`): the app passes its i18n instance with the framework catalogs merged in.
Styles come with the components (dockview's, then `shell.css`, `deck.css`, `workspaces.css`,
`accountSwitcher.css`, `paneTheme.css`); colors are `--wb-c-*` tokens with Night Ink fallbacks,
set by the theme store (the chrome and each pane group) and cached for the first frame:
`bootScript()` (`frame/boot.ts`) is the `boot.js` an app serves before its modules (a Vite plugin or
a build step writes it). `installPreviewMocks(handlers)` answers native commands from memory, so
the real shell renders in a plain browser for development previews and screenshots.
Native commands the frame calls: the host's (`tabs_sync`, `tab_navigate`, `tab_action`,
`shell_focus`, `shell_raise`, `open_external_url`, `window_system_menu`, `profiles_*`), and for the
features an app turns on `settings_get`, `column_configure`, `workspaces_*`, `sync_*`, `dev_*`,
`plugins_list`, `tab_run_command`, `media_get`/`gallery_*`/`clip_*`/`tab_attach_image`/
`tab_insert_text`, `theme_scopes_*` and `gfonts_*`, `app_ready`/`update_status`/`apply_update`. It
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.<flag>.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.<file>.name|description` (its bundled plugins),
`theme.<id>.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.
### 1. Native: `SiteSpec` (Rust)
```rust
use waybetter_host::site::{AccountRules, SiteSpec};
fn kick_handle(value: &str) -> bool {
(3..=25).contains(&value.len()) && value.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
pub static SITE: SiteSpec = SiteSpec {
product: "wayBetter for Kick",
hosts: &["kick.com"], // exact https origin(s) of site tabs
runtime_global: "WayBetterKick", // window.<global> of the page runtime
accounts: AccountRules {
valid_handle: kick_handle,
avatar_prefixes: &["https://files.kick.com/"],
max_name_chars: 50,
max_avatar_len: 512,
},
};
```
`SiteSpec::is_origin` is the only definition of "a site tab". Site-only commands check
`policy::require_site_tab(&SITE, label, url)` (or `host::site_tab_only`), which also requires a
`tab-*` label.
### 2. Page: `SiteAdapter` (TypeScript)
```ts
import { configureRuntime, type SiteAdapter } from 'waybetter/packages/runtime/src/site.ts';
export const KICK: SiteAdapter = {
product: 'wayBetter for Kick',
hosts: ['kick.com'],
runtimeGlobal: 'WayBetterKick',
heavyPath: null, // pages where offOnHeavy DOM features pause
apiMarks: ['/api/'], // request URLs the net hub stages may see
xhrMarks: [],
plugins: { name: 'WayBetterKick', product: 'wayBetter for Kick', storagePrefix: 'wbk-plugin:',
styleDataKey: 'wbkPlugin', toastId: 'wbk-toast', toastBackground: '#53fc18',
itemSelector: '[data-chat-entry]', chordKeys: [] },
rail: { prefix: 'wbk', rail: '#sidebar-wrapper', anchor: 'a[href="/"]', main: 'main',
modalOpen: '[role="dialog"]', menuOpen: '[role="menu"]',
paint: { width: 64, background: '#0b0e0f', line: 'rgba(255,255,255,.12)', accent: '#53fc18', rtl: false } },
account: { read: readKickAccount, signedOut: root => !!root.querySelector('[data-test="login"]') },
links: { configKey: 'site', clickedUrl: kickClickedUrl },
themeSources: { dark: KICK_DARK_AXIS },
};
configureRuntime(KICK);
```
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) | 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, and the host's `commands::SITE` (`open_panel`) |
| other local webviews (`popover-*`, ...) | their own narrow capability |
```json
{ "identifier": "tab-chrome", "webviews": ["tab-*"], "local": false,
"remote": { "urls": ["https://*/*", "http://*/*"] },
"permissions": ["allow-tab-report", "allow-tab-shortcut", "allow-tab-link-drag"] }
```
```json
{ "identifier": "site-tab", "webviews": ["tab-*"], "local": false,
"remote": { "urls": ["https://kick.com/*"] },
"permissions": ["allow-open-panel"] }
```
Native code re-checks every one of these (the capability file alone is not the boundary): the
caller's label, the webview's own URL (never the page's claim), payload bounds. A tab can speak only
about itself; the account it reports is recorded only for its own profile, only while it is on the
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_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.
## What the host gives an app
- `app` (feature `app`): the whole app. `App::new(AppConfig, hooks).setup(..).run(context,
handler)` (or `run_app`) registers single-instance, deep-link (opt-in), window-state, opener,
updater (opt-in), process, notification and dialog; makes the app-data folder (0700 on Unix),
loads the profiles and the language, runs the app's setup, then builds the window (frameless
with the shell's titlebar, or the OS frame), restores its geometry (lost geometry reset),
routes helper-window closes (Windows), follows window resizes natively and adds the shell
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`, `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:
`profiles`, `tab_profile`, `account_seen`, `tr`/`trf`, `i18n_page_script`, `notify`,
`open_external`.
To show the first window only after restored panes are placed, opt in on both sides:
`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 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).
- `profiles`: `ProfileSettings` (validated, default profile required, profiles with open tabs cannot be
removed), `data_dir` (ids cannot escape `profiles/`), `orphan_dirs`, `store_identifier` (macOS).
- `plugins`: `PluginStore` with a `PluginHost` (runtime global, origin, product, bundled plugins).
Bundled plugins are written disabled and upgraded only while untouched.
- `hotfix`: minisign-verified, schema-checked, monotonic, expiring data; delivered frozen as data.
- `update`: check schedule with jitter, crash handshake (automatic apply off after two failed boots).
- `tabs`: shell payloads and validation; `deliver_script` hands JSON to a runtime member or parks it.
- `bridge`: the tab bridge (`SOURCE`, or `script(BridgeOptions)` to leave shortcut and link-drag
forwarding off when the shell does not handle them).
- `backup` + `sync`: the `.waybetter` settings backup (the app registers its sections and files;
secret-looking keys are scrubbed both ways) and encrypted snapshots in a folder the owner syncs.
- `workspaces`: validation of saved layouts (slug ids, known tab kinds, http(s) URLs, size caps).
- `devmode`: the live-reload watcher (plugins, `custom.css`, one theme file; the app turns the theme
document into its own state through a callback).
- `alerts`: keyword settings, snippets, `Throttle`, `AlertGate` over any `KeywordMatch`;
`alerts::notify` (feature `tauri`) shows a native notification.
- `media`: gallery folders and the opt-in clipboard history; `media::clipboard::watch` (feature
`tauri`) polls the OS clipboard and never reads a copy a password manager marked private.
- `gfonts` + `fonts` (feature `net`): Google Fonts downloaded natively from the two Google hosts
only, cached with a sha256 manifest and handed to site pages as bytes (`page_script(&SITE, ..)`).
- `updater` (features `tauri` + `net`): the update loop, the signed hotfix channel and
`status`/`apply`/`ready` for the app's commands, configured by an `UpdaterConfig`.
- `plugins::commands`: palette commands a site tab reports, and `run_script(&SITE, id)`.
- `store`: the wayBetter Store for any app from a `StoreConfig` (app id, link scheme, store URL,
public keys with rotation, download hosts): `waybetter://install` link parsing, the allow-list,
size caps, catalog verification (Ed25519, strict schema, each app sees only its items), `Store`
(pending links, staged installs, commit of exactly the staged bytes, records, offline catalog),
and with feature `net` no-redirect/no-cookie downloads. The shell half is `waybetter/shell`'s
`InstallHost`, `StoreView` and install controller; the tooling is `waybetter store`
(docs/STORE.md).
- `host` (feature `tauri`): `shell_only`, `tab_only`, `site_tab_only`, `emit_shell`, `tab_webview`,
`eval_in_site_tabs`, `navigate_tab`, `tab_action`, `forward_shortcut`, `forward_link_drag`,
`read_json`/`write_json`, `remove_profile_dirs`, `prune_profile_dirs`, `migrate_identifier`,
`system_menu`.
Besides the commands above, the host serves optional groups of shell-only commands that an app turns
on with `AppConfig::with_*` (see "Optional command groups" in the README): `commands::STORE`,
`MEDIA`, `GFONTS`, `UPDATE`, `SYNC`, `DEV`, `WORKSPACES` and `BACKUP`, with the `SiteHooks` methods
that carry what only the app knows (`fonts_changed`, `backup_sections`, `backup_section_names`,
`backup_drafts`, `backup_apply`, `dev_theme_apply`, `dev_theme_end`). The app keeps its own
`#[tauri::command]` wrappers for everything site-specific, and its capability files; its `build.rs`
lists its commands through `commands::manifest`, which adds the host's.
The npm package adds the app-side tooling:
- `waybetter/build`: `buildRuntime({ entry, outfile, catalog, prefixes, ... })` bundles a page
runtime into one IIFE with the app's esbuild (`?inline` CSS as text, other CSS dropped, only the
runtime's own catalog prefixes compiled in).
- `waybetter release windows|macos`: signed native releases and the update manifest from the
app's `waybetter.release.json` (product and file names, key folder, CDN and API URLs, an optional
manifest validator). Windows: the signed NSIS build, the installer and `.sig` in
`<outDir>/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 -- <command>` 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). MSVC has no
prefix map, so there the C and C++ a build script compiles (a CMake library, the cc crate) lose
the same roots through `/d1trimfile:<root>` in the `CL` variable, and any PDB they link through
`/PDBALTPATH` in `LINK`; cl.exe and link.exe read both themselves, whatever runs them:
`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 strings check <pack>`: a string pack (data that replaces the wrapped site's own UI
strings) against the site's string inventory: only inventory keys, parameter names, plural and
select kinds, no markup; prints the coverage. See docs/STRING-PACKS.md.
- `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/<Language>.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
it is newer than what is installed (an upgrade in place, app data untouched); otherwise it opens
the installed app and exits 0, so an old setup left in Downloads never replaces or downgrades an
install the updater has moved on. `/FORCE` reinstalls the same version (repair), `/NORUN` does
not open the app, `/UPDATE` is the updater's path and always installs. An app renamed after its
first release keeps its registry keys by defining `WAYBETTER_LEGACY_NAME` in its installer hooks
(`bundle.windows.nsis.installerHooks`). An install made under the old name (its `DisplayName` is
still that name) counts as older than any setup of the renamed app, whatever its version number:
the renamed app may start its numbering again and still upgrades such an install in place.
## Consuming it
wayBetter for X adds this repository as a git submodule at `waybetter/` and consumes it from source:
- Rust: a path dependency, `waybetter-host = { path = "../../../waybetter/crates/waybetter-host" }`,
with `features = ["app", "net", "macos-private-api"]` enabled by the app's desktop feature (and
as a build-dependency for `commands::manifest`).
- TypeScript: relative imports of `waybetter/packages/*/src/*.ts`: the X site for the shell frame
(`src/shell/site.tsx`), the page runtime's adapter and a few X modules. Its Vite config dedupes
React, dockview and the Tauri API (the frame's imports use the app's copies) and serves
`bootScript()` as `/boot.js`. The
packages are not Bun workspace members of the app on purpose: the app's server CI clones without
submodules and runs `bun i`, which fails when a declared workspace package is missing; and Node's
type stripping refuses `.ts` files under `node_modules`, while sources outside it work with Bun's
isolated linker on Windows.
## Dev loop
`waybetter dev [--stable] --watch "<build watcher>"...` starts the app's watchers, waits for their
first build and runs `tauri dev` (`--stable` adds `--no-watch`: a Rust file saved by someone else
does not restart the app; restart it yourself after Rust changes). Debug builds only:
- The app names its page scripts with `waybetter_host::page_script!(include_str!("../x.js"), "x.js")`
in `SiteHooks::init_scripts`. A debug build reads the file from disk (path relative to the app
crate, falling back to the embedded copy) each time a tab's init scripts are built and watches it
(`devloop`, using `devmode`'s debounced signature watcher). When it changes, every tab webview is
rebuilt on its current URL through `tabs_sync`, because a webview's document-start scripts are
fixed at creation. Route is kept, scroll is not. About 1 s from save to visible.
- `buildRuntime({ watch: watchRequested(), ... })` (`waybetter/build`) keeps esbuild rebuilding the
file; a failed build leaves the last good one.
- The shell reloads through the frontend dev server (`beforeDevCommand`), instantly.
- Restart needed: Rust, `tauri.conf.json`, capabilities, bundled plugin sources (`include_str!` in the
plugin table; installed plugin files reload with developer mode as before).
- Release builds contain none of it: `devloop` is `cfg(debug_assertions)`, the macro's release arm is
`$embedded.to_owned()` and the path literal is never expanded. `release_guard` (lib.rs) checks that
every mention is gated; `cargo test --release` also runs `release_page_script_is_the_embedded_copy`.
- `.taurignore` the watched output files (`observer.js`, `x-runtime.js`), or plain `tauri dev` restarts
on every rebuild. `create-waybetter` apps get `npm run dev` and `npm run dev:stable`.
## Scripts (no CI)
```sh
bun install # typescript + @types/node for the checks
bun run typecheck # tsc over both packages and their tests, and create-waybetter (checkJs)
bun run test # node --test (runtime + shell), cargo test (headless host), create-waybetter
bun run test:ts
bun run test:rust
bun run test:create # scaffolds into temp dirs; its cargo check of an app is ~1 min cold
# (WAYBETTER_SKIP_CARGO_CHECK=1 skips it; needs the local crate cache)
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+.

View file

@ -34,13 +34,15 @@ JSON Schema: `waybetter/store-catalog.schema.json` (npm package). The rules apps
| --- | --- |
| `format` | `2`. An app that reads another format says "update the app". Format 1 (before `apps`) is gone. |
| `apps` | 1–16 distinct app ids (`[a-z0-9-]{1,32}`), e.g. `"x"`; an item for several apps lists each. |
| `kind`, `id` | `theme` or `plugin`; `[a-z0-9-]{1,40}`, unique per app and kind. |
| `kind`, `id` | `theme`, `plugin` or `strings` (a string pack, docs/STRING-PACKS.md); `[a-z0-9-]{1,40}`, unique per app and kind. |
| `name`, `author`, `version`, `description`, `category`, `tags` | plain text (no control characters), ≤ 60 / 60 / 32 / 600 / 32 characters, ≤ 12 tags of ≤ 32. Known categories show in the reader's language (`wb.store.category.*`). |
| `url`, `preview` | https; for the reading app's own items, on its download hosts (below). |
| `file` | plugins only: `name.plugin.js` (letters, digits, `-_. `), unique per app ignoring case. |
| `sha256`, `size` | of the exact file; size 1 byte … 2 MiB. |
| `permissions` | plugins only: the header's `@permissions` (`null` = no line, legacy). |
| `colors` | themes only: `#rrggbb` swatches for the card. |
| `language` | string packs only, required: the pack's language tag. |
| `license`, `credits` | any kind, optional: its licence (≤ 60 characters, e.g. an SPDX id) and who made, translated or reviewed it (≤ 600). The install screen shows them. |
Also refused: unknown fields anywhere, more than 500 items, a catalog over 1 MiB, a signature file
over 512 bytes. A malformed item for another app refuses the whole catalog (one file, one set of

186
docs/STRING-PACKS.md Normal file
View file

@ -0,0 +1,186 @@
# String packs
A string pack replaces the wrapped site's own UI strings with data: it adds a language the site
does not offer, fixes its translation, or rewords it. The framework has the formats, the validator,
the application engine, the hook interface, `waybetter strings check`, the Store kind `strings`
with its install screen, the Languages section and translate mode. Sentences with element slots
(rich text) cannot be replaced yet.
## Rules
1. **Idempotent.** The result is a pure function of (the site's own values, the ordered pack list).
Applying twice equals applying once. Packs apply in the listed order; a later pack wins per key.
2. **The site's own language is the fallback.** A pack patches on top of whatever language the site
shows. A key no pack changes keeps exactly the site's value.
3. **An inventory of the site's known keys.** A pack can change only inventory keys. An unknown key
is reported and never applied.
4. **Packs are data.** Plain text in an ICU MessageFormat subset. Never HTML, never code.
## The pack
```json
{
"format": 1,
"site": "x",
"catalog": "web",
"language": "en-x-pirate",
"name": "Pirate",
"authors": ["Someone"],
"base": "en",
"strings": {
"a0000001": "Home port",
"b0000002": "{count, plural, one {# sighting} other {# sightings}}"
}
}
```
- `site` and `catalog` name the inventory the pack is for. One site can have several catalogs
(different builds of the site with different key spaces); each has its own inventory and packs.
- `language` is a BCP 47 tag; a private-use tag is fine. `base` is the language whose plural rules
the pack follows when the runtime does not know `language`; without either, every number takes
the `other` form.
- `strings` maps a key id to text. The ids are the inventory's; a pack never carries the site's own
text.
A value may use `{name}`, `{name, plural, one {…} other {…}}` (with `#` for the number and `=0`,
`=1` exact forms) and `{name, select, a {…} other {…}}`. A value is refused, and the site's text
stays, when:
- it names a parameter the original does not take;
- it pluralizes a parameter the original does not pluralize, or selects on one the original does
not select on (the original's plural parameters are the ones known to be numbers);
- a plural or select has no `other`;
- it uses a number or date format, `selectordinal` or a plural offset;
- it contains `<` or `>` (unless the inventory gives the key tag slots; then exactly those tags);
- it contains control or bidi-override characters, is empty or is longer than 2000 characters;
- the key's kind cannot be replaced by data yet (`rich`, `format`).
A parameter is inserted the way string concatenation would insert it (`String(value)`).
## The inventory
```json
{
"format": 1, "site": "x", "catalog": "web", "base": "en", "build": "…",
"entries": {
"a0000001": { "kind": "text", "hash": "0k3j…" },
"b0000002": { "kind": "message", "params": ["count"], "plural": ["count"], "hash": "…" },
"c0000003": { "kind": "rich", "group": "rich", "hash": "…" }
}
}
```
| Kind | The site's value | A pack can replace it |
|---|---|---|
| `text` | a string | yes |
| `message` | a function of parameters that returns a string | yes |
| `rich` | text with element slots | not yet |
| `format` | a compiled number, date or currency formatter | no |
`hash` is a hash of the base-language value (`hashText`), for the drift report; the inventory holds
no text of the site. `group` names the part of the catalog a key arrives with (default `main`).
`driftReport(inventory, observed, loadedGroups)` compares an inventory with a newer build: `added`,
`reworded` (the hash changed), `reshaped` (kind or parameters changed) and `vanished`. A key is
called vanished only when its group's base catalog was actually read.
`packInventory(inventory)` is the compact form: ids and shapes, no hashes. A page does not need
the whole inventory: `sliceInventory(inventory, ids)` is the part that the packs' keys need, and it
travels to the page together with the packs (`isPageInventory` checks its shape on arrival). The
full inventory stays where packs are installed and checked.
## The engine
```ts
const engine = createStringEngine(inventory, [compilePack(packA, inventory), compilePack(packB, inventory)]);
engine.resolve(id, siteValue); // packB's value, else packA's, else exactly siteValue
```
`resolve` returns a string for a `text` key and a function with the original's call shape for a
`message` key (closures over the parsed message; nothing is evaluated). Feeding a value the engine
produced back in returns the same value. It keeps the site's own value of every key it changed
(`engine.originals()`), which is what a restore needs; `applyPacks` and `restoreCatalog` do both
for a whole catalog object without changing it. A live value whose kind differs from the
inventory's is left alone and listed in `engine.stats().mismatched`; a key the site has and the
inventory lacks is listed in `unlisted`.
## Hooking a site
How a site hands its strings to its own code is that site's implementation detail, so the hook is
an adapter the app supplies:
```ts
const adapter: CatalogHookAdapter = {
catalog: 'web',
install(win, sink) {
// At document start: arrange for the site's catalog to pass through
// sink.seen(group) a catalog file is loading
// sink.matched(language, group) the hook matched
// sink.resolve(id, original) the value to register
return () => { /* remove the hook */ };
},
};
const handle = installStringPacks(window, [{ adapter, inventory, packs }], { onStatus });
```
- The adapter must not change the site's objects: hand the site a shadow
(`Object.create(module)`) instead.
- Everything fails open: an exception in a wrapper leaves the site's behaviour as it was.
- A catalog without a usable pack is not hooked at all.
- The self-check decides after `settleMs`: `ok`, `not-matched` (a catalog file was seen but the
hook did not match: the site changed) or `no-catalog` (no catalog file was seen).
For a webpack site, `watchChunkArray(win, name, onChunk)` sees every chunk before the site's own
`push` gets it and passes it on unchanged; `mapChunkRequires(chunk, map)` lets one identified
chunk's modules receive a shadow of what they `require`.
`installTextNet(win, { map })` is a DOM safety net for labels no catalog hook can reach (the server
sends them already worded): exact text in text nodes, `aria-label`, `placeholder` and `title`, the
site's value kept per node, restored on `dispose()`. It is secondary: it cannot see parameters or
plural forms.
## Checking a pack
```sh
waybetter strings check pack.strings.json --inventory strings/x.web.inventory.json
```
Prints what was refused and why, the unknown keys, and the coverage per group (translated of
translatable, and how many keys are not translatable yet). Exit 1 when anything would not be
applied. Without `--inventory`, the inventories come from `waybetter.strings.json`
(`{ "inventories": ["…"] }`) in the app's root.
## Installing and turning packs on
String packs are a Store kind (`kind: "strings"`, with `language`; every item may also carry
`license` and `credits`) and install like themes and plugins: a dropped `*.strings.json`, a
`waybetter://install?kind=strings&url=…` link or the signed Store, always through the install screen.
The screen shows the pack's language, its coverage against the site's inventory, what is ignored
and what cannot be replaced yet, a sample of its text, that it is data only, and the pack file.
Native code (waybetter-host `store::strings`) only keeps data: it checks the envelope and that every
value is plain text, writes `<app data>/strings/<id>.json` and remembers the order and which packs
are on (at most 8). It never sees the inventory. Shell-only commands: `strings_list`,
`strings_read`, `strings_set {order, enabled}`, `strings_remove {id}`, `strings_apply {delivery}`.
The shell builds the delivery (`buildDelivery`: the packs that are on, in order, with the slice of
the inventory their keys need) and hands it to `strings_apply`. Native code stores it under a new
revision and puts it into every site tab's session storage (`wayBetter.stringPacks`) with a
data-only script that checks `https:` and the site's own hosts, then reloads the tab; a new tab
gets the same script as the first document-start layer. Safe mode leaves the layer out. A tab keeps
the newest revision it was given. The page runtime reads the delivery at document start, before
the site's scripts.
The Languages section of the panel (`createStringPacksSection({ inventory })`) lists the installed
packs with their coverage, turns them on and off, orders and removes them.
## Translate mode
Switched on in the Languages section. The delivery then carries the whole inventory, packs or not,
and the page runtime marks every replaceable string with an invisible marker naming its key
(`createMarker`). A bar at the bottom of each site tab says so; a click on a word opens an editor
with the key, the current text and its parameters. An edit is checked with the pack rules
(`checkEdit`) and kept in the tab's draft (`wayBetter.translateDraft`), which applies as the last
pack after a reload. "Copy pack file" copies the draft as a pack document. "Leave" turns the mode
off for that tab. The markers can reach places that compare text exactly (the window title), so the
mode is for authors only and is never on by default.

View file

@ -6,7 +6,9 @@ npm create waybetter
Scaffolds something for [wayBetter](https://waybetter.fyi), the framework behind wayBetter for X:
a **plugin**, a **theme**, or a whole new **wayBetter app** for another site. It asks what it needs
when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+.
when run in a terminal; every answer is also a flag. No dependencies, Node 18.3+. Source: [git.crt.fyi/CRT/waybetter](https://git.crt.fyi/CRT/waybetter)
(`packages/create-waybetter`); its tests scaffold each kind into a temporary folder and check the
result against the framework's real contracts.
## Plugin
@ -40,10 +42,14 @@ Presets: `midnight`, `paper`, `dusk`. Import it in **wayBetter → Appearance
## App
```sh
npm create waybetter app -- --site kick.com
npm create waybetter app -- --site youtube.com --name "wayBetter for YouTube"
npm create waybetter app kickapp -- --site kick.com --name "wayBetter for Kick" --yes
npm create waybetter app ytapp -- --site youtube.com --name "wayBetter for YouTube"
```
The first argument after `app` is the folder to create. The tool then prints its next steps:
`git init && git submodule add https://git.crt.fyi/CRT/waybetter.git waybetter`, `npm install`,
`npm run build`, `npm run tauri dev`, and replacing the placeholder selectors.
A wayBetter app skeleton, the same system as wayBetter for X: a Tauri 2 window with a trusted
local shell and one native child webview per site tab (`waybetter-host`), the page runtime and
shell models from the `waybetter` package, and the site adapter in its three parts:

View file

@ -151,9 +151,9 @@ const COMMANDS = {
*/
export const HOST_COMMANDS = {
shell: [
'tabs_sync', 'tab_navigate', 'tab_action', 'open_external_url', 'shell_focus', 'shell_ready', 'tab_still_ready', 'shell_raise', 'window_system_menu',
'tabs_sync', 'tab_navigate', 'tab_action', 'tab_zoom', 'tab_find', 'safe_mode_get', 'safe_mode_set', 'diag_get', 'diag_log', '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',
'plugins_list', 'plugin_set_enabled', 'plugins_open_folder', 'custom_css_get', 'custom_css_set', 'features_get', 'features_set', 'mode_get', 'mode_set', 'settings_get', 'settings_set',
],
tab: ['tab_shortcut', 'tab_link_drag'],
site: ['open_panel'],
@ -384,6 +384,8 @@ function pluginsRs(o) {
' example: Some(("example.plugin.js", include_str!("../../plugins/example.plugin.js"))),',
' // First-party plugins shipped with the app: written disabled, upgraded only while untouched.',
' bundled: &[],',
' // Plugin files a later version turned into feature flags (waybetter_host::plugins::migrate).',
' superseded: &[],',
'};',
'',
'#[cfg(test)]',
@ -528,7 +530,8 @@ function desktopRs(o) {
' // 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(),',
' // Debug builds read the file from disk and rebuild the tabs when `npm run dev` rebuilds it.',
' waybetter_host::page_script!(RUNTIME, "runtime/runtime.js"),',
' ]',
' }',
'',
@ -810,19 +813,23 @@ function runtimeTs(o) {
"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 { createFeatureRegistry, type FeatureRegistry } from 'waybetter/runtime/featureModules';",
"import { effectiveFlags, tableDefaults, type Flags } from 'waybetter/runtime/featureTable';",
"import { createCorePluginApi, type CorePluginApi } 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 { TABLE } from '../features.ts';",
"import { SITE } from '../site.ts';",
"import { MODULES } from './modules.ts';",
'',
'/**',
' * 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`.',
' * The flags are the feature table\'s (src/features.ts): the owner toggles them on the panel\'s',
' * area cards and native `features_set` delivers them. A feature module (src/runtime/modules.ts)',
' * is started by the registry; a part of the runtime that must install on a flag at document',
' * start (a request gate) goes into `INSTALLERS` with `backing: \'app\'` in the table.',
' */',
'const FLAGS: Record<string, boolean> = {};',
'const INSTALLERS: FlagInstaller<typeof FLAGS>[] = [];',
'const INSTALLERS: FlagInstaller<Flags>[] = [];',
'',
'/** The app\'s logo for the floating panel button (a data URI: the site\'s CSP may block other images). */',
`const LOGO = ${str(`data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="9" fill="${o.site.accent}"/></svg>`)}`)};`,
@ -832,12 +839,24 @@ function runtimeTs(o) {
' if ((window as unknown as Record<string, unknown>)[SITE.runtimeGlobal]) return;',
' configureRuntime(SITE);',
' const invoke = pageInvoke(window, SITE.product);',
' const flags = createFeatureFlags({ defaults: FLAGS, label: SITE.product, installers: INSTALLERS, document });',
' let registry: FeatureRegistry<CorePluginApi> | null = null;',
' const flags = createFeatureFlags<Flags>({',
' defaults: tableDefaults(TABLE), label: SITE.product, installers: INSTALLERS, document,',
' // An area that is switched off turns off the features it owns.',
' resolve: all => effectiveFlags(TABLE, all),',
' apply: config => registry?.setFlags(config),',
' });',
' // 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, { i18n: strings.source });',
' // The feature modules: each runs only while its flag and its area are on. `surfaces` names the',
' // parts of the site the page is (PLACEHOLDER: classify location.pathname; a feature that lists',
' // surfaces in the table only runs on those).',
" registry = createFeatureRegistry({ win: window, table: TABLE, api, label: SITE.product, surfaces: () => ['page'], message: strings.message, locale: strings.locale });",
' for (const module of MODULES) registry.define(module);',
' registry.setFlags(flags.current());',
' // 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;',
@ -879,7 +898,9 @@ function shellTs(o) {
"import { isSiteUrl } from 'waybetter/runtime/site';",
"import { parseAddress } from 'waybetter/shell/addressModel';",
"import { createShell, type ShellSite } from 'waybetter/shell/frame';",
"import { openOnboardingWhenDue } from 'waybetter/shell/panel';",
"import { ADDRESS_SITE } from '../address.ts';",
"import { MESSAGES } from '../features.ts';",
"import { SITE } from '../site.ts';",
"import { Panel } from './Panel.tsx';",
"import './app.css';",
@ -887,7 +908,7 @@ function shellTs(o) {
`const ORIGIN = ${str(o.origin)};`,
'',
'/** English; merge `waybetter/locales/<tag>.json` (and your own catalog) for other languages. */',
"const i18n = createI18n({ source: en.messages, available: ['en'] });",
"const i18n = createI18n({ source: { ...en.messages, ...MESSAGES }, available: ['en'] });",
'',
'const site: ShellSite = {',
` name: ${str(o.label)},`,
@ -918,8 +939,16 @@ function shellTs(o) {
' ],',
' },',
' // 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.',
' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },',
' // plugins::commands) and panel sections it does not have (the Store, the updater): the frame',
' // shows nothing of them until they are switched on here. Page zoom (`tab_zoom`) is the host\'s own.',
' features: { workspaces: false, sync: false, developer: false, pluginCommands: false, store: false, updates: false },',
' // The app menu (the titlebar\'s "Settings and more", Alt+F / F10) needs nothing: without `menu`',
' // the app gets every built-in row it can serve (new tab, splits, zoom, Plugins, the palette,',
' // About, Settings). `menu.groups` orders them and adds rows of your own, e.g.',
' // menu: { groups: menuWith(DEFAULT_MENU, "plugins", [{ id: "help", label: () => "Help", run: () => openHelp() }]) },',
' // and `menu.languages` / `menu.modes` (menuModes() from waybetter/shell/panel) add those submenus.',
' // The first-run screen (the modes of src/features.ts) is the panel\'s: open it when it is due.',
' start() { openOnboardingWhenDue(); return undefined; },',
'};',
'',
'const { core, event, window: tauriWindow } = window.__TAURI__;',
@ -928,15 +957,83 @@ function shellTs(o) {
);
}
/** @param {AppOptions} o */
function featuresTs(o) {
return lines(
'// The feature table: everything the owner can switch, as data (waybetter/runtime/featureTable).',
'// An AREA is one card in the panel\'s Plugins section with a switch of its own; a FEATURE is one',
'// flag, owned by an area or by nobody (a core flag: listed under "Fixes"); a MODE is a preset the',
'// first-run screen offers. The page runtime (src/runtime/main.ts) and the panel',
'// (src/shell/Panel.tsx) both read this table, so they cannot disagree. A flag\'s id never changes',
'// once it shipped: it is in the owner\'s features.json and backups.',
'',
"import type { FeatureTable } from 'waybetter/runtime/featureTable';",
'',
'/** PLACEHOLDER: one example area with one feature; its code is in src/runtime/modules.ts. */',
'export const TABLE: FeatureTable = {',
' areas: [',
` { id: 'reading', name: 'Reading+', description: 'area.reading.description', owner: ${str(`${o.prefix}-reading-plus.plugin.js`)}, namespace: 'reading-plus' },`,
' ],',
' features: [',
" // `backing: 'module'`: a feature module the registry starts while the flag is on. Other kinds:",
" // 'app' (a part of the runtime that installs on the flag) and 'plugin' (a plugin file).",
" { id: 'reading.focusRing', area: 'reading', default: false, backing: 'module', label: 'feature.focusRing.label', description: 'feature.focusRing.description' },",
' ],',
' modes: [',
" { id: 'basic', name: 'mode.basic.name', description: 'mode.basic.description', flags: { 'area.reading': false } },",
" { id: 'advanced', name: 'mode.advanced.name', description: 'mode.advanced.description', recommended: true, flags: {} },",
" { id: 'power', name: 'mode.power.name', description: 'mode.power.description', flags: { 'reading.focusRing': true } },",
' ],',
'};',
'',
'/** The table\'s words in English (merged into the shell\'s catalog in src/shell/main.tsx). */',
'export const MESSAGES: Record<string, string> = {',
" 'area.reading.description': 'Reading the page: small comforts.',",
" 'feature.focusRing.label': 'Mark the focused item',",
" 'feature.focusRing.description': 'Draws a ring around the item that has keyboard focus.',",
" 'mode.basic.name': 'Basic',",
` 'mode.basic.description': ${str(`Only the app around ${o.label}. The page looks the way the site ships it.`)},`,
" 'mode.advanced.name': 'Advanced',",
" 'mode.advanced.description': 'Every plugin on with calm defaults.',",
" 'mode.power.name': 'Power User',",
" 'mode.power.description': 'Advanced, plus the keyboard helpers.',",
'};',
);
}
function modulesTs() {
return lines(
'// Feature modules: the code of the table\'s features (src/features.ts). The registry starts a',
'// module only while its flag is on, its area is on and the page is on one of its surfaces, and',
'// undoes everything the module did through its context when any of those stops being true.',
'',
"import type { FeatureModule } from 'waybetter/runtime/featureModules';",
"import type { CorePluginApi } from 'waybetter/runtime/pluginApi';",
"import { SITE } from '../site.ts';",
'',
'export const MODULES: ReadonlyArray<FeatureModule<CorePluginApi>> = [',
' {',
" id: 'reading.focusRing',",
' start(ctx) {',
' // One stylesheet while the feature is on; removed when it stops.',
' ctx.css(`${SITE.plugins.itemSelector}:focus-within { outline: 2px solid Highlight; outline-offset: 2px; }`);',
' },',
' },',
'];',
);
}
function panelTsx(o) {
return lines(
'// 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',
'// sections this app serves: Home, Plugins (the area cards of src/features.ts, plugin files and',
'// 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 { createPanel } from 'waybetter/shell/panel';",
"import { TABLE } from '../features.ts';",
"import { SITE } from '../site.ts';",
'',
'export const Panel = createPanel({',
@ -951,6 +1048,8 @@ function panelTsx(o) {
" { section: 'accounts', title: () => 'Accounts', text: () => 'Real logins side by side, one per profile.' },",
' ],',
' },',
' // Area plugins, the Fixes list and the modes (first-run screen, Settings): src/features.ts.',
' features: { table: TABLE },',
' // 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; }`)} },`,
'});',
@ -967,6 +1066,7 @@ function tauriTypes() {
' toggleMaximize(): Promise<void>;',
' close(): Promise<void>;',
" startResizeDragging(direction: 'North' | 'South' | 'East' | 'West' | 'NorthEast' | 'NorthWest' | 'SouthEast' | 'SouthWest'): Promise<void>;",
' startDragging(): Promise<void>;',
' isMaximized(): Promise<boolean>;',
' onResized(handler: () => void): Promise<() => void>;',
' setBackgroundColor(color: [number, number, number, number]): Promise<void>;',
@ -1044,11 +1144,12 @@ function buildMjs() {
'// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with',
"// `waybetter/build`, and writes the shell's first-frame script.",
"import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';",
"import { buildRuntime } from 'waybetter/build';",
"import { buildRuntime, watchRequested } from 'waybetter/build';",
"import { bootScript } from 'waybetter/shell/frame/boot';",
'',
"mkdirSync('dist', { recursive: true });",
`await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`,
"// `node scripts/build.mjs --watch` (npm run dev) keeps rebuilding the runtime; a debug app reloads its tabs.",
`await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)}, watch: watchRequested() });`,
'await buildRuntime({',
" entry: 'src/shell/main.tsx',",
" outfile: 'dist/shell.js',",
@ -1063,7 +1164,7 @@ function buildMjs() {
"writeFileSync('dist/boot.js', bootScript());",
"copyFileSync('src/shell/index.html', 'dist/index.html');",
"copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');",
"console.log('built dist/ and " + APP_OUTPUTS.runtime + "');",
"console.log(watchRequested() ? 'watching " + APP_OUTPUTS.runtime + "' : 'built dist/ and " + APP_OUTPUTS.runtime + "');",
);
}
@ -1085,6 +1186,8 @@ function readme(o) {
'npm install',
'npm run build # dist/ (shell) and ' + APP_OUTPUTS.runtime + ' (page runtime)',
'npm run tauri dev # the app',
'npm run dev # the app with the dev loop: a saved runtime change reloads the tabs (debug build)',
'npm run dev:stable # the same, and Rust changes do not restart the app',
'npm run test:rust # site adapter + plugin host tests, headless',
'```',
'',
@ -1095,7 +1198,9 @@ 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, tweaks, account report, the panel button',
'src/features.ts the feature table: areas (plugin cards), feature flags, modes (first-run presets)',
'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, feature flags and modules, account report, the panel button',
'src/runtime/modules.ts feature modules: the code of the table\'s features',
'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: the wayBetter panel (createPanel) with this app\'s home page',
'plugins/example.plugin.js written (disabled) into a new plugins folder',
@ -1122,8 +1227,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. 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`.',
'4. Features: add a row to `TABLE` in `src/features.ts` (an area is a card in Plugins; a feature',
' a toggle on it; `area: null` lists it under Fixes) and its module to `src/runtime/modules.ts`.',
' The modes of the first-run screen are `TABLE.modes`.',
'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',
@ -1157,6 +1263,8 @@ export function appFiles(o) {
build: 'node scripts/build.mjs',
typecheck: 'tsc -p tsconfig.json',
tauri: 'tauri',
dev: 'waybetter dev --watch "node scripts/build.mjs --watch"',
'dev:stable': 'waybetter dev --stable --watch "node scripts/build.mjs --watch"',
'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',
@ -1193,7 +1301,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/features.ts', content: featuresTs(o) },
{ path: 'src/runtime/main.ts', content: runtimeTs(o) },
{ path: 'src/runtime/modules.ts', content: modulesTs() },
{ path: 'src/shell/main.tsx', content: shellTs(o) },
{ path: 'src/shell/Panel.tsx', content: panelTsx(o) },
{ path: 'src/shell/index.html', content: indexHtml(o) },

View file

@ -398,7 +398,7 @@ export function pluginFiles(o) {
type: 'module',
description: o.description,
scripts: { build: 'node build.mjs', typecheck: 'tsc -p tsconfig.json' },
devDependencies: { typescript: '^5.9.0', waybetter: '^0.2.0' },
devDependencies: { typescript: '^5.9.0', waybetter: '^0.6.0' },
};
const tsconfig = {
compilerOptions: {

View file

@ -335,13 +335,19 @@ test('app: every site skeleton is consistent across its native and page halves',
assert.ok(existsSync(join(PACKAGE, 'windows', 'installer.nsi')), 'the package has the installer template');
assert.ok(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).files.includes('windows'), 'and publishes it');
// Every `waybetter/...` import is a published subpath of the package.
const sources = ['src/site.ts', 'src/address.ts', 'src/runtime/main.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n');
const sources = ['src/site.ts', 'src/address.ts', 'src/features.ts', 'src/runtime/main.ts', 'src/runtime/modules.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n');
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\(\{/);
// The example of a feature module and of modes: one table read by the runtime and the panel.
assert.match(file('src', 'features.ts'), /export const TABLE: FeatureTable = \{/);
assert.match(file('src', 'runtime', 'main.ts'), /createFeatureRegistry\(\{ win: window, table: TABLE/);
assert.match(file('src', 'runtime', 'modules.ts'), /id: 'reading\.focusRing'/);
assert.match(file('src', 'shell', 'Panel.tsx'), /features: \{ table: TABLE \}/);
assert.match(file('src', 'shell', 'main.tsx'), /openOnboardingWhenDue\(\)/);
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.

View file

@ -5,6 +5,11 @@
// text, a named attribute) and they run together in the next frame: layout readers first, then DOM
// writers, so a reader never forces a synchronous layout behind another feature's write. Features
// marked `offOnHeavy` do not run on the site's heavy pages (see `configureDomHub`), e.g. a WASM chat.
//
// A site that renders a part of itself inside an open shadow root (X's chat, since 2026-10-01, in
// the shadow root of its embed host) names the host in `shadowHosts`: the hub's one observer then
// observes each such root too (picked up when the host appears or gets its root, dropped with the
// observer), selector observers look inside, and `domRoots` gives features the roots to query.
export type DomWatch = {
/** Also run on text changes (characterData). */
@ -23,6 +28,8 @@ export type DomHubConfig = {
label: string;
/** Pathnames where `offOnHeavy` features are skipped; null = none. */
heavyPath: RegExp | null;
/** Selectors of hosts whose open shadow roots are part of the page (observed and searched like it). */
shadowHosts: readonly string[];
};
export type DomWindow = {
@ -34,7 +41,7 @@ export type DomWindow = {
type Sub = { run: () => void; opts: DomWatch; pending: boolean };
type Hub = { subs: Sub[]; mark(sub: Sub): void; refresh(): void };
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null };
const config: DomHubConfig = { label: 'wayBetter', heavyPath: null, shadowHosts: [] };
const hubs = new WeakMap<object, Hub>();
/** Set once by the site adapter, before features register. */
@ -42,6 +49,31 @@ export function configureDomHub(next: Partial<DomHubConfig>): void {
Object.assign(config, next);
}
/** The page's roots: the document, then the open shadow roots of the configured hosts now in it. */
export function domRoots(win: { document: Document }): Array<Document | ShadowRoot> {
const doc = win.document;
const out: Array<Document | ShadowRoot> = [doc];
if (!config.shadowHosts.length) return out;
let hosts: Element[] = [];
try { hosts = Array.from(doc.querySelectorAll(config.shadowHosts.join(','))); } catch { return out; }
for (const host of hosts) {
const root = (host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot;
if (root) out.push(root);
}
return out;
}
/** The site names hosts whose shadow roots are part of the page. */
export function hasShadowHosts(): boolean {
return config.shadowHosts.length > 0;
}
/** A configured host is in the page but has no open shadow root yet (it may attach one later). */
function hostWithoutRoot(doc: Document): boolean {
if (!config.shadowHosts.length) return false;
try { return Array.from(doc.querySelectorAll(config.shadowHosts.join(','))).some(host => !(host as Element & { shadowRoot?: ShadowRoot | null }).shadowRoot); } catch { return false; }
}
export function isHeavyPath(pathname: string): boolean {
return !!config.heavyPath && config.heavyPath.test(pathname);
}
@ -53,6 +85,28 @@ function hubFor(win: DomWindow): Hub {
let frameRequested = false;
let observer: MutationObserver | null = null;
let observing = '';
let options: MutationObserverInit = { childList: true, subtree: true };
// Shadow roots the observer already observes (with the current options).
let roots = new WeakSet<Node>();
let retries = 0;
let retry: ReturnType<typeof setTimeout> | null = null;
/** Observes configured shadow roots that are new; a new one marks every feature (its content is new to them). */
const observeRoots = () => {
if (!observer || !config.shadowHosts.length) return;
let added = false;
for (const root of domRoots(win).slice(1)) {
if (roots.has(root)) continue;
roots.add(root);
observer.observe(root, options);
added = true;
}
if (added) { retries = 0; for (const sub of hub.subs) hub.mark(sub); }
// attachShadow makes no mutation: a host that has no root yet is looked at again, a few times.
if (!retry && retries < 20 && hostWithoutRoot(doc)) {
retries += 1;
retry = setTimeout(() => { retry = null; observeRoots(); }, 300);
}
};
const frame = () => {
frameRequested = false;
@ -78,6 +132,7 @@ function hubFor(win: DomWindow): Hub {
else if (record.type === 'attributes' && record.attributeName) (attributes ??= new Set()).add(record.attributeName);
}
}
if (!known || childList) observeRoots();
for (const sub of hub.subs) {
if (!known || childList || (characterData && sub.opts.characterData)
|| (attributes && sub.opts.attributes?.some(name => attributes!.has(name)))) hub.mark(sub);
@ -91,12 +146,15 @@ function hubFor(win: DomWindow): Hub {
if (observer && observing === key) return;
observer ??= new win.MutationObserver(onRecords);
observing = key;
// Re-observing the same node replaces its options.
observer.observe(doc.body, {
options = {
childList: true, subtree: true,
...(characterData ? { characterData: true } : {}),
...(filter.length ? { attributes: true, attributeFilter: filter } : {}),
});
};
// Re-observing the same node replaces its options (the shadow roots get them again too).
observer.observe(doc.body, options);
roots = new WeakSet();
observeRoots();
};
const hub: Hub = {
@ -110,6 +168,8 @@ function hubFor(win: DomWindow): Hub {
observer?.disconnect();
observer = null;
observing = '';
roots = new WeakSet();
if (retry) { clearTimeout(retry); retry = null; }
doc.removeEventListener('DOMContentLoaded', start);
hubs.delete(win);
return;
@ -122,6 +182,55 @@ function hubFor(win: DomWindow): Hub {
return hub;
}
type SelectorSub = { selector: string; callback: (element: Element) => void; seen: WeakSet<Element>; report(error: unknown): void };
type SelectorHub = { subs: SelectorSub[]; handle: DomWatchHandle | null };
// One per window and heavy-page behaviour: every selector observer of that kind shares its watch.
const selectorHubs = new WeakMap<object, Map<boolean, SelectorHub>>();
export type ObserveOptions = {
/** Skip on the site's heavy pages (default false). */
offOnHeavy?: boolean;
/** A callback that throws is handed here (default: the hub's console line). */
report?(error: unknown): void;
};
/**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Every call shares the hub's one MutationObserver and one frame: a page with a hundred selector
* observers still has one observer, and a mutation costs one frame in which each observer looks
* for elements it has not seen yet. Returns the disposer.
*/
export function observeSelector(win: DomWindow, selector: string, callback: (element: Element) => void, options: ObserveOptions = {}): () => void {
const offOnHeavy = !!options.offOnHeavy;
let kinds = selectorHubs.get(win);
if (!kinds) { kinds = new Map(); selectorHubs.set(win, kinds); }
let hub = kinds.get(offOnHeavy);
if (!hub) { hub = { subs: [], handle: null }; kinds.set(offOnHeavy, hub); }
const owner = hub;
const report = options.report ?? ((error: unknown) => console.error(`[${config.label}] DOM feature failed`, error));
const sub: SelectorSub = { selector, callback, seen: new WeakSet(), report };
const scan = (target: SelectorSub) => {
for (const root of domRoots(win)) {
for (const element of Array.from(root.querySelectorAll(target.selector))) {
if (target.seen.has(element)) continue;
target.seen.add(element);
try { target.callback(element); } catch (error) { target.report(error); }
}
}
};
owner.subs.push(sub);
owner.handle ??= watchDom(win, () => { for (const item of owner.subs.slice()) scan(item); }, { offOnHeavy });
if (!(offOnHeavy && isHeavyPath(win.location.pathname ?? ''))) scan(sub);
let active = true;
return () => {
if (!active) return;
active = false;
const index = owner.subs.indexOf(sub);
if (index >= 0) owner.subs.splice(index, 1);
if (!owner.subs.length) { owner.handle?.dispose(); owner.handle = null; }
};
}
/**
* Runs `run` in the next animation frame after body mutations of the watched kinds (child list
* always), or whenever `schedule()` is called (scroll, popstate, input, ...). Several calls in one

View file

@ -0,0 +1,545 @@
// Feature modules: the code side of the feature table (featureTable.ts). An app's area plugins
// ("Navigation+") are sets of small modules, one per feature; the registry starts a module only
// while its flag is on, its area's switch is on and the page is on one of its surfaces, and
// disposes everything it did when any of those stops being true. A hundred features then cost what
// the ones on screen cost:
//
// const registry = createFeatureRegistry({ win, table, api, label, surfaces, message });
// registry.define({ id: 'navigation.keyboardPlus', start(ctx) { ctx.onKey(...); } });
// registry.setFlags(effectiveFlags(table, flags)); // from the app's feature flags
//
// A module's `start(ctx)` gets a context whose every helper is undone on stop: CSS, listeners,
// nodes, DOM watching through the shared hub (one MutationObserver for every feature, domHub.ts),
// palette commands under its area's name, its words, its storage and its settings. A module with a
// `settings` schema gets a settings dialog drawn from the UI kit (settingsForm.ts); each area with
// such a feature gets one "settings" palette command.
//
// Health: a module names the selectors it depends on (`probes`). After the page has settled, a
// probe that matches nothing is a miss; three misses in a row (three visits) pause that one feature
// for the session, with one toast and a note in the settings dialog. The site's markup changed; the
// rest of the area keeps working. A signed hotfix may replace a probe's selector
// (`selectors["<feature id>.<probe>"]`) or switch a feature off (`flags["<feature id>"] = false`).
import { domRoots, hasShadowHosts, isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts';
import { adoptStyles, type RootStyles } from './styles.ts';
import { HEALTH_COMMAND, areaFlag, healthKeywords, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts';
import { formatMessage, type Params } from './i18n.ts';
import type { CommandDefinition } from './commands.ts';
import type { PluginI18n } from './pluginI18n.ts';
import type { Dispose, PluginScope, PluginStorage } from './pluginApi.ts';
import { buildSettingsForm, normalizeSettings, validateSchema, type SettingValues, type SettingsSchema } from './settingsForm.ts';
import { KIT_MESSAGES, type KitKey, type UiKit } from './ui.ts';
/** Palette commands one area may register: its "settings" entry and four actions (the tab reports at most 48). */
export const AREA_COMMAND_BUDGET = 5;
/** Misses in a row (separate visits) before a feature pauses itself. */
export const PROBE_STRIKES = 3;
/**
* A selector a feature depends on. `english`: it reads an English label, so it only counts on an
* English page. `when`: it only counts while this selector matches (the part of the page it lives
* in is there: a column the site drops in a narrow window is no verdict).
*/
export type Probe = string | { selector: string; english?: boolean; when?: string };
export type FeatureSettings = {
/** The stored values, normalized by the schema. */
get(): SettingValues;
/** Saves (merged over the current values). False when storage refused it. */
set(patch: SettingValues): boolean;
/** Calls `callback(values)` after a save, until the feature stops. */
onChange(callback: (values: SettingValues) => void): void;
/** Opens this feature's settings dialog. */
open(): void;
};
export type FeatureContext<Api> = {
/** The flag id and the feature's own name (`navigation.focusMode` -> `focusMode`). */
readonly id: string;
readonly name: string;
readonly area: AreaSpec;
/** The app's plugin API, unrestricted: a feature module is the app's own code. */
readonly api: Api;
/** The page's window (use it and its `document` instead of the globals: tests run without them). */
readonly win: Window & typeof globalThis;
/** This feature's stylesheet (one per `name`, replaced in place, cleared by an empty string; removed on stop). It also styles the site's configured open shadow roots (domHub `shadowHosts`). */
css(css: string, name?: string): void;
/** `callback` once per element matching `selector`, through the shared hub; paused on heavy pages unless the feature says `heavy`. */
observe(selector: string, callback: (element: Element) => void): void;
/** A raw hub subscription (domHub `watchDom`), disposed on stop. */
watch(run: () => void, options?: DomWatch): DomWatchHandle;
on(target: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
onKey(callback: (event: KeyboardEvent, item: Element | null) => void): void;
onRouteChange(callback: (href: string, previous: string) => void): void;
/** Tracks a node the feature inserted; removed on stop. */
add<T extends Node>(node: T): T;
/** Runs `fn` on stop. */
defer(fn: Dispose): void;
/** The UI kit; what the feature opened is closed on stop. */
readonly ui: UiKit;
/** A palette command under the area's name (counts towards `AREA_COMMAND_BUDGET`), removed on stop. */
command(definition: CommandDefinition): void;
/**
* The feature's word `key`: `plugin.<area namespace>.<name>.<key>` in the app's catalog, or
* `plugin.<words>.<key>` for a module that names its own namespace (`words`). (Not
* named `t`: the i18n tools read `t('…')` as a whole catalog key.)
*/
text(key: string, params?: Params): string;
/** The feature's storage (its module's `storage` namespace). */
readonly storage: PluginStorage;
/** Its settings (a module with a `settings` schema; otherwise empty values). */
readonly settings: FeatureSettings;
/** The selector of probe `name` (a hotfix override wins). */
selector(name: string): string;
/** The surfaces the page is on right now. */
surfaces(): readonly string[];
};
export type FeatureModule<Api> = {
/** The flag id; the table must list it with `backing: 'module'`. */
id: string;
/** Selectors it depends on, by name (read them back with `ctx.selector(name)`). */
probes?: Readonly<Record<string, Probe>>;
/**
* Where its words are in the catalog. Default: `plugin.<area namespace>.<name>.<key>`. A feature
* ported from a plugin names that plugin's namespace (`focus-mode`) and keeps its keys
* (`plugin.focus-mode.<key>`, its label `plugin.focus-mode.name`): nothing is retranslated.
*/
words?: string;
/** Storage namespace (default `<area namespace>.<name>`; a ported plugin keeps its old one). */
storage?: string;
/** The key its settings are stored under (default `settings`). */
settingsKey?: string;
settings?: SettingsSchema;
start(ctx: FeatureContext<Api>): void;
};
/** What the registry needs of the plugin API (the core API has all of it). */
export type RegistryApi = {
scope(): PluginScope;
injectCSS(id: string, css: string): void;
clearCSS(id: string): void;
storage(namespace: string): PluginStorage;
onRouteChange(callback: (href: string, previous: string) => void): Dispose;
ui: UiKit;
i18n: PluginI18n;
commands: { withOwner<T>(owner: string, fn: () => T): T };
};
export type HotfixData = { selectors?: Readonly<Record<string, unknown>>; flags?: Readonly<Record<string, unknown>> };
export type FeatureHealth = { id: string; area: string; state: 'paused' | 'needs-english'; probes: string[] };
export type FeatureRegistryOptions<Api extends RegistryApi> = {
win: Window & typeof globalThis;
table: FeatureTable;
api: Api;
/** Console prefix (the app's name). */
label: string;
/** The surfaces the page is on (`['timeline', 'home']`); the app's classifier. */
surfaces(): readonly string[];
/** The app catalog's message for `key` in the active language (the registry's words are the kit's: `kit.feature.*`, `kit.save`). */
message?(key: string): string | undefined;
locale?(): string;
/** The signed hotfix data, when the app has any (selector overrides and kill flags). */
hotfix?(): HotfixData | null | undefined;
/** The page has rendered its content (the site's main column is there); default: the body has children. */
settled?(): boolean;
/** The page's language is English (probes marked `english` only count then); default: `<html lang>` starts with `en`. */
english?(): boolean;
/** ms after the page settled before probes are judged (default 3000) and between settle checks (default 500). */
settleMs?: number;
pollMs?: number;
timers?: { setTimeout(fn: () => void, ms: number): unknown; clearTimeout(id: unknown): void };
};
export type FeatureRegistry<Api> = {
define(module: FeatureModule<Api>): void;
/** The effective flags (featureTable `effectiveFlags`): starts and stops modules to match. */
setFlags(flags: Readonly<Flags>): void;
/** Re-checks surfaces (the registry also does it on every route change). */
refresh(): void;
/** The ids of the modules running right now. */
active(): string[];
/** Paused features and features waiting for an English page. */
health(): FeatureHealth[];
/** Opens the settings dialog of an area (or of one feature). False when nothing in it has settings right now. */
openSettings(area: string, feature?: string): boolean;
/** Stops everything (the runtime is going away; tests). */
dispose(): void;
};
type Running<Api> = {
module: FeatureModule<Api>;
spec: FeatureSpec;
area: AreaSpec;
scope: PluginScope;
commands: number;
listeners: Set<(values: SettingValues) => void>;
settings: FeatureSettings;
visit: number;
timer: unknown;
};
const featureName = (id: string) => id.slice(id.indexOf('.') + 1);
export function createFeatureRegistry<Api extends RegistryApi>(options: FeatureRegistryOptions<Api>): FeatureRegistry<Api> {
const { win, table, api, label } = options;
const doc = win.document;
const timers = options.timers ?? { setTimeout: (fn: () => void, ms: number) => win.setTimeout(fn, ms), clearTimeout: (id: unknown) => win.clearTimeout(id as number) };
const settleMs = options.settleMs ?? 3000;
const pollMs = options.pollMs ?? 500;
const specs = new Map(table.features.map(feature => [feature.id, feature]));
const areas = new Map(table.areas.map(area => [area.id, area]));
const modules = new Map<string, FeatureModule<Api>>();
const running = new Map<string, Running<Api>>();
const areaScopes = new Map<string, PluginScope>();
const healthScopes = new Map<string, { scope: PluginScope; ids: string }>();
const strikes = new Map<string, number>();
const paused = new Map<string, string[]>();
const waiting = new Map<string, string[]>();
let flags: Readonly<Flags> = {};
let stopRoutes: Dispose | null = null;
let visit = 0;
// The registry's own words are the kit's (`kit.feature.*`, `kit.save`): English unless the app delivers them.
const text = (key: KitKey, params: Params = {}) =>
formatMessage(options.message?.(key) ?? KIT_MESSAGES[key], params, options.locale?.() ?? 'en');
const hotfix = (): HotfixData => { try { return options.hotfix?.() ?? {}; } catch { return {}; } };
const english = () => options.english?.() ?? /^en\b/i.test(doc.documentElement?.getAttribute?.('lang') ?? 'en');
const settled = () => options.settled?.() ?? !!doc.body?.firstElementChild;
/** A selector matches in the page or in one of its configured open shadow roots. */
const inPage = (selector: string) => domRoots(doc.defaultView ?? { document: doc }).some(root => !!root.querySelector(selector));
const words = (area: AreaSpec) => api.i18n.namespace(area.namespace);
/** A feature's word `key`: under its own namespace when it names one (`words`), else under its area's. */
const wordOf = (module: FeatureModule<Api>, area: AreaSpec, key: string, params?: Params) =>
(module.words ? api.i18n.namespace(module.words).t(key, params) : words(area).t(`${featureName(module.id)}.${key}`, params));
/** A feature's label in the page, when the page has it (`plugin.*` words only reach a site tab). */
const featureLabel = (spec: FeatureSpec, area: AreaSpec) => {
const legacy = modules.get(spec.id)?.words;
if (legacy) { const own = api.i18n.namespace(legacy); return own.has('name') ? own.t('name') : null; }
const i18n = words(area);
const key = `feature.${featureName(spec.id)}.label`;
return i18n.has(key) ? i18n.t(key) : null;
};
const selectorOf = (module: FeatureModule<Api>, name: string) => {
const override = hotfix().selectors?.[`${module.id}.${name}`];
if (typeof override === 'string' && override.trim()) return override;
const probe = module.probes?.[name];
if (probe === undefined) throw new Error(`${module.id}: no probe named ${JSON.stringify(name)}`);
return typeof probe === 'string' ? probe : probe.selector;
};
function wanted(module: FeatureModule<Api>): boolean {
const spec = specs.get(module.id)!;
if (flags[module.id] !== true || paused.has(module.id) || hotfix().flags?.[module.id] === false) return false;
if (!spec.heavy && isHeavyPath(win.location.pathname ?? '')) return false;
if (!spec.surfaces?.length) return true;
const on = options.surfaces();
return spec.surfaces.some(surface => on.includes(surface));
}
function settingsOf(module: FeatureModule<Api>, area: AreaSpec, listeners: Set<(values: SettingValues) => void>): FeatureSettings {
const schema = module.settings ?? [];
const store = () => api.storage(module.storage ?? `${area.namespace}.${featureName(module.id)}`);
const key = module.settingsKey ?? 'settings';
const get = () => normalizeSettings(schema, store().get<unknown>(key, null));
return {
get,
set(patch) {
const next = normalizeSettings(schema, { ...get(), ...patch });
const saved = store().set(key, next);
for (const listener of [...listeners]) {
try { listener(next); } catch (error) { console.error(`[${label}] ${module.id} settings listener failed`, error); }
}
return saved;
},
onChange(callback) { listeners.add(callback); },
open() { openSettings(area.id, module.id); },
};
}
function start(module: FeatureModule<Api>) {
const spec = specs.get(module.id)!;
const area = areas.get(spec.area!)!;
const scope = api.commands.withOwner(area.owner, () => api.scope());
const listeners = new Set<(values: SettingValues) => void>();
const entry: Running<Api> = { module, spec, area, scope, commands: 0, listeners, settings: settingsOf(module, area, listeners), visit: -1, timer: null };
const name = featureName(module.id);
const domWin = win as unknown as DomWindow;
const styles = new Set<string>();
// The same sheets, adopted by each configured open shadow root of the page (a site part rendered
// inside one, e.g. X's chat embed); roots that appear later get them on the next hub frame.
const rootCss = new Map<string, string>();
const rootSheets = new Map<Node, Map<string, { sheet: RootStyles; css: string }>>();
let rootWatch: DomWatchHandle | null = null;
const syncRoots = () => {
const roots = domRoots(domWin).slice(1);
for (const [root, sheets] of rootSheets) {
if (roots.includes(root as ShadowRoot)) continue;
for (const item of sheets.values()) item.sheet.remove();
rootSheets.delete(root);
}
for (const root of roots) {
let sheets = rootSheets.get(root);
if (!sheets) { sheets = new Map(); rootSheets.set(root, sheets); }
for (const [styleId, item] of sheets) if (!rootCss.has(styleId)) { item.sheet.remove(); sheets.delete(styleId); }
for (const [styleId, css] of rootCss) {
const item = sheets.get(styleId);
if (!item) sheets.set(styleId, { sheet: adoptStyles(root as ShadowRoot, css), css });
else if (item.css !== css) { item.sheet.update(css); item.css = css; }
}
}
};
const ctx: FeatureContext<Api> = {
id: module.id,
name,
area,
api,
win,
css(css, part = '') {
const styleId = `wbf-${module.id}${part ? `-${part}` : ''}`;
if (!styles.has(styleId)) { styles.add(styleId); scope.defer(() => api.clearCSS(styleId)); }
if (css) api.injectCSS(styleId, css); else api.clearCSS(styleId);
if (css) rootCss.set(styleId, css); else rootCss.delete(styleId);
if (!rootWatch && css && hasShadowHosts()) {
rootWatch = watchDom(domWin, syncRoots, { offOnHeavy: !spec.heavy });
scope.defer(() => {
rootWatch?.dispose(); rootWatch = null;
rootCss.clear();
for (const sheets of rootSheets.values()) for (const item of sheets.values()) item.sheet.remove();
rootSheets.clear();
});
}
if (rootWatch) syncRoots();
},
observe(selector, callback) {
scope.defer(observeSelector(domWin, selector, callback, { offOnHeavy: !spec.heavy, report: error => console.error(`[${label}] ${module.id} failed`, error) }));
},
watch(run, watchOptions = {}) {
const handle = watchDom(domWin, run, { offOnHeavy: !spec.heavy, ...watchOptions });
scope.defer(() => handle.dispose());
return handle;
},
on: (target, type, listener, listenerOptions) => scope.on(target, type, listener, listenerOptions),
onKey: callback => scope.onKey(callback),
onRouteChange: callback => scope.onRouteChange(callback),
add: node => scope.add(node),
defer: fn => scope.defer(fn),
get ui() { return scope.ui; },
command(definition) {
const reserved = table.features.some(feature => feature.area === area.id && feature.settings) ? 1 : 0;
const used = [...running.values()].filter(other => other.area.id === area.id).reduce((sum, other) => sum + other.commands, 0);
if (used + reserved >= AREA_COMMAND_BUDGET) throw new Error(`${area.name}: at most ${AREA_COMMAND_BUDGET} palette commands per area`);
scope.commands.register(definition);
entry.commands += 1;
},
text: (key, params) => wordOf(module, area, key, params),
get storage() { return api.storage(module.storage ?? `${area.namespace}.${name}`); },
settings: entry.settings,
selector: probe => selectorOf(module, probe),
surfaces: () => options.surfaces(),
};
running.set(module.id, entry);
try {
module.start(ctx);
} catch (error) {
console.error(`[${label}] ${module.id} failed`, error);
stop(module.id);
return;
}
scheduleProbes(entry);
}
function stop(id: string) {
const entry = running.get(id);
if (!entry) return;
running.delete(id);
if (entry.timer !== null) timers.clearTimeout(entry.timer);
entry.listeners.clear();
entry.scope.dispose();
}
// ---- Health ----------------------------------------------------------------------------------
function scheduleProbes(entry: Running<Api>) {
if (!entry.module.probes || !Object.keys(entry.module.probes).length || entry.visit === visit) return;
entry.visit = visit;
if (entry.timer !== null) timers.clearTimeout(entry.timer);
const mine = visit;
let tries = 0;
const waitForSettle = () => {
entry.timer = null;
if (running.get(entry.module.id) !== entry || mine !== visit) return;
if (!settled()) {
tries += 1;
// A page that never settles (an error page, a sign-in wall) is no verdict.
if (tries <= 20) entry.timer = timers.setTimeout(waitForSettle, pollMs);
return;
}
entry.timer = timers.setTimeout(judge, settleMs);
};
const judge = () => {
entry.timer = null;
if (running.get(entry.module.id) !== entry || mine !== visit) return;
const id = entry.module.id;
const missing: string[] = [];
const needEnglish: string[] = [];
const inEnglish = english();
for (const [name, probe] of Object.entries(entry.module.probes ?? {})) {
if (typeof probe !== 'string' && probe.english && !inEnglish) { needEnglish.push(name); continue; }
if (typeof probe !== 'string' && probe.when) {
let there = false;
try { there = inPage(probe.when); } catch { there = false; }
if (!there) continue;
}
let found = false;
try { found = inPage(selectorOf(entry.module, name)); } catch { found = false; }
if (!found) missing.push(name);
}
if (needEnglish.length) waiting.set(id, needEnglish); else waiting.delete(id);
if (!missing.length) { strikes.delete(id); return; }
const count = (strikes.get(id) ?? 0) + 1;
strikes.set(id, count);
if (count < PROBE_STRIKES) return;
paused.set(id, missing);
stop(id);
syncAreas();
console.warn(`[${label}] ${id} paused: nothing matches ${missing.join(', ')}`);
const feature = featureLabel(entry.spec, entry.area);
try {
api.ui.toast(feature ? text('kit.feature.paused', { feature, area: entry.area.name }) : text('kit.feature.pausedOne', { area: entry.area.name }), { tone: 'warning', duration: 8000 });
} catch { /* a page without a body yet: the note in the settings dialog remains */ }
};
entry.timer = timers.setTimeout(waitForSettle, pollMs);
}
// ---- Settings dialog and the area's command --------------------------------------------------
function openSettings(areaId: string, only?: string): boolean {
const area = areas.get(areaId);
if (!area) return false;
const entries = [...running.values()].filter(entry => entry.area.id === areaId && entry.module.settings?.length && (!only || entry.module.id === only));
const notes = health().filter(note => note.area === areaId);
if (!entries.length && !notes.length) return false;
const ui = api.ui;
const h = ui.h;
const forms = entries.map(entry => {
const name = featureName(entry.module.id);
return { entry, title: featureLabel(entry.spec, area) ?? name, form: buildSettingsForm(h, entry.module.settings!, entry.settings.get(), key => wordOf(entry.module, area, key)) };
});
const single = forms.length === 1 && !notes.length ? forms[0]! : null;
ui.dialog({
title: text('kit.feature.settings', { name: single ? single.title : area.name }),
content: body => {
forms.forEach((item, index) => {
if (index > 0) body.append(h('div', { class: 'wb-divider' }));
if (!single) body.append(h('p', { class: 'wb-label' }, item.title));
body.append(...item.form.nodes);
});
for (const note of notes) {
const spec = specs.get(note.id)!;
const feature = featureLabel(spec, area) ?? featureName(note.id);
body.append(h('p', { class: 'wb-hint' }, note.state === 'paused' ? text('kit.feature.paused', { feature, area: area.name }) : text('kit.feature.needsEnglish', { feature })));
}
},
actions: forms.length ? [
{ label: text('kit.cancel') },
{
label: text('kit.save'), tone: 'primary', default: true,
onClick: handle => {
const failed = forms.filter(item => !item.entry.settings.set(item.form.read()));
if (failed.length) { handle.setError(text('kit.failed')); return false; }
return undefined;
},
},
] : undefined,
});
return true;
}
/** Each area with a running feature that has settings gets its one "settings" palette command. */
function syncAreas() {
for (const area of table.areas) {
const needs = [...running.values()].some(entry => entry.area.id === area.id && entry.module.settings?.length);
const scope = areaScopes.get(area.id);
if (needs && !scope) {
const created = api.commands.withOwner(area.owner, () => api.scope());
areaScopes.set(area.id, created);
try {
created.commands.register({ id: 'settings', title: text('kit.feature.settings', { name: area.name }), keywords: `settings options configure ${area.name}`, run: () => { openSettings(area.id); } });
} catch (error) { console.error(`[${label}] ${area.name} settings command failed`, error); }
} else if (!needs && scope) {
scope.dispose();
areaScopes.delete(area.id);
}
// A paused feature that would run (its flag and area are on) is named in the palette: the
// entry opens the notes, and the panel reads it for the feature's row (featureTable `pausedFeatures`).
const ids = [...paused.keys()].filter(id => specs.get(id)!.area === area.id && flags[id] === true).join(' ');
const shown = healthScopes.get(area.id);
if (shown && shown.ids !== ids) { shown.scope.dispose(); healthScopes.delete(area.id); }
if (ids && !healthScopes.has(area.id)) {
const created = api.commands.withOwner(area.owner, () => api.scope());
healthScopes.set(area.id, { scope: created, ids });
try {
created.commands.register({ id: HEALTH_COMMAND, title: text('kit.feature.pausedList', { area: area.name }), keywords: healthKeywords(ids.split(' ')), run: () => { openSettings(area.id); } });
} catch (error) { console.error(`[${label}] ${area.name} health command failed`, error); }
}
}
}
function health(): FeatureHealth[] {
const out: FeatureHealth[] = [];
for (const [id, probes] of paused) out.push({ id, area: specs.get(id)!.area!, state: 'paused', probes });
for (const [id, probes] of waiting) if (!paused.has(id)) out.push({ id, area: specs.get(id)!.area!, state: 'needs-english', probes });
return out;
}
function refresh() {
for (const module of modules.values()) {
const on = running.has(module.id);
const want = wanted(module);
if (want && !on) start(module);
else if (!want && on) stop(module.id);
else if (want && on) scheduleProbes(running.get(module.id)!);
}
syncAreas();
}
return {
define(module) {
const spec = specs.get(module.id);
if (!spec || spec.backing !== 'module' || spec.area === null || !areas.has(spec.area)) throw new Error(`${label}: ${module.id} is not a feature module in the table`);
if (modules.has(module.id)) throw new Error(`${label}: ${module.id} is defined twice`);
const problems = validateSchema(module.settings ?? []);
if (problems.length) throw new Error(`${label}: ${module.id} settings: ${problems.join('; ')}`);
if (!!module.settings?.length !== !!spec.settings) throw new Error(`${label}: ${module.id}: the table's "settings" and the module's schema disagree`);
modules.set(module.id, module);
stopRoutes ??= api.onRouteChange(() => { visit += 1; refresh(); });
if (wanted(module)) { start(module); syncAreas(); }
},
setFlags(next) {
flags = { ...next };
refresh();
},
refresh,
active: () => [...running.keys()],
health,
openSettings,
dispose() {
stopRoutes?.();
stopRoutes = null;
for (const id of [...running.keys()]) stop(id);
for (const scope of areaScopes.values()) scope.dispose();
areaScopes.clear();
for (const shown of healthScopes.values()) shown.scope.dispose();
healthScopes.clear();
modules.clear();
},
};
}
/** Whether an area's switch is on in `flags` (a missing value counts as on). */
export const areaEnabled = (flags: Readonly<Flags>, area: string) => flags[areaFlag(area)] !== false;

View file

@ -0,0 +1,290 @@
// The feature table: one data description of everything an app lets its owner switch, shared by the
// page runtime (which flags exist, who owns them), the panel (the area cards, the Fixes list, the
// onboarding modes) and the app's native side (the migration list it generates from it). Pure data
// and pure functions: no DOM, no storage.
//
// - An AREA is one card in the Plugins list ("Navigation+"): a master switch and the features it
// owns. Its switch is the flag `area.<id>`.
// - A FEATURE is one on/off flag. It belongs to an area, or to nobody (`area: null`: a core flag
// such as a reliability fix, which no plugin switch can turn off). Where its code lives is its
// `backing`: a feature module in the registry (featureModules.ts), a part of the app runtime
// (request hubs, native commands, document-start timing), or an old plugin file that has not
// been ported yet (then it is not a flag at all: its switch is that file's enabled state).
// - A MODE is a preset (Basic / Advanced / Power User): the flag values it starts from. A mode is a
// starting point, not a lock: every flag stays individually switchable afterwards.
//
// Flags are stored sparsely (`sparseFlags`): only values that differ from the table's defaults.
/** Flags a store may hold (the native cap, waybetter-host `settings::MAX_FEATURES`). */
export const FLAG_LIMIT = 256;
/** Characters in a flag key (the native cap). */
export const FLAG_KEY_LIMIT = 64;
export type FeatureBacking = 'module' | 'app' | 'plugin';
export type FeatureSpec = {
/** The flag key. Existing names stay as they are; new ones are `<area>.<feature>`. */
id: string;
/** The owning area, or null for a core flag. */
area: string | null;
/** The rows it is listed with inside its card (words: `features.group.<group>`). */
group?: string;
/** Its value when nothing is stored. */
default: boolean;
/**
* Where its code lives: `module` = a feature module (featureModules.ts); `app` = a part of the
* app runtime that installs on the flag; `plugin` = an old plugin file until it is ported.
*/
backing: FeatureBacking;
/** `backing: 'plugin'`: that file. Its enabled state is the switch; `id` is the flag it becomes. */
file?: string;
/** The old plugin file this feature replaces: the one-time migration turns its enabled state into this flag. */
supersedes?: string;
/** Surfaces it runs on (ids from the app's surface classifier); omitted = every page. */
surfaces?: readonly string[];
/** Also runs on the site's heavy pages (domHub `heavyPath`). */
heavy?: boolean;
/** Catalog key of its label (default `features.<id>.label`). */
label?: string;
/** Catalog key of its description (default `features.<id>.description`). */
description?: string;
/** It has settings of its own (a settings schema on its module): the card offers "Settings". */
settings?: boolean;
/** Extra words the panel search matches (an old plugin's name). */
keywords?: string;
/** The gated plugin API it uses (shown on the card). */
permissions?: readonly string[];
};
export type AreaSpec = {
/** `navigation`: lowercase letters, digits and `-`. */
id: string;
/** The card's name: a product name, the same in every language. */
name: string;
/** Catalog key of the card's description. */
description: string;
/** A 16x16 stroke path for the card's icon. */
icon?: string;
/**
* The owner of its palette commands and the file it ships as once it is a plugin file
* (`bt-navigation-plus.plugin.js`). A valid plugin file name.
*/
owner: string;
/** Its words in the page: `plugin.<namespace>.*` (`navigation-plus`). */
namespace: string;
};
export type ModeSpec = {
id: string;
/** Catalog keys of its name and one-line description. */
name: string;
description: string;
/** The preselected one on the first-run screen. */
recommended?: boolean;
/** Flag values that differ from the table's defaults. */
flags: Readonly<Record<string, boolean>>;
};
export type FeatureTable = {
areas: readonly AreaSpec[];
features: readonly FeatureSpec[];
modes: readonly ModeSpec[];
};
export type Flags = Record<string, boolean>;
/** The flag that is an area's master switch. */
export const areaFlag = (area: string) => `area.${area}`;
/** Features that are flags (everything but the ones still backed by an old plugin file). */
export const flagFeatures = (table: FeatureTable) => table.features.filter(feature => feature.backing !== 'plugin');
export const areaFeatures = (table: FeatureTable, area: string) => table.features.filter(feature => feature.area === area);
export const coreFeatures = (table: FeatureTable) => table.features.filter(feature => feature.area === null);
/** The catalog keys of a feature's label and description. */
export function featureWords(feature: FeatureSpec): { label: string; description: string } {
return { label: feature.label ?? `features.${feature.id}.label`, description: feature.description ?? `features.${feature.id}.description` };
}
/** Every flag with its default: the features that are flags, and each area's switch (on). */
export function tableDefaults(table: FeatureTable): Flags {
const out: Flags = {};
for (const feature of flagFeatures(table)) out[feature.id] = feature.default;
for (const area of table.areas) out[areaFlag(area.id)] = true;
return out;
}
/** The full flag map for `input`: unknown keys are dropped, anything not a boolean takes the default. */
export function normalizeFlags(table: FeatureTable, input: unknown): Flags {
const source = input && typeof input === 'object' ? input as Record<string, unknown> : {};
const out = tableDefaults(table);
for (const key of Object.keys(out)) if (typeof source[key] === 'boolean') out[key] = source[key] as boolean;
return out;
}
/** What is stored: only the flags whose value differs from the default. */
export function sparseFlags(table: FeatureTable, flags: Readonly<Record<string, unknown>>): Flags {
const defaults = tableDefaults(table);
const out: Flags = {};
for (const [key, fallback] of Object.entries(defaults)) {
const value = flags[key];
if (typeof value === 'boolean' && value !== fallback) out[key] = value;
}
return out;
}
/**
* What runs: a feature owned by an area is off while that area's switch is off. Core flags and the
* area switches themselves pass through.
*/
export function effectiveFlags(table: FeatureTable, flags: Readonly<Flags>): Flags {
const out: Flags = { ...flags };
for (const feature of flagFeatures(table)) {
if (feature.area !== null && flags[areaFlag(feature.area)] === false) out[feature.id] = false;
}
return out;
}
export const modeById = (table: FeatureTable, id: string | null | undefined) => table.modes.find(mode => mode.id === id) ?? null;
/** The full flag map a mode starts from (an unknown or null mode: the defaults). */
export function modeFlags(table: FeatureTable, mode: string | null | undefined): Flags {
const out = tableDefaults(table);
const preset = modeById(table, mode)?.flags ?? {};
for (const [key, value] of Object.entries(preset)) if (key in out) out[key] = value;
return out;
}
/** The flags whose value is not what `mode` starts from: the owner's own changes. */
export function manualChanges(table: FeatureTable, flags: Readonly<Flags>, mode: string | null | undefined): string[] {
const preset = modeFlags(table, mode);
return Object.keys(preset).filter(key => typeof flags[key] === 'boolean' && flags[key] !== preset[key]);
}
/**
* The flags after choosing mode `to` while on mode `from` (null = never chosen). `keep`: the
* owner's own changes (whatever differs from `from`) stay on top of the new mode; otherwise the
* new mode's values apply as they are.
*/
export function switchMode(table: FeatureTable, flags: Readonly<Flags>, from: string | null | undefined, to: string, keep: boolean): Flags {
const next = modeFlags(table, to);
if (keep) for (const key of manualChanges(table, flags, from)) next[key] = flags[key]!;
return next;
}
export type ModeStatus = {
/** The flags differ from what the mode starts from: "Custom (based on <mode>)". */
custom: boolean;
/** What applying the mode again would turn on and off (flag ids, in table order). */
on: string[];
off: string[];
/**
* Of those, the ones the mode gained since it was applied (an update made its preset larger).
* Empty when nothing is known about the preset of that time.
*/
added: string[];
};
/**
* How the stored flags relate to mode `mode` (null or unknown: no mode, nothing to say). A mode is
* a starting point: nothing here applies anything. `applied` is the mode's `flags` as they were
* when it was applied (the shell stores it with the choice); without it a difference is simply the
* owner's own change.
*/
export function modeStatus(table: FeatureTable, flags: Readonly<Flags>, mode: string | null | undefined, applied?: Readonly<Record<string, boolean>> | null): ModeStatus {
const spec = modeById(table, mode);
if (!spec) return { custom: false, on: [], off: [], added: [] };
const preset = modeFlags(table, spec.id);
const defaults = tableDefaults(table);
const differs = Object.keys(preset).filter(key => typeof flags[key] === 'boolean' && flags[key] !== preset[key]);
const was = (key: string) => typeof applied?.[key] === 'boolean' ? applied[key] : defaults[key];
return {
custom: differs.length > 0,
on: differs.filter(key => preset[key]),
off: differs.filter(key => !preset[key]),
added: applied ? differs.filter(key => was(key) !== preset[key]) : [],
};
}
/**
* Feature health, as the panel learns it. A feature that paused itself (featureModules.ts: its
* selector probes failed) is named by its area's `health` palette command in the page: the entry
* opens the notes there, and its keywords carry the paused flags. The panel reads the focused
* tab's command list (it already has it for the palette), so no new report crosses to the host.
*/
export const HEALTH_COMMAND = 'health';
const HEALTH_WORD = 'paused';
/** The keywords of an area's health command: the paused flags of that area. */
export const healthKeywords = (ids: readonly string[]) => [HEALTH_WORD, ...ids].join(' ');
/** The flags of `table` a tab's reported commands say are paused (unknown words are ignored). */
export function pausedFeatures(table: FeatureTable, commands: ReadonlyArray<{ id: string; keywords?: string }> | null | undefined): Set<string> {
const paused = new Set<string>();
for (const area of table.areas) {
const words = commands?.find(command => command.id === `${area.owner}:${HEALTH_COMMAND}`)?.keywords?.split(' ') ?? [];
if (words[0] !== HEALTH_WORD) continue;
for (const feature of table.features) if (feature.area === area.id && words.includes(feature.id)) paused.add(feature.id);
}
return paused;
}
/** The old plugin files the table's features replace, for the app's native migration list. */
export function supersededFiles(table: FeatureTable): { file: string; flag: string }[] {
return table.features.filter(feature => feature.supersedes && feature.backing !== 'plugin').map(feature => ({ file: feature.supersedes!, flag: feature.id }));
}
const FLAG_ID = /^[A-Za-z][A-Za-z0-9]*(?:\.[A-Za-z][A-Za-z0-9]*)?$/;
const AREA_ID = /^[a-z][a-z0-9-]{0,31}$/;
const MODE_ID = /^[a-z][a-z0-9-]{0,31}$/;
const PLUGIN_FILE = /^[A-Za-z0-9_\- ][A-Za-z0-9_.\- ]{0,117}\.plugin\.js$/;
/** Problems in a table (an empty list: valid). Run it in the app's tests. */
export function validateTable(table: FeatureTable): string[] {
const problems: string[] = [];
const areas = new Set<string>();
for (const area of table.areas) {
if (!AREA_ID.test(area.id)) problems.push(`area ${JSON.stringify(area.id)}: invalid id`);
if (areas.has(area.id)) problems.push(`area ${area.id}: listed twice`);
areas.add(area.id);
if (!PLUGIN_FILE.test(area.owner)) problems.push(`area ${area.id}: owner must be a plugin file name`);
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(area.namespace)) problems.push(`area ${area.id}: invalid namespace`);
if (!area.name.trim() || !area.description.trim()) problems.push(`area ${area.id}: name and description are required`);
}
const ids = new Set<string>();
const files = new Set<string>();
for (const feature of table.features) {
if (!FLAG_ID.test(feature.id) || feature.id.length > FLAG_KEY_LIMIT) problems.push(`feature ${JSON.stringify(feature.id)}: invalid id`);
if (feature.id.startsWith('area.')) problems.push(`feature ${feature.id}: "area." is kept for the area switches`);
if (ids.has(feature.id)) problems.push(`feature ${feature.id}: owned twice`);
ids.add(feature.id);
if (feature.area !== null && !areas.has(feature.area)) problems.push(`feature ${feature.id}: unknown area ${feature.area}`);
if (feature.backing === 'plugin') {
if (!feature.file || !PLUGIN_FILE.test(feature.file)) problems.push(`feature ${feature.id}: a plugin-backed feature names its file`);
if (feature.area === null) problems.push(`feature ${feature.id}: a plugin-backed feature belongs to an area`);
if (feature.default) problems.push(`feature ${feature.id}: a plugin file is off until its owner turns it on`);
} else if (feature.file) problems.push(`feature ${feature.id}: only a plugin-backed feature names a file`);
for (const file of [feature.file, feature.supersedes]) {
if (!file) continue;
if (!PLUGIN_FILE.test(file)) problems.push(`feature ${feature.id}: invalid file ${JSON.stringify(file)}`);
if (files.has(file)) problems.push(`feature ${feature.id}: ${file} is named twice`);
files.add(file);
}
if (feature.backing !== 'module' && feature.settings) problems.push(`feature ${feature.id}: only a feature module has a settings schema`);
}
const defaults = tableDefaults(table);
if (Object.keys(defaults).length > FLAG_LIMIT) problems.push(`${Object.keys(defaults).length} flags: at most ${FLAG_LIMIT}`);
const modes = new Set<string>();
for (const mode of table.modes) {
if (!MODE_ID.test(mode.id)) problems.push(`mode ${JSON.stringify(mode.id)}: invalid id`);
if (modes.has(mode.id)) problems.push(`mode ${mode.id}: listed twice`);
modes.add(mode.id);
for (const [key, value] of Object.entries(mode.flags)) {
if (!(key in defaults)) problems.push(`mode ${mode.id}: unknown flag ${key}`);
else if (value === defaults[key]) problems.push(`mode ${mode.id}: ${key} is already the default`);
}
}
if (table.modes.length && table.modes.filter(mode => mode.recommended).length !== 1) problems.push('exactly one mode is the recommended one');
return problems;
}

View file

@ -9,6 +9,7 @@
import { createThemeApi, type ThemeApi, type ThemeSource } from './themeApi.ts';
import { createUiKit, type UiKit } from './ui.ts';
import { adoptStyles, type RootStyles } from './styles.ts';
import { observeSelector } from './domHub.ts';
import { createCommandRegistry, type CommandDefinition, type CommandInfo, type CommandRegistry } from './commands.ts';
import { createPluginI18n, type I18nSource, type PluginI18n, type PluginMessages } from './pluginI18n.ts';
@ -60,7 +61,10 @@ export type CorePluginApi = {
storage(namespace: string): PluginStorage;
/** Called after the page changes route (pushState/replaceState/back/forward). */
onRouteChange(callback: (href: string, previous: string) => void): Dispose;
/** Calls `callback` once for every element matching `selector`, now and as the page renders more. */
/**
* Calls `callback` once for every element matching `selector`, now and as the page renders more.
* Page-wide observers share one MutationObserver (domHub.ts); pass `root` only for a tree of your own.
*/
observe(selector: string, callback: (element: Element) => void, root?: ParentNode): Dispose;
/**
* Single-key shortcuts: `callback(event, focusedItem)` runs only when the user is not typing, no
@ -145,6 +149,25 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
});
const styleNodes = new Map<string, HTMLStyleElement>();
const adoptedFallbacks = new Map<string, RootStyles>();
// At document start the engine may run us before the document has an element to hold a <style>
// (WebView2: `documentElement` is still null). Such styles wait here and are attached, and their
// CSP check run, as soon as the document has a root.
const pendingStyles = new Set<string>();
let pendingObserver: MutationObserver | null = null;
const attachPending = () => {
const parent = doc.head || doc.documentElement;
if (!parent) return;
pendingObserver?.disconnect();
pendingObserver = null;
const ids = [...pendingStyles];
pendingStyles.clear();
for (const id of ids) {
const node = styleNodes.get(id);
if (!node) continue;
parent.appendChild(node);
api.injectCSS(id, node.textContent ?? '');
}
};
const report = (error: unknown) => console.error(`[${site.product}] plugin callback failed`, error);
const registry = createCommandRegistry({ target: doc, isTyping: event => isTypingTarget(event.target) || isTypingTarget(doc.activeElement), report });
const commands: CommandRegistry = Object.freeze({
@ -165,6 +188,8 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
const previous = lastHref;
lastHref = href;
for (const listener of [...routeListeners]) {
// A listener removed by an earlier one in this round (a feature stopped by the route) is not called.
if (!routeListeners.has(listener)) continue;
try { listener(href, previous); } catch (error) { report(error); }
}
};
@ -172,11 +197,25 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
const api: CorePluginApi = {
injectCSS(id, css) {
let node = styleNodes.get(id);
if (node && pendingStyles.has(id)) {
node.textContent = css;
return;
}
if (!node?.isConnected) {
node = doc.createElement('style');
node.dataset[site.styleDataKey] = id;
(doc.head || doc.documentElement).appendChild(node);
styleNodes.set(id, node);
const parent = doc.head || doc.documentElement;
if (!parent) {
node.textContent = css;
pendingStyles.add(id);
if (!pendingObserver) {
pendingObserver = new win.MutationObserver(attachPending);
pendingObserver.observe(doc, { childList: true, subtree: true });
}
return;
}
parent.appendChild(node);
}
node.textContent = css;
// A CSP that refuses inline styles leaves the element without a sheet: the same rules as an
@ -192,6 +231,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
}
},
clearCSS(id) {
pendingStyles.delete(id);
styleNodes.get(id)?.remove();
styleNodes.delete(id);
adoptedFallbacks.get(id)?.remove();
@ -251,6 +291,8 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
if (!routeTimer) {
lastHref = win.location.href;
routeTimer = setInterval(checkRoute, ROUTE_POLL_MS);
// Outside a browser (tests) the poll never keeps the process alive.
(routeTimer as { unref?: () => void }).unref?.();
win.addEventListener('popstate', checkRoute);
}
return () => {
@ -263,13 +305,16 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
};
},
observe(selector, callback, root) {
// The whole page: the shared hub (one MutationObserver and one frame for every plugin and
// feature). A root of the caller's own (a shadow root, a detached tree) keeps its own observer.
if (!root || root === doc) return observeSelector(win, selector, callback, { report });
const seen = new WeakSet<Element>();
let frame = 0;
let disposed = false;
const scan = () => {
frame = 0;
if (disposed) return;
for (const element of Array.from((root ?? doc).querySelectorAll(selector))) {
for (const element of Array.from(root.querySelectorAll(selector))) {
if (seen.has(element)) continue;
seen.add(element);
try { callback(element); } catch (error) { report(error); }
@ -278,7 +323,7 @@ export function createCorePluginApi(win: Window & typeof globalThis, site: Plugi
const observer = new win.MutationObserver(() => {
if (!frame) frame = win.requestAnimationFrame(scan);
});
observer.observe((root as Node | undefined) ?? doc.documentElement, { childList: true, subtree: true });
observer.observe(root as Node, { childList: true, subtree: true });
scan();
return () => {
disposed = true;

View file

@ -0,0 +1,135 @@
// A settings schema: what a feature (or a plugin) lets its owner adjust, as data. The same schema
// gives the stored values their shape (`normalizeSettings`: anything missing or of the wrong type
// takes the field's default, so an old or damaged store never breaks a feature) and draws the
// controls from the UI kit's form parts (`buildSettingsForm`: check boxes, number, text, select and
// list fields inside a kit dialog). Labels and hints are catalog keys the caller translates.
import type { UiKit } from './ui.ts';
type FieldBase = {
/** The key in the stored values. */
key: string;
/** Catalog key of the label. */
label: string;
/** Catalog key of a line under the label. */
hint?: string;
};
export type SettingField =
| (FieldBase & { type: 'toggle'; default: boolean })
| (FieldBase & { type: 'number'; default: number; min?: number; max?: number; step?: number })
| (FieldBase & { type: 'text'; default: string; maxLength?: number; multiline?: boolean; placeholder?: string })
| (FieldBase & { type: 'select'; default: string; options: ReadonlyArray<{ value: string; label: string }> })
/** Lines of text (patterns, handles): one per line in the form. */
| (FieldBase & { type: 'list'; default: readonly string[]; maxItems?: number; maxLength?: number })
| { type: 'divider' };
export type SettingsSchema = readonly SettingField[];
export type SettingValue = boolean | number | string | string[];
export type SettingValues = Record<string, SettingValue>;
export const SETTINGS_LIMITS = Object.freeze({ fields: 64, text: 2000, listItems: 500, listItem: 500 });
type ValueField = Exclude<SettingField, { type: 'divider' }>;
const valueFields = (schema: SettingsSchema) => schema.filter((field): field is ValueField => field.type !== 'divider');
function fieldValue(field: ValueField, value: unknown): SettingValue {
switch (field.type) {
case 'toggle':
return typeof value === 'boolean' ? value : field.default;
case 'number': {
if (typeof value !== 'number' || !Number.isFinite(value)) return field.default;
return Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, value));
}
case 'text':
return typeof value === 'string' ? value.slice(0, Math.min(field.maxLength ?? SETTINGS_LIMITS.text, SETTINGS_LIMITS.text)) : field.default;
case 'select':
return typeof value === 'string' && field.options.some(option => option.value === value) ? value : field.default;
case 'list': {
if (!Array.isArray(value)) return [...field.default];
const max = Math.min(field.maxLength ?? SETTINGS_LIMITS.listItem, SETTINGS_LIMITS.listItem);
return value.filter((item): item is string => typeof item === 'string' && item.trim() !== '').map(item => item.slice(0, max)).slice(0, Math.min(field.maxItems ?? SETTINGS_LIMITS.listItems, SETTINGS_LIMITS.listItems));
}
}
}
/** The values for `schema` from whatever was stored: every field present, every value of its type and in range. */
export function normalizeSettings(schema: SettingsSchema, stored: unknown): SettingValues {
const source = stored && typeof stored === 'object' ? stored as Record<string, unknown> : {};
const out: SettingValues = {};
for (const field of valueFields(schema)) out[field.key] = fieldValue(field, source[field.key]);
return out;
}
/** Problems in a schema (an empty list: valid). */
export function validateSchema(schema: SettingsSchema): string[] {
const problems: string[] = [];
const keys = new Set<string>();
const fields = valueFields(schema);
if (fields.length > SETTINGS_LIMITS.fields) problems.push(`at most ${SETTINGS_LIMITS.fields} fields`);
for (const field of fields) {
if (!/^[A-Za-z][A-Za-z0-9]{0,39}$/.test(field.key)) problems.push(`invalid key ${JSON.stringify(field.key)}`);
if (keys.has(field.key)) problems.push(`${field.key}: listed twice`);
keys.add(field.key);
if (!field.label) problems.push(`${field.key}: a label is required`);
if (field.type === 'select' && !field.options.some(option => option.value === field.default)) problems.push(`${field.key}: the default is not an option`);
if (field.type === 'number' && (field.min ?? -Infinity) > (field.max ?? Infinity)) problems.push(`${field.key}: min is above max`);
}
return problems;
}
export type SettingsForm = {
/** The controls, in schema order: append them to a dialog's body. */
nodes: HTMLElement[];
/** The values as the controls show them now (normalized). */
read(): SettingValues;
};
/**
* The controls for `schema` showing `values`, built with the kit's element builder and styled by the
* kit's form classes. `text(key)` translates a label, hint or option key.
*/
export function buildSettingsForm(h: UiKit['h'], schema: SettingsSchema, values: SettingValues, text: (key: string) => string): SettingsForm {
const readers: Array<[ValueField, () => unknown]> = [];
const nodes: HTMLElement[] = [];
for (const field of schema) {
if (field.type === 'divider') { nodes.push(h('div', { class: 'wb-divider' })); continue; }
const value = values[field.key];
const hint = field.hint ? text(field.hint) : '';
if (field.type === 'toggle') {
const input = h('input', { type: 'checkbox', checked: value === true }) as HTMLInputElement;
nodes.push(h('label', { class: 'wb-check' }, input, h('span', null, text(field.label), hint ? h('small', null, hint) : null)));
readers.push([field, () => input.checked]);
continue;
}
let control: HTMLElement;
if (field.type === 'number') {
const input = h('input', { type: 'number', value: String(value), min: field.min, max: field.max, step: field.step ?? 1 }) as HTMLInputElement;
readers.push([field, () => (input.value.trim() === '' ? NaN : Number(input.value))]);
control = input;
} else if (field.type === 'select') {
const select = h('select', null, field.options.map(option => h('option', { value: option.value, selected: option.value === value }, text(option.label)))) as HTMLSelectElement;
readers.push([field, () => select.value]);
control = select;
} else if (field.type === 'list') {
const area = h('textarea', { class: 'wb-mono', rows: 5, spellcheck: false, value: (value as string[]).join('\n') }) as HTMLTextAreaElement;
readers.push([field, () => area.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean)]);
control = area;
} else {
const input = (field.multiline
? h('textarea', { rows: 4, value: String(value), maxLength: field.maxLength, placeholder: field.placeholder })
: h('input', { type: 'text', value: String(value), maxLength: field.maxLength, placeholder: field.placeholder })) as HTMLInputElement | HTMLTextAreaElement;
readers.push([field, () => input.value]);
control = input;
}
nodes.push(h('label', { class: 'wb-field' }, h('span', { class: 'wb-label' }, text(field.label)), control, hint ? h('p', { class: 'wb-hint' }, hint) : null));
}
return {
nodes,
read() {
const raw: Record<string, unknown> = {};
for (const [field, read] of readers) raw[field.key] = read();
return normalizeSettings(schema, raw);
},
};
}

View file

@ -19,6 +19,8 @@ export type SiteAdapter = {
runtimeGlobal: string;
/** Pages where heavy-page-sensitive DOM features pause (e.g. a WASM chat); null = none. */
heavyPath: RegExp | null;
/** Hosts whose open shadow roots are part of the page (the DOM hub observes and searches them; `domRoots`). */
shadowHosts?: readonly string[];
/** Request URL substrings that are the site's API calls; only these reach the net hub stages. */
apiMarks: string[];
/** Extra URL substrings that reach XHR gates only. */
@ -38,7 +40,7 @@ export type SiteAdapter = {
/** Applies the adapter's global knobs (DOM hub, net hub). Call once, before features start. */
export function configureRuntime(site: SiteAdapter): void {
configureDomHub({ label: site.product, heavyPath: site.heavyPath });
configureDomHub({ label: site.product, heavyPath: site.heavyPath, shadowHosts: site.shadowHosts ?? [] });
configureNetHub({ apiMarks: site.apiMarks, xhrMarks: site.xhrMarks });
}

View file

@ -55,14 +55,22 @@ export type FeatureFlagsOptions<Flags extends Record<string, boolean>> = {
label: string;
/** Parts that install when their flag turns on and dispose when it turns off, in install order. */
installers: ReadonlyArray<FlagInstaller<Flags>>;
/** Every applied config, before the installers (flags that are CSS, or that another part reads). */
apply?(config: Partial<Flags>): void;
/** Every applied config (the full map), before the installers (flags that are CSS, or that another part reads). */
apply?(config: Flags): void;
/**
* What owns what: given the delivered flags over the defaults, the flags that really run (an
* area whose switch is off turns its features off; featureTable `effectiveFlags`).
*/
resolve?(flags: Flags): Flags;
/** The page's document: a column's flags delivered at document start wait for `<html>` to exist. */
document?: Document;
};
export type FeatureFlags<Flags extends Record<string, boolean>> = {
/** The flags native code delivers (the owner's tweaks); a deck column's overrides stay on top. */
/**
* The flags native code delivers (the owner's choices); a deck column's overrides stay on top.
* A delivery is the whole state, stored sparsely: a flag it does not name is at its default.
*/
apply(config: Partial<Flags>): void;
/**
* A deck column's flag overrides (allow-listed natively; unknown keys and non-booleans are
@ -75,6 +83,8 @@ export type FeatureFlags<Flags extends Record<string, boolean>> = {
set(flag: keyof Flags & string, enabled: boolean): void;
/** Whether a flag's installer is installed right now. */
installed(flag: keyof Flags & string): boolean;
/** Every flag as it runs right now (defaults, the delivery, ownership, the column). */
current(): Flags;
};
export function createFeatureFlags<Flags extends Record<string, boolean>>(options: FeatureFlagsOptions<Flags>): FeatureFlags<Flags> {
@ -99,38 +109,43 @@ export function createFeatureFlags<Flags extends Record<string, boolean>>(option
let globalFlags: Partial<Flags> = {};
let columnFlags: Partial<Flags> = {};
const merged = (previous: Partial<Flags> = {}): Partial<Flags> => {
const restore = Object.fromEntries(Object.keys(previous).map(key => [key, defaults[key]])) as Partial<Flags>;
return { ...restore, ...globalFlags, ...columnFlags };
};
const applyAll = (config: Partial<Flags>) => {
options.apply?.(config);
for (const [flag] of installers) {
const enabled = config[flag];
if (typeof enabled === 'boolean') set(flag, enabled);
const known = (input: unknown): Partial<Flags> => {
const out: Record<string, boolean> = {};
if (input && typeof input === 'object') {
for (const [key, value] of Object.entries(input)) if (key in defaults && typeof value === 'boolean') out[key] = value;
}
return out as Partial<Flags>;
};
// What runs: the defaults, the delivered flags over them, what owns what (`resolve`), and a
// column's own choices on top.
const current = (): Flags => {
const base = { ...defaults, ...globalFlags } as Flags;
return { ...(options.resolve ? options.resolve(base) : base), ...columnFlags };
};
const applyAll = () => {
const config = current();
options.apply?.(config);
for (const [flag] of installers) set(flag, config[flag]);
};
return {
apply(config) {
globalFlags = { ...globalFlags, ...config };
applyAll(Object.keys(columnFlags).length ? merged() : config);
globalFlags = known(config);
applyAll();
},
setColumnFlags(flags) {
const next: Partial<Flags> = {};
if (flags && typeof flags === 'object') {
for (const [key, value] of Object.entries(flags)) if (key in defaults && typeof value === 'boolean') (next as Record<string, boolean>)[key] = value;
}
const next = known(flags);
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 apply = () => { try { applyAll(); } 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),
current,
};
}

View file

@ -0,0 +1,279 @@
// String packs in the page (published as `waybetter/runtime/stringPackHook`): the per-site
// "catalog hook adapter" interface, the installer that connects adapters to the engine of
// stringPacks.ts, a self-check that says when a hook did not match, and the generic half of a
// common hook point (a webpack chunk array).
//
// How a site hands its strings to its own code is that site's implementation detail, so the hook
// is an adapter the app supplies. One site can have several catalogs (different builds of the
// site, different key spaces); each gets its own adapter, inventory and packs.
//
// Everything here fails open: an exception inside a wrapper leaves the site's own behaviour as it
// was, and with no pack installed nothing is hooked at all.
import {
compilePack, createStringEngine, type CompiledPack, type EngineStats, type PackReport, type PageInventory, type StringEngine,
type StringInventory,
} from './stringPacks.ts';
// -------------------------------------------------------------------------------------------
// The adapter interface
/** What an adapter reports to and asks from the framework. None of these throw. */
export type CatalogSink = {
/** A catalog file of this adapter was seen loading (whether or not the hook then matches). */
seen(group?: string): void;
/** The hook matched: the site is about to register values in `language`. */
matched(language: string, group?: string): void;
/** The value to register for `id`: a pack's, or exactly `original`. */
resolve(id: string, original: unknown): unknown;
};
export type CatalogHookAdapter = {
/** The catalog (key space) this adapter hooks; packs and the inventory name the same one. */
catalog: string;
/** Installs the hook at document start; returns its removal. Must not change the site's objects. */
install(win: Window, sink: CatalogSink): () => void;
};
export type CatalogSetup = {
adapter: CatalogHookAdapter;
inventory: StringInventory | PageInventory;
/** Pack documents in application order (a later one wins). Untrusted data: validated here. */
packs: readonly unknown[];
};
/**
* `ok`: the hook matched and keys went through it.
* `not-matched`: a catalog file was seen but the hook did not match it (the site changed).
* `no-catalog`: no catalog file was seen at all (another build of the site, or not loaded yet).
*/
export type HookStatus = 'pending' | 'ok' | 'not-matched' | 'no-catalog';
export type CatalogReport = {
catalog: string;
status: HookStatus;
/** Languages the site registered through the hook. */
languages: string[];
/** Catalog files seen, per group. */
seen: Record<string, number>;
packs: { name: string; language: string; report: PackReport }[];
/** Pack documents that were refused as a whole. */
refused: string[];
engine: EngineStats;
};
export type StringPacksHandle = {
status(catalog?: string): HookStatus;
report(): CatalogReport[];
/** The engines, per catalog (the originals they keep are what a restore needs). */
engine(catalog: string): StringEngine | undefined;
dispose(): void;
};
export type StringPacksOptions = {
/** When the self-check decides (default 15 s after install). */
settleMs?: number;
/** Called once per catalog when its status is decided (`ok` as soon as it is reached). */
onStatus?: (report: CatalogReport) => void;
/**
* Translate mode: every value passes through here after the packs (the marker of
* stringPackTranslate.ts), and the catalog is hooked even without a usable pack.
*/
mark?: (id: string, value: unknown) => unknown;
};
type TimerWindow = { setTimeout(handler: () => void, ms: number): unknown; clearTimeout(id: never): void };
/**
* Installs the adapters that have at least one usable pack. A catalog without packs is not hooked
* (the site runs untouched), so its status stays `pending`.
*/
export function installStringPacks(win: Window, setups: readonly CatalogSetup[], options: StringPacksOptions = {}): StringPacksHandle {
const timers = win as unknown as TimerWindow;
const states = setups.map(setup => {
const packs: CompiledPack[] = [];
const refused: string[] = [];
for (const document of setup.packs) {
try {
packs.push(compilePack(document, setup.inventory));
} catch (error) {
refused.push(error instanceof Error ? error.message : String(error));
}
}
const usable = packs.filter(pack => pack.values.size > 0);
return {
catalog: setup.adapter.catalog, adapter: setup.adapter, packs, refused, usable,
engine: usable.length || options.mark ? createStringEngine(setup.inventory, usable) : null,
seen: {} as Record<string, number>, languages: new Set<string>(), keys: 0, settled: false, told: false,
remove: null as null | (() => void),
};
});
type State = (typeof states)[number];
const status = (state: State): HookStatus => {
if (state.languages.size && state.keys > 0) return 'ok';
if (!state.settled) return 'pending';
return Object.keys(state.seen).length ? 'not-matched' : 'no-catalog';
};
const reportOf = (state: State): CatalogReport => ({
catalog: state.catalog,
status: status(state),
languages: [...state.languages],
seen: { ...state.seen },
packs: state.packs.map(pack => ({ name: pack.name, language: pack.language, report: pack.report })),
refused: [...state.refused],
engine: state.engine?.stats() ?? { seen: 0, applied: 0, unlisted: [], mismatched: [] },
});
const tell = (state: State) => {
if (state.told || status(state) === 'pending') return;
state.told = true;
try { options.onStatus?.(reportOf(state)); } catch { /* a reporter must not break the page */ }
};
for (const state of states) {
const engine = state.engine;
if (!engine) continue;
const sink: CatalogSink = {
seen(group = 'main') { state.seen[group] = (state.seen[group] ?? 0) + 1; },
matched(language) { state.languages.add(String(language)); },
resolve(id, original) {
try {
state.keys += 1;
const resolved = engine.resolve(id, original);
const value = options.mark ? options.mark(id, resolved) : resolved;
if (state.keys === 1) tell(state);
return value;
} catch {
return original;
}
},
};
try {
state.remove = state.adapter.install(win, sink);
} catch {
state.remove = null;
}
}
const hooked = states.filter(state => state.engine);
const timer = hooked.length
? timers.setTimeout(() => { for (const state of hooked) { state.settled = true; tell(state); } }, options.settleMs ?? 15000)
: null;
return {
status: catalog => {
const state = catalog ? states.find(item => item.catalog === catalog) : hooked[0] ?? states[0];
return state ? status(state) : 'pending';
},
report: () => states.map(reportOf),
engine: catalog => states.find(item => item.catalog === catalog)?.engine ?? undefined,
dispose() {
if (timer !== null) timers.clearTimeout(timer as never);
for (const state of states) {
try { state.remove?.(); } catch { /* the hook is gone either way */ }
state.remove = null;
}
},
};
}
// -------------------------------------------------------------------------------------------
// A webpack chunk array as the hook point
//
// A webpack site loads its code as chunks pushed onto a global array
// (`(globalThis.webpackChunk_x ||= []).push([ids, modules, runtime?])`); webpack's runtime later
// replaces the array's `push` with its own and replays what is already there. Watching the array
// therefore sees every chunk before its modules are installed, whichever loads first.
type Chunk = [unknown, Record<string, unknown> | unknown[], ...unknown[]];
/**
* Calls `onChunk(chunk, script)` for every chunk pushed onto `win[name]`, before the site's own
* `push` gets it; `script` is the URL of the script doing the push (`''` when unknown). Install at
* document start. The array and webpack's own `push` replacement keep working unchanged: the
* wrapper calls exactly the `push` that was current when it was read, with the same arguments. An
* exception in `onChunk` is swallowed. Returns the removal.
*/
export function watchChunkArray(win: object, name: string, onChunk: (chunk: Chunk, script: string) => void): () => void {
const holder = win as Record<string, unknown> & { document?: { currentScript?: { src?: string } | null } };
const existing = holder[name];
const array: unknown[] = Array.isArray(existing) ? existing : [];
if (!Array.isArray(existing)) holder[name] = array;
const done = new WeakSet<object>();
let current: (...items: unknown[]) => number = array.push;
let active = true;
const look = (items: ArrayLike<unknown>) => {
if (!active) return;
for (let index = 0; index < items.length; index += 1) {
const chunk = items[index];
if (typeof chunk !== 'object' || chunk === null || done.has(chunk)) continue;
done.add(chunk);
try {
onChunk(chunk as Chunk, holder.document?.currentScript?.src ?? '');
} catch {
// Fail open: the chunk goes on to the site exactly as it came.
}
}
};
try {
Object.defineProperty(array, 'push', {
configurable: true,
enumerable: false,
get() {
const target = current;
return function push(this: unknown, ...items: unknown[]) {
look(items);
return target.apply(this, items);
};
},
set(next: (...items: unknown[]) => number) { current = next; },
});
} catch {
return () => {};
}
return () => {
active = false;
try {
if (current === Array.prototype.push) delete (array as { push?: unknown }).push;
else Object.defineProperty(array, 'push', { configurable: true, enumerable: false, writable: true, value: current });
} catch {
// Left as the pass-through wrapper.
}
};
}
/**
* Wraps the module factories of one chunk so that what they `require` passes through `map`:
* `map(exports)` returns a replacement for that one call, or `undefined` to hand out the module's
* own exports. The module itself is never changed (return a shadow, e.g. `Object.create(exports)`).
* Only call this for a chunk you have identified; other chunks must stay untouched.
*/
export function mapChunkRequires(chunk: Chunk, map: (exports: unknown) => unknown): void {
const modules = chunk[1];
if (typeof modules !== 'object' || modules === null) return;
const table = modules as Record<string, unknown>;
for (const id of Object.keys(table)) {
const factory = table[id];
if (typeof factory !== 'function') continue;
table[id] = function (this: unknown, module: unknown, exports: unknown, require: unknown, ...rest: unknown[]) {
let through = require;
if (typeof require === 'function') {
try {
through = new Proxy(require, {
apply(target, self, args) {
const result = Reflect.apply(target as (...a: unknown[]) => unknown, self, args);
try {
const replaced = map(result);
return replaced === undefined ? result : replaced;
} catch {
return result;
}
},
});
} catch {
through = require;
}
}
return (factory as (...a: unknown[]) => unknown).call(this, module, exports, through, ...rest);
};
}
}

View file

@ -0,0 +1,270 @@
// Translate mode for string packs (published as `waybetter/runtime/stringPackTranslate`): the site's
// strings carry an invisible marker naming their key, so clicking a word on the page tells which
// key it is. The author types a replacement (checked with the pack rules right there), the edits
// collect in the tab as a draft pack that applies on the next reload, and Export copies the pack
// file. Nothing leaves the page; the draft lives in the tab's session storage.
//
// The markers change the site's text (invisible characters at the end of each string), so exact
// comparisons in the site's own code may notice: translate mode is for authors, never on by default,
// and leaving it reloads the page without markers.
import { compilePack, inventoryLookup, validateString, type InventoryLookup, type PageInventory, type StringPack } from './stringPacks.ts';
const START = '⁣';
const DIGITS = ['​', '‌', '‍', '⁠'];
const MARKED = /⁣([​‌‍⁠]+)⁣/g;
export type Marker = {
/** The value with its key's marker (strings, and functions whose result is a string). */
mark(id: string, value: unknown): unknown;
/** The keys marked in a text, in order. */
ids(text: string): string[];
/** The text without markers. */
strip(text: string): string;
};
export function createMarker(): Marker {
const ids: string[] = [];
const index = new Map<string, number>();
const code = (id: string) => {
let n = index.get(id);
if (n === undefined) { n = ids.length; ids.push(id); index.set(id, n); }
let digits = '';
do { digits = DIGITS[n % 4] + digits; n = Math.floor(n / 4); } while (n);
return START + digits + START;
};
return {
mark(id, value) {
if (typeof value === 'string') return value + code(id);
if (typeof value === 'function') {
const original = value as (...args: unknown[]) => unknown;
return function (this: unknown, ...args: unknown[]) {
const out = original.apply(this, args);
return typeof out === 'string' ? out + code(id) : out;
};
}
return value;
},
ids(text) {
const out: string[] = [];
for (const match of text.matchAll(MARKED)) {
let n = 0;
for (const ch of match[1]!) n = n * 4 + DIGITS.indexOf(ch);
const id = ids[n];
if (id && !out.includes(id)) out.push(id);
}
return out;
},
strip: text => text.replace(MARKED, ''),
};
}
/** The author's edits in this tab. */
export type TranslateDraft = { language: string; name: string; strings: Record<string, string> };
export const DRAFT_KEY = 'wayBetter.translateDraft';
export function readDraft(storage: Pick<Storage, 'getItem'>): TranslateDraft | null {
try {
const value = JSON.parse(storage.getItem(DRAFT_KEY) ?? 'null') as TranslateDraft | null;
return value && typeof value === 'object' && typeof value.strings === 'object' && value.strings !== null ? value : null;
} catch {
return null;
}
}
/** The draft as a pack document for `site`/`catalog`. */
export function draftPack(draft: TranslateDraft, site: string, catalog: string): StringPack {
return {
format: 1, site, catalog, language: draft.language || 'en-x-draft', name: draft.name || 'My strings', authors: ['Me'],
version: '0.1.0', strings: { ...draft.strings },
};
}
/** Checks one edit against the key's shape; `null` when it can be used. */
export function checkEdit(lookup: InventoryLookup, id: string, value: string): string | null {
const shape = lookup(id);
if (!shape) return 'this key is not in the inventory';
const result = validateString(shape, value);
return 'reason' in result ? result.reason : null;
}
export type TranslateWords = {
bar: string; hint: string; edits(count: number): string; exportPack: string; copied: string; exit: string; reload: string;
key: string; original: string; parameters: string; save: string; cancel: string; remove: string; notTranslatable: string; choose: string;
};
/** English defaults (the app passes its own words). */
export const TRANSLATE_WORDS: TranslateWords = {
bar: 'Translate mode', hint: 'Click a word to change it.', edits: count => `${count} ${count === 1 ? 'edit' : 'edits'}`,
exportPack: 'Copy pack file', copied: 'Pack file copied', exit: 'Leave', reload: 'Reload to see it',
key: 'Key', original: 'Now', parameters: 'Parameters', save: 'Save', cancel: 'Cancel', remove: 'Remove edit',
notTranslatable: 'This string cannot be changed by a pack yet.', choose: 'Which one?',
};
export type TranslateUiOptions = {
inventory: PageInventory;
marker: Marker;
site: string;
catalog: string;
words?: Partial<TranslateWords>;
/** Leaves translate mode (the app drops the flag and reloads). */
exit(): void;
};
const CSS = `
:host { all: initial; }
.bar { position: fixed; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 2147483646; display: flex; gap: 10px; align-items: center;
padding: 8px 12px; border-radius: 12px; background: #111827; color: #f9fafb; font: 13px/1.3 system-ui, sans-serif; box-shadow: 0 8px 24px rgba(0,0,0,.35); }
.bar b { font-weight: 600; } .bar span { color: #cbd5e1; }
button { font: inherit; border: 0; border-radius: 8px; padding: 6px 10px; cursor: pointer; background: #334155; color: #f9fafb; }
button.primary { background: #2563eb; }
.pop { position: fixed; z-index: 2147483647; width: 360px; max-width: calc(100vw - 24px); padding: 12px; border-radius: 12px; background: #fff; color: #111827;
font: 13px/1.4 system-ui, sans-serif; box-shadow: 0 12px 32px rgba(0,0,0,.3); display: grid; gap: 8px; }
.pop small { color: #475569; } .pop code { font-size: 12px; color: #334155; }
.pop textarea { width: 100%; box-sizing: border-box; min-height: 64px; font: inherit; padding: 6px; border: 1px solid #cbd5e1; border-radius: 8px; }
.pop .row { display: flex; gap: 8px; justify-content: flex-end; } .pop .err { color: #b91c1c; }
.pop .pick { display: grid; gap: 4px; } .pop .pick button { text-align: left; background: #e2e8f0; color: #111827; }
`;
/**
* The page part of translate mode: a bar (edits, copy the pack file, leave) and an editor for the
* string under a click. Clicks on marked text are the editor's while the mode is on.
*/
export function installTranslateUi(win: Window, options: TranslateUiOptions): { dispose(): void } {
const doc = win.document;
const words = { ...TRANSLATE_WORDS, ...options.words };
const lookup = inventoryLookup(options.inventory);
const storage = win.sessionStorage;
const draft = (): TranslateDraft => readDraft(storage) ?? { language: '', name: '', strings: {} };
const save = (next: TranslateDraft) => { try { storage.setItem(DRAFT_KEY, JSON.stringify(next)); } catch { /* storage full or blocked */ } };
const host = doc.createElement('wb-translate');
const root = host.attachShadow({ mode: 'open' });
const style = doc.createElement('style');
style.textContent = CSS;
root.append(style);
const bar = doc.createElement('div');
bar.className = 'bar';
root.append(bar);
let pop: HTMLElement | null = null;
let changed = false;
const button = (label: string, onClick: () => void, primary = false) => {
const el = doc.createElement('button');
el.textContent = label;
if (primary) el.className = 'primary';
el.addEventListener('click', event => { event.preventDefault(); event.stopPropagation(); onClick(); });
return el;
};
const renderBar = () => {
bar.replaceChildren();
const title = doc.createElement('b');
title.textContent = words.bar;
const hint = doc.createElement('span');
hint.textContent = `${words.hint} · ${words.edits(Object.keys(draft().strings).length)}`;
bar.append(title, hint);
if (changed) bar.append(button(words.reload, () => win.location.reload(), true));
bar.append(button(words.exportPack, () => {
const text = JSON.stringify(draftPack(draft(), options.site, options.catalog), null, 2);
void win.navigator.clipboard?.writeText(text).then(() => { hint.textContent = words.copied; }).catch(() => {});
}));
bar.append(button(words.exit, options.exit));
};
const closePop = () => { pop?.remove(); pop = null; };
const edit = (id: string, x: number, y: number, now: string) => {
closePop();
pop = doc.createElement('div');
pop.className = 'pop';
pop.style.left = `${Math.max(12, Math.min(x, win.innerWidth - 372))}px`;
pop.style.top = `${Math.max(12, Math.min(y + 12, win.innerHeight - 260))}px`;
const shape = lookup(id);
const head = doc.createElement('small');
head.textContent = `${words.key}: `;
const code = doc.createElement('code');
code.textContent = id;
head.append(code);
const current = doc.createElement('div');
current.textContent = `${words.original}: ${now}`;
pop.append(head, current);
if (!shape || (shape.kind !== 'text' && shape.kind !== 'message')) {
const note = doc.createElement('div');
note.textContent = words.notTranslatable;
pop.append(note, button(words.cancel, closePop));
root.append(pop);
return;
}
if (shape.params?.length) {
const params = doc.createElement('small');
params.textContent = `${words.parameters}: ${shape.params.map(name => `{${name}}${shape.plural?.includes(name) ? ' (plural)' : ''}`).join(', ')}`;
pop.append(params);
}
const input = doc.createElement('textarea');
input.value = draft().strings[id] ?? now;
const error = doc.createElement('div');
error.className = 'err';
const row = doc.createElement('div');
row.className = 'row';
if (draft().strings[id] !== undefined) {
row.append(button(words.remove, () => { const next = draft(); delete next.strings[id]; save(next); changed = true; closePop(); renderBar(); }));
}
row.append(button(words.cancel, closePop), button(words.save, () => {
const value = input.value.trim();
const problem = checkEdit(lookup, id, value);
if (problem) { error.textContent = problem; return; }
const next = draft();
next.strings[id] = value;
save(next);
changed = true;
closePop();
renderBar();
}, true));
pop.append(input, error, row);
root.append(pop);
input.focus();
};
/** The marked keys at a click: the element's own text and labels, then up to three parents. */
const keysAt = (target: Element | null) => {
for (let el = target, depth = 0; el && depth < 4; el = el.parentElement, depth += 1) {
const texts = [el.textContent ?? '', el.getAttribute('aria-label') ?? '', el.getAttribute('placeholder') ?? '', el.getAttribute('title') ?? ''];
const found = texts.flatMap(text => options.marker.ids(text).map(id => ({ id, text: options.marker.strip(text) })));
if (found.length) return found.filter((item, i) => found.findIndex(other => other.id === item.id) === i).slice(0, 8);
}
return [];
};
const onClick = (event: MouseEvent) => {
if (event.composedPath().includes(host)) return;
const found = keysAt(event.target as Element | null);
if (!found.length) return;
event.preventDefault();
event.stopPropagation();
if (found.length === 1) { edit(found[0]!.id, event.clientX, event.clientY, found[0]!.text); return; }
closePop();
pop = doc.createElement('div');
pop.className = 'pop';
pop.style.left = `${Math.max(12, Math.min(event.clientX, win.innerWidth - 372))}px`;
pop.style.top = `${Math.max(12, Math.min(event.clientY + 12, win.innerHeight - 260))}px`;
const pick = doc.createElement('div');
pick.className = 'pick';
const label = doc.createElement('small');
label.textContent = words.choose;
pick.append(label, ...found.map(item => button(`${item.text.slice(0, 60)} · ${item.id}`, () => edit(item.id, event.clientX, event.clientY, item.text))));
pop.append(pick, button(words.cancel, closePop));
root.append(pop);
};
const mount = () => { (doc.body ?? doc.documentElement).append(host); renderBar(); };
if (doc.body) mount(); else doc.addEventListener('DOMContentLoaded', mount, { once: true });
win.addEventListener('click', onClick, true);
return { dispose() { win.removeEventListener('click', onClick, true); host.remove(); } };
}
/** The draft as the last pack of a delivery (it applies over the others), when it has any string. */
export function withDraft(packs: readonly unknown[], storage: Pick<Storage, 'getItem'>, site: string, catalog: string, inventory: PageInventory): unknown[] {
const draft = readDraft(storage);
if (!draft || !Object.keys(draft.strings).length) return [...packs];
const pack = draftPack(draft, site, catalog);
try { compilePack(pack, inventory); } catch { return [...packs]; }
return [...packs, pack];
}

View file

@ -0,0 +1,587 @@
// String packs: data-only packs that replace the wrapped site's own UI strings (published as
// `waybetter/runtime/stringPacks`). A pack adds a language the site does not offer, fixes its
// translation or rewords it. This file is the data side: the pack and inventory formats, the
// validator, the ordered application engine, coverage and the drift report. It touches no DOM and
// runs the same in the page, in the shell and in Node (`waybetter strings check`).
//
// The rules (they are the owner's, and every function here keeps them):
// - Idempotent. The result is a pure function of (the site's own values, the ordered pack list):
// applying twice equals applying once, and a later pack wins over an earlier one per key.
// - The site's own language is the fallback. A key no pack changes keeps exactly the site's value
// (the same object, not a copy).
// - An inventory of the site's known keys. A pack may change only inventory keys, and only keys
// whose kind can be replaced by data; unknown keys are reported, never applied.
// - Packs are data: plain text in an ICU MessageFormat subset ({param}, plural, select). Never
// HTML, never code. A message is interpreted by closures here; nothing is evaluated.
//
// One site can have several catalogs (each with its own key space, inventory and hook adapter,
// see stringPackHook.ts); a pack names the one it is for.
import { parseMessage } from './i18n.ts';
type Parts = ReturnType<typeof parseMessage>;
// -------------------------------------------------------------------------------------------
// Formats
/**
* What the site's value for a key is:
* - `text`: a plain string;
* - `message`: a function of a parameter object that returns a string;
* - `rich`: text with element slots (not replaceable by data yet);
* - `format`: a compiled number/date/currency formatter (not text).
* Only `text` and `message` can be replaced by a pack.
*/
export type StringKind = 'text' | 'message' | 'rich' | 'format';
export type InventoryEntry = {
kind: StringKind;
/** Parameter names the site's value takes (`message`). */
params?: string[];
/** Parameters the site's value pluralizes: known to be numbers, so a pack may pluralize them. */
plural?: string[];
/** Parameters the site's value selects on. */
select?: string[];
/** Tag slot names, for catalogs whose values carry `<tag>…</tag>` slots. */
tags?: string[];
/** Hash of the base-language value (`hashText`): drift detection; never the text itself. */
hash: string;
/** Part of the catalog the key arrives with (default `main`), e.g. a lazily loaded `emoji` group. */
group?: string;
};
/** The known keys of one catalog of one site. It carries ids and shapes, never the site's text. */
export type StringInventory = {
format: 1;
site: string;
catalog: string;
/** Language the hashes were taken from. */
base: string;
/** The site build the inventory was read from. */
build?: string;
entries: Record<string, InventoryEntry>;
};
/** A string pack document: metadata and `key id -> text`. */
export type StringPack = {
format: 1;
site: string;
catalog: string;
/** BCP 47 tag of the pack's language (private-use tags are fine: `en-x-pirate`). */
language: string;
name: string;
authors: string[];
/** A language whose plural rules the pack follows when the runtime does not know `language`. */
base?: string;
version?: string;
description?: string;
strings: Record<string, string>;
};
export const STRING_PACK_LIMITS = Object.freeze({ strings: 40000, value: 2000, name: 80, authors: 16 });
export const MAIN_GROUP = 'main';
const TAG = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
const IDENT = /^[a-z][a-z0-9-]{0,31}$/;
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f‪-‮⁦-⁩]/;
const CATEGORIES = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);
/** Whether a pack can replace a value of this kind. */
export function translatable(kind: StringKind): boolean {
return kind === 'text' || kind === 'message';
}
/** 53-bit hash of a text as 11 base-36 characters. Same result in every runtime. */
export function hashText(text: string): string {
let h1 = 0xdeadbeef;
let h2 = 0x41c6ce57;
for (let i = 0; i < text.length; i += 1) {
const ch = text.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36).padStart(11, '0');
}
// -------------------------------------------------------------------------------------------
// Inventory lookup (the full inventory, or its compact page form)
/** The facts the validator and the engine need about one key. */
export type EntryShape = Pick<InventoryEntry, 'kind' | 'params' | 'plural' | 'select' | 'tags'>;
export type InventoryLookup = (id: string) => EntryShape | undefined;
/**
* The inventory as it ships inside a page runtime: ids and shapes only, no hashes, a fraction of
* the size. `text` and `closed` are space-separated ids; a message is `name name*` (`*` = plural,
* `?` = select).
*/
export type PageInventory = {
site: string;
catalog: string;
text: string;
message: Record<string, string>;
closed: string;
/** A slice: only the keys some pack names. A key missing from a slice is not a new key of the site. */
partial?: boolean;
};
function compact(site: string, catalog: string, shapes: Iterable<[string, EntryShape]>): PageInventory {
const text: string[] = [];
const closed: string[] = [];
const message: Record<string, string> = {};
for (const [id, entry] of shapes) {
if (entry.kind === 'text' && !entry.tags?.length) text.push(id);
else if (entry.kind === 'message' && !entry.tags?.length) {
message[id] = (entry.params ?? []).map(name => `${name}${entry.plural?.includes(name) ? '*' : ''}${entry.select?.includes(name) ? '?' : ''}`).join(' ');
} else closed.push(id);
}
return { site, catalog, text: text.join(' '), message, closed: closed.join(' ') };
}
export function packInventory(inventory: StringInventory): PageInventory {
return compact(inventory.site, inventory.catalog, Object.entries(inventory.entries));
}
/**
* The part of an inventory that the given keys need: what travels to a page together with the
* packs it should apply (a page never needs the rest). Keys the inventory does not have are left
* out, so they stay unknown there too.
*/
export function sliceInventory(inventory: StringInventory | PageInventory, ids: Iterable<string>): PageInventory {
const lookup = inventoryLookup(inventory);
const shapes: [string, EntryShape][] = [];
for (const id of new Set(ids)) {
const shape = lookup(id);
if (shape) shapes.push([id, shape]);
}
return { ...compact(inventory.site, inventory.catalog, shapes), partial: true };
}
/** Whether untrusted data has the shape of a page inventory (ids and parameter names only). */
export function isPageInventory(input: unknown): input is PageInventory {
if (!isRecord(input)) return false;
const ids = (value: unknown) => typeof value === 'string' && value.length <= 2_000_000 && /^[\w$. -]*$/.test(value);
return typeof input.site === 'string' && IDENT.test(input.site) && typeof input.catalog === 'string' && IDENT.test(input.catalog)
&& ids(input.text) && ids(input.closed) && isRecord(input.message)
&& Object.entries(input.message).every(([id, names]) => /^[\w$.-]+$/.test(id) && typeof names === 'string' && /^[\w$*? ]*$/.test(names))
&& (input.partial === undefined || typeof input.partial === 'boolean');
}
const TEXT_SHAPE: EntryShape = Object.freeze({ kind: 'text' });
const CLOSED_SHAPE: EntryShape = Object.freeze({ kind: 'rich' });
/** A lookup over either form. The page form is decoded on first use. */
export function inventoryLookup(inventory: StringInventory | PageInventory): InventoryLookup {
if ('entries' in inventory) {
const entries = inventory.entries;
return id => (Object.prototype.hasOwnProperty.call(entries, id) ? entries[id] : undefined);
}
let table: Map<string, EntryShape> | null = null;
const decode = () => {
const map = new Map<string, EntryShape>();
if (inventory.text) for (const id of inventory.text.split(' ')) map.set(id, TEXT_SHAPE);
if (inventory.closed) for (const id of inventory.closed.split(' ')) map.set(id, CLOSED_SHAPE);
for (const [id, spec] of Object.entries(inventory.message)) {
const names = spec ? spec.split(' ') : [];
map.set(id, {
kind: 'message',
params: names.map(name => name.replace(/[*?]+$/, '')),
plural: names.filter(name => name.includes('*')).map(name => name.replace(/[*?]+$/, '')),
select: names.filter(name => name.includes('?')).map(name => name.replace(/[*?]+$/, '')),
});
}
return map;
};
return id => (table ??= decode()).get(id);
}
// -------------------------------------------------------------------------------------------
// Validator
export type PackIssue = { level: 'error' | 'warning'; key?: string; message: string };
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);
/** Checks the document envelope. Errors mean the pack is not applied at all. */
export function checkPackShape(input: unknown): PackIssue[] {
const issues: PackIssue[] = [];
const error = (message: string) => { issues.push({ level: 'error', message }); };
if (!isRecord(input)) return [{ level: 'error', message: 'a string pack is a JSON object' }];
if (input.format !== 1) error('"format" must be 1');
for (const field of ['site', 'catalog'] as const) {
if (typeof input[field] !== 'string' || !IDENT.test(input[field])) error(`"${field}" must be a short lowercase id`);
}
if (typeof input.language !== 'string' || !TAG.test(input.language)) error('"language" must be a language tag (en, pt-BR, en-x-pirate)');
if (input.base !== undefined && (typeof input.base !== 'string' || !TAG.test(input.base))) error('"base" must be a language tag');
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > STRING_PACK_LIMITS.name || CONTROL.test(input.name) || /[<>]/.test(input.name)) {
error(`"name" must be 1 to ${STRING_PACK_LIMITS.name} characters of plain text`);
}
if (!Array.isArray(input.authors) || input.authors.length > STRING_PACK_LIMITS.authors
|| input.authors.some(author => typeof author !== 'string' || !author.trim() || author.length > STRING_PACK_LIMITS.name || CONTROL.test(author) || /[<>]/.test(author))) {
error(`"authors" must be a list of at most ${STRING_PACK_LIMITS.authors} plain-text names`);
}
for (const field of ['version', 'description'] as const) {
const value = input[field];
if (value !== undefined && (typeof value !== 'string' || value.length > 400 || CONTROL.test(value) || /[<>]/.test(value))) error(`"${field}" must be plain text`);
}
if (!isRecord(input.strings)) error('"strings" must be an object of key id -> text');
else if (Object.keys(input.strings).length > STRING_PACK_LIMITS.strings) error(`"strings" has more than ${STRING_PACK_LIMITS.strings} entries`);
const known = new Set(['$schema', 'format', 'site', 'catalog', 'language', 'base', 'name', 'authors', 'version', 'description', 'strings']);
for (const key of Object.keys(input)) if (!known.has(key)) issues.push({ level: 'warning', message: `unknown field "${key}" is ignored` });
return issues;
}
const TAG_TOKEN = /<\/?([A-Za-z][A-Za-z0-9-]*)>/g;
/** Tag rule: only the original's tag slots, each opened and closed; any other `<` or `>` is refused. */
function checkTags(value: string, tags: readonly string[]): string | null {
if (!value.includes('<') && !value.includes('>')) {
return tags.length ? `the original's tags are missing: ${tags.map(tag => `<${tag}>`).join(' ')}` : null;
}
if (!tags.length) return 'markup is not allowed: a pack is text, < and > cannot be used';
const open: string[] = [];
const seen = new Set<string>();
for (const match of value.matchAll(TAG_TOKEN)) {
const name = match[1]!;
if (!tags.includes(name)) return `<${name}> is not a tag of the original`;
if (match[0].startsWith('</')) {
if (open.pop() !== name) return `</${name}> does not close an open tag`;
} else {
open.push(name);
seen.add(name);
}
}
if (open.length) return `<${open[open.length - 1]}> is not closed`;
if (/[<>]/.test(value.replace(TAG_TOKEN, ''))) return '< and > may only be used for the original\'s tags';
const missing = tags.filter(tag => !seen.has(tag));
return missing.length ? `the original's tags are missing: ${missing.map(tag => `<${tag}>`).join(' ')}` : null;
}
/** Walks a parsed message against the key's shape; returns the first problem. */
function checkParts(parts: Parts, shape: EntryShape): string | null {
const params = shape.params ?? [];
for (const part of parts) {
if (typeof part === 'string' || part.kind === 'pound') continue;
if (!params.includes(part.name)) {
return params.length ? `{${part.name}} is not a parameter of the original (it has: ${params.join(', ')})` : `{${part.name}}: the original takes no parameters`;
}
if (part.kind === 'arg') {
if (part.format) return `{${part.name}, ${part.format}} is not supported: only {name}, plural and select`;
continue;
}
if (part.kind === 'plural') {
if (part.ordinal) return `{${part.name}, selectordinal} is not supported: only {name}, plural and select`;
if (part.offset) return `{${part.name}, plural, offset:…} is not supported`;
if (!shape.plural?.includes(part.name)) return `{${part.name}} is not a plural of the original`;
for (const selector of Object.keys(part.options)) {
if (!CATEGORIES.has(selector) && !/^=\d+$/.test(selector)) return `"${selector}" is not a plural form (zero, one, two, few, many, other, =N)`;
}
} else if (!shape.select?.includes(part.name)) {
return `{${part.name}} is not a select of the original`;
}
for (const option of Object.values(part.options)) {
const nested = checkParts(option, shape);
if (nested) return nested;
}
}
return null;
}
/**
* Validates one pack value against the key's inventory entry. Returns the parsed message, or the
* reason it is refused (the original then stays).
*/
export function validateString(shape: EntryShape, value: unknown): { parts: Parts } | { reason: string } {
if (!translatable(shape.kind)) return { reason: `not translatable yet (${shape.kind})` };
if (typeof value !== 'string') return { reason: 'the value must be text' };
if (!value) return { reason: 'the value is empty' };
if (value.length > STRING_PACK_LIMITS.value) return { reason: `longer than ${STRING_PACK_LIMITS.value} characters` };
if (CONTROL.test(value)) return { reason: 'control or bidi-override characters are not allowed' };
const tags = checkTags(value, shape.tags ?? []);
if (tags) return { reason: tags };
let parts: Parts;
try {
parts = parseMessage(value);
} catch (error) {
return { reason: `invalid message syntax: ${error instanceof Error ? error.message : String(error)}` };
}
const problem = checkParts(parts, shape.kind === 'message' ? shape : { kind: 'text' });
return problem ? { reason: problem } : { parts };
}
// -------------------------------------------------------------------------------------------
// Compiling a pack (validation against an inventory)
export type CompiledValue = { text: string } | { parts: Parts };
export type PackReport = {
/** Entries in the pack. */
total: number;
/** Entries that are valid for an inventory key. */
valid: number;
/** Ids the inventory does not have: never applied. */
unknown: string[];
/** Values that failed validation: not applied, the original stays. */
rejected: { id: string; reason: string }[];
};
export type CompiledPack = {
name: string;
language: string;
base?: string;
site: string;
catalog: string;
values: ReadonlyMap<string, CompiledValue>;
report: PackReport;
};
/** A message without arguments as its literal text (quotes resolved). */
function literal(parts: Parts): string {
return parts.map(part => (typeof part === 'string' ? part : '')).join('');
}
/**
* Validates a pack against an inventory. Throws on a malformed envelope or a pack for another
* site/catalog; every other problem is per key and lands in `report`.
*/
export function compilePack(input: unknown, inventory: StringInventory | PageInventory): CompiledPack {
const shapeErrors = checkPackShape(input).filter(issue => issue.level === 'error');
if (shapeErrors.length) throw new Error(`invalid string pack: ${shapeErrors.map(issue => issue.message).join('; ')}`);
const pack = input as StringPack;
if (pack.site !== inventory.site || pack.catalog !== inventory.catalog) {
throw new Error(`the pack is for ${pack.site}/${pack.catalog}, the inventory is ${inventory.site}/${inventory.catalog}`);
}
const lookup = inventoryLookup(inventory);
const values = new Map<string, CompiledValue>();
const report: PackReport = { total: 0, valid: 0, unknown: [], rejected: [] };
for (const [id, value] of Object.entries(pack.strings)) {
report.total += 1;
const shape = lookup(id);
if (!shape) { report.unknown.push(id); continue; }
const result = validateString(shape, value);
if ('reason' in result) { report.rejected.push({ id, reason: result.reason }); continue; }
values.set(id, shape.kind === 'text' ? { text: literal(result.parts) } : { parts: result.parts });
report.valid += 1;
}
return { name: pack.name, language: pack.language, base: pack.base, site: pack.site, catalog: pack.catalog, values, report };
}
// -------------------------------------------------------------------------------------------
// Interpreting a message (closures over the parsed parts; nothing is evaluated)
const rulesCache = new Map<string, Intl.PluralRules | null>();
/** Plural rules of the first language the runtime knows; `null` = every number is `other`. */
function rulesFor(languages: readonly (string | undefined)[]): Intl.PluralRules | null {
const key = languages.join('|');
let rules = rulesCache.get(key);
if (rules !== undefined) return rules;
rules = null;
for (const language of languages) {
if (!language) continue;
const tag = language.split(/-x-/i)[0]!;
try {
if (Intl.PluralRules.supportedLocalesOf([tag]).length) { rules = new Intl.PluralRules(tag); break; }
} catch {
// Not a tag this runtime accepts: try the next.
}
}
rulesCache.set(key, rules);
return rules;
}
/**
* Renders a validated message. A parameter is inserted the way string concatenation would
* (`String(value)`, nothing for a missing one); `#` is the plural's own value.
*/
export function renderMessage(parts: Parts, params: Readonly<Record<string, unknown>>, languages: readonly (string | undefined)[], pound: unknown = undefined): string {
let out = '';
for (const part of parts) {
if (typeof part === 'string') { out += part; continue; }
// The parser only yields `#` inside a plural, so there is always a value it stands for.
if (part.kind === 'pound') { out += pound === undefined || pound === null ? '' : String(pound); continue; }
const value = params[part.name];
if (part.kind === 'arg') { out += value === undefined || value === null ? '' : String(value); continue; }
if (part.kind === 'select') {
out += renderMessage(part.options[String(value)] ?? part.options.other!, params, languages, pound);
continue;
}
const n = typeof value === 'number' ? value : Number(value);
const option = Number.isFinite(n)
? part.options[`=${n}`] ?? part.options[rulesFor(languages)?.select(n) ?? 'other'] ?? part.options.other!
: part.options.other!;
out += renderMessage(option, params, languages, value);
}
return out;
}
// -------------------------------------------------------------------------------------------
// The ordered application engine
export type EngineStats = {
/** Keys the site registered. */
seen: number;
/** Keys a pack value was used for. */
applied: number;
/** Keys the site registered that the inventory does not have (new keys: drift). */
unlisted: string[];
/** Keys whose live value does not have the inventory's kind: left untouched. */
mismatched: string[];
};
export type StringEngine = {
/**
* The value to use for `id`, given the site's own value: a pack's, or exactly `original`.
* Feeding a value this engine produced back in returns the same value (idempotent).
*/
resolve(id: string, original: unknown): unknown;
/** The site's own values of the keys a pack changed: what restoring needs. */
originals(): ReadonlyMap<string, unknown>;
stats(): EngineStats;
};
const MAX_LISTED = 200;
/** `packs` in application order: a later pack wins over an earlier one for the same key. */
export function createStringEngine(inventory: StringInventory | PageInventory | InventoryLookup, packs: readonly CompiledPack[]): StringEngine {
const lookup = typeof inventory === 'function' ? inventory : inventoryLookup(inventory);
// A slice only knows the packs' keys: what it lacks is not a new key of the site.
const whole = typeof inventory === 'function' || !('partial' in inventory && inventory.partial);
const originals = new Map<string, unknown>();
const applied = new Map<string, unknown>();
const produced = new WeakMap<object, unknown>();
const seen = new Set<string>();
const unlisted = new Set<string>();
const mismatched = new Set<string>();
const winner = (id: string): { pack: CompiledPack; value: CompiledValue } | null => {
for (let index = packs.length - 1; index >= 0; index -= 1) {
const value = packs[index]!.values.get(id);
if (value) return { pack: packs[index]!, value };
}
return null;
};
const resolve = (id: string, incoming: unknown): unknown => {
let original = incoming;
// A value of ours coming back in (a second application): work from the site's own value again.
if (typeof incoming === 'function' && produced.has(incoming)) original = produced.get(incoming);
else if (typeof incoming === 'string' && applied.has(id) && applied.get(id) === incoming) original = originals.get(id);
seen.add(id);
const found = winner(id);
if (!found) {
if (whole && unlisted.size < MAX_LISTED && !lookup(id)) unlisted.add(id);
return original;
}
const shape = lookup(id);
if (!shape || !translatable(shape.kind)) return original;
if (shape.kind === 'text' ? typeof original !== 'string' : typeof original !== 'function') {
if (mismatched.size < MAX_LISTED) mismatched.add(id);
return original;
}
if (originals.has(id) && originals.get(id) === original) return applied.get(id);
let next: unknown;
if ('text' in found.value) {
next = found.value.text;
} else {
const parts = found.value.parts;
const languages = [found.pack.language, found.pack.base];
const message = (params?: unknown): string => renderMessage(parts, isRecord(params) ? params : {}, languages);
produced.set(message, original);
next = message;
}
originals.set(id, original);
applied.set(id, next);
return next;
};
return {
resolve,
originals: () => originals,
stats: () => ({ seen: seen.size, applied: applied.size, unlisted: [...unlisted], mismatched: [...mismatched] }),
};
}
/**
* The whole catalog at once: a new object with the packs applied; `catalog` itself is not
* changed. `applyPacks(applyPacks(c, …), …)` with one engine equals `applyPacks(c, …)`.
*/
export function applyPacks(catalog: Readonly<Record<string, unknown>>, engine: StringEngine): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const id of Object.keys(catalog)) out[id] = engine.resolve(id, catalog[id]);
return out;
}
/** The inverse: every value a pack changed is the site's own again; `catalog` is not changed. */
export function restoreCatalog(catalog: Readonly<Record<string, unknown>>, engine: StringEngine): Record<string, unknown> {
const originals = engine.originals();
const out: Record<string, unknown> = {};
for (const id of Object.keys(catalog)) out[id] = originals.has(id) ? originals.get(id) : catalog[id];
return out;
}
// -------------------------------------------------------------------------------------------
// Coverage
export type Coverage = {
/** Keys a pack can replace (text and messages). */
translatable: number;
/** Of those, keys the pack has a valid value for. */
translated: number;
/** Keys that exist but cannot be replaced by data yet (rich text, formatters). */
closed: number;
};
/** Coverage of a compiled pack per group of the inventory, plus `all`. */
export function coverage(inventory: StringInventory, pack: Pick<CompiledPack, 'values'>): Record<string, Coverage> {
const out: Record<string, Coverage> = { all: { translatable: 0, translated: 0, closed: 0 } };
for (const [id, entry] of Object.entries(inventory.entries)) {
const group = (out[entry.group ?? MAIN_GROUP] ??= { translatable: 0, translated: 0, closed: 0 });
for (const bucket of [group, out.all!]) {
if (!translatable(entry.kind)) { bucket.closed += 1; continue; }
bucket.translatable += 1;
if (pack.values.has(id)) bucket.translated += 1;
}
}
return out;
}
// -------------------------------------------------------------------------------------------
// Drift (the site shipped a new build)
export type DriftReport = {
/** Keys the site has that the inventory lacks. */
added: string[];
/** Keys whose base-language value changed (same shape). */
reworded: string[];
/** Keys whose kind or parameters changed: pack values for them have to be checked again. */
reshaped: string[];
/** Inventory keys the site no longer has. Only for groups whose base catalog was loaded. */
vanished: string[];
};
const sameList = (a: readonly string[] = [], b: readonly string[] = []) => a.length === b.length && [...a].sort().join('\n') === [...b].sort().join('\n');
/**
* Compares an inventory with what was observed now. `loaded` names the groups whose base catalog
* was actually read: a key can only be called vanished when its group was (a lazily loaded group
* that never arrived says nothing about its keys).
*/
export function driftReport(inventory: StringInventory, observed: Readonly<Record<string, InventoryEntry>>, loaded: readonly string[]): DriftReport {
const report: DriftReport = { added: [], reworded: [], reshaped: [], vanished: [] };
for (const [id, now] of Object.entries(observed)) {
const before = Object.prototype.hasOwnProperty.call(inventory.entries, id) ? inventory.entries[id] : undefined;
if (!before) { report.added.push(id); continue; }
if (before.kind !== now.kind || !sameList(before.params, now.params) || !sameList(before.plural, now.plural) || !sameList(before.select, now.select) || !sameList(before.tags, now.tags)) {
report.reshaped.push(id);
} else if (before.hash !== now.hash) {
report.reworded.push(id);
}
}
const groups = new Set(loaded);
for (const [id, entry] of Object.entries(inventory.entries)) {
if (!Object.prototype.hasOwnProperty.call(observed, id) && groups.has(entry.group ?? MAIN_GROUP)) report.vanished.push(id);
}
return report;
}

View file

@ -0,0 +1,129 @@
// A DOM safety net for strings a catalog hook cannot reach (published as
// `waybetter/runtime/textNet`): labels the server sends already worded, or text that is painted
// before the hook can act. It replaces exact texts in text nodes and in `aria-label`,
// `placeholder` and `title`, keeps the site's own value per node, and puts everything back when it
// is disposed. It is secondary to a catalog hook: it cannot see parameters or plural forms, and a
// rendered text only maps back to one key in a language without homonyms.
//
// Text is written through `nodeValue` / `setAttribute` (never `textContent` or HTML), so the site's
// framework keeps owning its nodes; when the site rewrites a node, the net looks at it again.
export type TextNetOptions = {
/** Exact original text -> replacement. A text that is not a key is left alone. */
map: ReadonlyMap<string, string>;
/** Attributes to cover (default `aria-label`, `placeholder`, `title`). */
attributes?: readonly string[];
/** Elements whose content is never touched (default: scripts, styles, editable text). */
skip?: string;
};
export type TextNetHandle = {
/** Text nodes and attributes currently replaced. */
count(): number;
/** Restores every node and attribute to the site's own value and stops observing. */
dispose(): void;
};
const DEFAULT_ATTRIBUTES = ['aria-label', 'placeholder', 'title'];
const DEFAULT_SKIP = 'script, style, noscript, textarea, [contenteditable=""], [contenteditable="true"]';
const TEXT_NODE = 3;
const ELEMENT_NODE = 1;
const SHOW_TEXT = 4;
export function installTextNet(win: Window, options: TextNetOptions): TextNetHandle {
const doc = win.document;
const attributes = options.attributes ?? DEFAULT_ATTRIBUTES;
const skip = options.skip ?? DEFAULT_SKIP;
const map = options.map;
/** The site's own value and ours, per text node. */
const texts = new WeakMap<Node, { original: string; applied: string }>();
/** The same per element and attribute. */
const attrs = new WeakMap<Element, Map<string, { original: string; applied: string }>>();
let count = 0;
let active = true;
const skipped = (element: Element | null) => !!element && !!skip && !!element.closest(skip);
const text = (node: Node) => {
const value = node.nodeValue ?? '';
const kept = texts.get(node);
if (kept) {
if (value === kept.applied) return;
// The site wrote the node again: what it wrote is the new original.
texts.delete(node);
count -= 1;
}
const next = map.get(value);
if (next === undefined || next === value || skipped(node.parentElement)) return;
texts.set(node, { original: value, applied: next });
count += 1;
node.nodeValue = next;
};
const attribute = (element: Element, name: string) => {
const value = element.getAttribute(name);
const kept = attrs.get(element)?.get(name);
if (kept) {
if (value === kept.applied) return;
attrs.get(element)!.delete(name);
count -= 1;
}
if (value === null) return;
const next = map.get(value);
if (next === undefined || next === value || skipped(element)) return;
let own = attrs.get(element);
if (!own) attrs.set(element, own = new Map());
own.set(name, { original: value, applied: next });
count += 1;
element.setAttribute(name, next);
};
const sweep = (root: Node) => {
if (root.nodeType === TEXT_NODE) { text(root); return; }
if (root.nodeType !== ELEMENT_NODE) return;
const element = root as Element;
const walker = doc.createTreeWalker(element, SHOW_TEXT);
while (walker.nextNode()) text(walker.currentNode);
for (const name of attributes) {
if (element.hasAttribute(name)) attribute(element, name);
for (const child of element.querySelectorAll(`[${name}]`)) attribute(child, name);
}
};
const observer = new (win as unknown as { MutationObserver: typeof MutationObserver }).MutationObserver(records => {
if (!active) return;
for (const record of records) {
if (record.type === 'characterData') text(record.target);
else if (record.type === 'attributes') { if (record.attributeName) attribute(record.target as Element, record.attributeName); }
else for (const node of record.addedNodes) sweep(node);
}
});
if (map.size) {
if (doc.documentElement) sweep(doc.documentElement);
observer.observe(doc, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: [...attributes] });
}
return {
count: () => count,
dispose() {
if (!active) return;
active = false;
observer.disconnect();
if (!doc.documentElement) return;
const walker = doc.createTreeWalker(doc.documentElement, SHOW_TEXT);
while (walker.nextNode()) {
const node = walker.currentNode;
const kept = texts.get(node);
if (kept && node.nodeValue === kept.applied) node.nodeValue = kept.original;
texts.delete(node);
}
for (const name of attributes) {
for (const element of doc.querySelectorAll(`[${name}]`)) {
const kept = attrs.get(element)?.get(name);
if (kept && element.getAttribute(name) === kept.applied) element.setAttribute(name, kept.original);
}
}
count = 0;
},
};
}

View file

@ -3,14 +3,21 @@
// to every site tab; the shell's theme store and the panel edit it. A site brings its built-in
// themes (`createThemeCatalog(builtins)`; the first one is the site's own look, the default). Pure.
import { sanitizeIconPack, type IconPack } from './themeIcons.ts';
import { applyOverrides, isHex, sanitizeSpec, type Palette, type ThemeOverrides, type ThemeSpec } from './themeSpec.ts';
/** What is persisted natively and handed to the page runtime. */
export type ThemeChoice = { preset: string; accent: string | null; overrides: ThemeOverrides; themes: ThemeSpec[] };
/**
* What is persisted natively and handed to the page runtime. `icons` is the owner's icon pack (theme
* engine v2): absent follows the theme's suggestion, `site` keeps the site's own icons, else a pack id.
*/
export type ThemeChoice = { preset: string; accent: string | null; overrides: ThemeOverrides; themes: ThemeSpec[]; icons?: string; packs?: IconPack[] };
/** Icon packs the owner imported (standalone documents, kept with the choice so every site tab has them). */
export const MAX_USER_PACKS = 8;
/** Imported themes kept in a choice (the JSON Schema of the native side says the same). */
export const MAX_USER_THEMES = 24;
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css'] as const;
const OVERRIDE_GROUPS = ['colors', 'font', 'shape', 'layout', 'background', 'effects', 'css', 'variants'] as const;
export type ThemeCatalog = {
/** The site's built-in themes; the first is its own look (and the default choice). */
@ -53,7 +60,15 @@ export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog
const value = rawOverrides[key];
if (value && typeof value === 'object' && !Array.isArray(value)) (overrides as Record<string, unknown>)[key] = value;
}
return { preset, accent, overrides, themes };
const icons = typeof source.icons === 'string' && /^[a-z0-9-]{1,40}$/.test(source.icons) && source.icons !== 'theme' ? source.icons : undefined;
const packs: IconPack[] = [];
if (Array.isArray(source.packs)) {
for (const raw of source.packs.slice(0, MAX_USER_PACKS)) {
const pack = sanitizeIconPack(raw);
if (pack && !packs.some(item => item.id === pack.id)) packs.push(pack);
}
}
return { preset, accent, overrides, themes, ...(icons ? { icons } : {}), ...(packs.length ? { packs } : {}) };
}
const base = (choice: ThemeChoice) => choice.themes.find(item => item.id === choice.preset) ?? builtins.find(item => item.id === choice.preset) ?? first;
@ -69,11 +84,11 @@ export function createThemeCatalog(builtins: readonly ThemeSpec[]): ThemeCatalog
/** The choice a tab's theme id stands for (themeScopes: account and pane themes): the global choice itself, or that theme without customizations. */
export function choiceForId(global: ThemeChoice, id: string): ThemeChoice {
return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes };
return id === global.preset ? global : { preset: id, accent: null, overrides: {}, themes: global.themes, ...(global.icons ? { icons: global.icons } : {}), ...(global.packs?.length ? { packs: global.packs } : {}) };
}
/** The shape persisted natively: empty groups are dropped so "no override" stays unambiguous. */
export function serializeChoice(choice: ThemeChoice) {
const overrides = Object.fromEntries(Object.entries(choice.overrides).filter(([, value]) => value && Object.keys(value).length));
return { preset: choice.preset, accent: choice.accent, ...(Object.keys(overrides).length ? { overrides } : {}), ...(choice.themes.length ? { themes: choice.themes } : {}) };
return { preset: choice.preset, accent: choice.accent, ...(Object.keys(overrides).length ? { overrides } : {}), ...(choice.themes.length ? { themes: choice.themes } : {}), ...(choice.icons ? { icons: choice.icons } : {}), ...(choice.packs?.length ? { packs: choice.packs } : {}) };
}

View file

@ -0,0 +1,472 @@
// Component tokens: the part of a theme that says how each piece of the site is built (a button's
// radius and border, a post's padding and fill, the size and case of a handle), instead of one radius
// and one density for everything. A theme names generic components (`post`, `buttonPrimary`,
// `navItem`); the site adapter says which selectors they are (its part map). Pure.
//
// Safety is the same as the rest of a theme document: every token is a clamped number, a fixed word
// or a color role name. No token carries CSS text, a selector or a color literal, so one contrast
// pass over the palette covers every component, and the CSS is built from the vocabulary below.
//
// How it lands in the page: values are custom properties at zero specificity
// (`:where(:root){--wb-part-post-radius:0px}`), rules are rigid (`:root:root <part>{border-radius:
// var(--wb-part-post-radius) !important}`). An owner's Custom CSS or a plugin overrides a value by
// setting the variable, for the whole page or for one subtree, without fighting `!important`.
//
// The bevel borders (`bevel-out`, `bevel-in`) follow 98.css's raised and sunken edges (MIT, Jordan
// Scales, https://github.com/jdan/98.css): four inset shadows, here computed from the theme's roles.
import { contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
// ---------------------------------------------------------------------------------------------
// Vocabulary
/** Color roles a component may name. `onAccent` is the readable label on the accent. */
export const COLOR_ROLES = ['bg', 'surface', 'elevated', 'page', 'border', 'text', 'muted', 'accent', 'onAccent', 'inverse', 'onInverse'] as const;
export type ColorRole = typeof COLOR_ROLES[number];
export type RoleColors = Record<ColorRole, string>;
export const BORDER_STYLES = ['none', 'solid', 'dashed', 'dotted', 'double', 'bevel-out', 'bevel-in'] as const;
export const SHADOWS = ['none', 'soft', 'deep', 'hard', 'inset', 'glow'] as const;
export const CASES = ['none', 'upper', 'lower', 'capitalize', 'small-caps'] as const;
export const AVATAR_SHAPES = ['circle', 'rounded', 'square', 'squircle', 'hexagon', 'octagon', 'diamond'] as const;
export const CORNERS = ['round', 'cut'] as const;
const FONT_ROLES: readonly FontRoleName[] = ['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog'];
export type Gradient = { from: ColorRole; to: ColorRole; angle: number };
export type Fill = ColorRole | 'transparent' | 'glass' | Gradient;
export type StateTokens = { fill?: Fill; text?: ColorRole; borderColor?: ColorRole; shadow?: typeof SHADOWS[number]; lift?: number; scale?: number; underline?: boolean };
export type ComponentTokens = {
preset?: string;
radius?: number | 'pill';
borderWidth?: number;
borderStyle?: typeof BORDER_STYLES[number];
borderColor?: ColorRole;
fill?: Fill;
text?: ColorRole;
padX?: number;
padY?: number;
gap?: number;
height?: number;
width?: number;
size?: number;
maxHeight?: number;
font?: FontRoleName;
fontSize?: number;
weight?: number;
case?: typeof CASES[number];
tracking?: number;
leading?: number;
shadow?: typeof SHADOWS[number];
shape?: typeof AVATAR_SHAPES[number];
corner?: typeof CORNERS[number];
visible?: boolean;
hover?: StateTokens;
active?: StateTokens;
focus?: StateTokens;
};
type ComponentDef = {
/** Tokens set on the parent apply to this component too. */
parent?: string;
/** A text part: type tokens land on its leaves. */
text?: boolean;
/** Size ranges in px (absent: the token is not accepted on this component). */
height?: [number, number]; width?: [number, number]; size?: [number, number]; maxHeight?: [number, number]; fontSize?: [number, number];
/** Tokens only some components take. */
shape?: boolean; corner?: boolean; visible?: boolean;
/** Glass fills (a blur) are allowed here; never on parts that repeat down a timeline. */
glass?: boolean;
/** Gradient fills are allowed here (bars and buttons). */
gradient?: boolean;
/** Presets of this component's family. */
presets?: keyof typeof PRESETS;
/** Contrast its text must reach on its own fill. */
contrast?: number;
};
const LABEL: [number, number] = [12, 20];
const SMALL: [number, number] = [11, 18];
/** Every component a theme can name. Sites map them to selectors; a component a site does not have is ignored. */
export const COMPONENTS = {
nav: { width: [56, 320], glass: true, gradient: true },
navItem: { height: [36, 64], fontSize: LABEL, text: true },
topBar: { height: [40, 64], glass: true, gradient: true, fontSize: LABEL },
tabs: { presets: 'tabs', gradient: true },
tab: { height: [32, 56], fontSize: LABEL, text: true, presets: 'tabs' },
post: { corner: true, presets: 'post', contrast: 7 },
avatar: { size: [20, 64], shape: true, visible: true },
displayName: { text: true, fontSize: LABEL, visible: true },
handle: { text: true, fontSize: SMALL, visible: true },
postText: { text: true, fontSize: [13, 24], contrast: 7 },
meta: { text: true, fontSize: SMALL },
actionBar: {},
action: { size: [28, 44] },
count: { text: true, fontSize: SMALL, visible: true },
media: { corner: true, maxHeight: [200, 700] },
linkCard: { corner: true },
quote: {},
button: { height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
buttonPrimary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
buttonSecondary: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
buttonGhost: { parent: 'button', height: [24, 56], fontSize: LABEL, text: true, gradient: true, presets: 'button' },
input: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' },
search: { height: [32, 56], fontSize: LABEL, text: true, presets: 'input' },
composer: { fontSize: [13, 24], text: true },
/** The tool icons under a composer (media, poll, emoji); `text` is their color. */
composerTool: { size: [28, 44] },
panel: { glass: true, presets: 'panel' },
menu: { parent: 'panel', glass: true, presets: 'panel' },
dialog: { parent: 'panel', glass: true, presets: 'panel' },
toast: { parent: 'panel', glass: true, presets: 'panel' },
hoverCard: { parent: 'panel', glass: true, presets: 'panel' },
sidebarCard: { parent: 'panel', glass: true, corner: true, presets: 'panel' },
badge: { size: [14, 24], corner: true, fontSize: SMALL, text: true },
pill: { fontSize: SMALL, text: true },
divider: {},
scrollbar: {},
profileHeader: {},
} as const satisfies Record<string, ComponentDef>;
export type ComponentId = keyof typeof COMPONENTS;
export const COMPONENT_IDS = Object.keys(COMPONENTS) as ComponentId[];
export type ThemeComponents = Partial<Record<ComponentId, ComponentTokens>>;
/** Clamp ranges of the tokens every component shares (the JSON Schema says the same; tested). */
export const TOKEN_LIMITS = {
radius: [0, 32], borderWidth: [0, 4], padX: [0, 32], padY: [0, 32], gap: [0, 24], weight: [100, 900],
tracking: [-0.05, 0.2], leading: [1.1, 2], angle: [0, 360], lift: [0, 4], scale: [0.96, 1.04],
} as const;
/** Named token bundles per family; a theme's own tokens win over its preset's. Frozen once shipped. */
export const PRESETS = {
button: {
pill: { radius: 'pill', borderWidth: 0 },
soft: { radius: 8, borderWidth: 0 },
square: { radius: 0, borderWidth: 1, borderStyle: 'solid' },
outline: { radius: 6, borderWidth: 1, borderStyle: 'solid', fill: 'transparent', text: 'text', borderColor: 'border' },
bevel: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', text: 'text', active: { shadow: 'inset' } },
gloss: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', shadow: 'soft' },
'flat-link': { radius: 0, borderWidth: 0, fill: 'transparent', text: 'accent', hover: { underline: true } },
},
post: {
flat: { radius: 0, borderWidth: 0, fill: 'transparent', shadow: 'none' },
card: { radius: 14, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface' },
bubble: { radius: 20, borderWidth: 0, fill: 'surface' },
window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface' },
ruled: { radius: 0, borderWidth: 0, fill: 'transparent' },
},
input: {
pill: { radius: 'pill', borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
underline: { radius: 0, borderWidth: 0, fill: 'transparent' },
sunken: { radius: 0, borderStyle: 'bevel-in', fill: 'bg', text: 'text' },
boxed: { radius: 4, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'bg' },
},
panel: {
sheet: { radius: 12, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'surface', shadow: 'soft' },
window: { radius: 0, borderStyle: 'bevel-out', fill: 'surface', shadow: 'none' },
glass: { radius: 16, borderWidth: 1, borderStyle: 'solid', borderColor: 'border', fill: 'glass', shadow: 'soft' },
},
tabs: {
underline: { radius: 0 },
pills: { radius: 'pill' },
folder: { radius: 6, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
blocks: { radius: 0, borderWidth: 1, borderStyle: 'solid', borderColor: 'border' },
},
} as const satisfies Record<string, Record<string, ComponentTokens>>;
// ---------------------------------------------------------------------------------------------
// Sanitizing
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
const clamp = (value: number, [min, max]: readonly [number, number]) => Math.min(max, Math.max(min, value));
const oneOf = <T extends string>(value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined;
const role = (value: unknown) => oneOf(value, COLOR_ROLES);
function sanitizeFill(value: unknown, def: ComponentDef): Fill | undefined {
if (value === 'transparent') return 'transparent';
if (value === 'glass') return def.glass ? 'glass' : undefined;
const named = role(value);
if (named) return named;
const source = obj(value);
const from = role(source.from), to = role(source.to);
if (def.gradient && from && to) return { from, to, angle: Math.round(clamp(finite(source.angle) ? source.angle : 180, TOKEN_LIMITS.angle)) };
return undefined;
}
function sanitizeState(value: unknown, def: ComponentDef): StateTokens | undefined {
const source = obj(value);
const out: StateTokens = {};
const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill;
const text = role(source.text); if (text) out.text = text;
const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor;
const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow;
if (finite(source.lift)) out.lift = +clamp(source.lift, TOKEN_LIMITS.lift).toFixed(1);
if (finite(source.scale)) out.scale = +clamp(source.scale, TOKEN_LIMITS.scale).toFixed(3);
if (typeof source.underline === 'boolean') out.underline = source.underline;
return Object.keys(out).length ? out : undefined;
}
/** One component's tokens from JSON: clamped, unknown names and tokens the component does not take dropped. */
export function sanitizeComponentTokens(id: ComponentId, value: unknown): ComponentTokens | undefined {
const def: ComponentDef = COMPONENTS[id];
const source = obj(value);
const out: ComponentTokens = {};
if (def.presets && typeof source.preset === 'string' && Object.hasOwn(PRESETS[def.presets], source.preset)) out.preset = source.preset;
if (source.radius === 'pill') out.radius = 'pill';
else if (finite(source.radius)) out.radius = Math.round(clamp(source.radius, TOKEN_LIMITS.radius));
if (finite(source.borderWidth)) out.borderWidth = +clamp(source.borderWidth, TOKEN_LIMITS.borderWidth).toFixed(1);
const borderStyle = oneOf(source.borderStyle, BORDER_STYLES); if (borderStyle) out.borderStyle = borderStyle;
const borderColor = role(source.borderColor); if (borderColor) out.borderColor = borderColor;
const fill = sanitizeFill(source.fill, def); if (fill !== undefined) out.fill = fill;
const text = role(source.text); if (text) out.text = text;
for (const key of ['padX', 'padY', 'gap'] as const) if (finite(source[key])) out[key] = Math.round(clamp(source[key] as number, TOKEN_LIMITS[key]));
for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) {
const range = def[key];
if (range && finite(source[key])) out[key] = Math.round(clamp(source[key] as number, range));
}
if (def.text || def.fontSize) {
const font = oneOf(source.font, FONT_ROLES); if (font) out.font = font;
if (finite(source.weight)) out.weight = Math.round(clamp(source.weight, TOKEN_LIMITS.weight) / 50) * 50;
const textCase = oneOf(source.case, CASES); if (textCase && id !== 'postText') out.case = textCase;
if (finite(source.tracking)) out.tracking = +clamp(source.tracking, TOKEN_LIMITS.tracking).toFixed(3);
if (finite(source.leading)) out.leading = +clamp(source.leading, TOKEN_LIMITS.leading).toFixed(2);
}
const shadow = oneOf(source.shadow, SHADOWS); if (shadow) out.shadow = shadow;
if (def.shape) { const shape = oneOf(source.shape, AVATAR_SHAPES); if (shape) out.shape = shape; }
if (def.corner) { const corner = oneOf(source.corner, CORNERS); if (corner) out.corner = corner; }
if (def.visible && typeof source.visible === 'boolean') out.visible = source.visible;
for (const state of ['hover', 'active', 'focus'] as const) { const tokens = sanitizeState(source[state], def); if (tokens) out[state] = tokens; }
return Object.keys(out).length ? out : undefined;
}
/** The `components` group from JSON. Null when nothing valid is left (the theme sets no component). */
export function sanitizeComponents(value: unknown): ThemeComponents | null {
const source = obj(value);
const out: ThemeComponents = {};
for (const id of COMPONENT_IDS) {
if (!Object.hasOwn(source, id)) continue;
const tokens = sanitizeComponentTokens(id, source[id]);
if (tokens) out[id] = tokens;
}
return Object.keys(out).length ? out : null;
}
/** Every component with its preset and its parent's tokens folded in (own tokens win, then the preset, then the parent). */
export function resolveComponents(components: ThemeComponents): ThemeComponents {
const expand = (id: ComponentId, tokens: ComponentTokens | undefined): ComponentTokens => {
if (!tokens) return {};
const def: ComponentDef = COMPONENTS[id];
const preset = tokens.preset && def.presets ? (PRESETS[def.presets] as Record<string, ComponentTokens>)[tokens.preset] : undefined;
const { preset: _name, ...own } = tokens;
return { ...preset, ...own };
};
const out: ThemeComponents = {};
for (const id of COMPONENT_IDS) {
const def: ComponentDef = COMPONENTS[id];
const parent = def.parent as ComponentId | undefined;
const inherited = parent ? expand(parent, components[parent]) : {};
const merged = { ...inherited, ...expand(id, components[id]) };
if (Object.keys(merged).length) out[id] = merged;
}
return out;
}
// ---------------------------------------------------------------------------------------------
// Compiling
/** A site's selectors for one component. */
export type PartDef = {
/** The component's box. */
sel: string;
/** Its text leaves (sites often put type on leaf spans); defaults to the box. */
text?: string;
/** Where a fill is painted when it is not the box itself. */
fill?: string;
/** Tokens the site cannot honor on this part (left out of the CSS). */
skip?: ReadonlyArray<keyof ComponentTokens>;
};
export type PartMap = Partial<Record<ComponentId, PartDef>>;
export type ComponentContext = {
/** Every role as `#rrggbb` (the theme's palette, legible). */
colors: RoleColors;
/** `font-family` per font role. */
fonts: Record<FontRoleName, string>;
};
const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${alpha})`;
const dark = (hex: string) => relativeLuminance(hex) < 0.18;
/** The most readable of the theme's text-capable roles on `fill`. */
export function readableRole(fill: string, colors: RoleColors, preferred?: ColorRole): ColorRole {
const candidates: ColorRole[] = ['text', 'onAccent', 'onInverse', 'bg', 'inverse'];
if (preferred && !candidates.includes(preferred)) candidates.unshift(preferred);
return candidates.reduce((best, candidate) => contrastRatio(colors[candidate], fill) > contrastRatio(colors[best], fill) ? candidate : best, preferred ?? 'text');
}
function fillCss(fill: Fill, colors: RoleColors): { decl: Array<[string, string]>; solid: string | null } {
if (fill === 'transparent') return { decl: [['background-color', 'transparent'], ['background-image', 'none']], solid: null };
if (fill === 'glass') return { decl: [['background-color', rgba(colors.surface, 0.72)], ['backdrop-filter', 'blur(14px) saturate(1.4)'], ['-webkit-backdrop-filter', 'blur(14px) saturate(1.4)']], solid: colors.surface };
if (typeof fill === 'string') return { decl: [['background-color', colors[fill]], ['background-image', 'none']], solid: colors[fill] };
// A gradient is judged at its less readable end: the midpoint stands in for both when choosing a label.
return { decl: [['background-color', colors[fill.to]], ['background-image', `linear-gradient(${fill.angle}deg, ${colors[fill.from]}, ${colors[fill.to]})`]], solid: mix(colors[fill.from], colors[fill.to], 0.5) };
}
/** Raised and sunken edges after 98.css: two light and two dark inset lines, from the part's own fill. */
function bevel(out: boolean, face: string): string {
const light = mix(face, '#ffffff', 0.85), soft = mix(face, '#ffffff', 0.35), shade = mix(face, '#000000', 0.35), deep = mix(face, '#000000', 0.9);
return out
? `inset -1px -1px ${deep}, inset 1px 1px ${light}, inset -2px -2px ${shade}, inset 2px 2px ${soft}`
: `inset -1px -1px ${light}, inset 1px 1px ${shade}, inset -2px -2px ${soft}, inset 2px 2px ${deep}`;
}
function shadowCss(name: typeof SHADOWS[number], colors: RoleColors): string {
const base = dark(colors.bg);
switch (name) {
case 'soft': return base ? `0 1px 2px ${rgba('#000000', 0.4)}, 0 8px 24px ${rgba('#000000', 0.35)}` : `0 1px 2px ${rgba('#000000', 0.06)}, 0 8px 24px ${rgba('#000000', 0.1)}`;
case 'deep': return `0 0 0 1px ${rgba(colors.border, 0.6)}, 0 24px 64px ${rgba('#000000', base ? 0.6 : 0.28)}`;
case 'hard': return `4px 4px 0 ${colors.accent}`;
case 'inset': return `inset 1px 1px 3px ${rgba('#000000', base ? 0.6 : 0.25)}`;
case 'glow': return `0 0 0 1px ${rgba(colors.accent, 0.5)}, 0 0 18px ${rgba(colors.accent, 0.35)}`;
default: return 'none';
}
}
const SHAPES: Record<typeof AVATAR_SHAPES[number], Array<[string, string]>> = {
circle: [['border-radius', '50%']],
rounded: [['border-radius', '26%']],
square: [['border-radius', '2px']],
squircle: [['border-radius', '34%']],
hexagon: [['border-radius', '0'], ['clip-path', 'polygon(25% 4%, 75% 4%, 100% 50%, 75% 96%, 25% 96%, 0 50%)']],
octagon: [['border-radius', '0'], ['clip-path', 'polygon(30% 0, 70% 0, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0 70%, 0 30%)']],
diamond: [['border-radius', '0'], ['clip-path', 'polygon(50% 0, 100% 50%, 50% 100%, 0 50%)']],
};
const CASE_CSS: Record<typeof CASES[number], Array<[string, string]>> = {
none: [['text-transform', 'none'], ['font-variant-caps', 'normal']],
upper: [['text-transform', 'uppercase']],
lower: [['text-transform', 'lowercase']],
capitalize: [['text-transform', 'capitalize']],
'small-caps': [['text-transform', 'none'], ['font-variant-caps', 'all-small-caps']],
};
/** A part rule's selector: two `:root`s lift it over the site's atomic classes and inline styles' non-important values. */
export const partRule = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `:root:root ${one.trim()}`).join(',');
export type CompiledComponents = {
/** `--wb-part-*` declarations (for `:where(:root)`). */
values: string[];
/** Rules that read them. */
rules: string[];
/** What the contrast pass changed, for import notes and the builder's report. */
notes: string[];
};
/**
* CSS for a theme's components over a site's part map. A component without a part, and a token the
* part skips, emits nothing. Text on a fill the theme chose is held to the component's contrast
* (the text role is swapped for the most readable one); sizes stay at or above a 24px target.
*/
export function compileComponents(components: ThemeComponents, parts: PartMap, ctx: ComponentContext): CompiledComponents {
const values: string[] = [], rules: string[] = [], notes: string[] = [];
const resolved = resolveComponents(components);
for (const id of COMPONENT_IDS) {
const tokens = resolved[id], part = parts[id];
if (!tokens || !part) continue;
const def: ComponentDef = COMPONENTS[id];
const skip = new Set<string>(part.skip ?? []);
const has = <K extends keyof ComponentTokens>(key: K): boolean => tokens[key] !== undefined && !skip.has(key);
const box: string[] = [], type: string[] = [], fillRule: string[] = [];
const put = (list: string[], token: string, property: string, value: string) => {
const name = `--wb-part-${id}-${token}`;
if (!values.some(item => item.startsWith(`${name}:`))) values.push(`${name}:${value}`);
list.push(`${property}:var(${name}) !important`);
};
// Fill first: the text role depends on it.
let face: string | null = null;
if (has('fill')) {
const { decl, solid } = fillCss(tokens.fill!, ctx.colors);
face = solid;
decl.forEach(([property, value], index) => put(part.fill ? fillRule : box, `fill${index ? `-${index}` : ''}`, property, value));
}
let textRole = has('text') ? tokens.text! : undefined;
if (face && (def.text || textRole)) {
const need = def.contrast ?? 4.5;
if (!textRole || contrastRatio(ctx.colors[textRole], face) < need) {
const readable = readableRole(face, ctx.colors, textRole);
if (textRole && readable !== textRole) notes.push(`${id}: text "${textRole}" on its fill is under ${need}:1, using "${readable}"`);
textRole = readable;
}
}
if (textRole) put(type, 'text', 'color', ctx.colors[textRole]);
if (has('radius')) put(box, 'radius', 'border-radius', tokens.radius === 'pill' ? '9999px' : `${tokens.radius}px`);
const style = has('borderStyle') ? tokens.borderStyle! : undefined;
if (style === 'bevel-out' || style === 'bevel-in') {
const base = face ?? ctx.colors.surface;
put(box, 'border-style', 'border-style', 'none');
put(box, 'bevel', 'box-shadow', bevel(style === 'bevel-out', base));
} else {
if (style) put(box, 'border-style', 'border-style', style);
if (has('borderWidth')) put(box, 'border-width', 'border-width', `${tokens.borderWidth}px`);
// A width without a style would draw nothing: X's boxes are `border: 0 solid`.
if (has('borderWidth') && !style && tokens.borderWidth! > 0) put(box, 'border-style', 'border-style', 'solid');
if (has('shadow')) put(box, 'shadow', 'box-shadow', shadowCss(tokens.shadow!, ctx.colors));
}
if (has('borderColor')) put(box, 'border-color', 'border-color', ctx.colors[tokens.borderColor!]);
if (has('padX')) put(box, 'pad-x', 'padding-inline', `${tokens.padX}px`);
if (has('padY')) put(box, 'pad-y', 'padding-block', `${tokens.padY}px`);
if (has('gap')) put(box, 'gap', 'gap', `${tokens.gap}px`);
if (has('height')) put(box, 'height', 'min-height', `${Math.max(24, tokens.height!)}px`);
if (has('width')) put(box, 'width', 'width', `${tokens.width}px`);
if (has('size')) { put(box, 'size', 'width', `${tokens.size}px`); box.push(`height:var(--wb-part-${id}-size) !important`); }
if (has('maxHeight')) put(box, 'max-height', 'max-height', `${tokens.maxHeight}px`);
if (has('shape')) SHAPES[tokens.shape!].forEach(([property, value], index) => put(box, `shape${index ? `-${index}` : ''}`, property, value));
if (has('corner') && tokens.corner === 'cut') put(box, 'corner', 'clip-path', 'polygon(0 0, calc(100% - 12px) 0, 100% 12px, 100% 100%, 12px 100%, 0 calc(100% - 12px))');
if (has('visible') && tokens.visible === false) put(box, 'display', 'display', 'none');
if (has('font')) put(type, 'font', 'font-family', ctx.fonts[tokens.font!]);
if (has('fontSize')) {
put(type, 'font-size', 'font-size', `${tokens.fontSize}px`);
put(type, 'line-height', 'line-height', String(tokens.leading ?? 1.3));
} else if (has('leading')) put(type, 'line-height', 'line-height', String(tokens.leading));
if (has('weight')) put(type, 'weight', 'font-weight', String(tokens.weight));
if (has('case')) CASE_CSS[tokens.case!].forEach(([property, value], index) => put(type, `case${index ? `-${index}` : ''}`, property, value));
if (has('tracking')) put(type, 'tracking', 'letter-spacing', `${tokens.tracking}em`);
const textSel = part.text ?? part.sel;
if (box.length) rules.push(`${partRule(part.sel)}{${box.join(';')}}`);
if (fillRule.length) rules.push(`${partRule(part.fill!)}{${fillRule.join(';')}}`);
if (type.length) rules.push(`${partRule(textSel)}{${type.join(';')}}`);
for (const state of ['hover', 'active', 'focus'] as const) {
const tokensOf = tokens[state];
if (!tokensOf || skip.has(state)) continue;
const pseudo = state === 'focus' ? ':focus-visible' : `:${state}`;
const still: string[] = [], moving: string[] = [], label: string[] = [];
let stateFace = face;
if (tokensOf.fill !== undefined) { const { decl, solid } = fillCss(tokensOf.fill, ctx.colors); stateFace = solid ?? face; for (const [property, value] of decl) still.push(`${property}:${value} !important`); }
let stateText = tokensOf.text;
if (stateFace && (stateText || tokensOf.fill !== undefined) && (def.text || stateText)) {
if (!stateText || contrastRatio(ctx.colors[stateText], stateFace) < (def.contrast ?? 4.5)) stateText = readableRole(stateFace, ctx.colors, stateText);
}
if (stateText) label.push(`color:${ctx.colors[stateText]} !important`);
if (tokensOf.underline !== undefined) label.push(`text-decoration:${tokensOf.underline ? 'underline' : 'none'} !important`);
if (tokensOf.borderColor) still.push(`border-color:${ctx.colors[tokensOf.borderColor]} !important`);
if (tokensOf.shadow) still.push(`box-shadow:${tokensOf.shadow === 'inset' && (style === 'bevel-out' || style === 'bevel-in') ? bevel(false, face ?? ctx.colors.surface) : shadowCss(tokensOf.shadow, ctx.colors)} !important`);
const transforms = [tokensOf.lift ? `translateY(-${tokensOf.lift}px)` : '', tokensOf.scale && tokensOf.scale !== 1 ? `scale(${tokensOf.scale})` : ''].filter(Boolean);
if (transforms.length) moving.push(`transform:${transforms.join(' ')} !important`);
const stateSel = (selector: string) => selector.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo}`).join(',');
if (still.length) rules.push(`${partRule(stateSel(part.sel))}{${still.join(';')}}`);
// The label of a hovered or pressed part: the box and the text leaves under it.
if (label.length) rules.push(`${partRule(`${stateSel(part.sel)},${part.sel.split(/,(?![^(]*\))/).map(one => `${one.trim()}${pseudo} :is(span,div,a)`).join(',')}`)}{${label.join(';')}}`);
// Movement only for people who have not asked for less of it.
if (moving.length) rules.push(`@media (prefers-reduced-motion:no-preference){${partRule(stateSel(part.sel))}{${moving.join(';')}}}`);
}
}
return { values, rules, notes };
}
/** The `colors.actions` group: the colors of an on state (liked, reposted, bookmarked) and of the reply hover. */
export const ACTION_NAMES = ['reply', 'repost', 'like', 'bookmark'] as const;
export type ActionColors = Partial<Record<typeof ACTION_NAMES[number], string>>;

View file

@ -0,0 +1,154 @@
// Decoration: what a theme draws between and around the components: divider lines, a title bar or a
// masthead, the focus ring, selection, scrollbars, link underlines, the feel of motion. Fixed words
// and clamped numbers, colors by role. Where the lines and bars go is the site's (its decor targets).
// Pure.
import { contrastRatio } from './themeApi.ts';
import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts';
export const DIVIDER_STYLES = ['none', 'hairline', 'solid', 'dashed', 'dotted', 'double'] as const;
export const CHROME_KINDS = ['none', 'titlebar', 'masthead', 'prompt'] as const;
export const RING_STYLES = ['solid', 'dashed', 'dotted', 'double'] as const;
export const MOTION_CURVES = ['standard', 'snappy', 'spring', 'linear', 'steps'] as const;
export const LINK_UNDERLINES = ['always', 'hover', 'never'] as const;
export type ThemeDecor = {
dividers?: { style: typeof DIVIDER_STYLES[number]; color?: ColorRole; width?: number };
/** A drawn frame around the main column: a window title bar, a newspaper masthead, a terminal prompt. `title` is plain text. */
chrome?: { kind: typeof CHROME_KINDS[number]; title?: string };
focusRing?: { width?: number; style?: typeof RING_STYLES[number]; color?: ColorRole; offset?: number };
selection?: { fill: ColorRole; text: ColorRole };
scrollbar?: { width?: 'auto' | 'thin'; thumb?: ColorRole; track?: ColorRole; style?: 'flat' | 'classic' };
links?: { underline: typeof LINK_UNDERLINES[number] };
motion?: { duration?: number; curve?: typeof MOTION_CURVES[number]; press?: number };
};
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const oneOf = <T extends string>(value: unknown, options: readonly T[]): T | undefined => options.includes(value as T) ? value as T : undefined;
const num = (value: unknown, min: number, max: number): number | undefined => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : undefined;
const role = (value: unknown) => oneOf(value, COLOR_ROLES);
/** Text a theme may put into a drawn bar: letters, digits, spaces and a little punctuation; it is written into a CSS string. */
export const chromeTitle = (value: unknown) => typeof value === 'string' ? value.replace(/[^\p{L}\p{N} .,:!?&+\-_/#@*~()[\]|>$]/gu, '').replace(/&/g, '+').trim().slice(0, 24) : '';
/** The `decor` group from JSON. Null when nothing valid is left. */
export function sanitizeDecor(value: unknown): ThemeDecor | null {
const source = obj(value);
const out: ThemeDecor = {};
const dividers = obj(source.dividers), dividerStyle = oneOf(dividers.style, DIVIDER_STYLES);
if (dividerStyle) {
const color = role(dividers.color), width = num(dividers.width, 0, 3);
out.dividers = { style: dividerStyle, ...(color ? { color } : {}), ...(width !== undefined ? { width: +width.toFixed(1) } : {}) };
}
const chrome = obj(source.chrome), kind = oneOf(chrome.kind, CHROME_KINDS);
if (kind && kind !== 'none') { const title = chromeTitle(chrome.title); out.chrome = { kind, ...(title ? { title } : {}) }; }
const ring = obj(source.focusRing);
if (Object.keys(ring).length) {
const width = num(ring.width, 2, 4), style = oneOf(ring.style, RING_STYLES), color = role(ring.color), offset = num(ring.offset, 0, 4);
const focusRing = { ...(width !== undefined ? { width: Math.round(width) } : {}), ...(style ? { style } : {}), ...(color ? { color } : {}), ...(offset !== undefined ? { offset: Math.round(offset) } : {}) };
if (Object.keys(focusRing).length) out.focusRing = focusRing;
}
const selection = obj(source.selection), fill = role(selection.fill), text = role(selection.text);
if (fill && text) out.selection = { fill, text };
const bar = obj(source.scrollbar);
if (Object.keys(bar).length) {
const width = oneOf(bar.width, ['auto', 'thin'] as const), thumb = role(bar.thumb), track = role(bar.track), style = oneOf(bar.style, ['flat', 'classic'] as const);
const scrollbar = { ...(width ? { width } : {}), ...(thumb ? { thumb } : {}), ...(track ? { track } : {}), ...(style ? { style } : {}) };
if (Object.keys(scrollbar).length) out.scrollbar = scrollbar;
}
const underline = oneOf(obj(source.links).underline, LINK_UNDERLINES);
if (underline) out.links = { underline };
const motion = obj(source.motion);
if (Object.keys(motion).length) {
const duration = num(motion.duration, 0, 400), curve = oneOf(motion.curve, MOTION_CURVES), press = num(motion.press, 0.96, 1);
const value = { ...(duration !== undefined ? { duration: Math.round(duration) } : {}), ...(curve ? { curve } : {}), ...(press !== undefined ? { press: +press.toFixed(3) } : {}) };
if (Object.keys(value).length) out.motion = value;
}
return Object.keys(out).length ? out : null;
}
/** Where a site's decoration goes. Every entry is optional: a site without it draws nothing for that key. */
export type DecorTargets<Context> = {
/** Rows whose bottom edge is the divider between items (a site's list cells). */
divider?: string;
/** Links inside running text. */
link?: string;
/** What takes keyboard focus. */
focusable?: string;
/** What moves with `motion` (buttons, links, rows). */
moving?: string;
/** What a press shrinks. */
pressable?: string;
/** The scrollable roots. */
scroller?: string;
/** The site's drawing of each chrome kind. */
chrome?: Partial<Record<Exclude<typeof CHROME_KINDS[number], 'none'>, (title: string, ctx: Context) => string>>;
};
const CURVES: Record<typeof MOTION_CURVES[number], string> = {
standard: 'cubic-bezier(.2,.7,.2,1)', snappy: 'cubic-bezier(.3,1.4,.5,1)', spring: 'cubic-bezier(.2,1.6,.4,1)', linear: 'linear', steps: 'steps(3,end)',
};
/** The role among `candidates` that reaches `ratio` on every surface, else the most visible one. */
function visibleOn(colors: RoleColors, wanted: ColorRole, surfaces: string[], ratio: number): string {
const worst = (hex: string) => Math.min(...surfaces.map(surface => contrastRatio(hex, surface)));
if (worst(colors[wanted]) >= ratio) return colors[wanted];
return (['accent', 'text', 'inverse'] as ColorRole[]).map(name => colors[name]).reduce((best, hex) => worst(hex) > worst(best) ? hex : best, colors[wanted]);
}
/**
* CSS for a theme's decoration. A focus ring is always drawn when the theme names one (at least 2px
* and 3:1 on the page's surfaces: the color is swapped for a visible one otherwise); motion only
* for people who have not asked for less of it.
*/
export function compileDecor<Context extends { colors: RoleColors }>(decor: ThemeDecor, targets: DecorTargets<Context>, ctx: Context): string[] {
const out: string[] = [];
const { colors } = ctx;
const surfaces = [colors.bg, colors.surface, colors.page];
if (decor.dividers && targets.divider) {
const { style, color = 'border', width } = decor.dividers;
const line = style === 'none' ? '0 none' : `${style === 'hairline' ? 1 : width ?? (style === 'double' ? 3 : 1)}px ${style === 'hairline' ? 'solid' : style} ${colors[color]}`;
out.push(`:root:root :is(${targets.divider}){border-bottom:${line} !important}`);
}
if (decor.focusRing && targets.focusable) {
const { width = 2, style = 'solid', color = 'accent', offset = 2 } = decor.focusRing;
out.push(`:root:root :is(${targets.focusable}):focus-visible{outline:${Math.max(2, width)}px ${style} ${visibleOn(colors, color, surfaces, 3)} !important;outline-offset:${offset}px !important}`);
}
if (decor.selection) {
const fill = colors[decor.selection.fill];
const text = contrastRatio(colors[decor.selection.text], fill) >= 4.5 ? colors[decor.selection.text] : (contrastRatio('#ffffff', fill) >= contrastRatio('#000000', fill) ? '#ffffff' : '#000000');
out.push(`:root:root ::selection{background-color:${fill} !important;color:${text} !important}`);
}
if (decor.scrollbar) {
const { width, thumb = 'border', track, style } = decor.scrollbar;
const scroller = targets.scroller ?? 'html,body';
const thumbColor = visibleOn(colors, thumb, [track ? colors[track] : colors.page], 1.5);
out.push(`:root:root :is(${scroller}){scrollbar-color:${thumbColor} ${track ? colors[track] : 'transparent'} !important${width ? `;scrollbar-width:${width} !important` : ''}}`);
// The classic look needs the engine's own scrollbar parts; `scrollbar-color` would switch them off where both are set.
if (style === 'classic') {
const face = track ? colors[track] : colors.surface;
out.push(`@supports selector(::-webkit-scrollbar){:root:root :is(${scroller}){scrollbar-color:auto !important;scrollbar-width:auto !important}:root:root ::-webkit-scrollbar{width:16px;height:16px;background:${face}}:root:root ::-webkit-scrollbar-thumb{background:${colors.surface};box-shadow:inset -1px -1px ${colors.text},inset 1px 1px ${colors.bg},inset -2px -2px ${colors.muted},inset 2px 2px ${colors.elevated}}:root:root ::-webkit-scrollbar-corner{background:${face}}}`);
}
}
if (decor.links && targets.link) {
const { underline } = decor.links;
out.push(`:root:root :is(${targets.link}){text-decoration:${underline === 'always' ? 'underline' : 'none'} !important;text-underline-offset:2px}`);
if (underline === 'hover') out.push(`:root:root :is(${targets.link}):hover{text-decoration:underline !important}`);
}
if (decor.motion && (targets.moving || targets.pressable)) {
const { duration, curve = 'standard', press } = decor.motion;
const rules: string[] = [];
if (duration !== undefined && targets.moving) {
rules.push(`:root:root :is(${targets.moving}){transition:background-color ${duration}ms ${CURVES[curve]},color ${duration}ms ${CURVES[curve]},border-color ${duration}ms ${CURVES[curve]},box-shadow ${duration}ms ${CURVES[curve]},transform ${duration}ms ${CURVES[curve]} !important}`);
}
if (press !== undefined && press < 1 && targets.pressable) rules.push(`:root:root :is(${targets.pressable}):active{transform:scale(${press}) !important}`);
if (rules.length) out.push(`@media (prefers-reduced-motion:no-preference){${rules.join('')}}`);
}
if (decor.chrome) {
const css = targets.chrome?.[decor.chrome.kind as Exclude<typeof CHROME_KINDS[number], 'none'>]?.(decor.chrome.title ?? '', ctx);
if (css) out.push(css);
}
return out;
}
/** A theme's text as a CSS string literal (for `content`): the allow-list of `chromeTitle` plus escaping of what could end the string. */
export const cssString = (value: string) => `"${value.replace(/[\\"\n\r\f]/g, match => `\\${match.charCodeAt(0).toString(16)} `)}"`;

View file

@ -0,0 +1,57 @@
// The theme doctor: advice, never a block. A theme may do anything its trust level allows; the doctor
// points at the lighter mechanism for what the theme does (a token before a component setting, a
// component setting before CSS, CSS before a script) and at performance, accessibility and contrast
// costs. Used by the import screen, the Theme Builder's report and `waybetter store check`. Pure.
import { contrastRatio } from './themeApi.ts';
import { ensureContrast, type ThemeSpec } from './themeSpec.ts';
export type DoctorAdvice = {
/** `lighter`: a lighter mechanism would do; `performance`, `accessibility`, `contrast`: a cost. */
kind: 'lighter' | 'performance' | 'accessibility' | 'contrast';
/** Stable id, for tests and translations (`wb.doctor.<id>`). */
id: string;
/** English text (the panel translates by id when it has the words). */
text: string;
};
type Rule = { id: string; kind: DoctorAdvice['kind']; test: RegExp; text: string };
/** What a theme's free-form CSS does that a v2 group does without CSS. */
const CSS_RULES: Rule[] = [
{ id: 'css-radius', kind: 'lighter', test: /border-radius\s*:/i, text: 'Corner radii: components.<part>.radius (or shape.radius) sets them without CSS and keeps working when the site renames its classes.' },
{ id: 'css-bevel', kind: 'lighter', test: /box-shadow\s*:[^;{}]*inset[^;{}]*inset[^;{}]*inset/i, text: 'Bevelled edges: components.<part>.borderStyle "bevel-out" / "bevel-in" draws them from the theme\'s colors.' },
{ id: 'css-hide', kind: 'lighter', test: /display\s*:\s*none/i, text: 'Hiding a part: components.<part>.visible (avatars, counts, names) or a layout variant (sidebar: hidden) does it, and the owner can switch it back.' },
{ id: 'css-color', kind: 'lighter', test: /(?:^|[;{\s])(?:color|background(?:-color)?)\s*:\s*#[0-9a-f]{3,8}/i, text: 'Literal colors: name a role (text, muted, accent, surface…) in colors or in a component, so the contrast pass covers it.' },
{ id: 'css-font', kind: 'lighter', test: /font-family\s*:/i, text: 'Fonts: font.roles sets the post, heading, numbers and mono faces without CSS.' },
{ id: 'css-has', kind: 'performance', test: /:has\(/i, text: ':has() is matched again on every change of the page; keep it off rules that repeat down a timeline.' },
{ id: 'css-universal', kind: 'performance', test: /(?:^|[\s,>+~])\*\s*(?:[,{>+~:\[]|$)/m, text: 'A universal selector (*) is matched against every element; anchor the rule on a part.' },
{ id: 'css-blur', kind: 'performance', test: /backdrop-filter\s*:/i, text: 'Blur (backdrop-filter) is costly on parts that repeat; the glass fill of bars and panels is the cheaper place for it.' },
{ id: 'css-outline-none', kind: 'accessibility', test: /outline\s*:\s*(?:none|0)\b/i, text: 'Removing the outline hides where keyboard focus is; decor.focusRing draws a visible one instead.' },
{ id: 'css-motion', kind: 'accessibility', test: /(?:animation|transition)\s*:/i, text: 'Motion should stay inside @media (prefers-reduced-motion: no-preference); decor.motion does that for you.' },
];
/** Advice for a theme document. Empty when there is nothing to say. */
export function themeDoctor(theme: ThemeSpec): DoctorAdvice[] {
const out: DoctorAdvice[] = [];
const css = theme.css ?? '';
if (css.trim()) {
for (const rule of CSS_RULES) if (rule.test.test(css)) out.push({ kind: rule.kind, id: rule.id, text: rule.text });
if (css.length > 20_000) out.push({ kind: 'performance', id: 'css-size', text: 'More than 20,000 characters of CSS: the site recalculates styles with every rule; tokens and component settings compile to fewer rules.' });
}
if (theme.colors) {
const fixed = ensureContrast(theme.colors);
for (const role of ['text', 'muted', 'accent'] as const) {
if (fixed[role] !== theme.colors[role]) out.push({ kind: 'contrast', id: `contrast-${role}`, text: `The ${role} color was adjusted to stay readable (${contrastRatio(theme.colors[role], theme.colors.bg).toFixed(2)}:1 on the background).` });
}
}
if (theme.components) {
const posts = theme.components.post;
if (posts?.fill === 'glass') out.push({ kind: 'performance', id: 'glass-post', text: 'Glass on posts is not drawn: blur on every post of a timeline is too costly.' });
const text = theme.components.postText?.fontSize;
if (text !== undefined && text < 14) out.push({ kind: 'accessibility', id: 'small-post-text', text: 'Post text under 14px is hard to read for many people.' });
}
if (theme.variants?.nav === 'top' || theme.variants?.nav === 'bottom') {
out.push({ kind: 'accessibility', id: 'nav-moved', text: 'Moving the navigation changes where people look for it; it only applies on wide panes, and the owner can turn layout changes off.' });
}
return out;
}

View file

@ -0,0 +1,296 @@
// Icon packs: a standalone document (`*.icons.json`) of glyphs by semantic name (`home`, `like`,
// `reply`), drawn over a site's own icons. A theme only names a pack (a suggestion); the owner's icon
// choice is separate ("Follow the theme", a pack, or the site's own icons). Pure.
//
// A pack is data, never an SVG document: a glyph is path data (checked against a path grammar), a few
// colored layers of path data, or a small PNG. The engine builds the SVG itself, so no element,
// attribute, script or reference can arrive with a pack.
//
// Drawing: nothing in the site's DOM is rewritten. The site's own `<svg>` box gets the glyph as a CSS
// mask filled with `currentColor` (so the site's color states keep working: a liked heart stays the
// like color) and its own paths are made transparent. Colored glyphs (layers, PNG) are a background
// image instead. Which `<svg>` is which icon is the site's table (container first, path signature
// second). No glyph, no match or no pack: no rule, the site's icon stays.
import { COLOR_ROLES, type ColorRole, type RoleColors } from './themeComponents.ts';
/** Semantic names a pack may draw. `.active` is a selected navigation item, `.on` an action that is set. */
export const ICON_NAMES = [
'home', 'home.active', 'explore', 'explore.active', 'notifications', 'notifications.active', 'messages', 'messages.active',
'grok', 'bookmarks', 'bookmarks.active', 'lists', 'communities', 'premium', 'profile', 'profile.active', 'more', 'compose',
'reply', 'repost', 'repost.on', 'like', 'like.on', 'views', 'bookmark', 'bookmark.on', 'share',
'verified', 'logo', 'caret', 'back', 'close', 'search', 'settings',
'media', 'gif', 'poll', 'emoji', 'schedule', 'location', 'pinned', 'repostContext', 'lock',
] as const;
export type IconName = typeof ICON_NAMES[number];
export const ICON_GROUPS = ['nav', 'actions', 'composer', 'misc'] as const;
export type IconGroup = typeof ICON_GROUPS[number];
/** Limits of a pack (the JSON Schema and the Store check say the same). */
export const ICON_LIMITS = { names: 64, pathChars: 4000, layers: 6, pngChars: 6000, packBytes: 120_000, labelChars: 12, overrides: 8 } as const;
/** Path data only: commands, numbers, separators. */
export const PATH_GRAMMAR = /^[MmLlHhVvCcSsQqTtAaZz0-9eE\s,.+-]{1,4000}$/;
const PNG_DATA = /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/;
const HEX = /^#[0-9a-f]{6}$/i;
/** Words a theme or pack may put next to an action: written into CSS strings. */
const LABEL_TEXT = /^[\p{L}\p{N} [\]().:+\-_/#@*~!?]{1,12}$/u;
export type IconFill = ColorRole | string | { from: string; to: string };
export type IconGlyph =
| { d: string; rule?: 'evenodd'; stroke?: boolean }
| { layers: Array<{ d: string; fill: IconFill; opacity?: number; rule?: 'evenodd' }> }
| { png: string; pixel?: boolean };
export type IconStyle = { stroke: number; cap: 'round' | 'square' | 'butt'; join: 'round' | 'miter' | 'bevel'; scale: number };
export const BASE_ICON_STYLE: IconStyle = { stroke: 1.75, cap: 'round', join: 'round', scale: 1 };
export const ICON_LABEL_NAMES = ['reply', 'repost', 'like', 'views', 'bookmark', 'share'] as const;
export type IconLabels = Partial<Record<typeof ICON_LABEL_NAMES[number], string>>;
export type IconSymbols = { like?: 'heart' | 'star' | 'custom'; separator?: 'dot' | 'bullet' | 'slash' | 'dash' | 'pipe' | 'none' };
export type IconPack = {
id: string;
name: string;
description: string;
author: string;
/** SPDX id, or `own` for the author's own drawings, or a plain name for artwork under other terms. */
license: string;
/** Where the drawings come from (a project name or URL as text) and whom to credit. */
source: string;
credits: string;
version: 1;
style: IconStyle;
glyphs: Partial<Record<IconName, IconGlyph>>;
symbols?: IconSymbols;
labels?: IconLabels;
};
/** What a theme says about icons: a pack by id, plus small adjustments. Never a whole pack. */
export type ThemeIcons = { pack?: string; style?: Partial<IconStyle>; overrides?: Partial<Record<IconName, IconGlyph>>; symbols?: IconSymbols; labels?: IconLabels };
const obj = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const plain = (value: unknown, max: number) => typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f<>]/g, '').trim().slice(0, max) : '';
const num = (value: unknown, min: number, max: number, fallback: number) => typeof value === 'number' && Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
const path = (value: unknown): value is string => typeof value === 'string' && PATH_GRAMMAR.test(value);
function sanitizeFill(value: unknown): IconFill | null {
if (typeof value === 'string') return (COLOR_ROLES as readonly string[]).includes(value) ? value : HEX.test(value) ? value.toLowerCase() : null;
const source = obj(value);
return typeof source.from === 'string' && typeof source.to === 'string' && HEX.test(source.from) && HEX.test(source.to) ? { from: source.from.toLowerCase(), to: source.to.toLowerCase() } : null;
}
/** One glyph from JSON, or null when it is not valid path data, layers or a small PNG. */
export function sanitizeGlyph(value: unknown): IconGlyph | null {
const source = obj(value);
if (path(source.d)) return { d: source.d.trim(), ...(source.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}), ...(source.stroke === true ? { stroke: true } : {}) };
if (Array.isArray(source.layers)) {
const layers = source.layers.slice(0, ICON_LIMITS.layers).flatMap(raw => {
const layer = obj(raw), fill = sanitizeFill(layer.fill);
if (!path(layer.d) || !fill) return [];
return [{ d: layer.d.trim(), fill, ...(typeof layer.opacity === 'number' ? { opacity: +num(layer.opacity, 0, 1, 1).toFixed(2) } : {}), ...(layer.rule === 'evenodd' ? { rule: 'evenodd' as const } : {}) }];
});
return layers.length ? { layers } : null;
}
if (typeof source.png === 'string' && source.png.length <= ICON_LIMITS.pngChars + 22 && PNG_DATA.test(source.png)) return { png: source.png, ...(source.pixel === true ? { pixel: true } : {}) };
return null;
}
export const sanitizeIconStyle = (value: unknown, base: IconStyle = BASE_ICON_STYLE): IconStyle => {
const source = obj(value);
const pick = <T extends string>(item: unknown, options: readonly T[], fallback: T) => options.includes(item as T) ? item as T : fallback;
return {
stroke: +num(source.stroke, 1, 2.5, base.stroke).toFixed(2), cap: pick(source.cap, ['round', 'square', 'butt'] as const, base.cap),
join: pick(source.join, ['round', 'miter', 'bevel'] as const, base.join), scale: +num(source.scale, 0.8, 1.25, base.scale).toFixed(2),
};
};
function sanitizeGlyphs(value: unknown, max: number): Partial<Record<IconName, IconGlyph>> {
const source = obj(value);
const out: Partial<Record<IconName, IconGlyph>> = {};
let count = 0;
for (const name of ICON_NAMES) {
if (count >= max || !Object.hasOwn(source, name)) continue;
const glyph = sanitizeGlyph(source[name]);
if (glyph) { out[name] = glyph; count++; }
}
return out;
}
function sanitizeSymbols(value: unknown): IconSymbols | undefined {
const source = obj(value);
const out: IconSymbols = {};
if (source.like === 'heart' || source.like === 'star' || source.like === 'custom') out.like = source.like;
if (['dot', 'bullet', 'slash', 'dash', 'pipe', 'none'].includes(source.separator as string)) out.separator = source.separator as IconSymbols['separator'];
return Object.keys(out).length ? out : undefined;
}
function sanitizeLabels(value: unknown): IconLabels | undefined {
const source = obj(value);
const out: IconLabels = {};
for (const name of ICON_LABEL_NAMES) if (typeof source[name] === 'string' && LABEL_TEXT.test(source[name] as string)) out[name] = (source[name] as string).trim();
return Object.keys(out).length ? out : undefined;
}
/** Any JSON to a valid pack, or null when it has no id, no name or no valid glyph. */
export function sanitizeIconPack(input: unknown): IconPack | null {
const source = obj(input);
const name = plain(source.name, 60);
const id = typeof source.id === 'string' && /^[a-z0-9-]{1,40}$/.test(source.id) ? source.id : '';
const glyphs = sanitizeGlyphs(source.glyphs, ICON_LIMITS.names);
if (!id || !name || !Object.keys(glyphs).length) return null;
const symbols = sanitizeSymbols(source.symbols), labels = sanitizeLabels(source.labels);
return {
id, name, description: plain(source.description, 200), author: plain(source.author, 60), license: plain(source.license, 60) || 'unknown',
source: plain(source.source, 200), credits: plain(source.credits, 400), version: 1, style: sanitizeIconStyle(source.style), glyphs,
...(symbols ? { symbols } : {}), ...(labels ? { labels } : {}),
};
}
/** Parses an imported `*.icons.json`; errors are human-readable. */
export function parseIconPackJson(json: string): { pack: IconPack; warnings: string[] } | { error: string } {
if (json.length > ICON_LIMITS.packBytes) return { error: 'This icon pack is larger than 120 KB.' };
let raw: unknown;
try { raw = JSON.parse(json); } catch { return { error: 'This file is not valid JSON.' }; }
const pack = sanitizeIconPack(raw);
if (!pack) return { error: 'An icon pack needs an "id", a "name" and at least one valid glyph.' };
const dropped = Object.keys(obj(obj(raw).glyphs)).length - Object.keys(pack.glyphs).length;
const warnings: string[] = [];
if (dropped > 0) warnings.push(`${dropped} glyph(s) were ignored: unknown names, or drawings that are not plain path data.`);
if (pack.license === 'unknown') warnings.push('This pack does not say under which license its drawings are.');
return { pack, warnings };
}
/** The `icons` group of a theme from JSON. Null when it says nothing valid. */
export function sanitizeThemeIcons(value: unknown): ThemeIcons | null {
const source = obj(value);
const out: ThemeIcons = {};
if (typeof source.pack === 'string' && /^[a-z0-9-]{1,40}$/.test(source.pack)) out.pack = source.pack;
if (Object.keys(obj(source.style)).length) {
const style = obj(source.style), full = sanitizeIconStyle(style);
out.style = Object.fromEntries((['stroke', 'cap', 'join', 'scale'] as const).filter(key => key in style).map(key => [key, full[key]])) as Partial<IconStyle>;
}
const overrides = sanitizeGlyphs(source.overrides, ICON_LIMITS.overrides);
if (Object.keys(overrides).length) out.overrides = overrides;
const symbols = sanitizeSymbols(source.symbols); if (symbols) out.symbols = symbols;
const labels = sanitizeLabels(source.labels); if (labels) out.labels = labels;
return Object.keys(out).length ? out : null;
}
// ---------------------------------------------------------------------------------------------
// The owner's choice and the catalog
/** `theme`: follow the theme's suggestion; `site`: the site's own icons; otherwise a pack id. */
export type IconChoice = 'theme' | 'site' | string;
export const normalizeIconChoice = (value: unknown): IconChoice => typeof value === 'string' && /^[a-z0-9-]{1,40}$/.test(value) ? value : 'theme';
export type IconCatalog = {
packs: readonly IconPack[];
get(id: string | undefined): IconPack | null;
/** The pack that is drawn: the owner's pick, else the theme's suggestion; null for the site's own icons or an unknown pack. */
resolve(choice: IconChoice, theme: ThemeIcons | null | undefined): IconPack | null;
};
export function createIconCatalog(builtins: readonly IconPack[], installed: readonly IconPack[] = []): IconCatalog {
const packs = [...builtins, ...installed.filter(pack => !builtins.some(item => item.id === pack.id))];
const get = (id: string | undefined) => packs.find(pack => pack.id === id) ?? null;
return { packs, get, resolve: (choice, theme) => choice === 'site' ? null : choice === 'theme' ? get(theme?.pack) : get(choice) };
}
// ---------------------------------------------------------------------------------------------
// Drawing
const esc = (value: string) => value.replace(/[<>&"']/g, '');
const paint = (fill: IconFill, colors: RoleColors | null, id: string): { attr: string; def: string } => {
if (typeof fill === 'string') return { attr: HEX.test(fill) ? fill : colors?.[fill as ColorRole] ?? '#000000', def: '' };
return { attr: `url(#${id})`, def: `<linearGradient id="${id}" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${esc(fill.from)}"/><stop offset="1" stop-color="${esc(fill.to)}"/></linearGradient>` };
};
/** The SVG document of a glyph, built from validated data. `colors` resolves role fills of layers; a single path is black (it is used as a mask). */
export function glyphSvg(glyph: IconGlyph, style: IconStyle, colors: RoleColors | null = null): string | null {
const open = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">';
if ('d' in glyph) {
const attrs = glyph.stroke
? `fill="none" stroke="#000" stroke-width="${style.stroke}" stroke-linecap="${style.cap}" stroke-linejoin="${style.join}"`
: `fill="#000"${glyph.rule ? ' fill-rule="evenodd"' : ''}`;
return `${open}<path d="${esc(glyph.d)}" ${attrs}/></svg>`;
}
if ('layers' in glyph) {
const defs: string[] = [];
const paths = glyph.layers.map((layer, index) => {
const { attr, def } = paint(layer.fill, colors, `g${index}`);
if (def) defs.push(def);
return `<path d="${esc(layer.d)}" fill="${attr}"${layer.opacity !== undefined ? ` opacity="${layer.opacity}"` : ''}${layer.rule ? ' fill-rule="evenodd"' : ''}/>`;
});
return `${open}${defs.length ? `<defs>${defs.join('')}</defs>` : ''}${paths.join('')}</svg>`;
}
return null;
}
const svgUrl = (svg: string) => `url("data:image/svg+xml,${encodeURIComponent(svg).replace(/'/g, '%27').replace(/"/g, '%22')}")`;
/** True for glyphs that carry their own colors (drawn as an image, not as a mask of the current color). */
export const isColored = (glyph: IconGlyph) => !('d' in glyph);
/** How a site finds one of its icons: the container that holds it (stable hooks), else the start of its path data. */
export type IconMatcher = {
/** Selector of the icon's `<svg>` by its container (`[data-testid="like"] svg`). */
ctx?: string;
/** Prefixes of the site's own path data for this icon, for icons without a container hook. */
sig?: readonly string[];
group: IconGroup;
/** Needed for its group to be drawn at all (a rail never shows half ours, half the site's). */
core?: boolean;
};
export type IconTable = Partial<Record<IconName, IconMatcher>>;
/** Selectors of the `<svg>` boxes of one icon. */
export function iconSelectors(matcher: IconMatcher): string[] {
const out: string[] = [];
if (matcher.ctx) out.push(...matcher.ctx.split(/,(?![^(]*\))/).map(one => one.trim()));
for (const prefix of matcher.sig ?? []) if (PATH_GRAMMAR.test(prefix)) out.push(`svg:has(> g > path[d^="${prefix}"])`);
return out;
}
export type IconContext = {
colors: RoleColors | null;
/** Attribute on `<html>` that lists the groups that are on (`data-wb-icons="nav actions"`); absent: every group draws. */
gate?: string;
/** The owner lets themes and packs change icons (default: yes). */
allowed?: boolean;
};
/**
* CSS that draws `pack` over a site's icons. One rule per glyph the pack has and the site's table
* knows, inside guards: forced colors remove backgrounds (a masked icon would vanish) and an engine
* without masks would paint solid squares.
*/
export function compileIcons(pack: IconPack | null, theme: ThemeIcons | null | undefined, table: IconTable, ctx: IconContext): string {
if (ctx.allowed === false) return '';
const glyphs: Partial<Record<IconName, IconGlyph>> = { ...pack?.glyphs, ...theme?.overrides };
const style = { ...(pack?.style ?? BASE_ICON_STYLE), ...theme?.style };
const masked: string[] = [], colored: string[] = [], hidden: string[] = [];
for (const name of ICON_NAMES) {
const glyph = glyphs[name], matcher = table[name];
if (!glyph || !matcher) continue;
const gate = ctx.gate ? `html[${ctx.gate}~="${matcher.group}"] ` : '';
const selectors = iconSelectors(matcher).map(one => `${gate}${one}`);
if (!selectors.length) continue;
const size = `${Math.round(style.scale * 100)}%`;
if ('png' in glyph) {
colored.push(`${selectors.join(',')}{background:url("${glyph.png}") center / ${size} no-repeat !important;${glyph.pixel ? 'image-rendering:pixelated;' : ''}}`);
} else {
const svg = glyphSvg(glyph, style, ctx.colors);
if (!svg) continue;
if (isColored(glyph)) colored.push(`${selectors.join(',')}{background:${svgUrl(svg)} center / ${size} no-repeat !important}`);
else masked.push(`${selectors.join(',')}{background-color:currentColor !important;-webkit-mask:${svgUrl(svg)} center / ${size} no-repeat;mask:${svgUrl(svg)} center / ${size} no-repeat}`);
}
hidden.push(...selectors.map(one => `${one} > *`));
}
if (!hidden.length) return '';
const hide = `${hidden.join(',')}{opacity:0 !important}`;
const images = colored.length ? `${colored.join('\n')}\n` : '';
// Colored glyphs need no mask support; masked ones are dropped together with their hiding rule where masks are missing.
if (!masked.length) return `@media (forced-colors:none){\n${images}${hide}\n}`;
return `@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){\n${images}${masked.join('\n')}\n${hide}\n}}`;
}
/** The groups of `table` whose core icons are all on the page (`has(selector)` says whether one matches). Empty table entries count as present. */
export function iconGroupsPresent(table: IconTable, has: (selector: string) => boolean): IconGroup[] {
return ICON_GROUPS.filter(group => {
const core = ICON_NAMES.map(name => table[name]).filter((matcher): matcher is IconMatcher => !!matcher && matcher.group === group && !!matcher.core);
return core.every(matcher => iconSelectors(matcher).some(selector => { try { return has(selector); } catch { return false; } }));
});
}

View file

@ -21,18 +21,64 @@ export function resolvedFonts(font: FontSpec, siteStack: string): ResolvedFonts
})) as ResolvedFonts;
}
/** Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s. */
export function collectRules(doc: Document, own: HTMLStyleElement | null): RuleLike[] {
type RuleNode = { selectorText?: string; style?: RuleLike['style']; cssRules?: ArrayLike<RuleNode>; conditionText?: string; type?: number; constructor?: { name?: string } };
const isSupports = (rule: RuleNode) => rule.type === 12 || rule.constructor?.name === 'CSSSupportsRule';
/**
* A style rule as it takes effect. Tailwind 4 writes an opacity utility as a fallback plus the real
* value in a nested `@supports`:
* `.bg-white\/15 { background-color: var(--white); @supports (color: color-mix(in lab, red, red)) { background-color: color-mix(in oklab, var(--white) 15%, transparent) } }`.
* Read alone, the outer declaration is a solid white fill; where the browser passes the condition the
* nested one is what paints, so it answers for the rule.
*/
function effectiveRule(rule: RuleNode, supported: (condition: string) => boolean): RuleLike {
const overrides: Array<RuleLike['style']> = [];
for (const child of Array.from(rule.cssRules ?? [])) {
if (!isSupports(child) || !supported(child.conditionText ?? '')) continue;
for (const inner of Array.from(child.cssRules ?? [])) {
// Bare declarations inside the group: a CSSNestedDeclarations, or `& { }` in older engines.
if (inner.style && (inner.selectorText === undefined || inner.selectorText === '&')) overrides.push(inner.style);
}
}
if (!overrides.length) return rule as RuleLike;
const outer = rule.style!;
return {
selectorText: rule.selectorText!,
style: {
getPropertyValue(name) {
for (let i = overrides.length - 1; i >= 0; i--) { const value = overrides[i]!.getPropertyValue(name); if (value) return value; }
return outer.getPropertyValue(name);
},
length: outer.length,
},
};
}
/**
* Every style rule of `doc`'s stylesheets (inside media/supports groups too), except `own`'s (the
* engine's own sheets: read as the site's, their radii and colors would be re-declared), each as it
* takes effect (`effectiveRule`). A `@supports` group the browser does not pass is left out.
*/
export function collectRules(doc: Document, own: HTMLStyleElement | null | ReadonlyArray<HTMLStyleElement | null>): RuleLike[] {
const ours = (Array.isArray(own) ? own : [own]).filter(Boolean) as HTMLStyleElement[];
const rules: RuleLike[] = [];
const walk = (list: CSSRuleList) => {
const css = (doc.defaultView as (Window & typeof globalThis) | null)?.CSS;
const verdicts = new Map<string, boolean>();
const supported = (condition: string) => {
if (!condition || !css?.supports) return true;
let verdict = verdicts.get(condition);
if (verdict === undefined) { try { verdict = css.supports(condition); } catch { verdict = true; } verdicts.set(condition, verdict); }
return verdict;
};
const walk = (list: ArrayLike<RuleNode>) => {
for (const rule of Array.from(list)) {
if ('selectorText' in rule && 'style' in rule) rules.push(rule as unknown as RuleLike);
else if ('cssRules' in rule && !('selectorText' in rule)) walk((rule as CSSGroupingRule).cssRules);
if (rule.selectorText !== undefined && rule.style) rules.push(effectiveRule(rule, supported));
else if (rule.cssRules && rule.selectorText === undefined && (!isSupports(rule) || supported(rule.conditionText ?? ''))) walk(rule.cssRules);
}
};
for (const sheet of Array.from(doc.styleSheets)) {
if (own && sheet.ownerNode === own) continue;
try { walk(sheet.cssRules); } catch { /* Cross-origin sheet. */ }
if (ours.includes(sheet.ownerNode as HTMLStyleElement)) continue;
try { walk(sheet.cssRules as unknown as ArrayLike<RuleNode>); } catch { /* Cross-origin sheet. */ }
}
return rules;
}
@ -96,6 +142,15 @@ export type ThemeRuntimeSite<Mode extends string = string> = {
resolved(choice: ThemeChoice, mode: Mode): ResolvedTheme;
/** Custom properties of the site's root read with the theme's sheet disabled (their unthemed values). */
siteVars?: readonly string[];
/**
* The theme's CSS that does not depend on the site's stylesheet: components, variants, decoration,
* icons. It lives in its own sheet (`staticId`), so the site inserting rules never rebuilds it; it is
* rebuilt when the theme or the site's mode changes and on `refresh()` (the owner's switches, the
* icon choice, the language).
*/
staticCss?(choice: ThemeChoice, mode: Mode): string;
/** Id of that sheet's `<style>` (default `wb-theme-static`). */
staticId?: string;
/** Id of the theme's `<style>` (default `wb-theme-css`). */
styleId?: string;
/** Name in console errors. */
@ -112,6 +167,8 @@ export type ThemeHandle<Mode extends string = string> = {
resolved(): ResolvedTheme;
/** Calls `listener` after the theme or the site's color mode changes. */
onChange(listener: () => void): () => void;
/** Rebuilds the theme's CSS now: something it depends on besides the theme changed (the owner's switches, the icon choice). */
refresh(): void;
};
export type ThemeRuntimeOptions = { /** Registers bundled families (e.g. "Geist") in the page before they are used. */ loadFonts?(names: string[]): void };
@ -122,6 +179,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
const doc = win.document;
const name = site.name ?? 'wayBetter';
const styleId = site.styleId ?? 'wb-theme-css';
const staticId = site.staticId ?? 'wb-theme-static';
const { catalog } = site;
// Document start (no <html> yet): the snapshot as an adopted sheet paints with the site's first
// frame. It stays while the live CSS is for the same theme and site mode, and goes when they differ.
@ -147,7 +205,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
let theme = catalog.resolve(choice);
let lastKey = '';
let timer: ReturnType<typeof setInterval> | null = null;
const active = () => !isNeutral(theme) || !!choice.accent;
const active = () => !isNeutral(theme) || !!choice.accent || !!choice.icons;
let mode: Mode = site.initialMode;
let resolved: ResolvedTheme = site.resolved(choice, mode);
let resolvedKey = themeKey(resolved);
@ -182,15 +240,34 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
modeObserver.observe(doc.body, { attributes: true, attributeFilter: ['style'] });
};
let staticKey = '';
let staticText = '';
/** The static sheet sits right after the palette sheet (its part rules are more specific anyway; order only breaks ties). */
const placeStatic = (fixed: HTMLStyleElement | null, style: HTMLStyleElement | null) => {
if (!fixed || !style?.isConnected) return;
if (style.nextElementSibling !== fixed) style.after(fixed);
};
const render = (force = false) => {
let style = doc.getElementById(styleId) as HTMLStyleElement | null;
let fixed = doc.getElementById(staticId) as HTMLStyleElement | null;
if (doc.body) { watchMode(); syncResolved(); }
if (!active()) { style?.remove(); lastKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!active()) { style?.remove(); fixed?.remove(); lastKey = ''; staticKey = ''; dropEarly(); if (savedCss) { savedCss = ''; writeSnapshot(storage, null); } return; }
if (!doc.body) return;
const snapshotKey = `${JSON.stringify(choice)}|${mode}`;
if (early && snapshot?.key !== snapshotKey) dropEarly();
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0)}`;
if (!force && key === lastKey) return;
// The static sheet follows the theme and the mode only (and `refresh()`), never the site's rules.
if (site.staticCss && (force || staticKey !== snapshotKey)) {
staticKey = snapshotKey;
let text = '';
try { text = site.staticCss(choice, mode); } catch (error) { console.error(`[${name}] theme structure failed`, error); }
staticText = text;
if (text) {
if (!fixed) { fixed = doc.createElement('style'); fixed.id = staticId; }
if (fixed.textContent !== text) fixed.textContent = text;
} else { fixed?.remove(); fixed = null; }
}
const key = `${JSON.stringify(choice)}|${mode}|${ruleCount(doc) - (style?.sheet?.cssRules.length ?? 0) - (fixed?.sheet?.cssRules.length ?? 0)}`;
if (!force && key === lastKey) { placeStatic(fixed, style); return; }
lastKey = key;
if (!style) { style = doc.createElement('style'); style.id = styleId; }
// The site's own values, not the ones our previous render overrode (switching themes re-reads them).
@ -201,11 +278,13 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
for (const name of site.siteVars) vars[name] = rootStyle.getPropertyValue(name).trim();
}
if (style.sheet) style.sheet.disabled = false;
const css = site.css(collectRules(doc, style), choice, mode, vars);
const css = site.css(collectRules(doc, [style, fixed]), choice, mode, vars);
if (style.textContent !== css) style.textContent = css;
// Last in <head> so equal-specificity `!important` rules win over the site's.
if (style.parentNode !== doc.head || doc.head.lastElementChild !== style) (doc.head || doc.documentElement).appendChild(style);
const full = `${themeVarsCss(resolved)}\n${css}`;
// Last in <head> so equal-specificity `!important` rules win over the site's; the static sheet after it.
const last = fixed?.isConnected && doc.head?.lastElementChild === fixed ? fixed.previousElementSibling : doc.head?.lastElementChild;
if (style.parentNode !== doc.head || last !== style) (doc.head || doc.documentElement).appendChild(style);
placeStatic(fixed, style);
const full = `${themeVarsCss(resolved)}\n${css}${staticText ? `\n${staticText}` : ''}`;
if (full !== savedCss) { savedCss = full; writeSnapshot(storage, { key: snapshotKey, choice, css: full }); }
};
@ -232,6 +311,7 @@ export function installThemeRuntime<Mode extends string>(win: Window, site: Them
listeners.add(listener);
return () => { listeners.delete(listener); };
},
refresh() { try { render(true); } catch (error) { console.error(`[${name}] theme failed`, error); } },
};
// The snapshot's theme until native code hands over the current one (usually the same): the
// live CSS then already renders at DOMContentLoaded instead of after the page finished loading.

View file

@ -0,0 +1,154 @@
// The JSON Schema of a theme's structure groups and of an icon pack, generated from the same tables
// the sanitizers use (themeComponents.ts, themeVariants.ts, themeDecor.ts, themeIcons.ts), so a range
// or a word exists in one place. `theme.schema.json` and `icons.schema.json` in the `waybetter`
// package are written from here (`scripts/theme-schema.mjs`); a test fails when they are stale. Pure.
import {
ACTION_NAMES, AVATAR_SHAPES, BORDER_STYLES, CASES, COLOR_ROLES, COMPONENTS, COMPONENT_IDS, CORNERS, PRESETS, SHADOWS, TOKEN_LIMITS,
} from './themeComponents.ts';
import { CHROME_KINDS, DIVIDER_STYLES, LINK_UNDERLINES, MOTION_CURVES, RING_STYLES } from './themeDecor.ts';
import { ICON_LABEL_NAMES, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR } from './themeIcons.ts';
import { VARIANT_AXES, VARIANT_AXIS_NAMES } from './themeVariants.ts';
type Json = Record<string, unknown>;
const range = ([minimum, maximum]: readonly [number, number], type = 'number'): Json => ({ type, minimum, maximum });
const words = (values: readonly string[]): Json => ({ enum: [...values] });
const closed = (properties: Json, extra: Json = {}): Json => ({ type: 'object', additionalProperties: false, properties, ...extra });
/** Schema-side guard for words written into CSS strings (the sanitizer's allow-list is stricter: letters, digits and a little punctuation). */
const LABEL_PATTERN = String.raw`^[^\u0000-\u001f"\\<>&{};'` + '`]+$';
const role = { $ref: '#/$defs/role' };
const hex = { $ref: '#/$defs/hex' };
type Def = { parent?: string; text?: boolean; height?: readonly [number, number]; width?: readonly [number, number]; size?: readonly [number, number]; maxHeight?: readonly [number, number]; fontSize?: readonly [number, number]; shape?: boolean; corner?: boolean; visible?: boolean; glass?: boolean; gradient?: boolean; presets?: keyof typeof PRESETS };
// Fills and states come in four kinds (with or without glass, with or without a gradient); each is one shared definition.
const kind = (def: Def) => `${def.glass ? 'Glass' : ''}${def.gradient ? 'Gradient' : ''}`;
function fillDef(glass: boolean, gradient: boolean): Json {
const options: Json[] = [role, { const: 'transparent' }];
if (glass) options.push({ const: 'glass' });
if (gradient) options.push(closed({ from: role, to: role, angle: range(TOKEN_LIMITS.angle) }, { required: ['from', 'to'] }));
return { oneOf: options };
}
const stateDef = (name: string): Json => closed({
fill: { $ref: `#/$defs/fill${name}` }, text: role, borderColor: role, shadow: { $ref: '#/$defs/shadow' }, lift: range(TOKEN_LIMITS.lift), scale: range(TOKEN_LIMITS.scale), underline: { type: 'boolean' },
});
const fill = (def: Def): Json => ({ $ref: `#/$defs/fill${kind(def)}` });
const state = (def: Def): Json => ({ $ref: `#/$defs/state${kind(def)}` });
function component(def: Def, id: string): Json {
const properties: Json = {
radius: { oneOf: [range(TOKEN_LIMITS.radius), { const: 'pill' }] },
borderWidth: range(TOKEN_LIMITS.borderWidth), borderStyle: words(BORDER_STYLES), borderColor: role,
fill: fill(def), text: role,
padX: range(TOKEN_LIMITS.padX), padY: range(TOKEN_LIMITS.padY), gap: range(TOKEN_LIMITS.gap),
shadow: { $ref: '#/$defs/shadow' }, hover: state(def), active: state(def), focus: state(def),
};
if (def.presets) properties.preset = words(Object.keys(PRESETS[def.presets]));
for (const key of ['height', 'width', 'size', 'maxHeight', 'fontSize'] as const) if (def[key]) properties[key] = range(def[key]!);
if (def.text || def.fontSize) {
properties.font = { $ref: '#/$defs/fontRoleName' };
properties.weight = range(TOKEN_LIMITS.weight);
if (id !== 'postText') properties.case = words(CASES);
properties.tracking = range(TOKEN_LIMITS.tracking);
properties.leading = range(TOKEN_LIMITS.leading);
}
if (def.shape) properties.shape = words(AVATAR_SHAPES);
if (def.corner) properties.corner = words(CORNERS);
if (def.visible) properties.visible = { type: 'boolean' };
return closed(properties);
}
const glyph: Json = {
oneOf: [
closed({ d: { $ref: '#/$defs/pathData' }, rule: { const: 'evenodd' }, stroke: { type: 'boolean' } }, { required: ['d'] }),
closed({
layers: {
type: 'array', minItems: 1, maxItems: ICON_LIMITS.layers,
items: closed({ d: { $ref: '#/$defs/pathData' }, fill: { oneOf: [role, hex, closed({ from: hex, to: hex }, { required: ['from', 'to'] })] }, opacity: range([0, 1]), rule: { const: 'evenodd' } }, { required: ['d', 'fill'] }),
},
}, { required: ['layers'] }),
closed({ png: { type: 'string', maxLength: ICON_LIMITS.pngChars + 22, pattern: '^data:image/png;base64,[A-Za-z0-9+/]+={0,2}$' }, pixel: { type: 'boolean' } }, { required: ['png'] }),
],
};
const iconStyle = closed({ stroke: range([1, 2.5]), cap: words(['round', 'square', 'butt']), join: words(['round', 'miter', 'bevel']), scale: range([0.8, 1.25]) });
const symbols = closed({ like: words(['heart', 'star', 'custom']), separator: words(['dot', 'bullet', 'slash', 'dash', 'pipe', 'none']) });
const labels = closed(Object.fromEntries(ICON_LABEL_NAMES.map(name => [name, { type: 'string', minLength: 1, maxLength: ICON_LIMITS.labelChars, pattern: LABEL_PATTERN }])));
const glyphs = (maxProperties: number): Json => closed(Object.fromEntries(ICON_NAMES.map(name => [name, { $ref: '#/$defs/glyph' }])), { maxProperties });
/** `$defs` shared by the structure groups and the pack schema. */
export const structureDefs = (): Json => ({
role: { description: 'A color role of the theme. Components never carry a color literal.', ...words(COLOR_ROLES) },
fontRoleName: words(['interface', 'post', 'heading', 'numbers', 'mono', 'chrome', 'dialog']),
shadow: words(SHADOWS),
...Object.fromEntries([[false, false], [true, false], [false, true], [true, true]].flatMap(([glass, gradient]) => {
const name = `${glass ? 'Glass' : ''}${gradient ? 'Gradient' : ''}`;
return [[`fill${name}`, fillDef(glass!, gradient!)], [`state${name}`, stateDef(name)]];
})),
pathData: { type: 'string', minLength: 1, maxLength: ICON_LIMITS.pathChars, pattern: PATH_GRAMMAR.source.replace(/\{1,4000\}\$$/, '+$') },
glyph,
});
/** The properties a theme document gains: `components`, `variants`, `decor`, `icons`. */
export function structureProperties(): Json {
return {
components: {
description: 'How each piece of the site is built. Every token is optional; a missing token changes nothing.',
...closed(Object.fromEntries(COMPONENT_IDS.map(id => [id, component(COMPONENTS[id] as Def, id)]))),
},
variants: {
description: 'Structural choices. The first option of each axis is the site\'s own layout.',
...closed(Object.fromEntries(VARIANT_AXIS_NAMES.map(axis => [axis, words(VARIANT_AXES[axis])]))),
},
decor: {
description: 'Lines, bars, focus ring, selection, scrollbars, link underlines, motion.',
...closed({
dividers: closed({ style: words(DIVIDER_STYLES), color: role, width: range([0, 3]) }, { required: ['style'] }),
chrome: closed({ kind: words(CHROME_KINDS), title: { type: 'string', maxLength: 24 } }, { required: ['kind'] }),
focusRing: closed({ width: range([2, 4]), style: words(RING_STYLES), color: role, offset: range([0, 4]) }),
selection: closed({ fill: role, text: role }, { required: ['fill', 'text'] }),
scrollbar: closed({ width: words(['auto', 'thin']), thumb: role, track: role, style: words(['flat', 'classic']) }),
links: closed({ underline: words(LINK_UNDERLINES) }, { required: ['underline'] }),
motion: closed({ duration: range([0, 400]), curve: words(MOTION_CURVES), press: range([0.96, 1]) }),
}),
},
icons: {
description: 'The icon pack this theme suggests (by id), with small adjustments. A whole pack is its own document (icons.schema.json).',
...closed({ pack: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' }, style: iconStyle, overrides: glyphs(ICON_LIMITS.overrides), symbols, labels }),
},
};
}
/** `colors.actions`. */
export const actionColorsSchema = (): Json => ({
description: 'Colors of a set action (liked, reposted, bookmarked) and of the reply hover. Absent: the site\'s own.',
...closed(Object.fromEntries(ACTION_NAMES.map(name => [name, hex]))),
});
/** The JSON Schema of an icon pack document (`*.icons.json`). */
export function iconPackSchema(id: string): Json {
return {
$schema: 'https://json-schema.org/draft/2020-12/schema',
$id: id,
title: 'wayBetter icon pack',
description: 'Glyphs by semantic name, drawn over a site\'s own icons. Path data, colored layers of path data, or small PNGs: never an SVG document.',
type: 'object',
required: ['id', 'name', 'license', 'glyphs'],
additionalProperties: false,
properties: {
$schema: { type: 'string' },
id: { type: 'string', pattern: '^[a-z0-9-]{1,40}$' },
name: { type: 'string', minLength: 1, maxLength: 60 },
description: { type: 'string', maxLength: 200 },
author: { type: 'string', maxLength: 60 },
license: { type: 'string', minLength: 1, maxLength: 60, description: 'SPDX id, "own" for the author\'s own drawings, or a plain name for artwork under other terms.' },
source: { type: 'string', maxLength: 200 },
credits: { type: 'string', maxLength: 400 },
version: { const: 1 },
style: iconStyle,
glyphs: { ...glyphs(ICON_LIMITS.names), minProperties: 1 },
symbols,
labels,
},
$defs: { hex: { type: 'string', pattern: '^#[0-9a-fA-F]{6}$' }, ...structureDefs() },
};
}

View file

@ -18,6 +18,10 @@
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts';
import { deriveColors } from './themeTokens.ts';
import { ACTION_NAMES, sanitizeComponents, type ActionColors, type ThemeComponents } from './themeComponents.ts';
import { sanitizeDecor, type ThemeDecor } from './themeDecor.ts';
import { sanitizeThemeIcons, type ThemeIcons } from './themeIcons.ts';
import { sanitizeVariants, type ThemeVariants } from './themeVariants.ts';
export { FONT_ROLE_NAMES } from './themeApi.ts';
export type { FontRoleName } from './themeApi.ts';
@ -26,8 +30,12 @@ export type Role = 'bg' | 'surface' | 'elevated' | 'border' | 'text' | 'muted' |
/** The site's filled primary button (X: "Post"/"Follow"): an `inverse` background with an `onInverse` label. */
export type ButtonRole = 'inverse' | 'onInverse';
export type Palette = Record<Role, string> & Partial<Record<ButtonRole, string>>;
/** `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`. */
export type ThemeColors = Palette & { page?: string };
/**
* `page` is the canvas behind the site's columns (defaults to `bg`); the columns stay on `bg`.
* `actions` are the colors of a set action (liked, reposted, bookmarked) and of the reply hover;
* absent, the site's own action colors stay.
*/
export type ThemeColors = Palette & { page?: string; actions?: ActionColors };
export type Density = 'compact' | 'default' | 'comfortable';
export type AvatarShape = 'circle' | 'rounded' | 'square';
@ -91,6 +99,16 @@ export type ThemeSpec = {
effects: EffectsSpec;
/** Free-form CSS appended last (owner-trusted, like Custom CSS). */
css: string;
// The groups below are optional and additive: a theme without them is drawn exactly as before,
// and an app that does not know them drops them and draws the rest.
/** How each piece of the site is built (themeComponents.ts). */
components?: ThemeComponents;
/** Structural choices: where the navigation sits, how a post is laid out (themeVariants.ts). */
variants?: ThemeVariants;
/** Lines, bars, focus ring, selection, scrollbars, motion (themeDecor.ts). */
decor?: ThemeDecor;
/** Which icon pack the theme suggests, with small adjustments (themeIcons.ts). */
icons?: ThemeIcons;
};
/** Panel overrides: any group may be partially overridden on top of the selected theme. */
@ -104,6 +122,8 @@ export type ThemeOverrides = {
effects?: Partial<EffectsSpec>;
/** The theme's own CSS as edited in the panel (replaces the theme document's `css`). */
css?: { text: string };
/** The owner's say on a theme's layout suggestions, axis by axis (an axis set to the site's own option switches it off). */
variants?: Record<string, string>;
};
// ---------------------------------------------------------------------------------------------
@ -132,7 +152,7 @@ export const isHex = (value: unknown): value is string => typeof value === 'stri
export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`;
/** Moves `color` toward black or white until it reaches `ratio` against every surface. */
function reach(color: string, surfaces: string[], ratio: number): string {
export function reach(color: string, surfaces: string[], ratio: number): string {
const worst = (c: string) => Math.min(...surfaces.map(s => contrastRatio(c, s)));
if (worst(color) >= ratio) return color;
const lightSurfaces = surfaces.reduce((sum, s) => sum + relativeLuminance(s), 0) / surfaces.length > 0.18;
@ -149,7 +169,7 @@ function reach(color: string, surfaces: string[], ratio: number): string {
* and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled
* button keeps a readable label and stands out from the page (3:1).
*/
export function ensureContrast<T extends Palette & { page?: string }>(colors: T): T {
export function ensureContrast<T extends Palette & { page?: string; actions?: ActionColors }>(colors: T): T {
const surfaces = [colors.bg, colors.surface, colors.elevated, ...(colors.page ? [colors.page] : [])];
const out = { ...colors };
out.text = reach(colors.text, surfaces, 7);
@ -160,6 +180,8 @@ export function ensureContrast<T extends Palette & { page?: string }>(colors: T)
const onInverse = colors.onInverse ?? colors.bg;
out.inverse = reach(inverse, [colors.bg], 3);
out.onInverse = reach(onInverse, [out.inverse], 4.5);
// Action colors are icons and counts: non-text contrast on the column and on a raised row.
if (colors.actions) out.actions = Object.fromEntries(Object.entries(colors.actions).map(([name, color]) => [name, reach(color as string, [colors.bg, colors.surface], 3)]));
return out;
}
@ -192,6 +214,9 @@ function sanitizeColors(value: unknown): ThemeColors | null {
.filter(role => isHex(source[role])).map(role => [role, (source[role] as string).toLowerCase()]));
const colors = deriveColors(named as { bg: string; text: string; accent: string }) as ThemeColors;
for (const role of ['inverse', 'onInverse', 'page'] as const) if (isHex(source[role])) colors[role] = (source[role] as string).toLowerCase();
const actions = obj(source.actions);
const named_actions = Object.fromEntries(ACTION_NAMES.filter(name => isHex(actions[name])).map(name => [name, (actions[name] as string).toLowerCase()]));
if (Object.keys(named_actions).length) colors.actions = named_actions;
return colors;
}
@ -309,9 +334,20 @@ export function sanitizeSpec(input: unknown): ThemeSpec {
background: sanitizeBackground(source.background),
effects: sanitizeEffects(source.effects, BASE_EFFECTS),
css: typeof source.css === 'string' ? source.css.slice(0, MAX_CSS_CHARS) : '',
...structureGroups(source),
};
}
/** The optional structure groups of a theme, each present only when it says something valid. */
function structureGroups(source: Record<string, unknown>): Pick<ThemeSpec, 'components' | 'variants' | 'decor' | 'icons'> {
const components = sanitizeComponents(source.components), variants = sanitizeVariants(source.variants);
const decor = sanitizeDecor(source.decor), icons = sanitizeThemeIcons(source.icons);
return { ...(components ? { components } : {}), ...(variants ? { variants } : {}), ...(decor ? { decor } : {}), ...(icons ? { icons } : {}) };
}
/** True when a theme carries any of the structure groups (components, variants, decoration, icons). */
export const hasStructure = (theme: ThemeSpec) => !!(theme.components || theme.variants || theme.decor || theme.icons);
/** Parses an imported file; errors are human-readable. */
export function parseThemeJson(json: string): { theme: ThemeSpec; warnings: string[] } | { error: string } {
let raw: unknown;
@ -345,13 +381,21 @@ export function applyOverrides(theme: ThemeSpec, overrides: ThemeOverrides = {},
background: o.background ? sanitizeBackground(o.background) : theme.background,
effects: o.effects ? sanitizeEffects({ ...theme.effects, ...o.effects }, theme.effects) : theme.effects,
css: o.css && typeof o.css.text === 'string' ? o.css.text.slice(0, MAX_CSS_CHARS) : theme.css,
...variantOverrides(theme, o.variants),
};
}
/** A theme's variants with the owner's per-axis say on top (the raw merge goes through the sanitizer, so the site's own option removes the axis). */
function variantOverrides(theme: ThemeSpec, overrides: unknown): Pick<ThemeSpec, 'variants'> {
if (!overrides || typeof overrides !== 'object') return {};
const variants = sanitizeVariants({ ...theme.variants, ...(overrides as Record<string, unknown>) });
return { variants: variants ?? undefined };
}
/** True when a theme changes nothing about the site (the site's own look without overrides). */
export function isNeutral(theme: ThemeSpec): boolean {
return !theme.colors && JSON.stringify([theme.font, theme.shape, theme.layout, theme.effects]) === JSON.stringify([BASE_FONT, BASE_SHAPE, BASE_LAYOUT, BASE_EFFECTS])
&& theme.background.kind === 'none' && !theme.css;
&& theme.background.kind === 'none' && !theme.css && !hasStructure(theme);
}
// ---------------------------------------------------------------------------------------------

View file

@ -53,6 +53,8 @@ const NEUTRAL_CHROMA = 0.05;
/** How far past the site's own background/text a neutral may sit and still be on the axis (pure white
* text in Lights out is slightly past the site's 231,233,234; black in Default is far past and is a shadow). */
const AXIS_SLACK = 0.12;
/** How close to a surface or to the secondary text a foreground may sit and still count as that role's own shade. */
const DIM_SLACK = 0.01;
export type ColorModel = {
sourceBg: Oklab;
@ -63,6 +65,14 @@ export type ColorModel = {
exact: Map<string, Rgb>;
sourceAccent: Oklab;
accent: Oklab | null;
/**
* Text only: the stretch of the site's axis between its most raised surface and its secondary text.
* A foreground the site paints there (a dimmed icon, a gray it also uses for borders) would land
* between the theme's background and its secondary text, under every contrast a theme guarantees;
* it becomes the theme's secondary text instead. Below `from` a foreground is as dark (or light) as
* the site's surfaces: a label on a filled surface, which keeps its place.
*/
dim: { from: number; to: number; color: Rgb } | null;
};
/**
@ -112,8 +122,15 @@ export function buildColorModel(source: SourceAxis, target: TargetAxis, usage: U
// accent backgrounds keep the site's lightness offsets (hover, pressed) through projectColor.
if (target.accent && usage !== 'background') for (const key of source.accent) if (!exact.has(key)) exact.set(key, hexToRgb(target.accent));
anchors.sort((a, b) => a.t - b.t);
let dim: ColorModel['dim'] = null;
if (usage === 'text' && target.muted && source.muted.length) {
const positions = (roles: AxisRole[]) => roles.flatMap(role => source[role].map(key => position(rgbToOklab(keyRgb(key)))));
const from = Math.max(0, ...positions(['bg', 'surface', 'elevated'])) + DIM_SLACK;
const to = Math.min(...positions(['muted'])) - DIM_SLACK;
if (to > from) dim = { from, to, color: hexToRgb(target.muted) };
}
return {
sourceBg, sourceText, anchors, exact,
sourceBg, sourceText, anchors, exact, dim,
sourceAccent: rgbToOklab(keyRgb(source.accent[0]!)),
accent: target.accent ? rgbToOklab(hexToRgb(target.accent)) : null,
};
@ -150,6 +167,7 @@ export function projectColor(model: ColorModel, rgb: Rgb): Rgb | null {
if (listed) return listed;
const c = rgbToOklab(rgb);
const t = axisPosition(model, rgb);
if (t !== null && model.dim && t > model.dim.from && t < model.dim.to) return model.dim.color;
if (t !== null) return oklabToRgb(onCurve(model, t));
if (model.accent && isAccentFamily(model, c)) {
// Keep the site's lightness offset (hover is darker, tints lighter) on the theme's accent.

View file

@ -0,0 +1,64 @@
// Layout variants: the structural choices a theme may suggest (navigation on top, compact posts,
// worded actions), as fixed words on a few axes. The vocabulary and the precedence are here; what a
// variant looks like on a site is that site's CSS (its skins). Pure.
//
// A theme suggests, the owner decides: an axis an owner's own switch already controls is left to that
// switch, and the owner can turn layout changes by themes off altogether.
/** The axes and their options. The first option of each axis is the site's own layout (no rule). */
export const VARIANT_AXES = {
nav: ['labels', 'icons', 'top', 'bottom'],
post: ['default', 'cards', 'bubbles', 'compact', 'broadsheet'],
actions: ['icons', 'labels', 'quiet'],
header: ['default', 'solid', 'bar'],
sidebar: ['default', 'narrow', 'hidden'],
width: ['default', 'full'],
} as const;
export type VariantAxis = keyof typeof VARIANT_AXES;
export const VARIANT_AXIS_NAMES = Object.keys(VARIANT_AXES) as VariantAxis[];
export type ThemeVariants = { [A in VariantAxis]?: typeof VARIANT_AXES[A][number] };
/** The `variants` group from JSON: known axes and options only; an axis left at the site's own layout is dropped. */
export function sanitizeVariants(value: unknown): ThemeVariants | null {
const source = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const out: Record<string, string> = {};
for (const axis of VARIANT_AXIS_NAMES) {
const options: readonly string[] = VARIANT_AXES[axis];
const option = source[axis];
if (typeof option === 'string' && options.includes(option) && option !== options[0]) out[axis] = option;
}
return Object.keys(out).length ? out as ThemeVariants : null;
}
export type VariantGate = {
/** The owner lets themes change the layout (default: yes). */
allowed?: boolean;
/** Axes an owner's own switch controls right now: the theme's suggestion is not drawn for them. */
owned?: readonly VariantAxis[];
};
/** The variants that are drawn: the theme's (with the owner's customization already merged in), minus what the owner holds. */
export function resolveVariants(variants: ThemeVariants | null | undefined, gate: VariantGate = {}): ThemeVariants {
if (!variants || gate.allowed === false) return {};
const out: Record<string, string> = {};
for (const axis of VARIANT_AXIS_NAMES) {
const option = variants[axis];
if (option && !gate.owned?.includes(axis)) out[axis] = option;
}
return out as ThemeVariants;
}
/** A site's CSS for each variant it can draw: `skins.nav.top(ctx)` returns the rules. */
export type VariantSkins<Context> = { [A in VariantAxis]?: Partial<Record<typeof VARIANT_AXES[A][number], (ctx: Context) => string>> };
/** The CSS of the resolved variants, in axis order. A variant the site has no skin for draws nothing. */
export function compileVariants<Context>(variants: ThemeVariants, skins: VariantSkins<Context>, ctx: Context): string[] {
const out: string[] = [];
for (const axis of VARIANT_AXIS_NAMES) {
const option = variants[axis];
const build = option ? (skins[axis] as Record<string, ((ctx: Context) => string) | undefined> | undefined)?.[option] : undefined;
const css = build?.(ctx);
if (css) out.push(css);
}
return out;
}

View file

@ -151,6 +151,13 @@ export const KIT_MESSAGES = {
'kit.value': 'Value',
'kit.checkValue': 'Please check this value.',
'kit.failed': 'Something went wrong.',
// Feature modules (featureModules.ts): the settings dialog and the health notes.
'kit.save': 'Save',
'kit.feature.paused': '{feature} ({area}) is paused: this page changed.',
'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.',
'kit.feature.pausedList': 'Paused features of {area}',
'kit.feature.needsEnglish': '{feature} needs the site in English.',
'kit.feature.settings': '{name} settings',
} as const;
export type KitKey = keyof typeof KIT_MESSAGES;

View file

@ -0,0 +1,498 @@
// The feature table (areas, flags, modes), the settings schema and the feature-module registry:
// flag and surface gating, ownership, one shared observer, the command budget, settings, hotfix
// overrides and the selector health check.
import assert from 'node:assert/strict';
import test from 'node:test';
import { configureDomHub, observeSelector, type DomWindow } from '../src/domHub.ts';
import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts';
import {
areaFlag, effectiveFlags, manualChanges, modeFlags, modeStatus, normalizeFlags, pausedFeatures, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable,
type FeatureTable,
} from '../src/featureTable.ts';
import { createCorePluginApi, type CorePluginApi, type PluginApiSite } from '../src/pluginApi.ts';
import { normalizeSettings, validateSchema, type SettingsSchema } from '../src/settingsForm.ts';
const TABLE: FeatureTable = {
areas: [
{ id: 'navigation', name: 'Navigation+', description: 'plugin.navigation-plus.description', owner: 'wb-navigation-plus.plugin.js', namespace: 'navigation-plus' },
{ id: 'reader', name: 'Reader+', description: 'plugin.reader-plus.description', owner: 'wb-reader-plus.plugin.js', namespace: 'reader-plus' },
],
features: [
{ id: 'fixScroll', area: null, group: 'fixes', default: true, backing: 'app' },
{ id: 'hideTrends', area: 'navigation', default: false, backing: 'module', surfaces: ['timeline'] },
{ id: 'navigation.focusMode', area: 'navigation', default: false, backing: 'module', settings: true, supersedes: 'wb-focus-mode.plugin.js' },
{ id: 'navigation.keys', area: 'navigation', default: false, backing: 'module' },
{ id: 'hideAds', area: 'reader', default: true, backing: 'app' },
{ id: 'reader.cleanLinks', area: 'reader', default: false, backing: 'plugin', file: 'wb-clean-links.plugin.js' },
],
modes: [
{ id: 'basic', name: 'mode.basic', description: 'mode.basic.text', flags: { 'area.navigation': false, 'area.reader': false } },
{ id: 'advanced', name: 'mode.advanced', description: 'mode.advanced.text', recommended: true, flags: {} },
{ id: 'power', name: 'mode.power', description: 'mode.power.text', flags: { 'navigation.keys': true } },
],
};
test('feature table: defaults, normalizing, sparse storage and ownership', () => {
assert.deepEqual(validateTable(TABLE), []);
const defaults = tableDefaults(TABLE);
assert.deepEqual(defaults, { fixScroll: true, hideTrends: false, 'navigation.focusMode': false, 'navigation.keys': false, hideAds: true, 'area.navigation': true, 'area.reader': true },
'a feature still backed by a plugin file is not a flag; every area has its switch, on');
assert.deepEqual(normalizeFlags(TABLE, { hideTrends: true, hideAds: 'yes', unknown: true, 'reader.cleanLinks': true }), { ...defaults, hideTrends: true }, 'unknown keys dropped, non-booleans take the default');
assert.deepEqual(sparseFlags(TABLE, { ...defaults, hideTrends: true, hideAds: false }), { hideTrends: true, hideAds: false }, 'only what differs from the default is stored');
assert.deepEqual(sparseFlags(TABLE, defaults), {});
// An area that is off turns off what it owns; core flags and other areas are untouched.
const off = effectiveFlags(TABLE, { ...defaults, hideTrends: true, [areaFlag('reader')]: false });
assert.equal(off.hideAds, false);
assert.equal(off.hideTrends, true);
assert.equal(off.fixScroll, true, 'no plugin switch turns a core flag off');
assert.deepEqual(supersededFiles(TABLE), [{ file: 'wb-focus-mode.plugin.js', flag: 'navigation.focusMode' }]);
});
test('feature table: a mode is a starting point; changing it keeps or drops the manual changes', () => {
const defaults = tableDefaults(TABLE);
assert.deepEqual(modeFlags(TABLE, 'advanced'), defaults);
assert.deepEqual(modeFlags(TABLE, null), defaults, 'never chosen: the defaults');
assert.equal(modeFlags(TABLE, 'basic')['area.reader'], false);
// The owner, on Advanced, turned trends hiding on and ads hiding off.
const mine = { ...defaults, hideTrends: true, hideAds: false };
assert.deepEqual(manualChanges(TABLE, mine, 'advanced').sort(), ['hideAds', 'hideTrends']);
const kept = switchMode(TABLE, mine, 'advanced', 'power', true);
assert.deepEqual(kept, { ...defaults, 'navigation.keys': true, hideTrends: true, hideAds: false });
const reset = switchMode(TABLE, mine, 'advanced', 'power', false);
assert.deepEqual(reset, { ...defaults, 'navigation.keys': true });
// From Basic back to Advanced with "keep": the areas Basic switched off are not manual changes.
const basic = switchMode(TABLE, mine, 'advanced', 'basic', false);
assert.deepEqual(manualChanges(TABLE, basic, 'basic'), []);
assert.deepEqual(switchMode(TABLE, basic, 'basic', 'advanced', true), defaults);
});
test('a mode is a starting point: exact, changed by the owner, and a preset that grew', () => {
const power = TABLE.modes.find(mode => mode.id === 'power')!;
const applied = modeFlags(TABLE, 'power');
// Exact match: the flags are what the mode starts from.
assert.deepEqual(modeStatus(TABLE, applied, 'power', power.flags), { custom: false, on: [], off: [], added: [] });
// No mode chosen, or one this table does not know: nothing to say, whatever the flags are.
assert.deepEqual(modeStatus(TABLE, { ...applied, hideTrends: true }, null), { custom: false, on: [], off: [], added: [] });
assert.equal(modeStatus(TABLE, applied, 'gone').custom, false);
// The owner changed features: custom, and re-applying says what it turns on and off. None of it is "new".
const mine = { ...applied, hideTrends: true, 'navigation.keys': false, 'area.reader': false };
assert.deepEqual(modeStatus(TABLE, mine, 'power', power.flags), { custom: true, on: ['navigation.keys', 'area.reader'], off: ['hideTrends'], added: [] });
// Applying again is exactly that list: afterwards the match is exact.
assert.equal(modeStatus(TABLE, switchMode(TABLE, mine, 'power', 'power', false), 'power', power.flags).custom, false);
// An update made the preset larger: the flags are as the old preset left them. Custom, nothing
// applied, and the additions are named so they can be mentioned.
const grown: FeatureTable = { ...TABLE, modes: TABLE.modes.map(mode => mode.id === 'power' ? { ...mode, flags: { ...mode.flags, hideTrends: true, hideAds: false } } : mode) };
assert.deepEqual(modeStatus(grown, applied, 'power', power.flags), { custom: true, on: ['hideTrends'], off: ['hideAds'], added: ['hideTrends', 'hideAds'] });
// Both at once: the owner's own change is a difference but not an addition.
assert.deepEqual(modeStatus(grown, { ...applied, 'navigation.keys': false }, 'power', power.flags), { custom: true, on: ['hideTrends', 'navigation.keys'], off: ['hideAds'], added: ['hideTrends', 'hideAds'] });
// An addition the owner already has is no difference at all.
assert.deepEqual(modeStatus(grown, { ...applied, hideTrends: true }, 'power', power.flags).added, ['hideAds']);
// Once the grown preset is the one remembered (the note was looked at), it is not "new" again; the mode stays custom.
assert.deepEqual(modeStatus(grown, applied, 'power', grown.modes.find(mode => mode.id === 'power')!.flags), { custom: true, on: ['hideTrends'], off: ['hideAds'], added: [] });
// A choice made before the preset was remembered: a difference, never a guess about what is new.
assert.deepEqual(modeStatus(grown, applied, 'power'), { custom: true, on: ['hideTrends'], off: ['hideAds'], added: [] });
assert.deepEqual(modeStatus(grown, applied, 'power', null).added, []);
});
test('feature table: problems are reported', () => {
const bad: FeatureTable = {
areas: [{ id: 'Nav', name: 'Nav', description: 'd', owner: 'nav.js', namespace: 'nav' }, ...TABLE.areas],
features: [
...TABLE.features,
{ id: 'hideTrends', area: 'reader', default: false, backing: 'app' },
{ id: 'area.x', area: null, default: false, backing: 'app' },
{ id: 'lost', area: 'nowhere', default: false, backing: 'app' },
{ id: 'reader.x', area: 'reader', default: true, backing: 'plugin' },
{ id: 'reader.y', area: 'reader', default: false, backing: 'app', settings: true },
],
modes: [...TABLE.modes, { id: 'odd', name: 'n', description: 'd', recommended: true, flags: { nope: true, hideAds: true } }],
};
const problems = validateTable(bad).join('\n');
for (const expected of ['area "Nav": invalid id', 'owner must be a plugin file name', 'hideTrends: owned twice', 'area.x: "area." is kept', 'lost: unknown area', 'reader.x: a plugin-backed feature names its file',
'reader.x: a plugin file is off', 'reader.y: only a feature module has a settings schema', 'mode odd: unknown flag nope', 'mode odd: hideAds is already the default', 'exactly one mode is the recommended one']) {
assert.ok(problems.includes(expected), `${expected}\n${problems}`);
}
});
const SCHEMA: SettingsSchema = [
{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' },
{ type: 'divider' },
{ key: 'days', type: 'number', default: 30, min: 1, max: 365, label: 'days' },
{ key: 'mode', type: 'select', default: 'calm', options: [{ value: 'calm', label: 'calm' }, { value: 'zen', label: 'zen' }], label: 'mode' },
{ key: 'note', type: 'text', default: '', maxLength: 5, label: 'note' },
{ key: 'patterns', type: 'list', default: [], maxItems: 2, label: 'patterns' },
];
test('settings schema: stored values are normalized to the schema, whatever was stored', () => {
assert.deepEqual(validateSchema(SCHEMA), []);
assert.deepEqual(normalizeSettings(SCHEMA, null), { enabled: true, days: 30, mode: 'calm', note: '', patterns: [] });
assert.deepEqual(normalizeSettings(SCHEMA, { enabled: 'no', days: 9999, mode: 'loud', note: 'too long', patterns: ['a', '', 3, 'b', 'c'], extra: 1 }),
{ enabled: true, days: 365, mode: 'calm', note: 'too l', patterns: ['a', 'b'] });
assert.deepEqual(normalizeSettings(SCHEMA, { enabled: false, days: 7, mode: 'zen' }), { enabled: false, days: 7, mode: 'zen', note: '', patterns: [] });
const bad: SettingsSchema = [{ key: 'a', type: 'toggle', default: true, label: 'a' }, { key: 'a', type: 'number', default: 1, min: 5, max: 2, label: '' }, { key: '1x', type: 'select', default: 'z', options: [], label: 'x' }];
const problems = validateSchema(bad).join('\n');
for (const expected of ['a: listed twice', 'a: a label is required', 'a: min is above max', 'invalid key "1x"', '1x: the default is not an option']) assert.ok(problems.includes(expected), `${expected}\n${problems}`);
});
// ---------------------------------------------------------------------------------------------
// A small page: one document, a body that can hold matching elements, counted observers.
type Listener = (event: unknown) => void;
class FakeTarget {
listeners = new Map<string, Set<Listener>>();
addEventListener(type: string, fn: Listener) { (this.listeners.get(type) ?? this.listeners.set(type, new Set()).get(type)!).add(fn); }
removeEventListener(type: string, fn: Listener) { this.listeners.get(type)?.delete(fn); }
emit(type: string, event: unknown = {}) { for (const fn of [...(this.listeners.get(type) ?? [])]) fn(event); }
count(type: string) { return this.listeners.get(type)?.size ?? 0; }
}
const SITE: PluginApiSite = {
name: 'Demo', product: 'wayBetter for Test', storagePrefix: 'demo-plugin:', styleDataKey: 'demoPlugin',
toastId: 'demo-toast', toastBackground: '#111', itemSelector: 'article', chordKeys: [],
};
function page() {
const styles: { dataset: Record<string, string>; textContent: string; isConnected: boolean; remove(): void }[] = [];
const matches = new Map<string, object[]>();
const observers: Array<() => void> = [];
const store = new Map<string, string>();
const doc = new FakeTarget() as FakeTarget & Record<string, unknown>;
Object.assign(doc, {
activeElement: null,
documentElement: { getAttribute: () => 'en' },
body: { firstElementChild: {} },
head: { appendChild(node: { isConnected: boolean }) { node.isConnected = true; } },
querySelectorAll: (selector: string) => matches.get(selector) ?? [],
querySelector: (selector: string) => (matches.get(selector) ?? [])[0] ?? null,
createElement: () => {
const node = { dataset: {} as Record<string, string>, textContent: '', isConnected: false, remove() { node.isConnected = false; } };
styles.push(node);
return node;
},
});
const win = new FakeTarget() as FakeTarget & Record<string, unknown>;
const location = { href: 'https://site.test/home', pathname: '/home' };
Object.assign(win, {
document: doc,
location,
localStorage: { get length() { return store.size; }, key: (i: number) => [...store.keys()][i] ?? null, getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); }, removeItem: (k: string) => { store.delete(k); } },
requestAnimationFrame: (fn: () => void) => { fn(); return 1; },
cancelAnimationFrame: () => {},
MutationObserver: class { constructor(fn: () => void) { observers.push(() => fn()); } observe() {} disconnect() {} },
});
const api = createCorePluginApi(win as unknown as Window & typeof globalThis, SITE);
return {
api, win: win as unknown as Window & typeof globalThis, doc, styles, matches, observers, store, location,
/** The site rendered something: every observer fires (one frame). */
mutate() { for (const fire of observers) fire(); },
go(path: string) { location.href = `https://site.test${path}`; location.pathname = path; win.emit('popstate'); },
liveStyles: () => styles.filter(style => style.isConnected && style.textContent).map(style => style.textContent),
};
}
type Timer = { fn: () => void; ms: number; id: number; at: number };
function fakeTimers() {
let now = 0;
let next = 1;
let queue: Timer[] = [];
return {
setTimeout(fn: () => void, ms: number) { const id = next++; queue.push({ fn, ms, id, at: now + ms }); return id; },
clearTimeout(id: unknown) { queue = queue.filter(timer => timer.id !== id); },
advance(ms: number) {
const end = now + ms;
for (;;) {
const due = queue.filter(timer => timer.at <= end).sort((a, b) => a.at - b.at)[0];
if (!due) break;
queue = queue.filter(timer => timer !== due);
now = due.at;
due.fn();
}
now = end;
},
pending: () => queue.length,
};
}
function registryFor(env: ReturnType<typeof page>, extra: { surfaces?: () => string[]; hotfix?: () => HotfixData; timers?: ReturnType<typeof fakeTimers> } = {}) {
return createFeatureRegistry<CorePluginApi>({
win: env.win, table: TABLE, api: env.api, label: 'Demo',
surfaces: extra.surfaces ?? (() => (env.location.pathname === '/home' ? ['timeline', 'home'] : ['profile'])),
hotfix: extra.hotfix, timers: extra.timers, settleMs: 3000, pollMs: 500,
});
}
test('registry: a module runs only while its flag is on and the page is on one of its surfaces, and leaves nothing behind', () => {
const env = page();
const registry = registryFor(env);
const log: string[] = [];
registry.define({ id: 'hideTrends', start(ctx) { log.push('+trends'); ctx.css('.trends{display:none}'); ctx.defer(() => log.push('-trends')); } });
registry.define({ id: 'navigation.keys', start(ctx) { log.push('+keys'); ctx.onKey(() => {}); ctx.defer(() => log.push('-keys')); } });
assert.deepEqual(registry.active(), [], 'off until the flags say so');
assert.equal(env.doc.count('keydown'), 0, 'an idle feature holds no listener');
registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true }));
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
assert.deepEqual(env.liveStyles(), ['.trends{display:none}']);
assert.equal(env.styles.at(-1)!.dataset.demoPlugin, 'wbf-hideTrends');
assert.equal(env.doc.count('keydown'), 1);
env.go('/someone');
assert.deepEqual(registry.active(), ['navigation.keys'], 'not a timeline: the surface-bound feature stopped');
assert.deepEqual(env.liveStyles(), []);
env.go('/home');
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
// The area's switch off: everything it owns stops, without touching the features' own flags.
registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true, 'navigation.keys': true, 'area.navigation': false }));
assert.deepEqual(registry.active(), []);
assert.deepEqual(env.liveStyles(), []);
assert.equal(env.doc.count('keydown'), 0);
assert.deepEqual(log, ['+trends', '+keys', '-trends', '+trends', '-trends', '-keys']);
assert.throws(() => registry.define({ id: 'hideAds', start() {} }), /hideAds is not a feature module in the table/);
assert.throws(() => registry.define({ id: 'hideTrends', start() {} }), /defined twice/);
registry.dispose();
});
test('registry: a feature stopped by a route change is not told about that route (nothing re-added after stop)', () => {
const env = page();
const registry = registryFor(env, { surfaces: () => (env.location.pathname === '/someone' ? ['profile'] : ['timeline']) });
const routes: string[] = [];
registry.define({ id: 'hideTrends', start(ctx) { ctx.css('.trends{display:none}'); ctx.onRouteChange(href => { routes.push(href); ctx.css('.trends{opacity:0}'); }); } });
registry.setFlags(effectiveFlags(TABLE, { ...tableDefaults(TABLE), hideTrends: true }));
env.go('/explore');
assert.deepEqual(routes.length, 1, 'still on a timeline: the feature hears the route');
assert.deepEqual(env.liveStyles(), ['.trends{opacity:0}']);
env.go('/someone');
assert.deepEqual(registry.active(), []);
assert.equal(routes.length, 1, 'stopped in this round: its listener is not called');
assert.deepEqual(env.liveStyles(), []);
registry.dispose();
});
test('registry: one MutationObserver however many features observe; plugins share it too', () => {
const env = page();
const registry = registryFor(env);
const seen: string[] = [];
const first = {};
env.matches.set('article', [first]);
registry.define({ id: 'hideTrends', start(ctx) { ctx.observe('article', () => seen.push('a')); ctx.observe('aside', () => seen.push('aside')); } });
registry.define({ id: 'navigation.keys', start(ctx) { ctx.observe('article', () => seen.push('b')); ctx.watch(() => seen.push('frame')); } });
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
const stopPlugin = env.api.observe('article', () => seen.push('plugin'));
assert.equal(env.observers.length, 1, 'one observer for three selector observers, a raw watch and a plugin');
assert.deepEqual(seen, ['a', 'b', 'plugin'], 'what is already there is reported at once, once');
env.matches.set('article', [first, {}]);
env.matches.set('aside', [{}]);
env.mutate();
assert.deepEqual(seen.slice(3).sort(), ['a', 'aside', 'b', 'frame', 'plugin'], 'only the new elements');
stopPlugin();
registry.dispose();
const before = seen.length;
env.mutate();
assert.equal(seen.length, before, 'nothing runs after dispose');
});
test('registry: a failing module is contained; heavy pages pause features that did not ask for them', () => {
const env = page();
const errors: unknown[] = [];
const original = console.error;
console.error = (...args: unknown[]) => { errors.push(args[0]); };
try {
const registry = registryFor(env, { surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', start(ctx) { ctx.css('x{}'); throw new Error('markup changed'); } });
registry.define({ id: 'navigation.keys', start() {} });
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
assert.deepEqual(registry.active(), ['navigation.keys']);
assert.match(String(errors[0]), /\[Demo\] hideTrends failed/);
assert.deepEqual(env.liveStyles(), [], 'what it did before failing is undone');
registry.dispose();
} finally { console.error = original; }
});
test('registry: settings come from the schema, are stored under the module\'s namespace and reach the running feature', () => {
const env = page();
const registry = registryFor(env);
const applied: unknown[] = [];
const module: FeatureModule<CorePluginApi> = {
id: 'navigation.focusMode',
// A feature ported from a plugin keeps that plugin's words and storage.
words: 'focus-mode',
storage: 'focus-mode',
settings: [{ key: 'enabled', type: 'toggle', default: true, label: 'enabled' }, { key: 'trends', type: 'toggle', default: true, label: 'trends' }],
start(ctx) {
applied.push(ctx.settings.get());
ctx.settings.onChange(values => applied.push(values));
ctx.command({ id: 'focusMode.toggle', title: ctx.text('toggle'), run: () => { ctx.settings.set({ enabled: !ctx.settings.get().enabled }); } });
},
};
env.api.i18n.namespace('focus-mode').register({ en: { toggle: 'Toggle Focus Mode' } });
env.api.i18n.namespace('navigation-plus').register({ en: { 'keys.hello': 'Hello {name}' } });
env.store.set('demo-plugin:focus-mode:settings', JSON.stringify({ enabled: true, trends: false, gone: 1 }));
registry.define(module);
assert.throws(() => registryFor(env).define({ id: 'navigation.keys', settings: [{ key: 'a', type: 'toggle', default: true, label: 'a' }], start() {} }), /the table's "settings" and the module's schema disagree/);
registry.setFlags({ 'navigation.focusMode': true });
assert.deepEqual(applied, [{ enabled: true, trends: false }], 'an old plugin\'s stored settings are read as they are');
// The area got its one settings command next to the feature's own; both belong to the area's owner.
assert.deepEqual(env.api.commands.list().map(command => command.id).sort(), ['wb-navigation-plus.plugin.js:focusMode.toggle', 'wb-navigation-plus.plugin.js:settings']);
assert.equal(env.api.commands.list().find(command => command.id.endsWith(':settings'))!.title, 'Navigation+ settings');
assert.equal(env.api.commands.list().find(command => command.id.endsWith('focusMode.toggle'))!.title, 'Toggle Focus Mode', 'its words are under the namespace of the plugin it came from');
// Without `words`, a feature's words are under its area: plugin.<area namespace>.<name>.<key>.
let greeting = '';
registry.define({ id: 'navigation.keys', start(ctx) { greeting = ctx.text('hello', { name: 'you' }); } });
registry.setFlags({ 'navigation.focusMode': true, 'navigation.keys': true });
assert.equal(greeting, 'Hello you');
env.api.commands.run('wb-navigation-plus.plugin.js:focusMode.toggle');
assert.deepEqual(applied.at(-1), { enabled: false, trends: false });
assert.equal(env.store.get('demo-plugin:focus-mode:settings'), '{"enabled":false,"trends":false}');
registry.setFlags({});
assert.deepEqual(env.api.commands.list(), [], 'commands go with the feature');
registry.dispose();
});
test(`registry: an area registers at most ${AREA_COMMAND_BUDGET} palette commands`, () => {
const env = page();
const errors: unknown[] = [];
const original = console.error;
console.error = (...args: unknown[]) => { errors.push(args[1]); };
try {
const registry = registryFor(env);
// Navigation+ has a feature with settings, so one of the five is kept for its settings command.
registry.define({ id: 'navigation.keys', start(ctx) { for (let n = 0; n < AREA_COMMAND_BUDGET; n += 1) ctx.command({ id: `keys.${n}`, title: `Key ${n}`, run() {} }); } });
registry.setFlags({ 'navigation.keys': true });
assert.match(String(errors[0]), /at most 5 palette commands per area/);
assert.deepEqual(registry.active(), [], 'the feature that went over the budget does not run');
assert.deepEqual(env.api.commands.list(), []);
registry.dispose();
} finally { console.error = original; }
});
test(`registry: a probe that matches nothing ${PROBE_STRIKES} visits in a row pauses that one feature; a hotfix selector or kill flag applies`, () => {
const env = page();
const timers = fakeTimers();
let hotfix: HotfixData = {};
const warnings: unknown[] = [];
const original = console.warn;
console.warn = (...args: unknown[]) => { warnings.push(args[0]); };
try {
const registry = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] });
const used: string[] = [];
registry.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]', label: { selector: '[aria-label="Trending"]', english: true } }, start(ctx) { used.push(ctx.selector('module')); } });
registry.define({ id: 'navigation.keys', start() {} });
env.matches.set('[aria-label="Trending"]', [{}]);
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
const visit = () => { env.go(env.location.pathname === '/home' ? '/explore' : '/home'); timers.advance(500 + 3000); };
timers.advance(3500);
assert.deepEqual(registry.health(), [], 'one miss is not a verdict');
visit();
// The selector comes back for a visit: the count starts over.
env.matches.set('[data-testid="trend"]', [{}]);
visit();
env.matches.delete('[data-testid="trend"]');
visit();
visit();
assert.deepEqual(registry.active().sort(), ['hideTrends', 'navigation.keys']);
visit();
assert.deepEqual(registry.active(), ['navigation.keys'], 'the feature paused itself; the rest of the area runs');
assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'paused', probes: ['module'] }]);
assert.match(String(warnings[0]), /\[Demo\] hideTrends paused: nothing matches module/);
// The area says so in the palette; the panel reads which features from the same entry.
const health = env.api.commands.list().filter(command => command.id.endsWith(':health'));
assert.deepEqual(health, [{ id: 'wb-navigation-plus.plugin.js:health', title: 'Paused features of Navigation+', keywords: 'paused hideTrends' }]);
assert.deepEqual([...pausedFeatures(TABLE, env.api.commands.list())], ['hideTrends']);
assert.deepEqual([...pausedFeatures(TABLE, [{ id: 'wb-navigation-plus.plugin.js:health', keywords: 'paused hideAds nope navigation.keys' }])], ['navigation.keys'], 'only flags of that area');
assert.deepEqual([...pausedFeatures(TABLE, [{ id: 'other.plugin.js:health', keywords: 'paused hideTrends' }]), ...pausedFeatures(TABLE, null)], []);
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
assert.deepEqual(registry.active(), ['navigation.keys'], 'paused for the session');
// Turned off by its owner: nothing to report about it any more.
registry.setFlags({ 'navigation.keys': true });
assert.deepEqual(env.api.commands.list(), []);
registry.setFlags({ hideTrends: true, 'navigation.keys': true });
assert.equal(env.api.commands.list().length, 1);
assert.equal(timers.pending(), 0, 'no timer left behind');
registry.dispose();
// A signed hotfix replaces the selector, or switches the feature off.
hotfix = { selectors: { 'hideTrends.module': '[data-testid="trendV2"]' } };
const patched = registryFor(env, { timers, hotfix: () => hotfix, surfaces: () => ['timeline'] });
patched.define({ id: 'hideTrends', probes: { module: '[data-testid="trend"]' }, start(ctx) { used.push(ctx.selector('module')); } });
patched.setFlags({ hideTrends: true });
assert.deepEqual(used, ['[data-testid="trend"]', '[data-testid="trendV2"]']);
hotfix = { flags: { hideTrends: false } };
patched.refresh();
assert.deepEqual(patched.active(), []);
patched.dispose();
} finally { console.warn = original; }
});
test('registry: a probe that reads an English label waits for an English page instead of counting misses', () => {
const env = page();
const timers = fakeTimers();
(env.doc.documentElement as { getAttribute(): string }).getAttribute = () => 'tr';
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', probes: { label: { selector: '[aria-label="Trending"]', english: true } }, start() {} });
registry.setFlags({ hideTrends: true });
for (let n = 0; n < 5; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), ['hideTrends']);
assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'needs-english', probes: ['label'] }]);
registry.dispose();
});
test('registry: a probe with `when` only counts while the part of the page it lives in is there', () => {
const env = page();
const timers = fakeTimers();
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', probes: { trend: { selector: '[data-testid="trend"]', when: '[data-testid="sidebarColumn"]' } }, start() {} });
registry.setFlags({ hideTrends: true });
// A narrow window: no right column, so no verdict, however often.
for (let n = 0; n < 4; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), ['hideTrends']);
// The column is there and the selector still matches nothing: that is the site's markup changing.
env.matches.set('[data-testid="sidebarColumn"]', [{}]);
for (let n = 0; n < 3; n += 1) { env.go(n % 2 ? '/home' : '/explore'); timers.advance(3500); }
assert.deepEqual(registry.active(), []);
assert.equal(registry.health()[0]!.state, 'paused');
registry.dispose();
});
test('observeSelector: heavy pages skip observers that ask for it', () => {
const env = page();
const seen: string[] = [];
env.matches.set('article', [{}]);
env.location.pathname = '/home';
const stop = observeSelector(env.win as unknown as DomWindow, 'article', () => seen.push('x'), { offOnHeavy: true });
assert.deepEqual(seen, ['x']);
stop();
stop();
});
test('registry: a configured open shadow root gets the features\' sheets and counts for probes (a site part rendered inside one)', () => {
configureDomHub({ shadowHosts: ['[data-host]'] });
try {
const env = page();
const timers = fakeTimers();
class Sheet { css = ''; replaceSync(css: string) { this.css = css; } }
const inside = new Map<string, object[]>([['[data-row]', [{}]]]);
const root = {
nodeType: 11, adoptedStyleSheets: [] as Sheet[], ownerDocument: { defaultView: { CSSStyleSheet: Sheet } },
querySelector: (selector: string) => (inside.get(selector) ?? [])[0] ?? null,
querySelectorAll: (selector: string) => inside.get(selector) ?? [],
};
env.matches.set('[data-host]', [{ shadowRoot: root }]);
const registry = registryFor(env, { timers, surfaces: () => ['timeline'] });
registry.define({ id: 'hideTrends', probes: { row: '[data-row]' }, start(ctx) { ctx.css('[data-row]{outline:1px solid}'); } });
registry.setFlags({ hideTrends: true });
assert.deepEqual(root.adoptedStyleSheets.map(sheet => sheet.css), ['[data-row]{outline:1px solid}'], 'the sheet is adopted by the root');
assert.deepEqual(env.liveStyles(), ['[data-row]{outline:1px solid}'], 'and the page keeps its own');
// The probe's element exists only inside the root: never a miss, however many visits.
for (let visit = 0; visit < 4; visit++) { env.go(visit % 2 ? '/home' : '/explore'); timers.advance(4000); }
assert.deepEqual(registry.health(), []);
assert.deepEqual(registry.active(), ['hideTrends']);
registry.setFlags({ hideTrends: false });
assert.deepEqual(root.adoptedStyleSheets, [], 'stopping takes the sheet off the root');
registry.dispose();
} finally { configureDomHub({ shadowHosts: [] }); }
});

View file

@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { test } from 'node:test';
import { configureRuntime, isSiteUrl, type SiteAdapter } from '../src/site.ts';
import { addGate, addRewrite, addTap, addXhrGate, fetchHooked, isApiUrl } from '../src/netHub.ts';
import { isHeavyPath, watchDom } from '../src/domHub.ts';
import { configureDomHub, domRoots, isHeavyPath, observeSelector, watchDom } from '../src/domHub.ts';
const SITE: SiteAdapter = {
product: 'wayBetter for Test',
@ -210,3 +210,40 @@ test('dom hub: a failing feature does not stop the others', () => {
console.error = original;
}
});
test('dom hub: an open shadow root of a configured host is observed and searched like the page (the X chat embed, 2026-10-01)', async () => {
configureDomHub({ shadowHosts: ['[data-testid="embedRoute"]'] });
try {
const { win, observers, flush, mutate } = fakeDomWindow('/chat/1');
const observed: unknown[] = [];
const inRoot = [{ id: 'row-1' }, { id: 'row-2' }];
const root = { querySelectorAll: (selector: string) => (selector === '.row' ? inRoot : []) };
const host: { shadowRoot: unknown } = { shadowRoot: null };
const doc = win.document as unknown as Record<string, unknown>;
doc.querySelectorAll = (selector: string) => (selector === '[data-testid="embedRoute"]' ? [host] : []);
const seen: string[] = [];
const stop = observeSelector(win, '.row', element => seen.push((element as unknown as { id: string }).id));
// Every observe call is recorded (the page body first, then each root).
const entry = observers[0]!;
const FakeObserver = win.MutationObserver as unknown as { prototype: { observe(node: unknown, options: MutationObserverInit): void } };
const original = FakeObserver.prototype.observe;
FakeObserver.prototype.observe = function (node: unknown, options: MutationObserverInit) { observed.push(node); return original.call(this, node as Node, options); };
try {
assert.deepEqual(domRoots(win), [win.document], 'the host has no root yet: only the page');
mutate('childList'); flush();
assert.deepEqual(seen, [], 'nothing inside yet');
// The host attaches its root (no mutation for that); the next page mutation picks it up.
host.shadowRoot = root;
mutate('childList'); flush();
assert.ok(observed.includes(root), 'the root is observed by the one observer of the hub');
assert.deepEqual(domRoots(win), [win.document, root]);
assert.deepEqual(seen, ['row-1', 'row-2'], 'the selector observer found the rows inside the root');
inRoot.push({ id: 'row-3' });
entry.callback([{ type: 'childList' }] as unknown as MutationRecord[], {} as MutationObserver); flush();
assert.deepEqual(seen, ['row-1', 'row-2', 'row-3'], 'a mutation in the root wakes the same observer');
assert.equal(observers.length, 1, 'still one MutationObserver');
} finally { FakeObserver.prototype.observe = original; }
stop();
assert.equal(entry.connected, false, 'the last subscriber off disconnects it, roots included');
} finally { configureDomHub({ shadowHosts: [] }); }
});

View file

@ -15,6 +15,7 @@ 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';
import MENU_MESSAGES from '../../shell/src/frame/menuMessages.en.json' with { type: 'json' };
const here = dirname(fileURLToPath(import.meta.url));
@ -214,7 +215,7 @@ 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, ...PANEL_MESSAGES, ...INSTALLER_MESSAGES }, 'en.json is the kit, shell-model, store, shell-frame, panel and installer source');
assert.deepEqual(en.messages, { ...KIT_MESSAGES, ...SHELL_MESSAGES, ...STORE_MESSAGES, ...FRAME_MESSAGES, ...MENU_MESSAGES, ...PANEL_MESSAGES, ...INSTALLER_MESSAGES }, 'en.json is the kit, shell-model, store, shell-frame, app-menu, 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ı');
// Translator notes (en.meta.json): where a message appears, and fragments a language may leave empty.

View file

@ -79,6 +79,36 @@ test('injectCSS marks its style with the site data key and replaces in place', (
assert.equal(styles[0]!.isConnected, false);
});
test('injectCSS at document start waits for the document root instead of throwing', () => {
const observers: { fire(): void; disconnected: boolean }[] = [];
const { api, doc, win, styles } = fakeEnv();
Object.assign(win, {
MutationObserver: class {
disconnected = false;
callback: () => void;
constructor(callback: () => void) { this.callback = callback; observers.push(this); }
observe() {}
disconnect() { this.disconnected = true; }
fire() { this.callback(); }
},
});
const head = doc.head;
Object.assign(doc, { head: null, documentElement: null });
assert.doesNotThrow(() => api.injectCSS('early', 'a{}'));
api.injectCSS('early', 'b{}');
api.injectCSS('gone', 'c{}');
api.clearCSS('gone');
assert.equal(styles.filter(node => node.isConnected).length, 0);
assert.equal(observers.length, 1, 'one observer for every waiting style');
Object.assign(doc, { head, documentElement: {} });
observers[0]!.fire();
const connected = styles.filter(node => node.isConnected);
assert.equal(connected.length, 1, 'a cleared style is never attached');
assert.equal(connected[0]!.dataset.demoPlugin, 'early');
assert.equal(connected[0]!.textContent, 'b{}', 'the latest text wins');
assert.equal(observers[0]!.disconnected, true);
});
test('onKey skips typing, modifiers and the second key of site chords', () => {
const { api, doc } = fakeEnv();
const keys: string[] = [];

View file

@ -41,7 +41,7 @@ test('feature flags: parts install on enable and dispose on disable, in order, a
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 }]);
assert.deepEqual(applied, [{ gate: false, pill: false, css: false }], 'the full map: a flag the delivery does not name is at its default');
flags.apply({ gate: true, pill: true });
assert.deepEqual(log, ['+gate', '-gate', '+gate']);
assert.equal(flags.installed('pill'), false);
@ -57,13 +57,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go
const flags = createFeatureFlags<Flags>({ 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');
assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: false }, 'only known booleans; the column wins');
flags.apply({ pill: true, css: true });
assert.deepEqual(applied.at(-1), { gate: true, 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');
assert.deepEqual(applied.at(-1), { gate: true, 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');
assert.deepEqual(applied.at(-1), { gate: true, pill: true, css: true }, 'an ordinary tab again: the global flags');
flags.apply({});
assert.deepEqual(applied.at(-1), { gate: true, pill: false, css: true }, 'a delivery is the whole state: what it does not name is at its default');
assert.deepEqual(flags.current(), { gate: true, pill: false, css: true });
const before = applied.length;
flags.setColumnFlags(undefined);
assert.equal(applied.length, before, 'nothing to change');
@ -75,9 +78,16 @@ test('feature flags: a deck column overrides global flags; dropped overrides go
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');
assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false }, 'recorded at once: a global delivery already respects it');
listeners[0]!();
assert.deepEqual(late.at(-1), { pill: true, css: false });
assert.deepEqual(late.at(-1), { gate: true, pill: true, css: false });
// Ownership: `resolve` decides what runs; a column's own choice still wins.
const owned: Array<Partial<Flags>> = [];
const gated = createFeatureFlags<Flags>({ defaults: { gate: true, pill: false, css: true }, label: 'Demo', installers: [], apply: config => owned.push(config), resolve: all => (all.gate ? all : { ...all, css: false }) });
gated.apply({ gate: false });
assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: false }, 'the owner is off, so what it owns is off');
gated.setColumnFlags({ css: true });
assert.deepEqual(owned.at(-1), { gate: false, pill: false, css: true });
});
function runtimeWindow(queued: Record<string, unknown> = {}) {

View file

@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { checkEdit, createMarker, draftPack, readDraft, withDraft, DRAFT_KEY } from '../src/stringPackTranslate.ts';
import { inventoryLookup, type PageInventory } from '../src/stringPacks.ts';
import { installStringPacks, type CatalogHookAdapter, type CatalogSink } from '../src/stringPackHook.ts';
const INVENTORY: PageInventory = { site: 'demo', catalog: 'web', text: 'a0000001 a0000002', message: { b0000001: 'count*' }, closed: 'c0000001' };
test('marker: strings and string results carry an invisible key marker that reads back', () => {
const marker = createMarker();
const home = marker.mark('a0000001', 'Home') as string;
const posts = (marker.mark('b0000001', (e: { count: number }) => `${e.count} posts`) as (e: unknown) => string)({ count: 3 });
assert.notEqual(home, 'Home');
assert.equal(marker.strip(home), 'Home');
assert.equal(marker.strip(posts), '3 posts');
assert.deepEqual(marker.ids(`${home} and ${posts}`), ['a0000001', 'b0000001']);
assert.deepEqual(marker.ids('no markers'), []);
const element = { element: true };
assert.equal((marker.mark('c0000001', () => element) as () => unknown)(), element, 'an element result is left alone');
assert.equal(marker.mark('x', 42), 42);
});
test('edits: checked with the pack rules; the draft is a pack applied last', () => {
const lookup = inventoryLookup(INVENTORY);
assert.equal(checkEdit(lookup, 'a0000001', 'Hejmo'), null);
assert.match(checkEdit(lookup, 'a0000001', '<b>x</b>')!, /markup/);
assert.match(checkEdit(lookup, 'b0000001', '{total}')!, /not a parameter/);
assert.match(checkEdit(lookup, 'c0000001', 'x')!, /not translatable yet/);
assert.match(checkEdit(lookup, 'zzzzzzzz', 'x')!, /not in the inventory/);
const store = new Map<string, string>();
const storage = { getItem: (key: string) => store.get(key) ?? null };
assert.equal(readDraft(storage), null);
assert.deepEqual(withDraft(['p1'], storage, 'demo', 'web', INVENTORY), ['p1']);
store.set(DRAFT_KEY, JSON.stringify({ language: 'eo', name: 'Mine', strings: { a0000001: 'Hejmo' } }));
const packs = withDraft(['p1'], storage, 'demo', 'web', INVENTORY);
assert.equal(packs.length, 2);
assert.deepEqual(packs[1], draftPack(readDraft(storage)!, 'demo', 'web'));
assert.equal((packs[1] as { language: string }).language, 'eo');
store.set(DRAFT_KEY, '{broken');
assert.equal(readDraft(storage), null);
});
test('translate mode hooks the catalog even without a pack and marks every value', () => {
const hooked: { sink: CatalogSink | null } = { sink: null };
const adapter: CatalogHookAdapter = { catalog: 'web', install: (_win, s) => { hooked.sink = s; return () => {}; } };
const win = { setTimeout: () => 0, clearTimeout() {} } as unknown as Window;
const marker = createMarker();
installStringPacks(win, [{ adapter, inventory: INVENTORY, packs: [] }], { mark: (id, value) => marker.mark(id, value) });
assert.ok(hooked.sink, 'hooked without packs');
const value = hooked.sink.resolve('a0000001', 'Home') as string;
assert.equal(marker.strip(value), 'Home');
assert.deepEqual(marker.ids(value), ['a0000001']);
});

View file

@ -0,0 +1,565 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import {
applyPacks, checkPackShape, compilePack, coverage, createStringEngine, driftReport, hashText, inventoryLookup, isPageInventory, packInventory,
renderMessage, restoreCatalog, sliceInventory, validateString, type InventoryEntry, type StringInventory, type StringPack,
} from '../src/stringPacks.ts';
import { parseMessage } from '../src/i18n.ts';
import { installStringPacks, mapChunkRequires, watchChunkArray, type CatalogHookAdapter, type CatalogSink } from '../src/stringPackHook.ts';
import { installTextNet } from '../src/textNet.ts';
// A small site: two texts, two messages (one plural), one rich entry, one formatter, one lazy group.
const INVENTORY: StringInventory = {
format: 1, site: 'demo', catalog: 'web', base: 'en', build: 'b1',
entries: {
a0000001: { kind: 'text', hash: hashText('Home') },
a0000002: { kind: 'text', hash: hashText('Following') },
b0000001: { kind: 'message', params: ['name'], hash: hashText('Hello {name}') },
b0000002: { kind: 'message', params: ['count', 'name'], plural: ['count'], hash: hashText('{count} posts by {name}') },
c0000001: { kind: 'rich', hash: hashText('rich') },
d0000001: { kind: 'format', hash: hashText('fmt') },
e0000001: { kind: 'text', group: 'emoji', hash: hashText('Grinning face') },
},
};
/** The site's own values, as its catalog registers them. */
const site = () => ({
a0000001: 'Home',
a0000002: 'Following',
b0000001: (e: { name: string }) => `Hello ${e.name}`,
b0000002: (e: { count: number; name: string }) => `${e.count} ${e.count === 1 ? 'post' : 'posts'} by ${e.name}`,
c0000001: () => ({ element: true }),
d0000001: (n: number) => String(n),
e0000001: 'Grinning face',
});
const pack = (strings: Record<string, string>, extra: Partial<StringPack> = {}): StringPack => ({
format: 1, site: 'demo', catalog: 'web', language: 'en-x-test', name: 'Test', authors: ['A tester'], base: 'en', strings, ...extra,
});
test('hashText: stable, 11 characters, different for different text', () => {
assert.equal(hashText('Home'), hashText('Home'));
assert.match(hashText('Home'), /^[0-9a-z]{11}$/);
assert.notEqual(hashText('Home'), hashText('home'));
assert.equal(hashText(''), hashText(''));
});
test('pack envelope: what is refused as a whole', () => {
assert.deepEqual(checkPackShape(pack({ a0000001: 'Hoom' })), []);
const errors = (input: unknown) => checkPackShape(input).filter(issue => issue.level === 'error').map(issue => issue.message).join(' | ');
assert.match(errors([]), /JSON object/);
assert.match(errors({ ...pack({}), format: 2 }), /format/);
assert.match(errors({ ...pack({}), language: 'not a tag' }), /language/);
assert.match(errors({ ...pack({}), name: '<b>x</b>' }), /name/);
assert.match(errors({ ...pack({}), authors: 'me' }), /authors/);
assert.match(errors({ ...pack({}), strings: [] }), /strings/);
assert.match(errors({ ...pack({}), site: 'Demo Site' }), /site/);
assert.deepEqual(checkPackShape({ ...pack({}), extra: 1 }).map(issue => issue.level), ['warning']);
assert.throws(() => compilePack({ ...pack({}), format: 2 }, INVENTORY), /invalid string pack/);
assert.throws(() => compilePack(pack({}, { catalog: 'other' }), INVENTORY), /the pack is for demo\/other/);
});
test('validator: parameters, plural kind, other, markup', () => {
const entry = (id: string) => INVENTORY.entries[id]!;
const reason = (id: string, value: unknown) => { const result = validateString(entry(id), value); return 'reason' in result ? result.reason : ''; };
// Accepted.
assert.equal(reason('a0000001', 'Hoom'), '');
assert.equal(reason('b0000001', 'Ahoy {name}'), '');
assert.equal(reason('b0000001', 'Ahoy'), '', 'a subset of the parameters is fine');
assert.equal(reason('b0000002', '{count, plural, one {# postle} other {# postles}} by {name}'), '');
assert.equal(reason('b0000002', '{count, plural, =0 {nothing} other {#}}'), '');
assert.equal(reason('b0000002', '{count} by {name}'), '', 'a language without plural forms needs none');
assert.equal(reason('a0000001', "It's '{'fine'}'"), '', 'quoted braces are text');
// Refused.
assert.match(reason('a0000001', 'Hi {name}'), /takes no parameters/);
assert.match(reason('b0000001', 'Ahoy {user}'), /not a parameter of the original \(it has: name\)/);
assert.match(reason('b0000001', '{name, plural, one {a} other {b}}'), /not a plural of the original/);
assert.match(reason('b0000002', '{name, select, a {x} other {y}}'), /not a select of the original/);
assert.match(reason('b0000002', '{count, plural, one {a}}'), /"other"/);
assert.match(reason('b0000002', '{count, plural, lots {a} other {b}}'), /not a plural form/);
assert.match(reason('b0000002', '{count, selectordinal, one {a} other {b}}'), /selectordinal/);
assert.match(reason('b0000002', '{count, number}'), /not supported/);
assert.match(reason('b0000002', '{count, plural, offset:1 other {b}}'), /offset/);
assert.match(reason('a0000001', '<b>Home</b>'), /markup is not allowed/);
assert.match(reason('a0000001', 'a > b'), /markup is not allowed/);
assert.match(reason('a0000001', 'Home {'), /invalid message syntax/);
assert.match(reason('a0000001', ''), /empty/);
assert.match(reason('a0000001', 42), /must be text/);
assert.match(reason('a0000001', 'x'.repeat(2001)), /longer than/);
assert.match(reason('a0000001', 'a‮b'), /control or bidi/);
assert.match(reason('c0000001', 'text'), /not translatable yet \(rich\)/);
assert.match(reason('d0000001', 'text'), /not translatable yet \(format\)/);
});
test('validator: tag slots must be the original\'s', () => {
const shape: InventoryEntry = { kind: 'text', tags: ['link'], hash: 'x' };
const reason = (value: string) => { const result = validateString(shape, value); return 'reason' in result ? result.reason : ''; };
assert.equal(reason('Read <link>the rules</link>'), '');
assert.match(reason('Read the rules'), /tags are missing: <link>/);
assert.match(reason('Read <b>the</b> <link>rules</link>'), /<b> is not a tag of the original/);
assert.match(reason('Read <link>the rules'), /not closed/);
assert.match(reason('Read </link>the rules<link>'), /does not close/);
assert.match(reason('1 < 2 <link>x</link>'), /may only be used for the original's tags/);
});
test('compilePack: unknown keys are reported and never applied; bad values are rejected one by one', () => {
const compiled = compilePack(pack({
a0000001: 'Hoom', b0000001: 'Ahoy {name}', zzzzzzzz: 'Nope', a0000002: '<i>x</i>', c0000001: 'rich text', b0000002: '{count, plural, one {# postle} other {# postles}}',
}), INVENTORY);
assert.deepEqual([...compiled.values.keys()].sort(), ['a0000001', 'b0000001', 'b0000002']);
assert.deepEqual(compiled.report.unknown, ['zzzzzzzz']);
assert.deepEqual(compiled.report.rejected.map(item => item.id).sort(), ['a0000002', 'c0000001']);
assert.equal(compiled.report.total, 6);
assert.equal(compiled.report.valid, 3);
// An unknown key reaches the engine as nothing at all.
const engine = createStringEngine(INVENTORY, [compiled]);
assert.equal(engine.resolve('zzzzzzzz', 'Site text'), 'Site text');
assert.equal(engine.resolve('a0000002', 'Following'), 'Following', 'a rejected value leaves the original');
});
test('renderMessage: concatenation semantics, plural by the pack language, exact forms, select', () => {
const render = (source: string, params: Record<string, unknown>, languages: (string | undefined)[] = ['en']) => renderMessage(parseMessage(source), params, languages);
assert.equal(render('Ahoy {name}!', { name: 'Ada' }), 'Ahoy Ada!');
assert.equal(render('Ahoy {name}!', {}), 'Ahoy !');
assert.equal(render('{count} of them', { count: '1,234' }), '1,234 of them', 'a parameter is inserted as it comes');
const plural = '{count, plural, =0 {none} one {# postle} other {# postles}}';
assert.equal(render(plural, { count: 0 }), 'none');
assert.equal(render(plural, { count: 1 }), '1 postle');
assert.equal(render(plural, { count: 5 }), '5 postles');
assert.equal(render(plural, { count: '7' }), '7 postles');
assert.equal(render(plural, { count: 'many' }), 'many postles', 'not a number: other');
// A language the runtime does not know falls back to the pack's base, then to `other`.
assert.equal(render(plural, { count: 1 }, ['qqq-x-made-up', 'en']), '1 postle');
assert.equal(render(plural, { count: 1 }, ['zz-x-test', undefined]), '1 postles');
assert.equal(render(plural, { count: 1 }, ['en-x-test']), '1 postle', 'a private-use tag uses its language');
assert.equal(render('{count, plural, one {# gönderi} other {# gönderi}}', { count: 2 }, ['tr']), '2 gönderi');
assert.equal(render('{kind, select, a {first} other {rest}}', { kind: 'a' }), 'first');
assert.equal(render('{kind, select, a {first} other {rest}}', { kind: 'b' }), 'rest');
});
test('engine: a pack value when the key has one, otherwise exactly the site\'s value', () => {
const values = site();
const engine = createStringEngine(INVENTORY, [compilePack(pack({
a0000001: 'Hoom', b0000002: '{count, plural, one {# postle} other {# postles}} by {name}',
}), INVENTORY)]);
const out = applyPacks(values, engine);
assert.equal(out.a0000001, 'Hoom');
assert.equal((out.b0000002 as (e: unknown) => string)({ count: 1, name: 'Ada' }), '1 postle by Ada');
assert.equal((out.b0000002 as (e: unknown) => string)({ count: 3, name: 'Ada' }), '3 postles by Ada');
assert.equal((out.b0000002 as () => string)(), ' postles by ', 'called without parameters: still a string');
// Untouched keys are the very same values (same function objects).
for (const id of ['a0000002', 'b0000001', 'c0000001', 'd0000001', 'e0000001'] as const) assert.equal(out[id], values[id], id);
// The site's catalog object was not changed.
assert.deepEqual(Object.keys(values), Object.keys(site()));
assert.equal(values.a0000001, 'Home');
assert.deepEqual(engine.stats(), { seen: 7, applied: 2, unlisted: [], mismatched: [] });
});
test('engine: applying twice equals applying once', () => {
const values = site();
const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]);
const once = applyPacks(values, engine);
const twice = applyPacks(once, engine);
const again = applyPacks(values, engine);
for (const id of Object.keys(values)) {
assert.equal(twice[id], once[id], `${id}: second application changes nothing`);
assert.equal(again[id], once[id], `${id}: the same input gives the same value`);
}
assert.equal(engine.stats().applied, 2);
// A fresh engine (a reload) gives the same result for the same input.
const reloaded = applyPacks(values, createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]));
assert.equal(reloaded.a0000001, once.a0000001);
assert.equal((reloaded.b0000001 as (e: unknown) => string)({ name: 'Ada' }), (once.b0000001 as (e: unknown) => string)({ name: 'Ada' }));
});
test('engine: packs apply in the listed order, the later one wins per key', () => {
const language = compilePack(pack({ a0000001: 'Hoom', a0000002: 'Trailing' }, { name: 'Language' }), INVENTORY);
const rewording = compilePack(pack({ a0000001: 'Den' }, { name: 'Rewording' }), INVENTORY);
const first = applyPacks(site(), createStringEngine(INVENTORY, [language, rewording]));
assert.equal(first.a0000001, 'Den');
assert.equal(first.a0000002, 'Trailing', 'a key only the earlier pack has keeps its value');
const second = applyPacks(site(), createStringEngine(INVENTORY, [rewording, language]));
assert.equal(second.a0000001, 'Hoom');
// No packs: everything is the site's.
const none = applyPacks(site(), createStringEngine(INVENTORY, []));
assert.equal(none.a0000001, 'Home');
});
test('engine: restore gives back exactly the site\'s values', () => {
const values = site();
const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]);
const applied = applyPacks(values, engine);
assert.deepEqual([...engine.originals().keys()].sort(), ['a0000001', 'b0000001'], 'only what a pack changed is kept');
const restored = restoreCatalog(applied, engine);
for (const id of Object.keys(values) as (keyof typeof values)[]) assert.equal(restored[id], values[id], id);
assert.equal(applied.a0000001, 'Hoom', 'restoring does not change the applied object');
});
test('engine: a live value of another kind than the inventory says is left alone', () => {
const engine = createStringEngine(INVENTORY, [compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}' }), INVENTORY)]);
const fn = () => 'now a function';
assert.equal(engine.resolve('a0000001', fn), fn);
assert.equal(engine.resolve('b0000001', 'now a string'), 'now a string');
assert.deepEqual(engine.stats().mismatched.sort(), ['a0000001', 'b0000001']);
assert.equal(engine.stats().applied, 0);
// A key the site has and the inventory lacks is counted as drift.
assert.equal(engine.resolve('f0000009', 'New text'), 'New text');
assert.deepEqual(engine.stats().unlisted, ['f0000009']);
});
test('page inventory: the compact form answers like the full one', () => {
const page = packInventory(INVENTORY);
assert.equal(JSON.stringify(page).includes('hash'), false);
const full = inventoryLookup(INVENTORY);
const compact = inventoryLookup(page);
assert.equal(compact('a0000001')?.kind, 'text');
assert.equal(compact('e0000001')?.kind, 'text');
assert.deepEqual(compact('b0000002'), { kind: 'message', params: ['count', 'name'], plural: ['count'], select: [] });
assert.equal(compact('nope'), undefined);
assert.equal(full('nope'), undefined);
assert.equal(full('constructor'), undefined, 'inherited names are not keys');
for (const id of ['c0000001', 'd0000001']) assert.notEqual(compact(id)?.kind, 'text');
// The same pack compiles the same against both.
const strings = { a0000001: 'Hoom', b0000002: '{count, plural, one {#} other {#}}', c0000001: 'x', zzzzzzzz: 'y' };
const a = compilePack(pack(strings), INVENTORY);
const b = compilePack(pack(strings), page);
assert.deepEqual([...a.values.keys()], [...b.values.keys()]);
assert.deepEqual(a.report.unknown, b.report.unknown);
assert.deepEqual(a.report.rejected.map(item => item.id), b.report.rejected.map(item => item.id));
});
test('inventory slice: only what the packs name travels to the page, and decides the same', () => {
const strings = { a0000001: 'Hoom', b0000002: '{count, plural, one {#} other {#}}', c0000001: 'x', zzzzzzzz: 'y' };
const slice = sliceInventory(INVENTORY, Object.keys(strings));
assert.deepEqual(slice, { site: 'demo', catalog: 'web', text: 'a0000001', message: { b0000002: 'count* name' }, closed: 'c0000001', partial: true });
assert.deepEqual(sliceInventory(packInventory(INVENTORY), Object.keys(strings)), slice, 'a slice of the compact form is the same');
const full = compilePack(pack(strings), INVENTORY);
const sliced = compilePack(pack(strings), slice);
assert.deepEqual([...sliced.values.keys()], [...full.values.keys()]);
assert.deepEqual(sliced.report, full.report, 'unknown and refused keys are the same');
// A key outside the slice is the site's own value, and is not reported as a new key of the site.
const engine = createStringEngine(slice, [sliced]);
assert.equal(engine.resolve('a0000002', 'Following'), 'Following');
assert.equal(engine.resolve('a0000001', 'Home'), 'Hoom');
assert.deepEqual(engine.stats().unlisted, []);
// Untrusted data: the shape check.
assert.ok(isPageInventory(slice));
assert.ok(isPageInventory(JSON.parse(JSON.stringify(packInventory(INVENTORY)))));
for (const bad of [null, [], {}, { ...slice, text: 5 }, { ...slice, text: 'a <b>' }, { ...slice, message: { a: 'x<y' } }, { ...slice, site: 'Demo Site' }, { ...slice, partial: 'yes' }]) assert.equal(isPageInventory(bad), false);
});
test('coverage: per group, with what cannot be translated yet counted apart', () => {
const compiled = compilePack(pack({ a0000001: 'Hoom', b0000001: 'Ahoy {name}', e0000001: 'Grin' }), INVENTORY);
assert.deepEqual(coverage(INVENTORY, compiled), {
all: { translatable: 5, translated: 3, closed: 2 },
main: { translatable: 4, translated: 2, closed: 2 },
emoji: { translatable: 1, translated: 1, closed: 0 },
});
});
test('drift report: new, reworded, reshaped; vanished only for a group whose base catalog was loaded', () => {
const observed: Record<string, InventoryEntry> = {
a0000001: { kind: 'text', hash: hashText('Home') },
a0000002: { kind: 'text', hash: hashText('Following now') },
b0000001: { kind: 'message', params: ['name', 'title'], hash: hashText('Hello {name}') },
c0000001: { kind: 'rich', hash: hashText('rich') },
d0000001: { kind: 'format', hash: hashText('fmt') },
f0000001: { kind: 'text', hash: hashText('Brand new') },
};
assert.deepEqual(driftReport(INVENTORY, observed, ['main']), {
added: ['f0000001'], reworded: ['a0000002'], reshaped: ['b0000001'], vanished: ['b0000002'],
});
// The emoji group was never loaded: its key is not called vanished. With it loaded, it is.
assert.deepEqual(driftReport(INVENTORY, observed, ['main', 'emoji']).vanished, ['b0000002', 'e0000001']);
// Nothing loaded: nothing can be called vanished.
assert.deepEqual(driftReport(INVENTORY, observed, []).vanished, []);
assert.deepEqual(driftReport(INVENTORY, INVENTORY.entries, ['main', 'emoji']), { added: [], reworded: [], reshaped: [], vanished: [] });
});
// -------------------------------------------------------------------------------------------
// The chunk array hook
/** A stand-in for webpack's runtime: takes over `push`, replays what is there, installs modules. */
function webpackRuntime(array: unknown[]) {
const installed: Record<string, unknown> = {};
const parentPush = array.push.bind(array);
const callback = (parent: ((chunk: unknown) => number) | 0, chunk: unknown) => {
const [, modules] = chunk as [unknown, Record<string, unknown>];
Object.assign(installed, modules);
if (parent) parent(chunk);
return 0;
};
array.forEach(chunk => callback(0, chunk));
array.push = ((chunk: unknown) => callback(parentPush, chunk)) as typeof array.push;
return installed;
}
test('chunk array hook: every chunk is seen once, before the site gets it, whichever loads first', () => {
const win: Record<string, unknown> & { document: { currentScript: { src: string } | null } } = { document: { currentScript: { src: 'https://cdn.test/a.js' } } };
const seen: string[] = [];
watchChunkArray(win, 'chunks', (chunk, script) => { seen.push(`${String((chunk[0] as unknown[])[0])}@${script}`); });
const array = win.chunks as unknown[];
const early = [[1], { m1: () => 1 }];
array.push(early);
assert.equal(array.length, 1, 'before the runtime loads, push is still the array\'s own');
const installed = webpackRuntime(array);
win.document.currentScript = { src: 'https://cdn.test/b.js' };
const late = [[2], { m2: () => 2 }];
array.push(late);
win.document.currentScript = null;
array.push([[3], {}]);
assert.deepEqual(seen, ['1@https://cdn.test/a.js', '2@https://cdn.test/b.js', '3@']);
assert.deepEqual(Object.keys(installed), ['m1', 'm2']);
assert.deepEqual(array, [early, late, [[3], {}]], 'the array holds the same chunks in the same order');
});
test('chunk array hook: a chunk nobody maps passes through byte-identical', () => {
const win: Record<string, unknown> = {};
watchChunkArray(win, 'chunks', () => { /* looks, touches nothing */ });
const array = win.chunks as unknown[];
const installed = webpackRuntime(array);
const factory = function (module: { exports: unknown }) { module.exports = 42; };
const runtime = () => {};
const chunk = [[7, 8], { m7: factory }, runtime];
const snapshot = { ids: chunk[0], modules: chunk[1], source: factory.toString(), keys: Object.keys(chunk[1] as object) };
array.push(chunk);
assert.equal(array[0], chunk, 'the same chunk object reaches the array');
assert.equal(chunk.length, 3);
assert.equal(chunk[0], snapshot.ids);
assert.equal(chunk[1], snapshot.modules);
assert.equal(chunk[2], runtime);
assert.equal((chunk[1] as Record<string, unknown>).m7, factory, 'the same factory function');
assert.equal(installed.m7, factory);
assert.equal(factory.toString(), snapshot.source);
assert.deepEqual(Object.keys(chunk[1] as object), snapshot.keys);
});
test('chunk array hook: fails open, and removal puts the site\'s push back', () => {
const win: Record<string, unknown> = {};
const remove = watchChunkArray(win, 'chunks', () => { throw new Error('boom'); });
const array = win.chunks as unknown[];
const installed = webpackRuntime(array);
const sitePush = Object.getOwnPropertyDescriptor(array, 'push');
assert.ok(sitePush?.get, 'the accessor is ours while installed');
assert.doesNotThrow(() => array.push([[1], { m1: 1 }]));
assert.deepEqual(Object.keys(installed), ['m1']);
remove();
assert.equal(typeof Object.getOwnPropertyDescriptor(array, 'push')?.value, 'function', 'a plain property again');
array.push([[2], { m2: 2 }]);
assert.deepEqual(Object.keys(installed), ['m1', 'm2']);
assert.equal(array.length, 2);
// Removed before any runtime took over: the array has no own push left.
const other: Record<string, unknown> = {};
watchChunkArray(other, 'chunks', () => {})();
assert.equal(Object.prototype.hasOwnProperty.call(other.chunks, 'push'), false);
// An existing array is kept (the site's `||= []` finds it).
const existing: unknown[] = [];
const third: Record<string, unknown> = { chunks: existing };
watchChunkArray(third, 'chunks', () => {});
assert.equal(third.chunks, existing);
});
test('mapChunkRequires: a module sees a shadow of what it requires; the required module is unchanged', () => {
const registry = { register: (language: string) => `site:${language}`, other: 1 };
const require = Object.assign((id: string): any => (id === 'registry' ? registry : { id }), { e: 'kept' });
const results: unknown[] = [];
const factory = function (this: unknown, module: { exports: unknown }, _exports: unknown, req: typeof require) {
results.push(req('registry').register('en'), req('plain'), req.e, this);
module.exports = 'done';
};
const chunk: [unknown, Record<string, unknown>] = [[1], { m: factory }];
mapChunkRequires(chunk, exports => {
if (exports !== registry) return undefined;
const shadow = Object.create(registry) as typeof registry;
Object.defineProperty(shadow, 'register', { value: (language: string) => `ours:${language}` });
return shadow;
});
assert.notEqual(chunk[1].m, factory);
const module = { exports: {} as unknown };
(chunk[1].m as (...args: unknown[]) => void).call('self', module, module.exports, require);
assert.deepEqual(results, ['ours:en', { id: 'plain' }, 'kept', 'self']);
assert.equal(module.exports, 'done');
assert.equal(registry.register('en'), 'site:en', 'the site\'s module is untouched');
assert.deepEqual(Object.keys(registry), ['register', 'other']);
// A throwing map hands out the module's own exports.
const failing: [unknown, Record<string, unknown>] = [[2], { m: factory }];
mapChunkRequires(failing, () => { throw new Error('boom'); });
results.length = 0;
(failing[1].m as (...args: unknown[]) => void).call('self', module, module.exports, require);
assert.equal(results[0], 'site:en');
});
// -------------------------------------------------------------------------------------------
// Adapters and the self-check
function fakeWindow() {
const timers: (() => void)[] = [];
const win = { setTimeout: (fn: () => void) => { timers.push(fn); return timers.length; }, clearTimeout: () => {} } as unknown as Window;
return { win, settle: () => { for (const fn of timers.splice(0)) fn(); } };
}
/** An adapter driven by the test: `drive` plays the site. */
function adapter(catalog = 'web') {
const state: { sink: CatalogSink | null; removed: number } = { sink: null, removed: 0 };
const hook: CatalogHookAdapter = { catalog, install: (_win, sink) => { state.sink = sink; return () => { state.removed += 1; }; } };
return { hook, state };
}
test('self-check: ok, "hook not matched" and "no catalog seen" are distinct', () => {
const packs = [pack({ a0000001: 'Hoom' })];
// ok: a catalog file was seen, the hook matched, keys went through.
{
const { win, settle } = fakeWindow();
const { hook, state } = adapter();
const told: string[] = [];
const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) });
assert.equal(handle.status(), 'pending');
state.sink!.seen();
state.sink!.matched('en-GB');
assert.equal(state.sink!.resolve('a0000001', 'Home'), 'Hoom');
assert.equal(state.sink!.resolve('a0000002', 'Following'), 'Following');
assert.equal(handle.status(), 'ok');
settle();
assert.deepEqual(told, ['ok'], 'told once');
const [report] = handle.report();
assert.deepEqual({ status: report!.status, languages: report!.languages, seen: report!.seen, applied: report!.engine.applied }, { status: 'ok', languages: ['en-GB'], seen: { main: 1 }, applied: 1 });
handle.dispose();
assert.equal(state.removed, 1);
}
// A catalog file was seen but nothing went through the hook.
{
const { win, settle } = fakeWindow();
const { hook, state } = adapter();
const told: string[] = [];
const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) });
state.sink!.seen('main');
assert.equal(handle.status(), 'pending');
settle();
assert.equal(handle.status(), 'not-matched');
assert.deepEqual(told, ['not-matched']);
}
// No catalog file at all.
{
const { win, settle } = fakeWindow();
const { hook } = adapter();
const told: string[] = [];
const handle = installStringPacks(win, [{ adapter: hook, inventory: INVENTORY, packs }], { onStatus: report => told.push(report.status) });
settle();
assert.equal(handle.status(), 'no-catalog');
assert.deepEqual(told, ['no-catalog']);
}
});
test('install: no usable pack means no hook; several catalogs keep their own packs', () => {
const { win } = fakeWindow();
const web = adapter('web');
const guest = adapter('guest');
const guestInventory: StringInventory = { format: 1, site: 'demo', catalog: 'guest', base: 'en', entries: { 'Sign in': { kind: 'text', hash: hashText('Sign in') } } };
const handle = installStringPacks(win, [
{ adapter: web.hook, inventory: INVENTORY, packs: [] },
{ adapter: guest.hook, inventory: guestInventory, packs: [pack({ 'Sign in': 'Sign inne' }, { catalog: 'guest' }), pack({ a0000001: 'Hoom' }), 'not a pack'] },
]);
assert.equal(web.state.sink, null, 'a catalog without packs is not hooked');
assert.ok(guest.state.sink);
assert.equal(guest.state.sink!.resolve('Sign in', 'Sign in'), 'Sign inne');
const report = handle.report();
assert.equal(report[1]!.packs.length, 1);
assert.equal(report[1]!.refused.length, 2, 'a pack for another catalog and a malformed one are refused as a whole');
assert.equal(handle.engine('web'), undefined);
assert.ok(handle.engine('guest'));
// Only unknown keys: nothing usable, nothing hooked.
const third = adapter();
installStringPacks(win, [{ adapter: third.hook, inventory: INVENTORY, packs: [pack({ zzzzzzzz: 'x' })] }]);
assert.equal(third.state.sink, null);
});
test('install: an adapter or engine that throws leaves the site\'s value', () => {
const { win } = fakeWindow();
const broken: CatalogHookAdapter = { catalog: 'web', install: () => { throw new Error('boom'); } };
assert.doesNotThrow(() => installStringPacks(win, [{ adapter: broken, inventory: INVENTORY, packs: [pack({ a0000001: 'Hoom' })] }]).dispose());
});
// -------------------------------------------------------------------------------------------
// The DOM safety net (a minimal document: text nodes, elements, attributes)
type FakeNode = { nodeType: number; nodeValue: string | null; parentElement: FakeElement | null };
class FakeElement {
nodeType = 1;
nodeValue = null;
parentElement: FakeElement | null = null;
children: (FakeElement | FakeNode)[] = [];
attrs = new Map<string, string>();
tag: string;
constructor(tag: string, attrs: Record<string, string> = {}) { this.tag = tag; for (const [k, v] of Object.entries(attrs)) this.attrs.set(k, v); }
add<T extends FakeElement | FakeNode>(child: T): T { child.parentElement = this; this.children.push(child); return child; }
text(value: string): FakeNode { return this.add({ nodeType: 3, nodeValue: value, parentElement: null }); }
getAttribute(name: string) { return this.attrs.get(name) ?? null; }
setAttribute(name: string, value: string) { this.attrs.set(name, value); }
hasAttribute(name: string) { return this.attrs.has(name); }
closest(selector: string): FakeElement | null {
const tags = selector.split(',').map(part => part.trim());
for (let el: FakeElement | null = this; el; el = el.parentElement) if (tags.includes(el.tag)) return el;
return null;
}
all(): FakeElement[] { return this.children.flatMap(child => (child instanceof FakeElement ? [child, ...child.all()] : [])); }
querySelectorAll(selector: string) { const name = selector.slice(1, -1); return this.all().filter(el => el.attrs.has(name)); }
textNodes(): FakeNode[] { return this.children.flatMap(child => (child instanceof FakeElement ? child.textNodes() : [child])); }
}
function fakeDocument() {
const root = new FakeElement('html');
let callback: (records: unknown[]) => void = () => {};
let observing = false;
const win = {
document: {
documentElement: root,
createTreeWalker(element: FakeElement) {
const nodes = element.textNodes();
let index = -1;
return { get currentNode() { return nodes[index]; }, nextNode() { index += 1; return index < nodes.length; } };
},
querySelectorAll: (selector: string) => [...(root.attrs.has(selector.slice(1, -1)) ? [root] : []), ...root.querySelectorAll(selector)],
},
MutationObserver: class { constructor(fn: (records: unknown[]) => void) { callback = fn; } observe() { observing = true; } disconnect() { observing = false; } },
};
return { root, win: win as unknown as Window, mutate: (records: unknown[]) => { if (observing) callback(records); } };
}
test('text net: exact texts and attributes are replaced once, rewritten nodes are looked at again, dispose restores', () => {
const { root, win, mutate } = fakeDocument();
const nav = root.add(new FakeElement('nav', { 'aria-label': 'Trending' }));
const label = nav.text('Trending');
const other = nav.text('Trending topics today');
const script = root.add(new FakeElement('script'));
const code = script.text('Trending');
const net = installTextNet(win, { map: new Map([['Trending', 'Trendish'], ['News', 'Newsish']]), skip: 'script' });
assert.equal(label.nodeValue, 'Trendish');
assert.equal(nav.getAttribute('aria-label'), 'Trendish');
assert.equal(other.nodeValue, 'Trending topics today', 'only an exact text is a match');
assert.equal(code.nodeValue, 'Trending', 'skipped elements are not touched');
assert.equal(net.count(), 2);
// Our own writes come back as mutations: nothing changes further.
mutate([{ type: 'characterData', target: label }, { type: 'attributes', target: nav, attributeName: 'aria-label' }]);
assert.equal(label.nodeValue, 'Trendish');
assert.equal(net.count(), 2);
// A node added later, and the site rewriting a node.
const added = new FakeElement('div', { title: 'News' });
const news = added.text('News');
root.add(added);
mutate([{ type: 'childList', addedNodes: [added] }]);
assert.equal(news.nodeValue, 'Newsish');
assert.equal(added.getAttribute('title'), 'Newsish');
label.nodeValue = 'News';
mutate([{ type: 'characterData', target: label }]);
assert.equal(label.nodeValue, 'Newsish');
label.nodeValue = 'Something of the site';
mutate([{ type: 'characterData', target: label }]);
assert.equal(label.nodeValue, 'Something of the site');
assert.equal(net.count(), 3);
net.dispose();
assert.equal(news.nodeValue, 'News');
assert.equal(added.getAttribute('title'), 'News');
assert.equal(nav.getAttribute('aria-label'), 'Trending');
assert.equal(label.nodeValue, 'Something of the site');
assert.equal(net.count(), 0);
// Disposed: later mutations do nothing.
label.nodeValue = 'Trending';
mutate([{ type: 'characterData', target: label }]);
assert.equal(label.nodeValue, 'Trending');
});

View file

@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { themeDoctor } from '../src/themeDoctor.ts';
import { sanitizeSpec } from '../src/themeSpec.ts';
const ids = (raw: unknown) => themeDoctor(sanitizeSpec(raw)).map(advice => advice.id);
test('a theme made of tokens and component settings gets no advice', () => {
assert.deepEqual(ids({ name: 'Clean', colors: { bg: '#000000', text: '#ffffff', accent: '#1d9bf0' }, components: { button: { radius: 4 } } }), []);
});
test('free-form CSS is pointed at the lighter mechanism and its costs', () => {
const css = [
'a { border-radius: 0; }',
'.x { display: none; }',
'.y { color: #ff0000; }',
'.z { font-family: Comic Sans MS; }',
'div:has(img) { opacity: .9; }',
'* { box-sizing: border-box; }',
'.g { backdrop-filter: blur(8px); }',
'button:focus { outline: none; }',
'.m { transition: all .2s; }',
'.b { box-shadow: inset 1px 1px #fff, inset -1px -1px #000, inset 2px 2px #ddd; }',
].join('\n');
const found = ids({ name: 'Heavy', css });
for (const id of ['css-radius', 'css-hide', 'css-color', 'css-font', 'css-has', 'css-universal', 'css-blur', 'css-outline-none', 'css-motion', 'css-bevel']) {
assert.ok(found.includes(id), `${id} is reported`);
}
});
test('advice is a hint, never a change: the theme is left as it was', () => {
const theme = sanitizeSpec({ name: 'Keep', css: '.x { display: none; }' });
const before = JSON.stringify(theme);
themeDoctor(theme);
assert.equal(JSON.stringify(theme), before);
});
test('unreadable colors are named with their contrast', () => {
const advice = themeDoctor(sanitizeSpec({ name: 'Low', colors: { bg: '#000000', text: '#111111', accent: '#1d9bf0' } }));
const text = advice.find(item => item.id === 'contrast-text');
assert.ok(text, 'text contrast is reported');
assert.equal(text.kind, 'contrast');
assert.match(text.text, /\d\.\d\d:1/);
});

View file

@ -5,7 +5,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { FONT_ROLE_NAMES, MONO_FONT, contrastRatio } from '../src/themeApi.ts';
import { choiceForId, createThemeCatalog, serializeChoice, MAX_USER_THEMES } from '../src/themeChoice.ts';
import { SNAPSHOT_LOCAL_MAX, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
import { SNAPSHOT_LOCAL_MAX, collectRules, readSnapshot, resolvedFonts, writeSnapshot, type ThemeSnapshot } from '../src/themeRuntime.ts';
import {
BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, FONT_CHOICES, ROLE_LIMITS, applyOverrides, backgroundLayers, ensureContrast, fontChoiceOf, fontStack, isNeutral,
pageBackgroundCss, parseThemeJson, resolveFontRoles, sanitizeSpec, withFamily, withRoles, type ThemeSpec,
@ -197,3 +197,58 @@ test('garbage in storage is no snapshot', () => {
stores.local!.setItem('wb:theme-snapshot', JSON.stringify({ key: 1, css: 'a{}' }));
assert.equal(readSnapshot(stores), null);
});
// collectRules: the site's rules as they take effect
type FakeRule = { selectorText?: string; style?: { getPropertyValue(name: string): string; length: number }; cssRules?: FakeRule[]; conditionText?: string; type?: number };
const decl = (values: Record<string, string>) => ({ getPropertyValue: (name: string) => values[name] ?? '', length: Object.keys(values).length });
const styleRule = (selectorText: string, values: Record<string, string>, cssRules: FakeRule[] = []): FakeRule => ({ selectorText, style: decl(values), cssRules });
const supportsRule = (conditionText: string, cssRules: FakeRule[]): FakeRule => ({ type: 12, conditionText, cssRules });
const mediaRule = (conditionText: string, cssRules: FakeRule[]): FakeRule => ({ type: 4, conditionText, cssRules });
const fakeDoc = (rules: FakeRule[], supports = (_condition: string) => true) => ({ styleSheets: [{ ownerNode: null, cssRules: rules }], defaultView: { CSS: { supports } } }) as unknown as Document;
const MIX = '(color: color-mix(in lab, red, red))';
test('collectRules reads a Tailwind opacity utility as its nested @supports value, not its solid fallback', () => {
const rules = collectRules(fakeDoc([
styleRule('.dark\:bg-white\/15', { 'background-color': 'var(--x-white)', 'border-radius': '9999px' }, [
supportsRule(MIX, [{ style: decl({ 'background-color': 'color-mix(in oklab, var(--x-white) 15%, transparent)' }) }]),
]),
styleRule('.plain', { color: 'rgb(1, 2, 3)' }),
]), null);
assert.equal(rules.length, 2, 'one rule per selector, the nested declarations are not a rule of their own');
assert.equal(rules[0]!.selectorText, '.dark\:bg-white\/15');
assert.equal(rules[0]!.style.getPropertyValue('background-color'), 'color-mix(in oklab, var(--x-white) 15%, transparent)');
assert.equal(rules[0]!.style.getPropertyValue('border-radius'), '9999px', 'what the group does not re-declare stays the rule\'s own');
assert.equal(rules[0]!.style.length, 2);
assert.equal(rules[1]!.style.getPropertyValue('color'), 'rgb(1, 2, 3)');
});
test('collectRules: the `& { }` form of nested declarations counts, a nested rule with its own selector does not', () => {
const [rule] = collectRules(fakeDoc([
styleRule('.border-accent\/50', { 'border-color': 'hsl(var(--accent))' }, [
supportsRule(MIX, [styleRule('&', { 'border-color': 'color-mix(in oklab, hsl(var(--accent)) 50%, transparent)' }), styleRule('&:hover', { 'border-color': 'red' })]),
mediaRule('(hover: hover)', [{ style: decl({ 'border-color': 'blue' }) }]),
]),
]), null);
assert.equal(rule!.style.getPropertyValue('border-color'), 'color-mix(in oklab, hsl(var(--accent)) 50%, transparent)');
});
test('collectRules keeps the fallback where the browser fails the @supports condition, and skips such top-level groups', () => {
const rules = collectRules(fakeDoc([
styleRule('.bg-white\/15', { 'background-color': 'var(--x-white)' }, [supportsRule(MIX, [{ style: decl({ 'background-color': 'color-mix(in oklab, var(--x-white) 15%, transparent)' }) }])]),
supportsRule(MIX, [styleRule('.hover\:bg-white\/10:hover', { 'background-color': 'color-mix(in oklab, var(--x-white) 10%, transparent)' })]),
mediaRule('(hover: hover)', [styleRule('.in-media', { color: 'red' })]),
], () => false), null);
assert.deepEqual(rules.map(rule => rule.selectorText), ['.bg-white\/15', '.in-media']);
assert.equal(rules[0]!.style.getPropertyValue('background-color'), 'var(--x-white)');
});
test('collectRules leaves the engine\'s own sheet out and survives a cross-origin sheet', () => {
const own = { id: 'own' } as unknown as HTMLStyleElement;
const doc = { styleSheets: [
{ ownerNode: own, cssRules: [styleRule('.ours', { color: 'red' })] },
{ ownerNode: null, get cssRules(): FakeRule[] { throw new Error('SecurityError'); } },
{ ownerNode: null, cssRules: [supportsRule(MIX, [mediaRule('(hover: hover)', [styleRule('.deep', { color: 'red' })])])] },
], defaultView: null } as unknown as Document;
assert.deepEqual(collectRules(doc, own).map(rule => rule.selectorText), ['.deep']);
});

View file

@ -0,0 +1,278 @@
// A theme's structure groups (components, variants, decoration, icons) and icon packs: what the
// sanitizers accept, what the compilers emit, and that the published schemas are generated from the
// same tables. Site selectors here are made up; a site's own part map is tested in that site's app.
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { contrastRatio } from '../src/themeApi.ts';
import {
COMPONENTS, COMPONENT_IDS, PRESETS, TOKEN_LIMITS, compileComponents, partRule, readableRole, resolveComponents, sanitizeComponents,
type ComponentContext, type PartMap, type RoleColors,
} from '../src/themeComponents.ts';
import { chromeTitle, compileDecor, cssString, sanitizeDecor } from '../src/themeDecor.ts';
import {
BASE_ICON_STYLE, ICON_LIMITS, ICON_NAMES, PATH_GRAMMAR, compileIcons, createIconCatalog, glyphSvg, iconGroupsPresent, normalizeIconChoice, parseIconPackJson, sanitizeGlyph,
sanitizeIconPack, sanitizeThemeIcons, type IconPack, type IconTable,
} from '../src/themeIcons.ts';
import { applyOverrides, hasStructure, isNeutral, sanitizeSpec } from '../src/themeSpec.ts';
import { VARIANT_AXES, compileVariants, resolveVariants, sanitizeVariants } from '../src/themeVariants.ts';
const COLORS: RoleColors = {
bg: '#ffffff', surface: '#f5f8fa', elevated: '#e8f1f7', page: '#c0deed', border: '#e1e8ed', text: '#292f33', muted: '#5b6b78',
accent: '#0077b0', onAccent: '#ffffff', inverse: '#0077b0', onInverse: '#ffffff',
};
const CTX: ComponentContext = {
colors: COLORS,
fonts: { interface: 'Helvetica, sans-serif', post: 'Georgia, serif', heading: 'Helvetica, sans-serif', numbers: 'Helvetica, sans-serif', mono: 'monospace', chrome: 'system-ui', dialog: 'system-ui' },
};
const PARTS: PartMap = {
post: { sel: '[data-part="post"]' },
postText: { sel: '[data-part="text"]', text: '[data-part="text"],[data-part="text"] :is(span,a)' },
buttonPrimary: { sel: '[data-part="primary"]', text: '[data-part="primary"] span' },
buttonSecondary: { sel: '[data-part="secondary"]' },
avatar: { sel: '[data-part="avatar"]', skip: ['size'] },
handle: { sel: '[data-part="handle"]' },
search: { sel: '[data-part="search"]' },
};
const css = (components: unknown) => { const out = compileComponents(sanitizeComponents(components) ?? {}, PARTS, CTX); return { ...out, text: [...out.values, ...out.rules].join('\n') }; };
test('component tokens are clamped, unknown names and tokens a component does not take are dropped', () => {
const clean = sanitizeComponents({
post: { radius: 999, borderWidth: -3, borderStyle: 'groove', fill: '#ff0000', padX: 12.6, shadow: 'soft', visible: false, fontSize: 40, corner: 'cut', nonsense: 1 },
avatar: { shape: 'hexagon', size: 3, visible: false, corner: 'cut' },
postText: { fontSize: 99, case: 'upper', weight: 433, tracking: 9, leading: 0.2, font: 'post' },
buttonPrimary: { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 720 }, hover: { lift: 40, scale: 2, underline: true, fill: 'url(x)' } },
topBar: { fill: 'glass', height: 1 },
handle: { fill: 'glass', preset: 'bevel' },
rocket: { radius: 4 },
nav: 'javascript:alert(1)',
})!;
assert.deepEqual(clean.post, { radius: TOKEN_LIMITS.radius[1], borderWidth: 0, padX: 13, shadow: 'soft', corner: 'cut' }, 'no literal color, no unknown style, no font size or visibility on a post');
assert.deepEqual(clean.avatar, { size: 20, shape: 'hexagon', visible: false });
assert.deepEqual(clean.postText, { fontSize: 24, font: 'post', weight: 450, tracking: 0.2, leading: 1.1 }, 'post text never changes case');
assert.deepEqual(clean.buttonPrimary, { preset: 'bevel', radius: 'pill', fill: { from: 'accent', to: 'surface', angle: 360 }, hover: { lift: 4, scale: 1.04, underline: true } });
assert.deepEqual(clean.topBar, { fill: 'glass', height: 40 });
assert.equal(clean.handle, undefined, 'glass is for bars and panels; a handle has no presets');
assert.ok(!('rocket' in clean) && !('nav' in clean));
assert.equal(sanitizeComponents({ post: {} }), null);
assert.equal(sanitizeComponents('nope'), null);
});
test('presets and parents: own tokens win over the preset, the preset over the parent', () => {
const resolved = resolveComponents(sanitizeComponents({ button: { radius: 4, weight: 700 }, buttonPrimary: { preset: 'pill', borderWidth: 2 }, panel: { preset: 'window' }, menu: { radius: 8 } })!);
assert.deepEqual(resolved.buttonPrimary, { radius: 'pill', weight: 700, borderWidth: 2 });
assert.deepEqual(resolved.buttonSecondary, { radius: 4, weight: 700 });
assert.equal(resolved.menu!.radius, 8);
assert.equal(resolved.menu!.borderStyle, 'bevel-out');
assert.equal(resolved.dialog!.radius, 0);
// Every preset is itself valid vocabulary for a component of its family.
for (const [family, presets] of Object.entries(PRESETS)) {
const id = COMPONENT_IDS.find(item => (COMPONENTS[item] as { presets?: string }).presets === family)!;
for (const [name, tokens] of Object.entries(presets)) assert.deepEqual(sanitizeComponents({ [id]: tokens })![id], tokens, `${family}.${name}`);
}
});
test('compiled components: soft values, rigid rules, nothing for a part the site does not have', () => {
const out = css({ post: { radius: 0, borderWidth: 1, borderColor: 'border', padX: 16, fill: 'surface' }, postText: { fontSize: 17, font: 'post', leading: 1.5 }, nav: { width: 200 }, avatar: { size: 32, shape: 'square' } });
assert.ok(out.values.includes('--wb-part-post-radius:0px') && out.values.includes('--wb-part-postText-font-size:17px') && out.values.includes('--wb-part-postText-line-height:1.5'));
assert.ok(out.rules.includes(':root:root [data-part="post"]{background-color:var(--wb-part-post-fill) !important;background-image:var(--wb-part-post-fill-1) !important;border-radius:var(--wb-part-post-radius) !important;border-width:var(--wb-part-post-border-width) !important;border-style:var(--wb-part-post-border-style) !important;border-color:var(--wb-part-post-border-color) !important;padding-inline:var(--wb-part-post-pad-x) !important}'), out.rules[0]);
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="text"],:root:root [data-part="text"] :is(span,a){') && rule.includes('font-family:var(--wb-part-postText-font)')), 'type lands on the text leaves');
assert.ok(!out.text.includes('nav') && !out.text.includes('--wb-part-avatar-size'), 'no part, or a skipped token: no rule');
assert.ok(out.text.includes('--wb-part-avatar-shape:2px'));
// Every rule is important and every value it reads was emitted with it.
for (const rule of out.rules) for (const name of rule.match(/var\((--[\w-]+)\)/g) ?? []) assert.ok(out.values.some(value => value.startsWith(`${name.slice(4, -1)}:`)), name);
assert.equal(partRule('a, b:is(c,d)'), ':root:root a,:root:root b:is(c,d)');
assert.equal(compileComponents({}, PARTS, CTX).rules.length, 0);
});
test('text on a fill the theme chose keeps its contrast: the role is swapped for a readable one', () => {
// Accent text on an accent button (1:1), and a post filled with the theme's text color.
const out = css({ buttonPrimary: { fill: 'accent', text: 'accent' }, post: { fill: 'text' }, postText: { text: 'muted' }, avatar: { fill: 'surface' } });
assert.ok(out.values.includes(`--wb-part-buttonPrimary-text:${COLORS.onAccent}`));
assert.ok(out.notes.some(note => note.startsWith('buttonPrimary:')));
assert.ok(out.values.includes(`--wb-part-postText-text:${COLORS.muted}`), 'no fill of its own: the theme\'s role stands (the palette guarantees it on the theme\'s surfaces)');
assert.ok(!out.text.includes('--wb-part-avatar-text'), 'a fill alone colors no text on a part that is not a text part');
assert.equal(readableRole('#000000', COLORS), 'onAccent');
for (const role of ['accent', 'text', 'surface', 'inverse'] as const) {
const label = css({ buttonPrimary: { fill: role } }).values.find(value => value.startsWith('--wb-part-buttonPrimary-text:'))!.split(':')[1]!;
assert.ok(contrastRatio(label, COLORS[role]) >= 4.5, `${role}: ${label}`);
}
});
test('bevels are four inset lines from the part\'s fill; states move only without reduced motion', () => {
const out = css({ buttonPrimary: { preset: 'bevel', hover: { lift: 2, fill: 'elevated' }, active: { shadow: 'inset', scale: 0.98 }, focus: { borderColor: 'accent' } } });
const bevel = out.values.find(value => value.startsWith('--wb-part-buttonPrimary-bevel:'))!;
assert.equal(bevel.match(/inset/g)!.length, 4);
assert.ok(out.values.includes('--wb-part-buttonPrimary-border-style:none'));
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:hover{background-color:#e8f1f7 !important')));
assert.ok(out.rules.some(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference){:root:root [data-part="primary"]:hover{transform:translateY(-2px) !important}')));
assert.ok(out.rules.some(rule => rule.includes('[data-part="primary"]:active{box-shadow:inset') && rule.match(/inset/g)!.length === 4), 'a pressed bevel is the sunken bevel');
assert.ok(out.rules.some(rule => rule.startsWith(':root:root [data-part="primary"]:focus-visible{border-color:#0077b0 !important}')));
assert.ok(out.rules.filter(rule => rule.includes('transform')).every(rule => rule.startsWith('@media (prefers-reduced-motion:no-preference)')));
});
test('variants: known axes and options only; the owner holds an axis or switches layout changes off', () => {
assert.deepEqual(sanitizeVariants({ nav: 'top', post: 'default', actions: 'explode', header: 'bar', zoom: 'in' }), { nav: 'top', header: 'bar' });
assert.equal(sanitizeVariants({ nav: 'labels', post: 'default' }), null, 'the site\'s own options are not a variant');
assert.deepEqual(resolveVariants({ nav: 'top', post: 'compact', sidebar: 'hidden' }, { owned: ['sidebar'] }), { nav: 'top', post: 'compact' });
assert.deepEqual(resolveVariants({ nav: 'top' }, { allowed: false }), {});
assert.deepEqual(resolveVariants(null), {});
const skins = { nav: { top: (ctx: { bar: string }) => `nav{top:0;background:${ctx.bar}}` }, post: { compact: () => 'article{padding:4px}' } };
assert.deepEqual(compileVariants({ post: 'compact', nav: 'top', actions: 'labels' }, skins, { bar: 'red' }), ['nav{top:0;background:red}', 'article{padding:4px}'], 'axis order; no skin, no rule');
for (const options of Object.values(VARIANT_AXES)) assert.ok(options.length >= 2);
});
test('an owner\'s per-axis say rides on the theme: the site\'s own option removes the axis', () => {
const theme = sanitizeSpec({ name: 'T', variants: { nav: 'top', post: 'compact' } });
assert.deepEqual(applyOverrides(theme, { variants: { nav: 'labels', actions: 'labels' } }).variants, { post: 'compact', actions: 'labels' });
assert.deepEqual(applyOverrides(theme).variants, { nav: 'top', post: 'compact' });
assert.equal(applyOverrides(theme, { variants: { nav: 'labels', post: 'default' } }).variants, undefined);
});
test('decoration: clamps, plain titles, a focus ring that is always visible', () => {
const decor = sanitizeDecor({
dividers: { style: 'dashed', color: 'muted', width: 9 }, chrome: { kind: 'titlebar', title: 'Timeline"};body{display:none}<script>' },
focusRing: { width: 0, style: 'wavy', color: 'surface', offset: 40 }, selection: { fill: 'accent', text: 'accent' },
scrollbar: { style: 'classic', thumb: 'surface', track: 'elevated', width: 'huge' }, links: { underline: 'always' }, motion: { duration: 9999, curve: 'steps', press: 0.5 }, cursor: 'url(x)',
})!;
assert.deepEqual(decor.dividers, { style: 'dashed', color: 'muted', width: 3 });
assert.deepEqual(decor.chrome, { kind: 'titlebar', title: 'Timelinebodydisplay:none' });
assert.deepEqual(decor.focusRing, { width: 2, color: 'surface', offset: 4 });
assert.deepEqual(decor.motion, { duration: 400, curve: 'steps', press: 0.96 });
assert.ok(!('cursor' in decor));
assert.equal(sanitizeDecor({ chrome: { kind: 'none' }, selection: { fill: 'accent' } }), null);
assert.equal(chromeTitle('C:\\WINDOWS> dir & "x"'), 'C:WINDOWS> dir + x');
assert.equal(cssString('a"b\\c'), '"a\\22 b\\5c c"');
const targets = { divider: '[data-cell]', focusable: 'a,button', link: '[data-text] a', moving: 'a,button', pressable: 'button', chrome: { titlebar: (title: string) => `[data-col]::before{content:${cssString(title)}}` } };
const out = compileDecor(decor, targets, { colors: COLORS }).join('\n');
assert.ok(out.includes(':root:root :is([data-cell]){border-bottom:3px dashed #5b6b78 !important}'));
// The theme asked for a ring in its surface color (1.07:1 on the page): the ring takes a visible role instead.
const ring = /outline:2px solid (#[0-9a-f]{6})/.exec(out)![1]!;
for (const surface of [COLORS.bg, COLORS.surface, COLORS.page]) assert.ok(contrastRatio(ring, surface) >= 3, `${ring} on ${surface}`);
assert.ok(out.includes('::selection{background-color:#0077b0 !important;color:#ffffff !important}'), 'selection text is readable on its fill');
assert.ok(out.includes('::-webkit-scrollbar-thumb') && out.includes('[data-col]::before{content:"Timelinebodydisplay:none"}'));
assert.ok(out.includes('@media (prefers-reduced-motion:no-preference){') && out.includes('steps(3,end)') && out.includes('button):active{transform:scale(0.96)'));
assert.deepEqual(compileDecor(decor, {}, { colors: COLORS }).filter(rule => !rule.includes('::selection') && !rule.includes('scrollbar')), [], 'a site without targets draws only what needs none');
});
const PACK: IconPack = sanitizeIconPack({
id: 'test-pack', name: 'Test pack', author: 'Someone', license: 'own', source: 'drawn for the test', credits: 'Someone',
style: { stroke: 2, cap: 'square', join: 'miter', scale: 0.9 },
glyphs: {
home: { d: 'M4 11l8-7 8 7v9H4z', stroke: true }, like: { d: 'M12 20l-8-8a5 5 0 0 1 8-6 5 5 0 0 1 8 6z' }, 'like.on': { d: 'M12 20l-8-8a5 5 0 0 1 8-6 5 5 0 0 1 8 6z' },
reply: { layers: [{ d: 'M3 4h18v12H9l-5 4z', fill: { from: '#ffffff', to: '#88ccff' } }, { d: 'M6 7h12v2H6z', fill: 'accent', opacity: 0.8 }] },
share: { png: 'data:image/png;base64,iVBORw0KGgo=', pixel: true },
},
labels: { reply: 'reply', like: 'fav' }, symbols: { like: 'star' },
})!;
const TABLE: IconTable = {
home: { ctx: '[data-nav="home"] svg', group: 'nav', core: true },
explore: { ctx: '[data-nav="explore"] svg', group: 'nav', core: true },
like: { ctx: '[data-act="like"] svg', group: 'actions', core: true },
'like.on': { ctx: '[data-act="unlike"] svg', group: 'actions' },
reply: { ctx: '[data-act="reply"] svg', group: 'actions', core: true },
share: { sig: ['M12 2.59l5.7 5.7'], group: 'actions' },
grok: { sig: ['M2.2 12"><script>'], group: 'nav' },
};
test('a glyph is path data, colored layers or a small PNG; nothing else gets in', () => {
for (const hostile of [
{ d: 'M0 0<script>alert(1)</script>' }, { d: 'M0 0" onload="x' }, { d: 'url(javascript:1)' }, { d: '&lt;' }, { d: 'M0 0'.padEnd(ICON_LIMITS.pathChars + 1, '0') }, { d: '' },
{ layers: [{ d: 'M0 0h1', fill: 'url(#x)' }] }, { layers: [{ d: 'M0 0h1', fill: 'red' }] }, { layers: [] },
{ png: 'data:image/svg+xml;base64,AAAA' }, { png: 'https://example.com/a.png' }, { png: `data:image/png;base64,${'A'.repeat(ICON_LIMITS.pngChars + 8)}` },
{ svg: '<svg/>' }, '<svg/>', null,
]) assert.equal(sanitizeGlyph(hostile), null, JSON.stringify(hostile).slice(0, 60));
assert.deepEqual(sanitizeGlyph({ d: ' M4 4L20 20 ', rule: 'evenodd', stroke: true, extra: 1 }), { d: 'M4 4L20 20', rule: 'evenodd', stroke: true });
assert.equal((sanitizeGlyph({ layers: Array.from({ length: 9 }, () => ({ d: 'M0 0h1v1z', fill: '#AABBCC' })) }) as { layers: unknown[] }).layers.length, ICON_LIMITS.layers);
assert.ok(PATH_GRAMMAR.test('M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM3 12h18') && !PATH_GRAMMAR.test('M0 0;'));
});
test('an icon pack document: id, name and at least one glyph; unknown names dropped; license stated or flagged', () => {
assert.equal(PACK.license, 'own');
assert.deepEqual(Object.keys(PACK.glyphs), ['home', 'reply', 'like', 'like.on', 'share']);
assert.deepEqual(PACK.style, { stroke: 2, cap: 'square', join: 'miter', scale: 0.9 });
assert.equal(sanitizeIconPack({ id: 'x', name: 'X', glyphs: { rocket: { d: 'M0 0h1' } } }), null);
assert.equal(sanitizeIconPack({ id: 'Bad Id', name: 'X', glyphs: { home: { d: 'M0 0h1' } } }), null);
const parsed = parseIconPackJson(JSON.stringify({ id: 'p', name: 'P <b>', glyphs: { home: { d: 'M0 0h1' }, rocket: { d: 'M0 0' }, like: { d: '<' } } }));
assert.ok('pack' in parsed && parsed.pack.name === 'P b' && parsed.pack.license === 'unknown' && parsed.warnings.length === 2);
assert.ok('error' in parseIconPackJson('{'));
assert.ok('error' in parseIconPackJson(JSON.stringify({ id: 'p', name: 'P', glyphs: {} })));
assert.ok('error' in parseIconPackJson(' '.repeat(ICON_LIMITS.packBytes + 1)));
assert.equal(new Set(ICON_NAMES).size, ICON_NAMES.length);
assert.ok(ICON_NAMES.length <= ICON_LIMITS.names);
});
test('a theme names a pack and may adjust it a little; the owner\'s icon choice is separate', () => {
const icons = sanitizeThemeIcons({ pack: 'test-pack', style: { stroke: 9 }, overrides: { home: { d: 'M1 1h2' }, rocket: { d: 'M0 0' } }, symbols: { like: 'star', verified: 'nope' }, labels: { reply: 'reply', like: 'a"b', share: 'way too long a label' }, glyphs: { home: { d: 'M0 0' } } })!;
assert.deepEqual(icons, { pack: 'test-pack', style: { stroke: 2.5 }, overrides: { home: { d: 'M1 1h2' } }, symbols: { like: 'star' }, labels: { reply: 'reply' } });
assert.equal(sanitizeThemeIcons({ pack: 'NOPE!' }), null);
const catalog = createIconCatalog([PACK]);
assert.equal(catalog.resolve('theme', icons), PACK);
assert.equal(catalog.resolve('theme', null), null);
assert.equal(catalog.resolve('site', icons), null, 'the owner asked for the site\'s own icons');
assert.equal(catalog.resolve('missing-pack', icons), null, 'a pack that is not installed falls back to the site\'s icons');
assert.equal(catalog.resolve('test-pack', null), PACK, 'an explicit pick needs no theme');
assert.equal(normalizeIconChoice('test-pack'), 'test-pack');
assert.equal(normalizeIconChoice({}), 'theme');
});
test('icons are drawn as masks of the current color (colored glyphs as images), behind guards, per group', () => {
const out = compileIcons(PACK, null, TABLE, { colors: COLORS, gate: 'data-wb-icons' });
assert.ok(out.startsWith('@media (forced-colors:none){@supports ((mask-image:url("")) or (-webkit-mask-image:url(""))){'));
const home = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="nav"] [data-nav="home"] svg{'))!;
assert.ok(home.includes('background-color:currentColor !important') && home.includes('-webkit-mask:url("data:image/svg+xml,') && home.includes('mask:url("data:image/svg+xml,') && home.includes('/ 90% no-repeat'));
const svgOf = (line: string) => decodeURIComponent(/url\("data:image\/svg\+xml,([^"]*)"\)/.exec(line)![1]!);
assert.ok(svgOf(home).includes('stroke-width="2" stroke-linecap="square" stroke-linejoin="miter"'), 'the pack\'s stroke style');
const reply = out.split('\n').find(line => line.startsWith('html[data-wb-icons~="actions"] [data-act="reply"] svg{'))!;
assert.ok(reply.includes('background:url("data:image/svg+xml,') && !reply.includes('mask'), 'layers carry their own colors');
assert.ok(svgOf(reply).includes(`fill="${COLORS.accent}" opacity="0.8"`) && svgOf(reply).includes('<linearGradient id="g0"'));
assert.ok(out.includes('svg:has(> g > path[d^="M12 2.59l5.7 5.7"]){background:url("data:image/png;base64,iVBORw0KGgo=") center / 90% no-repeat !important;image-rendering:pixelated;}'));
assert.ok(out.includes('[data-act="unlike"] svg > *') && out.includes('{opacity:0 !important}'), 'the site\'s own paths are hidden, not removed');
assert.ok(!out.includes('explore') && !out.includes('script'), 'no glyph: the site\'s icon stays; a signature that is not path data is never written');
// No encoded quote can end the url("…") early.
for (const url of out.match(/url\("data:image\/svg\+xml,[^)]*\)/g)!) assert.ok(!url.slice(5, -2).includes('"'));
assert.equal(compileIcons(PACK, null, TABLE, { colors: COLORS, allowed: false }), '');
assert.equal(compileIcons(null, null, TABLE, { colors: COLORS }), '');
assert.ok(compileIcons(null, { overrides: { explore: { d: 'M2 2h20v20H2z' } } }, TABLE, { colors: null }).includes('[data-nav="explore"] svg{'), 'a theme\'s own override needs no pack');
assert.equal(glyphSvg({ png: 'data:image/png;base64,AAAA' }, BASE_ICON_STYLE), null);
});
test('a group is drawn only when all of its core icons are on the page', () => {
const present = (selectors: string[]) => iconGroupsPresent(TABLE, selector => selectors.includes(selector));
assert.deepEqual(present(['[data-nav="home"] svg', '[data-nav="explore"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['nav', 'actions', 'composer', 'misc']);
assert.deepEqual(present(['[data-nav="home"] svg', '[data-act="like"] svg', '[data-act="reply"] svg']), ['actions', 'composer', 'misc'], 'a rail never shows half ours, half the site\'s');
assert.deepEqual(iconGroupsPresent(TABLE, () => { throw new Error('bad selector'); }), ['composer', 'misc']);
});
test('a theme document: structure groups are optional, additive and dropped when empty', () => {
const v1 = sanitizeSpec({ name: 'Plain', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc' } });
for (const key of ['components', 'variants', 'decor', 'icons']) assert.ok(!(key in v1), `${key} absent from a theme that does not set it`);
assert.ok(!hasStructure(v1));
const v2 = sanitizeSpec({
name: 'Built', colors: { bg: '#ffffff', text: '#111111', accent: '#0066cc', actions: { like: '#F5A623', reply: 'red' } },
components: { post: { preset: 'card' }, nope: {} }, variants: { nav: 'top' }, decor: { links: { underline: 'always' } }, icons: { pack: 'wb-classic' },
});
assert.deepEqual(v2.colors!.actions, { like: '#f5a623' });
assert.deepEqual([v2.components, v2.variants, v2.decor, v2.icons], [{ post: { preset: 'card' } }, { nav: 'top' }, { links: { underline: 'always' } }, { pack: 'wb-classic' }]);
assert.ok(hasStructure(v2));
assert.ok(!isNeutral(sanitizeSpec({ name: 'Only structure', variants: { nav: 'top' } })), 'a theme that only moves the navigation is not the site\'s own look');
assert.ok(!hasStructure(sanitizeSpec({ name: 'Nothing', components: { post: {} }, variants: { nav: 'labels' } })), 'empty groups and the site\'s own options are no structure');
});
test('the published schemas are generated from these tables and current', () => {
const script = fileURLToPath(new URL('../../waybetter/scripts/theme-schema.mjs', import.meta.url));
const run = spawnSync(process.execPath, [script, '--check'], { encoding: 'utf8' });
assert.equal(run.status, 0, run.stderr);
const schema = JSON.parse(readFileSync(new URL('../../waybetter/theme.schema.json', import.meta.url), 'utf8'));
assert.deepEqual(Object.keys(schema.properties.components.properties), COMPONENT_IDS);
assert.deepEqual([schema.properties.components.properties.post.properties.radius.oneOf[0].minimum, schema.properties.components.properties.post.properties.radius.oneOf[0].maximum], [...TOKEN_LIMITS.radius]);
assert.deepEqual(schema.properties.variants.properties.nav.enum, [...VARIANT_AXES.nav]);
assert.equal(schema.properties.components.properties.postText.properties.case, undefined);
assert.ok(new RegExp(schema.$defs.pathData.pattern).test('M4 4L20 20') && !new RegExp(schema.$defs.pathData.pattern).test('<svg>'));
const icons = JSON.parse(readFileSync(new URL('../../waybetter/icons.schema.json', import.meta.url), 'utf8'));
assert.deepEqual(Object.keys(icons.properties.glyphs.properties), [...ICON_NAMES]);
assert.deepEqual(icons.required, ['id', 'name', 'license', 'glyphs']);
});

View file

@ -50,3 +50,23 @@ test('derived roles follow the base structure', () => {
}
assert.equal(deriveColors({ bg: '#ffffff', text: '#000000', accent: '#000000', border: '#123456' }).border, '#123456');
});
test('a foreground the site paints dimmer than its secondary text becomes the theme\'s secondary text', () => {
const hex = (h: string) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
const text = buildColorModel(SOURCE, THEME, 'text')!;
// The site's border gray used as an icon color, and grays around it: all between the most raised surface and the secondary text.
for (const dim of ['50,52,58', '44,46,50', '70,72,78', '110,114,120']) assert.deepEqual(projectColor(text, rgb(dim)), hex(THEME.muted), dim);
// The ends keep their place: a surface-dark foreground is a label on a filled surface, brighter than secondary is text.
assert.deepEqual(projectColor(text, rgb('10,10,12')), hex(THEME.bg));
assert.notDeepEqual(projectColor(text, rgb('20,21,24')), hex(THEME.muted));
assert.notDeepEqual(projectColor(text, rgb('32,33,38')), hex(THEME.muted));
assert.deepEqual(projectColor(text, rgb('140,144,150')), hex(THEME.muted));
assert.notDeepEqual(projectColor(text, rgb('190,192,196')), hex(THEME.muted));
assert.deepEqual(projectColor(text, rgb('235,236,238')), hex(THEME.text));
// Backgrounds and borders are not foregrounds: the same gray stays the theme's border.
assert.deepEqual(projectColor(buildColorModel(SOURCE, THEME, 'border')!, rgb('50,52,58')), hex(THEME.border));
assert.deepEqual(projectColor(buildColorModel(SOURCE, THEME, 'background')!, rgb('50,52,58')), hex(THEME.border));
assert.equal(buildColorModel(SOURCE, THEME, 'background')!.dim, null);
// A theme without a secondary text color has nothing to raise it to.
assert.equal(buildColorModel(SOURCE, { bg: THEME.bg, text: THEME.text }, 'text')!.dim, null);
});

View file

@ -2,8 +2,8 @@
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 [`waybetter`](../waybetter/README.md) package; not published on its own. The repository's
`docs/ARCHITECTURE.md` ("The shell frame" and "The panel") describes 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

View file

@ -10,6 +10,7 @@ import { createPortal } from 'react-dom';
import type { InstallController, InstallRequest } from './installController.ts';
import type { StoreText } from './storeMessages.ts';
import { formatBytes, permissionBadges, previewLines, type InstallKind, type InstallPreview } from './storeModel.ts';
import { coveragePercent, type StringsSummary } from './stringPacksModel.ts';
/** Milliseconds before Install can be pressed (native code refuses a commit faster than 600 ms). */
export const REVIEW_MS = 1000;
@ -30,6 +31,8 @@ export type InstallHostProps<Theme> = {
openSection(kind: InstallKind): void;
/** A live preview of a staged theme (the app's theme preview). */
renderThemePreview?(theme: Theme): ReactNode;
/** A string pack's coverage against the site's inventory (the app has the inventory). */
stringsSummary?(text: string): StringsSummary | null;
/** Drops on elements matching this selector are handled by them (e.g. an import box). */
ownDropTargets?: string;
closeIcon?: ReactNode;
@ -54,6 +57,7 @@ const G = {
warn: 'M12 4l9 16H3zM12 10v4M12 17h.01',
copy: 'M9 9h10v10H9zM5 15V5h10',
close: 'M6 6l12 12M18 6L6 18',
strings: 'M4 5h9M8.5 3v2M11 5c-.8 3.8-3.4 6.6-7 8M6.5 8.5c1.1 1.6 2.7 3 4.5 3.8M13 21l4-9 4 9M14.4 18h5.2',
};
function Fact({ label, children, wide }: { label: string; children: ReactNode; wide?: boolean }) {
@ -97,22 +101,25 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
const [armed, setArmed] = useState(false);
// On by default only when it is from the signed store or declares its permissions and the code
// scan found nothing to point out; otherwise the owner turns it on deliberately.
const [enable, setEnable] = useState(preview.kind === 'theme' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0))));
const [enable, setEnable] = useState(preview.kind === 'theme' || preview.kind === 'strings' || (!preview.existing && (preview.source.signed || (preview.plugin?.permissions != null && preview.findings.length === 0))));
const [copied, setCopied] = useState(false);
useEffect(() => { const timer = setTimeout(() => setArmed(true), REVIEW_MS); return () => clearTimeout(timer); }, [preview.token]);
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? t('wb.install.untitled');
const author = plugin?.author || facts?.author || preview.theme?.author || '';
const strings = preview.kind === 'strings' ? preview.strings ?? null : null;
const summary = strings ? props.stringsSummary?.(preview.text) ?? null : null;
const name = plugin?.name ?? facts?.name ?? preview.theme?.name ?? strings?.name ?? t('wb.install.untitled');
const author = plugin?.author || facts?.author || preview.theme?.author || strings?.authors.join(', ') || '';
const version = preview.version || preview.store?.version || '';
const updating = preview.existing && !preview.existing.same;
const verb = preview.existing?.same ? t('wb.install.reinstall') : updating || ready?.replaces ? t('wb.install.update') : t('wb.store.install');
const eyebrow = t(preview.existing?.same ? 'wb.install.eyebrow.reinstall' : updating || ready?.replaces ? 'wb.install.eyebrow.update' : 'wb.install.eyebrow.install', { kind: preview.kind });
const step = preview.existing?.same ? 'reinstall' : updating || ready?.replaces ? 'update' : 'install';
const eyebrow = preview.kind === 'strings' ? t(`wb.install.eyebrow.strings.${step}`) : t(`wb.install.eyebrow.${step}`, { kind: preview.kind });
const badges = preview.kind === 'plugin' ? permissionBadges(plugin?.permissions, t, site) : [];
const installing = request.status === 'installing';
const description = plugin?.description || facts?.description;
const description = plugin?.description || facts?.description || strings?.description;
return <>
<header className="wbi-head">
<div className={`wbi-tile is-${preview.kind}`} style={facts?.tile ? { background: facts.tile.background, color: facts.tile.color, boxShadow: `inset 0 0 0 1px ${facts.tile.border}` } : undefined}>
<Glyph d={preview.kind === 'plugin' ? G.plugin : G.theme} size={22}/>
<Glyph d={preview.kind === 'plugin' ? G.plugin : preview.kind === 'strings' ? G.strings : G.theme} size={22}/>
</div>
<div className="wbi-title">
<span className="wbi-eyebrow">{eyebrow}</span>
@ -139,6 +146,8 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
<Fact label={t('wb.install.size')}>{formatBytes(preview.size)}</Fact>
{preview.existing && <Fact label={t('wb.install.installedNow')}>{preview.existing.same ? t('wb.install.identical', { version: preview.existing.version || '?' }) : `v${preview.existing.version || '?'}${preview.existing.enabled ? ` · ${t('wb.install.on')}` : ''}`}</Fact>}
{ready?.replaces && <Fact label={t('wb.install.replaces')}>{t('wb.install.replacesValue')}</Fact>}
{preview.store?.license && <Fact label={t('wb.install.license')}>{preview.store.license}</Fact>}
{preview.store?.credits && <Fact label={t('wb.install.credits')} wide>{preview.store.credits}</Fact>}
<Fact label="SHA-256" wide>
<span className="wbi-hash">{preview.sha256}</span>
<button className="wbi-copy" aria-label={t('wb.install.copyHash')} onClick={() => void navigator.clipboard?.writeText(preview.sha256).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1400); }).catch(() => {})}>
@ -156,13 +165,32 @@ function Ready<Theme>({ request, props }: { request: Extract<InstallRequest<Them
{preview.findings.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.theCode')}</strong>{preview.findings.map(finding => <span key={finding}>{finding}</span>)}</div>}
</section>}
{strings && <section className="wbi-perms wbi-strings" aria-label={t('wb.store.stringsItem')}>
<p className="wbi-note is-ok"><Glyph d={G.check} size={14}/>{t('wb.install.strings.dataOnly', { site })}</p>
<dl className="wbi-facts">
<Fact label={t('wb.install.strings.language')}>{strings.language}</Fact>
<Fact label={t('wb.install.strings.coverage')} wide>
{summary && !summary.otherCatalog
? t('wb.install.strings.coverageValue', { translated: String(summary.translated), translatable: String(summary.translatable), site, percent: coveragePercent(summary) })
: t('wb.install.strings.count', { count: strings.strings })}
</Fact>
</dl>
{summary?.otherCatalog && <p className="wbi-note"><Glyph d={G.warn} size={14}/>{t('wb.install.strings.otherCatalog', { site })}</p>}
{summary && !summary.otherCatalog && <ul className="wbi-strings-notes">
{summary.closed > 0 && <li>{t('wb.install.strings.closed', { count: summary.closed, site })}</li>}
{summary.unknown > 0 && <li>{t('wb.install.strings.unknown', { count: summary.unknown, site })}</li>}
{summary.refused > 0 && <li>{t('wb.install.strings.refused', { count: summary.refused, site })}</li>}
</ul>}
{summary && summary.sample.length > 0 && <div className="wbi-findings"><strong>{t('wb.install.strings.sample')}</strong>{summary.sample.map(text => <span key={text}>{text}</span>)}</div>}
</section>}
{theme !== null && <section className="wbi-theme">
{props.renderThemePreview?.(theme)}
{(ready?.warnings.length ?? 0) > 0 && <ul className="wbi-warnings">{ready!.warnings.map(warning => <li key={warning}>{warning}</li>)}</ul>}
</section>}
{facts?.css ? <CodePreview t={t} text={facts.css} label={t('wb.install.themeCss', { site })}/> : null}
<CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : t('wb.install.themeFile')}/>
<CodePreview t={t} text={preview.text} label={preview.kind === 'plugin' ? t('wb.install.code') : preview.kind === 'strings' ? t('wb.install.strings.file') : t('wb.install.themeFile')}/>
</div>
<footer className="wbi-foot">
@ -186,10 +214,12 @@ function Done<Theme>({ request, props }: { request: Extract<InstallRequest<Theme
<h2 id="wbi-title">{t('wb.install.done', { name: request.name })}</h2>
<p>{request.kind === 'plugin'
? (request.enabled ? t('wb.install.done.pluginOn', { site }) : t('wb.install.done.pluginOff'))
: (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p>
: request.kind === 'strings'
? (request.enabled ? t('wb.install.done.stringsOn', { site }) : t('wb.install.done.stringsOff'))
: (request.enabled ? t('wb.install.done.themeOn') : t('wb.install.done.themeOff'))}</p>
{request.fonts.length > 0 && <p className="wbi-muted">{t('wb.install.done.fonts', { fonts: request.fonts.join(', ') })}</p>}
<div className="wbi-state-actions">
<button className={classes.secondary} onClick={() => { controller.close(); props.openSection(request.kind); }}>{request.kind === 'plugin' ? t('wb.install.openPlugins') : t('wb.install.openAppearance')}</button>
<button className={classes.secondary} onClick={() => { controller.close(); props.openSection(request.kind); }}>{request.kind === 'plugin' ? t('wb.install.openPlugins') : request.kind === 'strings' ? t('wb.install.openStrings') : t('wb.install.openAppearance')}</button>
<button className={classes.primary} autoFocus onClick={controller.close}>{t('wb.install.doneButton')}</button>
</div>
</div>;

View file

@ -90,7 +90,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
const [view, setView] = useState<StoreCatalogView | null>(null);
const [loading, setLoading] = useState(false);
const [query, setQuery] = useState('');
const [kind, setKind] = useState<'all' | 'theme' | 'plugin'>('all');
const [kind, setKind] = useState<'all' | 'theme' | 'plugin' | 'strings'>('all');
const [category, setCategory] = useState<string>('all');
const request = useSyncExternalStore(controller.subscribe, controller.current, controller.current);
@ -137,7 +137,7 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<p className="wbs-intro">{t('wb.store.intro')}</p>
<div className="wbs-toolbar">
<SearchField label={t('wb.store.search')} placeholder={t('wb.store.searchPlaceholder')} value={query} onChange={setQuery}/>
<Segmented label={t('wb.store.kind')} size="sm" value={kind} onChange={next => { setKind(next); setCategory('all'); }} options={[{ value: 'all', label: t('wb.store.all') }, { value: 'theme', label: t('wb.store.themes') }, { value: 'plugin', label: t('wb.store.pluginsTab') }]}/>
<Segmented label={t('wb.store.kind')} size="sm" value={kind} onChange={next => { setKind(next); setCategory('all'); }} options={[{ value: 'all', label: t('wb.store.all') }, { value: 'theme', label: t('wb.store.themes') }, { value: 'plugin', label: t('wb.store.pluginsTab') }, ...(items.some(item => item.kind === 'strings') ? [{ value: 'strings' as const, label: t('wb.store.strings') }] : [])]}/>
<Button size="sm" tone="ghost" disabled={loading} onClick={() => void load(true)}>{loading ? t('wb.store.checking') : t('wb.store.refresh')}</Button>
</div>
<div className="wbs-cats" role="group" aria-label={t('wb.store.categories')}>
@ -159,9 +159,9 @@ export function StoreView<Theme>(props: StoreViewProps<Theme>) {
<div className="wbs-card-body">
<header>
<h3>{item.name}</h3>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : t('wb.store.plugin')}</Badge>
<Badge>{item.kind === 'theme' ? t('wb.store.theme') : item.kind === 'strings' ? t('wb.store.stringsItem') : t('wb.store.plugin')}</Badge>
</header>
<p className="wbs-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {categoryLabel(item.category, t)}</p>
<p className="wbs-meta">{item.author && `${t('wb.store.by', { author: item.author })} · `}v{item.version} · {item.kind === 'strings' && item.language ? item.language : categoryLabel(item.category, t)}{item.license ? ` · ${item.license}` : ''}</p>
<p className="wbs-desc">{item.description}</p>
{item.kind === 'plugin' && <ul className="wbs-perms" aria-label={t('wb.store.permissions')}>
{permissionBadges(item.permissions, t, site).map(badge => <li key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</li>)}

View file

@ -2,11 +2,13 @@ import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent,
import { createPortal } from 'react-dom';
import { DEFAULT_PROFILE, accountLabel as accountLabelCore, removeProfile, tabProfile, type Profile, type ProfileSettings } from '../profileModel.ts';
import { accountAction, addAccountProfile, focusedAccount, moveFocus, setDefaultAccount, tabsByAccount } from './accountModel.ts';
import { APP_MENU_KEYS, openAppMenu } from './AppMenu.tsx';
import { invoke } from './bridge.ts';
import { decks, forgetColumn, saveDecks } from './deckStore.ts';
import { usePaneTick, useProfiles, useT } from './hooks.ts';
import { t, tx } from './i18n.ts';
import { Avatar, Icon } from './icons.tsx';
import { menuText } from './menuModel.ts';
import { site } from './site.ts';
import { flushSync, paneInfos, setOverlay, setProfiles, shell } from './state.ts';
import { isTauri } from './windowBinding.ts';
@ -183,7 +185,7 @@ export function AccountSwitcher() {
}
if (event.key === 'Tab') { event.preventDefault(); close(true); return; }
const scope = inSub ? target.closest('.bt-acct-sub, .bt-acct-confirm')! : menu.current!;
const items = Array.from(scope.querySelectorAll<HTMLElement>(inSub ? 'button:not(:disabled)' : '.bt-acct-main, .bt-acct-add'));
const items = Array.from(scope.querySelectorAll<HTMLElement>(inSub ? 'button:not(:disabled)' : '.bt-acct-main, .bt-acct-add, .bt-acct-settings'));
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) {
event.preventDefault();
items[moveFocus(items.indexOf(target), event.key, items.length)]?.focus();
@ -268,6 +270,11 @@ export function AccountSwitcher() {
<span className="bt-acct-add-icon"><Icon name="plus"/></span>
<span className="bt-acct-text"><span className="bt-acct-name">{t('wb.acct.add')}</span><span className="bt-acct-meta">{t('wb.acct.addHint', { site: siteName })}</span></span>
</button>
<hr/>
{/* Settings are looked for where the account name is: the way to the app menu. */}
<button role="menuitem" className="bt-acct-settings" aria-haspopup="menu" onClick={event => { const keyboard = event.detail === 0; close(); openAppMenu({ keyboard }); }}>
<Icon name="settings"/><span className="bt-menu-label">{menuText('accountsRow')}</span><span className="bt-menu-keys">{APP_MENU_KEYS}</span>
</button>
{error && <div className="bt-acct-error" role="alert">{error}</div>}
</div>
</div>, document.body)}

View file

@ -0,0 +1,616 @@
// The app menu: the titlebar's "Settings and more" button, at the far end of the titlebar cluster
// (before the caption buttons on Windows and Linux; macOS has none there). It opens on click, on
// Alt+F and F10 (Shell.tsx; a focused tab forwards the keys), from the command palette, from the
// last row of the account menu, and from the app's logo at the start of the titlebar (the same
// menu, hung under the logo on its side of the window). Its rows are the app's (`ShellSite.menu`, menuModel.ts): built-in
// ones by name, each shown only when the app serves what it needs, and the app's own.
//
// Like every shell menu it is an overlay: while open the shell is raised above the tab webviews
// (`setOverlay`), panes stay visible and nothing is dimmed. Keyboard: arrows, Home/End, type-ahead,
// the arrow pointing along the reading direction opens a submenu and the other one closes it,
// Enter or Space chooses, Esc closes one level. Submenus fly out beside the menu and stay inside
// the window (in a narrow one they lie over it). Words: menuMessages.en.json (`menuText`).
import { useEffect, useLayoutEffect, useReducer, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { parseUpdateStatus, type UpdateStatus } from '../updateModel.ts';
import { invoke, listen } from './bridge.ts';
import { describe, diag } from './diag.ts';
import { decks } from './deckStore.ts';
import { refreshDev } from './devHost.ts';
import { useDev, usePaneTick, useT } from './hooks.ts';
import { formatNumber } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import {
DEFAULT_MENU, ZOOM_MAX, ZOOM_MIN, findSpec, joinGroups, languageChoice, languageRows, menuText, moveStop, planMenu, shortcutText, specRows, submenuKeys, submenuLeft, typeahead, updateRow,
type BuiltinMenuItem, type MenuEnv, type MenuItemRow, type MenuModeStatus, type MenuRow,
} from './menuModel.ts';
import { ReportDialog } from './ReportDialog.tsx';
import { safe, setSafeMode } from './safeStore.ts';
import { hasFeature, site } from './site.ts';
import { isWeb, setOverlay, shell, type TabParams } from './state.ts';
import { openWorkspaceSave } from './TitlebarExtras.tsx';
import { os, startDrag, systemMenu } from './windowBinding.ts';
import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
import { readZoom, stepZoom, zoomOf, zoomTarget } from './zoomStore.ts';
import './appMenu.css';
/** How the menu is asked to open: under the logo instead of its button, at a submenu, with the first row focused (keyboard), or closing if it is open. */
export type AppMenuRequest = { anchor?: 'button' | 'logo'; submenu?: string; keyboard?: boolean; toggle?: boolean };
/** Opens the app menu (Alt+F / F10, the palette, the account menu's last row). */
export const openAppMenu = (request: AppMenuRequest = {}) => window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: request }));
const mac = os === 'macos';
/** The keys that open the menu, as the button's tooltip and the account menu write them. */
export const APP_MENU_KEYS = mac ? 'F10' : 'Alt+F';
const getError = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^Error: /, '');
const percent = (factor: number) => formatNumber(factor, { style: 'percent', maximumFractionDigits: 0 });
type Focus = { level: number; id?: string; edge?: 'first' | 'last' | 'menu' };
/** Where the menu hangs: under its button (from the window's end edge) or under the logo (from its start edge). */
type Anchor = { at: 'button' | 'logo'; top: number; left?: number; right?: number };
/** Which trigger the open menu hangs from (null: closed), for the triggers' `aria-expanded`. */
let openAt: Anchor['at'] | null = null;
function noteOpen(at: Anchor['at'] | null) {
if (openAt === at) return;
openAt = at;
window.dispatchEvent(new CustomEvent('bt-app-menu-state'));
}
/** The rows of one level a key can stop on: enabled items; the zoom row counts once. */
function stopsOf(menu: HTMLElement): HTMLElement[] {
const all = Array.from(menu.querySelectorAll<HTMLElement>('[data-item]:not(:disabled)'));
const active = document.activeElement;
const zoom = all.filter(el => 'zoom' in el.dataset);
const keep = zoom.find(el => el === active) ?? zoom.find(el => el.getAttribute('aria-disabled') !== 'true') ?? zoom[0];
return all.filter(el => !('zoom' in el.dataset) || el === keep);
}
export function AppMenu({ trigger = true }: { trigger?: boolean } = {}) {
const t = useT();
usePaneTick();
const dev = useDev();
const config = site();
const menu = config.menu ?? {};
const [open, setOpen] = useState(false);
const [path, setPath] = useState<string[]>([]);
const [anchor, setAnchor] = useState<Anchor>({ at: 'button', top: 50, right: 8 });
const [mode, setMode] = useState<string | null>(null);
const [modeStatus, setModeStatus] = useState<MenuModeStatus | null>(null);
const [asking, setAsking] = useState<{ to: string; changes: number; reapply?: boolean } | null>(null);
const [version, setVersion] = useState('');
const [update, setUpdate] = useState<UpdateStatus>({ state: 'idle' });
const [askedUpdate, setAskedUpdate] = useState(false);
const [reporting, setReporting] = useState(false);
const [error, setError] = useState('');
const [, tick] = useReducer((n: number) => n + 1, 0);
const button = useRef<HTMLButtonElement>(null);
const layers = useRef<HTMLDivElement>(null);
const focusNext = useRef<Focus | null>(null);
const before = useRef<HTMLElement | null>(null);
const hover = useRef<{ el: Element | null; timer?: ReturnType<typeof setTimeout> }>({ el: null });
const typed = useRef({ text: '', at: 0 });
const live = useRef({ open, path });
live.current = { open, path };
// Whatever a row shows may change while the menu is open (a language or theme picked in it).
useEffect(() => {
const events = ['bt-zoom', 'bt-workspaces', 'bt-decks', 'bt-site', 'bt-safe'];
for (const event of events) window.addEventListener(event, tick);
const off = [config.themes?.subscribe(tick), menu.languages?.subscribe(tick)];
return () => {
for (const event of events) window.removeEventListener(event, tick);
for (const dispose of off) dispose?.();
};
}, []);
/** Where a request without an anchor opens: the button when this app shows one, else the logo. */
const home = (): Anchor['at'] => (trigger ? 'button' : 'logo');
function show(request: AppMenuRequest = {}) {
const at = request.anchor ?? home();
diag(`menu open: anchor=${at} keyboard=${!!request.keyboard} hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
const logo = at === 'logo' ? document.querySelector('.bt-titlebar-logo') : null;
const rect = (logo ?? button.current)?.getBoundingClientRect();
if (rect) {
const top = Math.round(rect.bottom + 6);
setAnchor(logo ? { at: 'logo', top, left: Math.max(8, Math.round(rect.left - 3)) } : { at: 'button', top, right: Math.max(8, Math.round(window.innerWidth - rect.right)) });
}
const active = document.activeElement as HTMLElement | null;
before.current = active && active !== document.body && document.hasFocus() ? active : null;
// Keys pressed in a tab open the menu: the shell takes the keyboard. A click on the shell already
// gave it the keyboard, so nothing native is asked for then.
if (!document.hasFocus()) invoke('shell_focus').catch(() => {});
setAsking(null); setError('');
setPath(request.submenu ? [request.submenu] : []);
focusNext.current = request.submenu ? { level: 1, edge: 'first' } : { level: 0, edge: request.keyboard ? 'first' : 'menu' };
setOpen(true);
// What the rows show, read fresh.
void readZoom(zoomTarget());
if (hasFeature('developer')) void refreshDev();
if (hasFeature('workspaces') && !workspaces.loaded) void loadWorkspaces().catch(() => {});
void config.themes?.loadThemes();
menu.modes?.current().then(setMode, () => {});
menu.modes?.status?.().then(setModeStatus, () => {});
if (!version) menu.version?.().then(setVersion, () => {});
setAskedUpdate(false);
if (hasFeature('updates')) invoke('update_status').then(value => setUpdate(parseUpdateStatus(value)), () => {});
}
/** `escape`: back to what had focus before. `action` and `away`: nothing focused, so typing returns to the active pane. */
function close(how: 'escape' | 'action' | 'away' = 'away', why = '') {
diag(`menu close: ${how}${why ? ` (${why})` : ''} hasFocus=${document.hasFocus()}`);
clearTimeout(hover.current.timer);
hover.current = { el: null };
focusNext.current = null;
setOpen(false); setPath([]); setAsking(null); setError('');
if (how === 'escape' && before.current?.isConnected) before.current.focus();
before.current = null;
}
// The updater's steps (checking, downloading, ready) as they happen.
useEffect(() => {
if (!hasFeature('updates')) return;
let disposed = false;
let unlisten: (() => void) | undefined;
listen('update-status', event => setUpdate(parseUpdateStatus(event.payload)))
.then(dispose => { if (disposed) dispose(); else unlisten = dispose; })
.catch(() => {});
return () => { disposed = true; unlisten?.(); };
}, []);
useEffect(() => {
const onRequest = (event: Event) => {
const request = (event as CustomEvent<AppMenuRequest | undefined>).detail ?? {};
// Asked again from the other trigger, the open menu moves there instead of closing.
if (live.current.open && request.toggle && (request.anchor ?? home()) === (openAt ?? home())) close('escape'); else show(request);
};
window.addEventListener('bt-app-menu', onRequest);
return () => window.removeEventListener('bt-app-menu', onRequest);
}, [version]);
useEffect(() => {
if (!open) return;
// Native tab webviews would cover the menu.
setOverlay(1);
noteOpen(anchor.at);
// The window lost the keyboard: the menu closes, unless the focus is back a moment later (taking the
// keyboard from a tab for Alt+F / F10 can pass through a blur on its way to the shell).
let leaving: ReturnType<typeof setTimeout> | undefined;
const away = () => {
diag(`menu: window blur hasFocus=${document.hasFocus()}`);
clearTimeout(leaving);
leaving = setTimeout(() => { if (!document.hasFocus()) close('away', 'blur'); else diag('menu: blur passed, focus is back'); }, 160);
};
const resized = () => close();
// Keys while nothing in the menu has focus (a click on its padding): Esc closes, arrows enter it.
const onKey = (event: KeyboardEvent) => {
if (layers.current?.contains(event.target as Node)) return;
if (event.key === 'Escape') { event.preventDefault(); close('escape'); return; }
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
focusNext.current = { level: live.current.path.length, edge: event.key === 'ArrowDown' ? 'first' : 'last' };
tick();
}
};
window.addEventListener('blur', away);
window.addEventListener('resize', resized);
window.addEventListener('keydown', onKey);
return () => { clearTimeout(leaving); setOverlay(-1); noteOpen(null); window.removeEventListener('blur', away); window.removeEventListener('resize', resized); window.removeEventListener('keydown', onKey); };
}, [open, anchor.at]);
const layer = (level: number) => layers.current?.querySelector<HTMLElement>(`[data-level="${level}"]`) ?? null;
// After every render: submenus sit beside their row, inside the window; then the focus that was asked for.
useLayoutEffect(() => {
if (!open) return;
for (let level = 1; level <= path.length; level += 1) {
const el = layer(level);
const parent = layer(level - 1);
const row = parent?.querySelector<HTMLElement>(`[data-item="${CSS.escape(path[level - 1]!)}"]`);
if (!el || !parent) continue;
const edge = 8;
const box = parent.getBoundingClientRect();
el.style.maxHeight = `${window.innerHeight - edge * 2}px`;
const { width, height } = el.getBoundingClientRect();
const left = submenuLeft(box, width, window.innerWidth, edge);
// It slides in from the side it hangs on.
el.style.setProperty('--bt-app-sub-from', left < box.left ? '6px' : '-6px');
const top = Math.max(edge, Math.min((row?.getBoundingClientRect().top ?? box.top) - 6, window.innerHeight - height - edge));
el.style.left = `${Math.round(left)}px`;
el.style.top = `${Math.round(top)}px`;
}
const want = focusNext.current;
const el = want ? layer(want.level) : null;
if (!want || !el) return;
focusNext.current = null;
const stops = stopsOf(el);
const target = want.id ? el.querySelector<HTMLElement>(`[data-item="${CSS.escape(want.id)}"]:not(:disabled)`)
: want.edge === 'menu' ? el : want.edge === 'last' ? stops[stops.length - 1] : stops[0];
(target ?? el).focus();
});
const openSub = (level: number, id: string, focus = false) => {
setPath(current => [...current.slice(0, level), id]);
setAsking(null); setError('');
if (focus) focusNext.current = { level: level + 1, edge: 'first' };
};
/** Closes the submenu at `level`; its row gets the focus back. */
const closeSub = (level: number) => {
focusNext.current = { level: level - 1, id: path[level - 1] };
setPath(current => current.slice(0, level - 1));
setAsking(null); setError('');
};
async function activate(row: MenuItemRow, level: number) {
if (row.disabled) return;
if (row.submenu) {
if (path[level] === row.id) { focusNext.current = { level: level + 1, edge: 'first' }; tick(); } else openSub(level, row.id, true);
return;
}
setError('');
if (!row.keepOpen) close('action');
try { await row.run?.(); }
catch (failure) { if (row.keepOpen) setError(getError(failure)); else console.error('[shell] menu', failure); }
}
// -------------------------------------------------------------------------------------------
// Rows
const item = (id: string, label: string, icon: IconName | undefined, rest: Partial<MenuItemRow> = {}): MenuItemRow => ({ kind: 'item', id, label, icon, ...rest });
/** "Plugins…": a row that opens a section of the app's panel. */
const section = (name: string) => menuText('section', { section: name });
const active = shell.api?.activePanel;
const activeParams = active?.params as TabParams | undefined;
const canSplit = !!active && (isWeb(active) || active.group.panels.length > 1);
const languageName = (code: string | undefined) => menu.languages?.list.find(language => language.code === code)?.name;
const themeState = config.themes?.current();
const themeId = config.themes && themeState ? config.themes.adapter.preset(themeState.choice) : '';
const modeList = menu.modes?.list() ?? [];
/** Settings → Language: the panel's Settings, scrolled to that group once it is there. */
function openSettingsAt(anchor: string) {
shell.openPanelSection('settings');
let tries = 0;
const find = () => {
const heading = document.getElementById(`${anchor}-h`);
if (heading) heading.scrollIntoView({ block: 'start' });
else if ((tries += 1) < 40) setTimeout(find, 50);
};
find();
}
function builtin(id: BuiltinMenuItem): MenuRow {
switch (id) {
case 'new-tab': return item(id, t('wb.shell.tab.new'), 'plus', { shortcut: 'Ctrl+T', run: () => shell.shortcut('new-tab') });
case 'split-right': return item(id, t('wb.shell.menu.splitRight'), 'split', { shortcut: 'Ctrl+\\', disabled: !canSplit, run: () => shell.shortcut('split-right') });
case 'split-down': return item(id, t('wb.shell.menu.splitDown'), 'splitDown', { shortcut: 'Ctrl+Shift+\\', disabled: !canSplit, run: () => shell.shortcut('split-down') });
case 'new-column': return item(id, menuText('newColumn'), 'columns', {
run: () => {
// The deck in front, else the first one; with none yet, the deck tab itself (it starts one).
const target = activeParams?.kind === 'deck' ? activeParams.deckId : decks.list[0]?.id;
shell.run(target ? { type: 'deck-add', deckId: target } : { type: 'deck' });
},
});
case 'language': return item(id, t('wb.settings.language.title'), 'globe', { submenu: true, hint: languageName(menu.languages?.state().locale) });
case 'theme': return item(id, menuText('theme'), 'palette', { submenu: true, hint: themeId ? config.themes!.themeName(themeId) : undefined });
case 'mode': {
const label = modeList.find(entry => entry.id === mode)?.label;
return item(id, t('wb.modes.section'), 'layers', { submenu: true, hint: label && modeStatus?.custom ? t('wb.modes.custom', { mode: label }) : label });
}
case 'zoom': return { kind: 'zoom', id: 'zoom' };
case 'plugins': return item(id, section(t('wb.panel.section.plugins')), 'plug', { run: () => shell.openPanelSection('plugins') });
case 'store': return item(id, section(t('wb.panel.section.store')), 'bag', { run: () => shell.openPanelSection('store') });
case 'strings': return item(id, section(menuText('strings')), 'globe', { run: () => shell.openPanelSection('languages') });
case 'workspaces': return item(id, t('wb.ws.title'), 'layout', { submenu: true, hint: workspaces.store.items.find(entry => entry.id === workspaces.active)?.name });
case 'find': return item(id, menuText('find'), 'search', { shortcut: 'Ctrl+F', disabled: !active || !isWeb(active), run: () => shell.shortcut('find') });
case 'shortcuts': return item(id, menuText('shortcuts'), 'keyboard', { run: () => (menu.shortcuts ? menu.shortcuts() : shell.shortcut('command-palette')) });
case 'palette': return item(id, menuText('palette'), 'command', { shortcut: 'Ctrl+K', run: () => shell.shortcut('command-palette') });
case 'developer': return item(id, menuText('developer'), 'code', { submenu: true });
case 'updates': {
// A real check: the row asks the updater now and says what came of it (the titlebar chip stays the loud part).
const row = updateRow(update, askedUpdate, version);
return item(id, row.label, 'reload', {
hint: row.hint, title: row.title, keepOpen: row.action === 'check' || row.action === 'wait',
run: async () => {
if (row.action === 'open') { shell.openPanelSection('updates'); return; }
if (row.action === 'restart') { await invoke('apply_update'); return; }
if (row.action !== 'check') return;
setAskedUpdate(true);
setUpdate({ state: 'checking' });
// One request, no retry: whatever the updater answers is what the row says.
try { setUpdate(parseUpdateStatus(await invoke('update_check'))); } catch { setUpdate({ state: 'error', message: '' }); }
},
});
}
// Off: a submenu that says what it does before anything reloads. On: one row that leaves it.
case 'safe-mode': return safe.active
? item(id, menuText('safeLeave'), 'shield', { run: () => setSafeMode(false) })
: item(id, menuText('safeRestart'), 'shield', { submenu: true });
case 'report': return item(id, menuText('report'), 'flag', { run: () => setReporting(true) });
case 'about': return item(id, menuText('about', { product: config.product }), 'info', { run: () => shell.openPanelSection('home') });
case 'settings': return item(id, section(t('wb.panel.section.settings')), 'settings', { run: () => shell.openPanelSection('settings') });
}
}
function submenuRows(id: string): MenuRow[] {
switch (id) {
case 'language': {
const languages = menu.languages;
if (!languages) return [];
const rows = languageRows(languages.list, languages.state(), { site: t('wb.settings.language.followSite'), system: t('wb.settings.language.followSystem'), more: menuText('moreLanguages') });
return rows.map(row => {
if (row.kind !== 'item') return row;
const choice = languageChoice(row.id);
// Switching is live and the menu stays: what was picked can be read (or undone) on the spot.
return choice ? { ...row, keepOpen: true, run: () => languages.set(choice) } : { ...row, run: () => openSettingsAt('language') };
});
}
case 'theme': {
const themes = config.themes;
if (!themes || !themeState) return [];
const list: MenuRow[] = themes.allThemes(themeState.choice).map(theme => item(`theme:${theme.id}`, theme.name, undefined, {
check: 'radio', checked: theme.id === themeId, keepOpen: true, swatch: themes.adapter.dots(theme),
// As Appearance does: a theme starts without the customizations made on another one.
run: () => themes.setChoice(themes.adapter.choiceForId(themeState.choice, theme.id)),
}));
return joinGroups([list, [
item('theme:builder', section(t('wb.panel.section.builder')), 'edit', { run: () => shell.openPanelSection('builder') }),
item('theme:more', menuText('moreAppearance'), 'palette', { run: () => shell.openPanelSection('themes') }),
]]);
}
case 'mode': {
const modes = menu.modes;
if (!modes) return [];
const name = (modeId: string) => modeList.find(entry => entry.id === modeId)?.label ?? modeId;
const apply = async (to: string, keep: boolean) => { await modes.apply(to, keep); setMode(to); close('action'); };
const at = path.indexOf('mode') + 1;
if (asking?.reapply && modeStatus) {
// What applying the mode again turns on and off, said before it happens.
return [
{ kind: 'note', id: 'mode:reapply-hint', title: t('wb.modes.reapply', { mode: name(asking.to) }), text: t('wb.modes.reapplyHint', { mode: name(asking.to) }) },
...(modeStatus.on.length ? [{ kind: 'note' as const, id: 'mode:reapply-on', title: '', text: t('wb.modes.turnsOn', { list: modeStatus.on.join(', ') }) }] : []),
...(modeStatus.off.length ? [{ kind: 'note' as const, id: 'mode:reapply-off', title: '', text: t('wb.modes.turnsOff', { list: modeStatus.off.join(', ') }) }] : []),
item('mode:reapply-yes', t('wb.modes.reapply', { mode: name(asking.to) }), 'reload', { keepOpen: true, run: async () => { await modes.reapply?.(); close('action'); } }),
item('mode:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => { focusNext.current = { level: at, id: 'mode:reapply' }; setAsking(null); } }),
];
}
if (asking) {
// The question Settings asks: what was changed by hand stays, or the mode is taken as it is.
return [
{ kind: 'note', id: 'mode:question', title: t('wb.modes.keepQuestion'), text: t('wb.modes.keepHint', { count: asking.changes }) },
item('mode:keep', t('wb.modes.keep'), 'check', { keepOpen: true, run: () => apply(asking.to, true) }),
item('mode:reset', t('wb.modes.reset', { mode: name(asking.to) }), 'reload', { keepOpen: true, run: () => apply(asking.to, false) }),
item('mode:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => { focusNext.current = { level: at, id: `mode:${asking.to}` }; setAsking(null); } }),
];
}
const list = modeList.map(entry => item(`mode:${entry.id}`, entry.label, undefined, {
check: 'radio', checked: entry.id === mode, keepOpen: true,
run: async () => {
if (entry.id === mode) { close('action'); return; }
const changes = await modes.changes(entry.id);
if (changes > 0) { focusNext.current = { level: at, edge: 'first' }; setAsking({ to: entry.id, changes }); } else await apply(entry.id, false);
},
}));
if (!mode || !modeStatus?.custom || !modes.reapply) return list;
// The mode is a starting point: the features moved on, and nothing applies it again unasked.
const grew: MenuRow[] = modeStatus.added > 0 ? [{ kind: 'note', id: 'mode:grew', title: '', text: t('wb.modes.grew', { mode: name(mode), count: modeStatus.added }) }] : [];
return joinGroups([list, [
{ kind: 'note', id: 'mode:custom', title: t('wb.modes.custom', { mode: name(mode) }) },
...grew,
item('mode:reapply', t('wb.modes.reapply', { mode: name(mode) }), 'reload', {
keepOpen: true,
run: () => {
focusNext.current = { level: at, edge: 'first' };
setAsking({ to: mode, changes: 0, reapply: true });
if (modeStatus.added > 0) void modes.seen?.().then(() => setModeStatus({ ...modeStatus, added: 0 }), () => {});
},
}),
]]);
}
case 'workspaces': {
const list = workspaceList();
const rows: MenuRow[] = list.length
? list.map(entry => item(`ws:${entry.id}`, entry.name, undefined, { check: 'radio', checked: entry.id === workspaces.active, hint: t('wb.ws.tabs', { count: entry.tabs }), run: () => restoreWorkspace(entry.id) }))
: [{ kind: 'note', id: 'ws:none', title: '', text: menuText('noWorkspaces') }];
return joinGroups([rows, [item('ws:save', menuText('saveLayout'), 'plus', { run: openWorkspaceSave })]]);
}
case 'safe-mode': return [
{ kind: 'note', id: 'safe:question', title: menuText('safeQuestion'), text: menuText('safeExplain') },
item('safe:confirm', menuText('safeConfirm'), 'shield', { run: () => setSafeMode(true) }),
item('safe:cancel', t('wb.common.cancel'), 'close', { keepOpen: true, run: () => closeSub(path.indexOf('safe-mode') + 1) }),
];
case 'developer': return [
item('dev:mode', t('wb.dev.mode'), undefined, { check: 'checkbox', checked: dev.enabled, keepOpen: true, run: async () => { await invoke('dev_set', { enabled: !dev.enabled }); await refreshDev(); } }),
item('dev:folder', menuText('pluginsFolder'), 'folder', { run: () => invoke('plugins_open_folder') }),
];
default: return specRows(findSpec(groups, id)?.submenu?.() ?? []);
}
}
const groups = menu.groups ?? DEFAULT_MENU;
const env: MenuEnv = {
decks: !!config.deck, languages: !!menu.languages, themes: !!config.themes, modes: modeList.length > 0,
zoom: hasFeature('zoom'), find: hasFeature('find'), safeMode: hasFeature('safeMode'), store: hasFeature('store'), strings: config.features?.strings === true, workspaces: hasFeature('workspaces'), developer: hasFeature('developer'), updates: hasFeature('updates'),
};
const rootRows = () => joinGroups(planMenu(groups, env).map(group => group.flatMap(entry => (typeof entry === 'string' ? [builtin(entry)] : specRows([entry])))));
const labelOf = (id: string, rows: MenuRow[]) => rows.find((row): row is MenuItemRow => row.kind === 'item' && row.id === id)?.label ?? '';
// -------------------------------------------------------------------------------------------
// Keyboard and pointer
function onKey(event: ReactKeyboardEvent<HTMLDivElement>) {
const target = event.target as HTMLElement;
const menuEl = target.closest<HTMLElement>('[data-level]');
if (!menuEl) return;
const level = Number(menuEl.dataset.level);
const { key } = event;
// The keyboard leads now: the row under a resting pointer takes the focus back only when the pointer moves on.
clearTimeout(hover.current.timer);
hover.current = { el: null };
const keys = submenuKeys(getComputedStyle(menuEl).direction === 'rtl');
const done = () => { event.preventDefault(); event.stopPropagation(); };
if (key === 'Escape') { done(); if (level > 0) closeSub(level); else close('escape'); return; }
if (key === 'Tab') { done(); close('escape'); return; }
// The zoom row is one stop: left and right move through − + and reset (laid out left to right).
if ('zoom' in target.dataset && (key === 'ArrowLeft' || key === 'ArrowRight')) {
done();
const controls = Array.from(menuEl.querySelectorAll<HTMLElement>('[data-zoom]'));
controls[Math.max(0, Math.min(controls.length - 1, controls.indexOf(target) + (key === 'ArrowRight' ? 1 : -1)))]?.focus();
return;
}
if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Home' || key === 'End') {
done();
const stops = stopsOf(menuEl);
stops[moveStop(stops.indexOf(target), key, stops.length)]?.focus();
return;
}
if (key === keys.open) {
if (target.getAttribute('aria-haspopup') === 'menu' && target.dataset.item) { done(); openSub(level, target.dataset.item, true); }
return;
}
if (key === keys.close) { if (level > 0) { done(); closeSub(level); } return; }
const now = Date.now();
const typing = !!typed.current.text && now - typed.current.at <= 700;
// Enter, and Space outside a typed word: the row's own click chooses it; on the menu itself nothing is chosen.
if (key === 'Enter' || (key === ' ' && !typing)) {
if (target === menuEl) done();
typed.current.text = '';
return;
}
if (key.length !== 1 || event.ctrlKey || event.metaKey || event.altKey) return;
// Type-ahead: the next row whose label starts with what was typed.
done();
typed.current = { text: typing ? typed.current.text + key : key, at: now };
const stops = stopsOf(menuEl);
const found = typeahead(stops.map(el => el.dataset.label ?? ''), stops.indexOf(target), typed.current.text);
if (found >= 0) stops[found]!.focus();
}
/** The pointer moves the focus, like the arrows do: one highlight. A row with a submenu opens it after a beat. */
function onHover(row: MenuItemRow | null, level: number, el: HTMLElement) {
if (hover.current.el === el) return;
clearTimeout(hover.current.timer);
hover.current = { el };
if (document.activeElement !== el) el.focus({ preventScroll: true });
if (row?.submenu) {
if (path[level] !== row.id) hover.current.timer = setTimeout(() => openSub(level, row.id), 170);
} else if (path.length > level) {
hover.current.timer = setTimeout(() => { setPath(current => current.slice(0, level)); setAsking(null); }, 280);
}
}
// -------------------------------------------------------------------------------------------
function renderRow(row: MenuRow, level: number, index: number) {
if (row.kind === 'separator') return <hr key={`sep${index}`} role="separator"/>;
if (row.kind === 'note') {
return <div key={row.id} className={`bt-app-note${row.tone === 'error' ? ' is-error' : ''}`} role={row.tone === 'error' ? 'alert' : 'presentation'}>
{row.title && <strong>{row.title}</strong>}{row.text && <span>{row.text}</span>}
</div>;
}
if (row.kind === 'zoom') {
const tab = zoomTarget();
const factor = zoomOf(tab);
const control = (id: string, label: string, icon: IconName, direction: 1 | -1 | 0, off: boolean, className = '') =>
<button type="button" role="menuitem" tabIndex={-1} className={className} data-item={`zoom:${id}`} data-zoom="" data-label={menuText('zoom')}
aria-label={label} title={tab ? label : menuText('zoomNone')} aria-disabled={off}
onPointerMove={event => onHover(null, level, event.currentTarget)} onClick={() => { if (!off) void stepZoom(direction, tab); }}>
<Icon name={icon}/>
</button>;
return <div key="zoom" className={`bt-app-zoom${tab ? '' : ' is-off'}`} role="group" aria-label={menuText('zoom')} title={tab ? undefined : menuText('zoomNone')}>
<Icon name="zoom"/>
<span className="bt-menu-label">{menuText('zoom')}</span>
<span className="bt-app-zoom-step">
{control('out', menuText('zoomOut'), 'minus', -1, !tab || factor <= ZOOM_MIN)}
<output className="bt-app-zoom-value" aria-live="polite">{percent(factor)}</output>
{control('in', menuText('zoomIn'), 'plus', 1, !tab || factor >= ZOOM_MAX)}
</span>
{control('reset', menuText('zoomReset'), 'reload', 0, !tab || factor === 1, 'bt-app-zoom-reset')}
</div>;
}
const expanded = row.submenu ? path[level] === row.id : undefined;
return <button key={row.id} type="button" tabIndex={-1} disabled={row.disabled} data-item={row.id} data-label={row.label} title={row.title}
role={row.check === 'radio' ? 'menuitemradio' : row.check ? 'menuitemcheckbox' : 'menuitem'} aria-checked={row.check ? !!row.checked : undefined}
aria-haspopup={row.submenu ? 'menu' : undefined} aria-expanded={expanded}
onPointerMove={event => onHover(row, level, event.currentTarget)} onClick={() => void activate(row, level)}>
{row.check ? <span className="bt-app-check">{row.checked && <Icon name="check"/>}</span> : row.icon ? <Icon name={row.icon}/> : <span className="bt-app-check"/>}
{/* A language's own name keeps its own direction (<bdi>) but starts where every other label does. */}
<span className="bt-menu-label">{row.lang ? <bdi lang={row.lang} dir={row.dir}>{row.label}</bdi> : row.label}</span>
{row.swatch && <span className="wb-dots" aria-hidden="true" style={{ background: row.swatch.page }}>
<i style={{ background: row.swatch.bg, boxShadow: `inset 0 0 0 1px ${row.swatch.border}` }}/><i style={{ background: row.swatch.text }}/><i style={{ background: row.swatch.accent }}/>
</span>}
{row.hint && <span className="bt-app-hint">{row.hint}</span>}
{row.shortcut && <span className="bt-menu-keys">{shortcutText(row.shortcut, mac)}</span>}
{row.submenu && <Icon name="chevronRight" className="bt-app-chevron"/>}
</button>;
}
function renderMenus() {
const root = rootRows();
const levels: Array<{ rows: MenuRow[]; label: string }> = [{ rows: root, label: menuText('label') }];
path.forEach((id, index) => levels.push({ rows: submenuRows(id), label: labelOf(id, levels[index]!.rows) }));
// An error belongs to the level it happened on: the deepest one open.
if (error) levels[levels.length - 1]!.rows = [...levels[levels.length - 1]!.rows, { kind: 'note', id: 'error', title: '', text: error, tone: 'error' }];
return levels.map(({ rows, label }, level) => <div key={level === 0 ? 'root' : `${level}:${path[level - 1]}`} role="menu" aria-label={label} tabIndex={-1} data-level={level}
className={level === 0 ? `bt-menu bt-app-menu bt-pop${anchor.at === 'logo' ? '' : ' bt-pop--right'}` : 'bt-menu bt-app-menu bt-app-sub'}
style={level === 0 ? { top: anchor.top, left: anchor.left, right: anchor.right, maxHeight: `calc(100vh - ${anchor.top + 8}px)` } : undefined}>
{rows.map((row, index) => renderRow(row, level, index))}
</div>);
}
const label = menuText('label');
return <>
{trigger && <button ref={button} type="button" className="bt-app-button" aria-haspopup="menu" aria-expanded={open && anchor.at === 'button'} aria-label={label} title={`${label} (${APP_MENU_KEYS})`}
onClick={event => (open && anchor.at === 'button' ? close('escape') : show({ keyboard: event.detail === 0 }))}>
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="5.75" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="12" cy="18.25" r="1.6"/></svg>
</button>}
{open && createPortal(<div className="bt-menu-backdrop" onMouseDown={() => close()} onContextMenu={event => { event.preventDefault(); close(); }}>
<div ref={layers} className="bt-app-layers" onMouseDown={event => event.stopPropagation()} onContextMenu={event => { event.preventDefault(); event.stopPropagation(); }} onKeyDown={onKey}>
{renderMenus()}
</div>
</div>, document.body)}
{reporting && <ReportDialog onClose={() => setReporting(false)}/>}
</>;
}
/**
* The app's logo at the start of the titlebar: a second trigger of the same menu, hung under the
* logo. A click opens it; a press that turns into a drag moves the window, as the titlebar around
* it does; a right-click shows the window's system menu, where a titlebar icon has always had it.
*/
export function AppMenuLogo() {
useT();
const [expanded, setExpanded] = useState(openAt === 'logo');
const press = useRef<{ x: number; y: number; dragged: boolean } | null>(null);
useEffect(() => {
const update = () => setExpanded(openAt === 'logo');
window.addEventListener('bt-app-menu-state', update);
return () => window.removeEventListener('bt-app-menu-state', update);
}, []);
const { product, logo } = site();
const label = menuText('label');
return <button type="button" className="bt-titlebar-logo" aria-haspopup="menu" aria-expanded={expanded} aria-label={`${product}: ${label}`} title={`${product} · ${label}`}
onPointerDown={event => { if (event.button === 0) press.current = { x: event.clientX, y: event.clientY, dragged: false }; }}
onPointerMove={event => {
const start = press.current;
if (!start || start.dragged || !(event.buttons & 1)) return;
// The press became a drag: the window moves, and no menu opens when the button is released.
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) { start.dragged = true; startDrag(); }
}}
onClick={event => {
const dragged = press.current?.dragged;
press.current = null;
if (!dragged) openAppMenu({ anchor: 'logo', toggle: true, keyboard: event.detail === 0 });
}}
onContextMenu={event => {
event.preventDefault(); event.stopPropagation();
const scale = window.devicePixelRatio || 1;
systemMenu(Math.round(event.screenX * scale), Math.round(event.screenY * scale));
}}>
<img src={logo} alt="" draggable={false}/>
</button>;
}

View file

@ -17,6 +17,7 @@ import {
addColumn, bump, columnSourceUrl, configureColumn, deckById, decks, patchColumn, removeColumn, shiftColumn,
type Deck, type DeckColumn,
} from './deckStore.ts';
import { FindBar } from './FindBar.tsx';
import { useDecks, useProfiles, useT } from './hooks.ts';
import { Icon, type IconName } from './icons.tsx';
import { site } from './site.ts';
@ -181,6 +182,13 @@ function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; c
const still = useTabStill(column.tabId);
const [menu, setMenu] = useState<null | { kind: 'filters' | 'menu'; anchor: DOMRect }>(null);
const [leaving, setLeaving] = useState(false);
// Find in page for this column (Ctrl+F pressed in it): the find bar lies over the column's header.
const [finding, setFinding] = useState(false);
useEffect(() => {
const openFindBar = (event: Event) => { if ((event as CustomEvent<string>).detail === column.tabId) setFinding(true); };
window.addEventListener('bt-find', openFindBar);
return () => window.removeEventListener('bt-find', openFindBar);
}, [column.tabId]);
const spec = deckSite();
const runtime = decks.runtime.get(column.tabId);
const account = tabProfile(profiles, column.profile);
@ -236,6 +244,7 @@ function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; c
<svg className="bt-glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 12h.01M12 12h.01M18 12h.01" strokeWidth="3"/></svg></button>
{number <= 9 && <span className="bt-col-key" aria-hidden="true">{number}</span>}
{runtime?.loading && <span className="bt-col-progress" aria-label={tr('wb.common.loading')}/>}
{finding && <div className="bt-col-find"><FindBar tabId={column.tabId} url={runtime?.url ?? source ?? ''} onClose={() => setFinding(false)}/></div>}
</header>
<div className="bt-col-body" ref={body}>
{still

View file

@ -0,0 +1,95 @@
// Find in page: the shell's find bar for one pane. It takes the address field's place in that
// pane's toolbar while it is open (so the page under it does not move and, in split view, the bar
// is plainly the searched pane's). Native code does the searching (`tab_find`, shell-only): the
// engine's own find where the build can drive it (WebView2: highlights and a match count, which
// arrive as `tab-find` events), else the engine's `window.find` evaluated by native code (next and
// previous work, no count). Only what the page has rendered can be found, as in a browser: a
// virtualized list (X's timeline) holds the posts near the viewport, not the whole feed.
//
// The query lives in this component's state while the bar is open and nowhere else: it is not
// saved, logged or put in a URL, and closing the bar clears the engine's highlights.
// Keys: Enter / F3 next, Shift+Enter / Shift+F3 previous, Esc closes and gives the page the focus.
import { useEffect, useRef, useState } from 'react';
import { invoke, listen } from './bridge.ts';
import { describe, diag } from './diag.ts';
import { useT } from './hooks.ts';
import { formatNumber } from './i18n.ts';
import { Icon } from './icons.tsx';
import { findLabel, menuText } from './menuModel.ts';
import { tabAction } from './state.ts';
import './findBar.css';
/** Opens (or focuses) the find bar of web tab `id`. */
export const openFind = (id: string) => window.dispatchEvent(new CustomEvent('bt-find', { detail: id }));
/** The next (`1`) or previous (`-1`) match in tab `id`, when its find bar is open (F3 anywhere in the shell). */
export const stepFind = (id: string, direction: 1 | -1) => window.dispatchEvent(new CustomEvent('bt-find-step', { detail: { id, direction } }));
const find = (id: string, action: 'start' | 'next' | 'previous' | 'stop', query?: string) =>
invoke('tab_find', { id, action, ...(query ? { query } : {}) }).catch(() => {});
export function FindBar({ tabId, url, onClose }: { tabId: string; url: string; onClose(): void }) {
useT();
const [query, setQuery] = useState('');
// What the engine reported for the query on screen (null: nothing yet, or an engine that does not count).
const [counts, setCounts] = useState<{ count: number; index: number } | null>(null);
const input = useRef<HTMLInputElement>(null);
const live = useRef(query);
live.current = query;
const close = () => {
onClose();
// The page gets the keyboard back.
void tabAction(tabId, 'focus');
};
const step = (direction: 1 | -1) => { if (live.current) void find(tabId, direction > 0 ? 'next' : 'previous', live.current); };
// The shell takes the keyboard (Ctrl+F was pressed in the page); closing clears the highlights.
useEffect(() => {
invoke('shell_focus').catch(() => {});
input.current?.focus();
diag(`find bar open: hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`);
setTimeout(() => diag(`find bar +300ms: hasFocus=${document.hasFocus()} active=${describe(document.activeElement)}`), 300);
const again = (event: Event) => { if ((event as CustomEvent<string>).detail === tabId) { input.current?.focus(); input.current?.select(); } };
const onStep = (event: Event) => { const detail = (event as CustomEvent<{ id: string; direction: 1 | -1 }>).detail; if (detail.id === tabId) step(detail.direction); };
window.addEventListener('bt-find', again);
window.addEventListener('bt-find-step', onStep);
let disposed = false;
let unlisten: (() => void) | undefined;
listen<{ id: string; count: number; index: number }>('tab-find', ({ payload }) => {
if (payload.id === tabId && live.current) setCounts({ count: payload.count, index: payload.index });
}).then(dispose => { if (disposed) dispose(); else unlisten = dispose; }).catch(() => {});
return () => {
disposed = true;
unlisten?.();
window.removeEventListener('bt-find', again);
window.removeEventListener('bt-find-step', onStep);
void find(tabId, 'stop');
};
}, [tabId]);
// A new query (or a new page under the same query) starts a new search, a beat after the last key.
useEffect(() => {
setCounts(null);
if (!query) { void find(tabId, 'stop'); return; }
const timer = setTimeout(() => void find(tabId, 'start', query), 140);
return () => clearTimeout(timer);
}, [query, url, tabId]);
const status = query && counts ? findLabel(counts, value => formatNumber(value)) : '';
return <div className={`bt-omni bt-omni--edit bt-find${query && counts?.count === 0 ? ' is-none' : ''}`} role="search" title={menuText('findHint')}>
<Icon name="search" className="bt-omni-lead"/>
<input ref={input} type="text" spellCheck={false} autoComplete="off" maxLength={256} value={query} placeholder={menuText('findField')} aria-label={menuText('findField')}
onChange={event => setQuery(event.target.value.replace(/[\u0000-\u001f\u007f]/g, ''))}
onKeyDown={event => {
if (event.key === 'Enter' || event.key === 'F3') { event.preventDefault(); event.stopPropagation(); step(event.shiftKey ? -1 : 1); }
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); }
}}/>
<span className="bt-find-count" role="status" aria-live="polite">{status}</span>
<button type="button" className="bt-omni-action" disabled={!query} title={`${menuText('findPrevious')} (Shift+Enter)`} aria-label={menuText('findPrevious')}
onMouseDown={event => event.preventDefault()} onClick={() => step(-1)}><Icon name="chevron" className="bt-find-up"/></button>
<button type="button" className="bt-omni-action" disabled={!query} title={`${menuText('findNext')} (Enter)`} aria-label={menuText('findNext')}
onMouseDown={event => event.preventDefault()} onClick={() => step(1)}><Icon name="chevron"/></button>
<button type="button" className="bt-omni-action" title={`${menuText('findClose')} (Esc)`} aria-label={menuText('findClose')} onClick={close}><Icon name="close"/></button>
</div>;
}

View file

@ -0,0 +1,102 @@
// "Report a problem": a small dialog that shows the diagnostic summary (reportModel.ts) exactly as
// it would be shared, with Copy and a button that opens the project's new-issue page in the system
// browser. The app sends nothing itself: no request, and the summary is never put in a URL (the
// issue page opens bare; the owner pastes what they copied). Without a configured issue page the
// button is off and says why.
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { invoke } from './bridge.ts';
import { useT } from './hooks.ts';
import { textLocale } from './i18n.ts';
import { Icon } from './icons.tsx';
import { menuText } from './menuModel.ts';
import { buildReport, systemFromUserAgent, webviewFromUserAgent, type ReportInfo } from './reportModel.ts';
import { safe } from './safeStore.ts';
import { site } from './site.ts';
import { setOverlay } from './state.ts';
type Hints = { platformVersion?: string; architecture?: string; bitness?: string; fullVersionList?: Array<{ brand?: string; version?: string }> };
/** What the engine says about the system when asked (Chromium webviews; others have the user agent only). */
async function systemHints(): Promise<Hints> {
try {
const data = (navigator as Navigator & { userAgentData?: { getHighEntropyValues(hints: string[]): Promise<Hints> } }).userAgentData;
return data ? await data.getHighEntropyValues(['platformVersion', 'architecture', 'bitness', 'fullVersionList']) : {};
} catch { return {}; }
}
/** Gathers the facts a report may say: from the app's config and the shell's own state, nothing about the person. */
async function collect(): Promise<ReportInfo> {
const config = site();
const menu = config.menu ?? {};
const themes = config.themes;
const [appVersion, hints, mode, plugins, details] = await Promise.all([
menu.version ? menu.version().catch(() => '') : Promise.resolve(''),
systemHints(),
menu.modes ? menu.modes.current().catch(() => null) : Promise.resolve(undefined),
invoke<Array<{ file?: unknown; enabled?: unknown }>>('plugins_list').then(list => list.filter(plugin => plugin.enabled === true).map(plugin => String(plugin.file ?? '')), () => null),
menu.report?.details ? Promise.resolve(menu.report.details()).catch(() => []) : Promise.resolve([]),
]);
if (themes) await themes.loadThemes().catch(() => {});
const choice = themes?.current().choice;
const theme = themes ? themes.adapter.resolve(choice) as { id?: unknown; icons?: { pack?: unknown } } : null;
return {
product: config.product,
appVersion,
system: systemFromUserAgent(navigator.userAgent, hints),
webview: webviewFromUserAgent(navigator.userAgent, hints.fullVersionList),
language: menu.languages?.state().locale ?? textLocale(),
languageChoice: menu.languages?.state().preference ?? 'fixed',
mode,
theme: themes ? themes.adapter.preset(choice) : undefined,
iconPack: theme ? (typeof theme.icons?.pack === 'string' ? theme.icons.pack : '') : undefined,
plugins,
details,
safeMode: safe.active,
};
}
export function ReportDialog({ onClose }: { onClose(): void }) {
const t = useT();
const [text, setText] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const dialog = useRef<HTMLDivElement>(null);
const issueUrl = site().menu?.report?.issueUrl;
const canOpen = typeof issueUrl === 'string' && /^https:\/\//.test(issueUrl);
useEffect(() => {
setOverlay(1);
invoke('shell_focus').catch(() => {});
let live = true;
collect().then(info => { if (live) setText(buildReport(info)); }, () => { if (live) setText(''); });
dialog.current?.focus();
return () => { live = false; setOverlay(-1); };
}, []);
const copy = async () => {
if (!text) return;
try { await navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2200); }
catch { dialog.current?.querySelector<HTMLTextAreaElement>('textarea')?.select(); }
};
return createPortal(<div className="bt-palette-backdrop bt-report-backdrop" onMouseDown={onClose}>
<div ref={dialog} className="bt-palette bt-report bt-pop" role="dialog" aria-modal="true" aria-labelledby="bt-report-title" aria-describedby="bt-report-lede" tabIndex={-1}
onMouseDown={event => event.stopPropagation()} onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose(); } }}>
<header className="bt-report-head">
<h2 id="bt-report-title">{menuText('reportTitle')}</h2>
<button className="bt-icon" aria-label={t('wb.common.close')} onClick={onClose}><Icon name="close"/></button>
</header>
<p id="bt-report-lede" className="bt-report-lede">{menuText('reportLede')}</p>
<textarea className="bt-report-text" readOnly spellCheck={false} dir="ltr" lang="en" rows={12} aria-label={menuText('reportTitle')}
value={text ?? t('wb.common.loading')} onFocus={event => event.currentTarget.select()}/>
{!canOpen && <p className="bt-report-note">{menuText('reportNoPage')}</p>}
<footer className="bt-report-foot">
<span className="bt-report-copied" role="status" aria-live="polite">{copied ? t('wb.common.copied') : ''}</span>
<button className="bt-deck-secondary" disabled={!canOpen} title={canOpen ? issueUrl : menuText('reportNoPage')}
onClick={() => { if (canOpen) invoke('open_external_url', { url: issueUrl }).catch(() => {}); }}><Icon name="external"/>{menuText('reportOpen')}</button>
<button className="bt-deck-primary" disabled={!text} onClick={() => void copy()}><Icon name="copy"/>{t('wb.common.copy')}</button>
</footer>
</div>
</div>, document.body);
}

View file

@ -16,9 +16,11 @@ import { besideGroup } from '../paneModel.ts';
import { tabProfile } from '../profileModel.ts';
import { accountAction } from './accountModel.ts';
import { accountLabel } from './AccountSwitcher.tsx';
import { openAppMenu } from './AppMenu.tsx';
import { invoke, listen } from './bridge.ts';
import { CommandPalette } from './CommandPalette.tsx';
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx';
import { openFind, stepFind } from './FindBar.tsx';
import { columnSourceUrl, createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts';
import { installDevHost } from './devHost.ts';
import { useProfiles, useT } from './hooks.ts';
@ -29,9 +31,11 @@ import { NewTabPage } from './NewTabPage.tsx';
import type { PaletteAction, PaletteContext } from './paletteModel.ts';
import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx';
import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts';
import { initDiag } from './diag.ts';
import { installSafeMode } from './safeStore.ts';
import { hasFeature, site } from './site.ts';
import {
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, resync, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
} from './state.ts';
import { installSyncHost } from './syncHost.ts';
@ -40,10 +44,14 @@ import { openWorkspaceSave } from './TitlebarExtras.tsx';
import { WebPanel } from './WebPanel.tsx';
import { frameless, isTauri, onMaximizedChange, os } from './windowBinding.ts';
import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
import { stepZoom, zoomTarget } from './zoomStore.ts';
import './shell.css';
type Placement = { referencePanel: string; direction: 'within' | 'right' | 'below' };
/** How long the startup cover waits, once the window is shown, for the visible site tabs to say they painted. */
export const STARTUP_CONTENT_WAIT = 8000;
/** A development build (createShell's `dev`): the shell keeps the devtools shortcut. */
let devBuild = false;
export function setDevBuild(value: boolean) {
@ -262,6 +270,8 @@ function runPalette(action: PaletteAction) {
case 'plugin-command': runPluginCommand(action.tab, action.command); break;
case 'workspace': void restoreWorkspace(action.id); break;
case 'workspace-save': openWorkspaceSave(); break;
case 'find': runShortcut('find'); break;
case 'menu': openAppMenu({ keyboard: true }); break;
}
}
@ -269,17 +279,37 @@ function runShortcut(shortcut: string, id?: string) {
const api = shell.api;
if (!api) return;
if (shortcut === 'command-palette') { togglePalette(); return; }
// Alt+F / F10: the app menu, opened for the keyboard (pressed again, it closes).
if (shortcut === 'app-menu') { openAppMenu({ keyboard: true, toggle: true }); return; }
// Page zoom of the tab the keys were pressed in (a deck column zooms itself), else the pane in front.
if (shortcut === 'zoom-in' || shortcut === 'zoom-out' || shortcut === 'zoom-reset') {
void stepZoom(shortcut === 'zoom-in' ? 1 : shortcut === 'zoom-out' ? -1 : 0, id ?? zoomTarget());
return;
}
if (shortcut === 'deck-toggle') { toggleDeck(); return; }
if (shortcut.startsWith('column-') || shortcut === 'deck-compose') {
const deckId = deckFor(id);
if (deckId) runDeckCommand(deckId, shortcut);
return;
}
// Find in page in a deck column: that column's own find bar (the keys were pressed in it, or it is the
// focused column of the deck in front).
if (shortcut === 'find' || shortcut === 'find-next' || shortcut === 'find-previous') {
const column = id && !api.getPanel(id) ? id : id === undefined && (api.activePanel?.params as TabParams | undefined)?.kind === 'deck' ? zoomTarget() : null;
if (column && findColumnTab(column)?.column) {
if (shortcut !== 'find') stepFind(column, shortcut === 'find-next' ? 1 : -1);
else if (hasFeature('find')) openFind(column);
return;
}
}
// A browser shortcut pressed inside a deck column acts on its deck tab.
if (id && !api.getPanel(id) && findColumnTab(id)) id = deckPanelId(findColumnTab(id)!.deck.id);
const panel = id === undefined ? api.activePanel : api.getPanel(id);
switch (shortcut) {
case 'new-tab': addStart(); break;
// Find in page: the find bar of that tab (the one the keys were pressed in, else the one in front).
case 'find': if (panel && isWeb(panel) && hasFeature('find')) { panel.api.setActive(); openFind(panel.id); } break;
case 'find-next': case 'find-previous': if (panel && isWeb(panel)) stepFind(panel.id, shortcut === 'find-next' ? 1 : -1); break;
case 'close-tab': if (panel) closeTab(panel); break;
case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; }
case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break;
@ -330,10 +360,20 @@ function shortcutFor(event: KeyboardEvent): string | null {
if (key === 'l') return 'focus-address';
if (key === 'g' && event.shiftKey) return 'media-panel';
if (key === 'k' && !event.shiftKey) return 'command-palette';
if (key === 'f' && !event.shiftKey && hasFeature('find')) return 'find';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return 'reload';
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
if (hasFeature('zoom')) {
if (key === '=' || key === '+' || event.code === 'NumpadAdd') return 'zoom-in';
if (key === '-' || event.code === 'NumpadSubtract') return 'zoom-out';
if (key === '0' || event.code === 'Numpad0') return 'zoom-reset';
}
}
if (event.key === 'F3' && !mod && !event.altKey) return event.shiftKey ? 'find-previous' : 'find-next';
// The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS).
if (event.key === 'F10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu';
if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && os !== 'macos') return 'app-menu';
if (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;
@ -542,6 +582,8 @@ export default function Shell() {
shell.openAccount = openAccount;
shell.openUrl = (url, profile) => { addWeb(url, undefined, true, profile); };
shell.openPanelSection = section => openPanel(section, shell.api?.activePanel?.id);
shell.shortcut = name => runShortcut(name);
shell.run = runPalette;
useEffect(() => {
document.documentElement.dataset.os = os;
@ -563,8 +605,13 @@ export default function Shell() {
return () => off.forEach(dispose => dispose());
}, []);
// Safe mode for this run (the host's flag): the titlebar says so and the chrome drops its theme.
useEffect(() => (hasFeature('safeMode') ? installSafeMode() : undefined), []);
// The site's own settings and events (e.g. X's Twitter/X wording).
useEffect(() => site().start?.(), []);
// Focus and layering diagnostics, when the app was started with them (`--diag`).
useEffect(() => { void initDiag(); }, []);
useEffect(() => {
const unlisten = [
@ -609,6 +656,8 @@ export default function Shell() {
if (payload.beside && source) { openBeside(payload.url, source, !payload.background, profile); return; }
addWeb(payload.url, payload.from ? { referencePanel: payload.from, direction: 'within' } : undefined, !payload.background, profile);
}),
// Native code builds every tab webview anew (safe mode switched): it needs the layout again.
listen('tabs-rebuild', () => resync()),
listen<{ id: string; shortcut: string }>('tab-shortcut', ({ payload }) => runShortcut(payload.shortcut, payload.id)),
listen<{ from: string; section?: string }>('open-panel', ({ payload }) => openPanel(payload.section, payload.from)),
// A tab's link drag: `start` carries the natively validated link, `enter` is an external drag.
@ -882,11 +931,15 @@ export default function Shell() {
const check = () => { if (done()) finish(); };
const finish = () => {
clearInterval(poll);
clearTimeout(limit);
window.removeEventListener('bt-tab-startup-state', check);
resolve();
};
// Dockview closes and deck layout changes do not always emit tab-state.
const poll = setInterval(check, 200);
// Never longer than this: a page that never says it painted (its script failed, the
// engine held its frames back) shows as it is rather than behind a cover for good.
const limit = setTimeout(finish, STARTUP_CONTENT_WAIT);
window.addEventListener('bt-tab-startup-state', check);
});
// The X DOM signal can precede its separate native WebView surface by a frame.

View file

@ -2,6 +2,7 @@ import { useEffect, type CSSProperties, type MouseEvent as ReactMouseEvent } fro
import { RESIZE_BORDER } from '../chrome.ts';
import { chipFor } from '../updateModel.ts';
import { AccountSwitcher } from './AccountSwitcher.tsx';
import { AppMenu, AppMenuLogo } from './AppMenu.tsx';
import { invoke } from './bridge.ts';
import { useT, useUpdateStatus } from './hooks.ts';
import { tx } from './i18n.ts';
@ -22,16 +23,19 @@ export function titlebarContextMenu(event: ReactMouseEvent | MouseEvent) {
/**
* The 44px titlebar row. It sits under the dockview root: the top groups' tab headers are
* transparent and let clicks through to the drag layer, the logo and the caption buttons.
* transparent and let clicks through to the drag layer, the logo and the caption buttons. The logo
* is the app menu's second trigger (AppMenu.tsx); everything else that is empty drags the window.
*/
export function Titlebar({ maximized }: { maximized: boolean }) {
return <header className="bt-titlebar" onContextMenu={titlebarContextMenu}>
<div className="bt-titlebar-drag" data-tauri-drag-region/>
<img className="bt-titlebar-logo" src={site().logo} alt="" draggable={false} data-tauri-drag-region/>
<AppMenuLogo/>
<div className="bt-titlebar-spacer" data-tauri-drag-region/>
<TitlebarExtras/>
<AccountSwitcher/>
<UpdateChip/>
{/* One home for the app menu: the logo. Alt+F, F10, the palette and the account menu's last row open it there. */}
<AppMenu trigger={false}/>
{os !== 'macos' && <WindowControls maximized={maximized}/>}
</header>;
}

View file

@ -6,15 +6,18 @@
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { createPortal } from 'react-dom';
import { ago } from './backupModel.ts';
import { useDev, useSync, useT } from './hooks.ts';
import { t } from './i18n.ts';
import { useDev, usePaneTick, useSync, useT } from './hooks.ts';
import { formatNumber, t } from './i18n.ts';
import { Icon } from './icons.tsx';
import { menuText } from './menuModel.ts';
import { safe, setSafeMode } from './safeStore.ts';
import { hasFeature } from './site.ts';
import { setOverlay, shell } from './state.ts';
import { WORKSPACE_LIMITS } from './workspaceModel.ts';
import {
deleteWorkspace, loadWorkspaces, renameSavedWorkspace, restoreWorkspace, saveCurrentWorkspace, setStartWorkspace, workspaceList, workspaces,
} from './workspaces.ts';
import { readZoom, stepZoom, zoomOf, zoomTarget } from './zoomStore.ts';
import './workspaces.css';
function useWorkspaces() {
@ -43,12 +46,54 @@ export function TitlebarExtras() {
return () => { observer.disconnect(); document.documentElement.style.removeProperty('--bt-tb-extra'); };
}, []);
return <div className="bt-tb-extras" ref={root}>
{hasFeature('safeMode') && <SafeChip/>}
{hasFeature('zoom') && <ZoomChip/>}
{hasFeature('sync') && <SyncChip/>}
{hasFeature('developer') && <DevChip/>}
{hasFeature('workspaces') && <WorkspaceMenu/>}
</div>;
}
/** Safe mode: said in the titlebar for as long as it is on; one click leaves it (the tabs load again with the owner's setup). */
function SafeChip() {
useT();
const [, tick] = useState(0);
const [busy, setBusy] = useState(false);
useEffect(() => {
const update = () => tick(value => value + 1);
window.addEventListener('bt-safe', update);
return () => window.removeEventListener('bt-safe', update);
}, []);
if (!safe.active) return null;
return <button className="bt-tb-chip bt-safe-chip" title={menuText('safeChip')} aria-label={`${menuText('safe')}. ${menuText('safeLeave')}`} disabled={busy}
onClick={() => { setBusy(true); void setSafeMode(false).catch(() => {}).finally(() => setBusy(false)); }}>
<Icon name="shield"/><span className="bt-tb-chip-text">{menuText('safe')}</span><span className="bt-safe-leave">{menuText('safeLeaveShort')}</span>
</button>;
}
/** The page zoom of the pane in front, only while it is not 100% (Ctrl with + and - say nothing else); a click resets it. */
function ZoomChip() {
useT();
usePaneTick();
const [, tick] = useState(0);
useEffect(() => {
const update = () => tick(value => value + 1);
window.addEventListener('bt-zoom', update);
window.addEventListener('bt-decks', update);
return () => { window.removeEventListener('bt-zoom', update); window.removeEventListener('bt-decks', update); };
}, []);
const tab = zoomTarget();
// A restored tab may come back zoomed: ask once it is the one in front.
useEffect(() => { void readZoom(tab); }, [tab]);
const factor = zoomOf(tab);
if (!tab || factor === 1) return null;
const percent = formatNumber(factor, { style: 'percent', maximumFractionDigits: 0 });
const label = menuText('zoomChip', { percent });
return <button className="bt-tb-chip bt-zoom-chip" title={label} aria-label={label} onClick={() => void stepZoom(0, tab)}>
<Icon name="zoom"/><span className="bt-tb-chip-text">{percent}</span>
</button>;
}
function DevChip() {
const t = useT();
const dev = useDev();

View file

@ -4,6 +4,7 @@ import { tabProfile } from '../profileModel.ts';
import { AccountAvatar, accountName } from './AccountSwitcher.tsx';
import { WB_MARK } from './brand.ts';
import { invoke } from './bridge.ts';
import { FindBar } from './FindBar.tsx';
import { useProfiles, useSiteText, useT } from './hooks.ts';
import { Icon } from './icons.tsx';
import { openPaneTheme } from './PaneTheme.tsx';
@ -22,6 +23,13 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
const [draft, setDraft] = useState<string | null>(null);
const [caret, setCaret] = useState(0);
const [splitMenu, setSplitMenu] = useState(false);
// Find in page: the find field takes the address field's place while it is open (FindBar.tsx).
const [finding, setFinding] = useState(false);
useEffect(() => {
const open = (event: Event) => { if ((event as CustomEvent<string>).detail === api.id) { setDraft(null); setFinding(true); } };
window.addEventListener('bt-find', open);
return () => window.removeEventListener('bt-find', open);
}, [api.id]);
// Windows: the page's last frame, shown while its webview is hidden (host `tab-still`).
const still = useTabStill(api.id);
useSiteText();
@ -74,6 +82,7 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
useEffect(() => {
const focusAddress = (event: Event) => {
if ((event as CustomEvent<string>).detail !== api.id) return;
setFinding(false);
if (draft === null) enterEdit();
else { input.current?.focus(); input.current?.select(); }
};
@ -121,7 +130,7 @@ export function WebPanel(props: IDockviewPanelProps<WebParams>) {
<button className="bt-icon" title={params.loading ? t('wb.web.stop') : t('wb.web.reloadTitle')} aria-label={params.loading ? t('wb.web.stop') : t('wb.shell.menu.reload')} onClick={() => tabAction(api.id, params.loading ? 'stop' : 'reload')}><Icon name={params.loading ? 'stop' : 'reload'}/></button>
{account && <span className="bt-pane-account" role="img" aria-label={t('wb.shell.tab.account', { name: accountName(account) })} title={t('wb.web.paneAccount', { name: accountName(account) })}
style={{ ['--bt-pane-account' as string]: account.color }}><AccountAvatar profile={account} size={20}/></span>}
{editing
{finding ? <FindBar tabId={api.id} url={params.url} onClose={() => setFinding(false)}/> : editing
? <div className="bt-omni bt-omni--edit" ref={omni}>
<Icon name="search" className="bt-omni-lead"/>
<input ref={input} spellCheck={false} aria-label={t('wb.web.address')} value={draft}

View file

@ -0,0 +1,121 @@
/* The app menu (AppMenu.tsx): the titlebar's "Settings and more" button, its menu and submenus.
Tokens come from shell.css (:root --bt-*), so it follows the chrome theme (and its first-frame
cache) like every other shell menu. Its width in the titlebar is reserved in --bt-tb-menu. */
/* The button: the last thing before the caption buttons. */
.bt-app-button {
align-self: center; display: inline-grid; place-items: center; width: 30px; height: 30px; flex: none; margin-right: 8px; padding: 0; box-sizing: border-box; /* rtl-ok: titlebar */
border: 1px solid transparent; border-radius: 15px; background: transparent; color: var(--bt-text-2); cursor: pointer;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease);
}
.bt-app-button:hover { background: var(--bt-hover); border-color: var(--bt-line-soft); color: var(--bt-text); }
.bt-app-button[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); color: var(--bt-text); }
.bt-app-button:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
.bt-shell .bt-app-button svg { width: 16px; height: 16px; fill: currentColor; stroke: none; }
/* An app that shows no menu button (`<AppMenu trigger={false}/>`, the logo is the menu's home) reserves no room for it. */
html:not(:has(.bt-app-button)) { --bt-tb-menu: 0px; }
/* The logo at the start of the titlebar: the menu's second trigger (a 30px target around the 20px
mark; with its margins it takes the 50px the tab strip leaves in --bt-tb-left). */
.bt-titlebar-logo {
align-self: center; display: inline-grid; place-items: center; width: 30px; height: 30px; flex: 0 0 30px; margin: 0 9px 0 11px; padding: 0; box-sizing: border-box; /* rtl-ok: titlebar */
border: 1px solid transparent; border-radius: 9px; background: transparent; cursor: pointer; -webkit-user-drag: none;
transition: background-color var(--bt-t1) var(--bt-ease), border-color var(--bt-t1) var(--bt-ease);
}
.bt-titlebar-logo img { display: block; width: 20px; height: 20px; pointer-events: none; -webkit-user-drag: none; }
.bt-titlebar-logo:hover { background: var(--bt-hover); border-color: var(--bt-line-soft); }
.bt-titlebar-logo[aria-expanded=true] { background: var(--bt-hover); border-color: rgb(var(--bt-accent-rgb) / .5); }
.bt-titlebar-logo:focus-visible { outline: 0; box-shadow: var(--bt-ring); }
/* The menu and its submenus. `display: contents`: the layers are positioned on their own. */
.bt-app-layers { display: contents; }
.bt-menu.bt-app-menu {
width: 304px; max-width: calc(100vw - 16px); padding: 6px; overflow-y: auto; overscroll-behavior: contain;
scrollbar-width: thin; scrollbar-color: var(--bt-line-strong) transparent;
}
.bt-menu.bt-app-menu:focus { outline: 0; }
.bt-menu.bt-app-sub {
width: max-content; min-width: 224px; max-width: min(320px, calc(100vw - 16px)); z-index: 1;
animation: bt-app-sub-in var(--bt-t1) var(--bt-ease-out);
}
@keyframes bt-app-sub-in { from { opacity: 0; transform: translateX(var(--bt-app-sub-from, 6px)); } }
.bt-app-menu hr { flex: none; width: auto; align-self: stretch; }
/* Rows: one highlight, wherever it comes from (the pointer moves the focus, as the arrows do);
a row whose submenu is open keeps it; the keyboard's focus also gets a hairline in the accent. */
.bt-app-menu button { flex: none; width: 100%; min-width: 0; box-sizing: border-box; }
.bt-app-menu button:hover:not(:disabled) { background: transparent; }
.bt-app-menu button:focus:not(:disabled), .bt-app-menu button[aria-expanded=true] { background: var(--bt-hover); outline: 0; }
.bt-app-menu button:focus-visible:not(:disabled) { box-shadow: inset 0 0 0 1px rgb(var(--bt-accent-rgb) / .6); }
.bt-app-menu button:active:not(:disabled) { background: var(--bt-press); }
.bt-app-menu button:focus > .bt-glyph, .bt-app-menu button[aria-expanded=true] > .bt-glyph { color: var(--bt-text); }
/* The leading column: an icon, or the check of a choice (empty while it is not the one chosen). */
.bt-app-check { display: inline-grid; place-items: center; width: 16px; height: 16px; flex: none; }
.bt-app-check .bt-glyph { width: 15px; height: 15px; color: var(--bt-accent); stroke-width: 2.1; }
.bt-app-menu [aria-checked=true] .bt-menu-label { color: var(--bt-text); font-weight: 600; }
/* The trailing column: a quiet value (the language in use, a version), the keys, the submenu arrow. */
.bt-app-hint { flex: 0 1 auto; min-width: 0; max-width: 46%; margin-inline-start: auto; padding-inline-start: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--bt-muted); font: 400 12px/1.3 var(--bt-ui); font-variant-numeric: tabular-nums; }
.bt-app-menu .bt-menu-keys { flex: none; padding-inline-start: 12px; unicode-bidi: isolate; direction: ltr; }
.bt-app-hint + .bt-menu-keys, .bt-app-menu .wb-dots + .bt-app-hint { margin-inline-start: 0; }
.bt-app-menu .bt-app-chevron { width: 14px; height: 14px; margin-inline: 2px -4px; color: var(--bt-faint); }
.bt-app-menu .bt-app-hint + .bt-app-chevron { margin-inline-start: -4px; }
.bt-app-menu button:focus > .bt-app-chevron, .bt-app-menu button[aria-expanded=true] > .bt-app-chevron { color: var(--bt-text-2); }
[dir="rtl"] .bt-app-menu .bt-app-chevron { transform: scaleX(-1); }
.bt-app-menu .wb-dots { margin-inline-start: 8px; }
/* Zoom: one line, − 100% + and a reset. The stepper reads left to right in every language. */
.bt-app-zoom { display: flex; align-items: center; gap: 10px; height: 36px; flex: none; padding-inline: 10px 3px; color: var(--bt-text); }
.bt-app-zoom > .bt-glyph { color: var(--bt-muted); }
.bt-app-zoom.is-off > .bt-glyph, .bt-app-zoom.is-off .bt-menu-label, .bt-app-zoom.is-off .bt-app-zoom-value { color: var(--bt-faint); }
.bt-app-zoom-step { display: flex; align-items: center; flex: none; height: 28px; border-radius: 9px; direction: ltr; background: rgb(var(--bt-text-rgb) / .04); box-shadow: inset 0 0 0 1px var(--bt-line); }
.bt-app-menu .bt-app-zoom button { width: 30px; height: 28px; flex: none; padding: 0; justify-content: center; border-radius: 8px; color: var(--bt-text-2); }
.bt-app-menu .bt-app-zoom button > .bt-glyph { width: 14px; height: 14px; color: inherit; }
.bt-app-menu .bt-app-zoom button:focus { color: var(--bt-text); }
.bt-app-menu .bt-app-zoom button[aria-disabled=true] { color: var(--bt-faint); cursor: default; }
.bt-app-menu .bt-app-zoom button[aria-disabled=true]:active { background: var(--bt-hover); }
.bt-app-zoom-value { min-width: 50px; padding: 0 2px; text-align: center; color: var(--bt-text); font: 500 12px/1 var(--bt-mono); font-variant-numeric: tabular-nums; }
.bt-app-menu .bt-app-zoom .bt-app-zoom-reset { width: 28px; border-radius: 9px; }
/* Words that are not a choice: the mode question, an empty list, an error. */
.bt-app-note { display: flex; flex-direction: column; gap: 3px; max-width: 288px; padding: 8px 10px 7px; box-sizing: border-box; }
.bt-app-note strong { color: var(--bt-text); font: 600 13px/1.3 var(--bt-ui); }
.bt-app-note span { color: var(--bt-muted); font: 400 12px/1.4 var(--bt-ui); white-space: normal; }
.bt-app-note.is-error span { color: var(--bt-danger); }
/* The account menu's last row: the way here from where the account name is. */
.bt-menu .bt-acct-settings { flex: none; height: 34px; gap: 11px; padding: 0 8px; border-radius: 10px; color: var(--bt-text-2); }
.bt-menu .bt-acct-settings > .bt-glyph { width: 32px; height: 15px; }
.bt-menu .bt-acct-settings:focus-visible { box-shadow: var(--bt-ring); }
/* The titlebar's zoom chip: only while the pane in front is not at 100% (TitlebarExtras.tsx). */
.bt-zoom-chip { font-family: var(--bt-mono); font-size: 11.5px; font-variant-numeric: tabular-nums; }
.bt-zoom-chip .bt-glyph { color: var(--bt-muted); }
/* Safe mode, said in the titlebar for as long as it is on (TitlebarExtras.tsx): amber, and one click leaves it. */
.bt-safe-chip { border-color: rgba(245, 158, 11, .38); background: rgba(245, 158, 11, .1); color: var(--bt-text); font-weight: 600; }
.bt-safe-chip:hover { border-color: rgba(245, 158, 11, .6); background: rgba(245, 158, 11, .16); }
.bt-safe-chip .bt-glyph { color: #f59e0b; }
.bt-safe-leave { margin-inline-start: 2px; padding-inline-start: 9px; border-inline-start: 1px solid rgba(245, 158, 11, .35); color: var(--bt-text-2); font-weight: 500; }
.bt-safe-chip:hover .bt-safe-leave { color: var(--bt-text); }
.bt-safe-chip:disabled { opacity: .6; cursor: default; }
.bt-app-sub .bt-app-note { max-width: 300px; }
/* "Report a problem" (ReportDialog.tsx): the summary, exactly as it would be shared. */
.bt-report { width: min(560px, 100%); max-height: min(86vh, 620px); display: flex; flex-direction: column; overflow: hidden; }
.bt-report:focus { outline: 0; }
.bt-report-head { display: flex; align-items: center; gap: 8px; padding-block: 16px 4px; padding-inline: 20px 12px; }
.bt-report-head h2 { margin: 0; flex: 1; font: 700 17px/1.2 var(--bt-ui); letter-spacing: -.015em; color: var(--bt-text); }
.bt-report-lede, .bt-report-note { margin: 0; padding: 0 20px; color: var(--bt-muted); font: 400 12.5px/1.5 var(--bt-ui); }
.bt-report-note { padding-top: 10px; color: var(--bt-text-2); }
.bt-report-text {
flex: 1 1 auto; min-height: 150px; margin: 12px 20px 0; padding: 12px 14px; box-sizing: border-box; resize: none; overflow: auto;
border: 1px solid var(--bt-line); border-radius: var(--bt-r3); background: var(--bt-field); color: var(--bt-text);
font: 400 12px/1.65 var(--bt-mono); white-space: pre-wrap; overflow-wrap: anywhere; user-select: text; text-align: left; /* rtl-ok: the report is English */
}
.bt-report-text:focus-visible { outline: 0; border-color: transparent; box-shadow: var(--bt-ring); }
.bt-report-foot { display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding: 14px 20px 18px; }
.bt-report-copied { margin-inline-end: auto; color: var(--bt-muted); font: 500 12px/1 var(--bt-ui); }
.bt-report-foot .bt-glyph { width: 15px; height: 15px; }

View file

@ -0,0 +1,36 @@
// Focus and layering diagnostics from the shell (waybetter-host `diag.rs`): off unless the app was
// started with `--diag` (or WAYBETTER_DIAG=1). While on, each event is one short line in the app's
// log folder (`diag.log`): menu requests and closes with their reason, overlays and raising, native
// focus calls and the shell document's focus, blur and visibility. Event names and states only;
// never a URL, a query or page text.
import { invoke } from './bridge.ts';
let enabled = false;
/** Asks native code once whether diagnostics are on, and starts following the document's focus. */
export async function initDiag(): Promise<void> {
try { enabled = await invoke<boolean>('diag_get') === true; } catch { enabled = false; }
if (!enabled) return;
const state = () => `hasFocus=${document.hasFocus()} visible=${document.visibilityState} active=${describe(document.activeElement)}`;
window.addEventListener('focus', () => diag(`window focus (${state()})`));
window.addEventListener('blur', () => diag(`window blur (${state()})`));
document.addEventListener('visibilitychange', () => diag(`visibility ${document.visibilityState}`));
diag(`diagnostics on (${state()})`);
}
/** An element as a few plain words: its tag and first class (never its text). */
export function describe(element: Element | null): string {
if (!element) return 'none';
const name = element.tagName.toLowerCase();
const first = typeof element.className === 'string' ? element.className.split(/\s+/).filter(Boolean)[0] : '';
return first ? `${name}.${first}` : name;
}
/** One event line (nothing happens while diagnostics are off). */
export function diag(line: string): void {
if (!enabled) return;
invoke('diag_log', { line: line.slice(0, 280) }).catch(() => {});
}
export const diagOn = () => enabled;

View file

@ -0,0 +1,14 @@
/* Find in page (FindBar.tsx): the find field takes the address field's place in its pane's toolbar,
so it borrows that field's shape (.bt-omni, shell.css) and only adds what is its own. */
.bt-omni.bt-find input { font: 400 13px/1 var(--bt-ui); }
.bt-omni.bt-find input::placeholder { color: var(--bt-faint); }
.bt-find-count { flex: none; padding-inline: 6px 4px; color: var(--bt-muted); font: 500 11.5px/1 var(--bt-mono); font-variant-numeric: tabular-nums; white-space: nowrap; }
.bt-find.is-none .bt-find-count { color: var(--bt-danger); }
.bt-find .bt-omni-action { color: var(--bt-muted); }
.bt-find .bt-omni-action:disabled { color: var(--bt-faint); opacity: .6; cursor: default; background: transparent; }
.bt-shell .bt-find .bt-omni-action svg { width: 15px; height: 15px; }
.bt-shell .bt-find .bt-find-up { transform: rotate(180deg); }
/* In a deck column the bar lies over the column's header (DeckView.tsx): same field, the column's width. */
.bt-col-find { position: absolute; inset: 0; z-index: 3; border-radius: inherit; display: flex; align-items: center; padding-inline: 8px; background: var(--bt-chrome); }
.bt-col-find .bt-find { flex: 1; min-width: 0; height: 32px; }

View file

@ -69,7 +69,7 @@ export const FRAME_MESSAGES = {
'wb.backup.section.accounts': 'Accounts',
'wb.backup.section.alerts': 'Keyword alerts',
'wb.backup.section.customCss': 'Custom CSS',
'wb.backup.section.decks': 'Power User decks',
'wb.backup.section.decks': 'Decks',
'wb.backup.section.drafts': 'Drafts',
'wb.backup.section.features': '{site} tweaks',
'wb.backup.section.plugins': 'Plugins',
@ -129,8 +129,8 @@ export const FRAME_MESSAGES = {
'wb.deck.prev': 'Previous page',
'wb.deck.prevTitle': 'Previous page (Alt+PageUp)',
'wb.deck.remove': 'Remove column',
'wb.deck.settings': 'Power User settings',
'wb.deck.title': 'Power User Mode',
'wb.deck.settings': 'Deck settings',
'wb.deck.title': 'Deck',
'wb.deck.unreadLabel': '{count} unread, jump to them',
'wb.deck.unreadTitle': 'Unread in this deck',
'wb.deck.viewingPost': 'Viewing a post',
@ -178,7 +178,7 @@ export const FRAME_MESSAGES = {
'wb.palette.next': 'Next',
'wb.palette.none': 'No matches',
'wb.palette.onStart': 'on start',
'wb.palette.openPower': 'Open Power User Mode',
'wb.palette.openPower': 'Open deck',
'wb.palette.plugins': 'Plugins',
'wb.palette.switchTo': 'Switch to {name}',
'wb.palette.title': 'Command palette',

View file

@ -0,0 +1,50 @@
// The icon pack of the shell's own chrome: the global theme's pack (or the owner's pick), drawn in
// place of the frame's line glyphs wherever the pack has a glyph for that meaning. The glyphs are
// the pack's validated path data (framework themeIcons.ts), rendered as SVG elements by React, never
// as markup.
import { useSyncExternalStore } from 'react';
import type { IconGlyph, IconName, IconPack } from '../../../runtime/src/themeIcons.ts';
let current: IconPack | null = null;
const listeners = new Set<() => void>();
/** Sets the chrome's pack (the theme store calls it with the global theme's). */
export function setChromeIconPack(pack: IconPack | null) {
if (pack === current) return;
current = pack;
for (const listener of [...listeners]) listener();
}
const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };
export const useChromeIconPack = () => useSyncExternalStore(subscribe, () => current, () => null);
/** Which pack glyph stands for each of the frame's own glyph names. */
export const CHROME_ICON_NAMES: Readonly<Record<string, IconName>> = {
home: 'home', search: 'search', explore: 'explore', bell: 'notifications', mail: 'messages', bookmark: 'bookmarks', user: 'profile',
list: 'lists', close: 'close', back: 'back', image: 'media', draft: 'compose', edit: 'compose', settings: 'settings',
};
let gradients = 0;
/** One pack glyph as SVG children (no `<svg>` wrapper). */
export function GlyphPaths({ glyph, pack }: { glyph: IconGlyph; pack: IconPack }) {
const style = pack.style;
if ('d' in glyph) {
return glyph.stroke
? <path d={glyph.d} style={{ fill: 'none', stroke: 'currentColor', strokeWidth: style.stroke, strokeLinecap: style.cap, strokeLinejoin: style.join }}/>
: <path d={glyph.d} fillRule={glyph.rule} style={{ fill: 'currentColor', stroke: 'none' }}/>;
}
if ('layers' in glyph) {
const base = `wbg${++gradients}`;
return <>{glyph.layers.map((layer, index) => {
const id = `${base}-${index}`;
const fill = typeof layer.fill === 'string'
? (layer.fill.startsWith('#') ? layer.fill : 'currentColor')
: `url(#${id})`;
return <g key={index}>
{typeof layer.fill === 'object' && <defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={layer.fill.from}/><stop offset="1" stopColor={layer.fill.to}/></linearGradient></defs>}
<path d={layer.d} fillRule={layer.rule} opacity={layer.opacity} style={{ fill, stroke: 'none' }}/>
</g>;
})}</>;
}
return <image href={glyph.png} width="24" height="24" style={glyph.pixel ? { imageRendering: 'pixelated' } : undefined}/>;
}

View file

@ -1,5 +1,7 @@
// Shared 24px stroke glyphs for the shell chrome (1.75 stroke, round joins; sized by CSS).
import { CHROME_ICON_NAMES, GlyphPaths, useChromeIconPack } from './iconPack.tsx';
export const ICONS = {
back: 'M15 5l-7 7 7 7',
forward: 'M9 5l7 7-7 7',
@ -37,12 +39,33 @@ export const ICONS = {
trash: 'M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13',
edit: 'M4 20h4L19 9l-4-4L4 16zM14 6l4 4',
grid: 'M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z',
// The app menu's rows (AppMenu.tsx).
chevronRight: 'M10 7l5 5-5 5',
minus: 'M5 12h14',
columns: 'M4 5h16v14H4zM9.5 5v14M14.5 5v14',
layers: 'M12 4l8 4-8 4-8-4zM4 12l8 4 8-4M4 16l8 4 8-4',
zoom: 'M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM20 20l-4-4M8.5 11h5M11 8.5v5',
plug: 'M9 3v5M15 3v5M6.5 8h11v3.5a5.5 5.5 0 0 1-11 0zM12 17v4',
bag: 'M5 8h14l-1 12H6zM9 8V7a3 3 0 0 1 6 0v1',
layout: 'M4 5h16v14H4zM10 5v14M10 12h10',
keyboard: 'M3 7h18v10H3zM7 10.5h.01M11 10.5h.01M15 10.5h.01M7.5 13.5h9',
command: 'M5 8l4 4-4 4M12 16h7',
code: 'M9 8l-4 4 4 4M15 8l4 4-4 4',
folder: 'M4 7h6l2 2h8v10H4z',
info: 'M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18zM12 11v5M12 8h.01',
shield: 'M12 3l7 3v5.5c0 4.2-2.9 7.9-7 9.5-4.1-1.6-7-5.3-7-9.5V6z',
flag: 'M6 21V4M6 5h11l-2 4 2 4H6',
} as const;
export type IconName = keyof typeof ICONS;
export const Icon = ({ name, className }: { name: IconName; className?: string }) =>
<svg className={className ? `bt-glyph ${className}` : 'bt-glyph'} viewBox="0 0 24 24" aria-hidden="true"><path d={ICONS[name]}/></svg>;
/** One of the frame's glyphs, or the chrome icon pack's glyph for the same meaning (iconPack.tsx). */
export const Icon = ({ name, className }: { name: IconName; className?: string }) => {
const pack = useChromeIconPack();
const mapped = CHROME_ICON_NAMES[name];
const glyph = pack && mapped ? pack.glyphs[mapped] : undefined;
return <svg className={className ? `bt-glyph ${className}` : 'bt-glyph'} viewBox="0 0 24 24" aria-hidden="true">{glyph && pack ? <GlyphPaths glyph={glyph} pack={pack}/> : <path d={ICONS[name]}/>}</svg>;
};
/** Readable initial on a profile color: dark ink on light colors, white on dark ones. */
export function inkOn(hex: string): string {

View file

@ -53,5 +53,10 @@ 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 {
DEFAULT_MENU, MENU_BUILTINS, MENU_MESSAGES, menuWith, menuWithout,
type BuiltinMenuItem, type MenuEntry, type MenuGroups, type MenuItemSpec, type MenuLanguages, type MenuModes, type ReportDetails, type ShellMenu,
} from './menuModel.ts';
export { openAppMenu, type AppMenuRequest } from './AppMenu.tsx';
export { createLanguage, resolveLocale, type Language, type LanguageOptions, type LanguagePreference } from './language.ts';
export { createAppI18n, type AppI18n, type AppI18nOptions, type AppLanguage } from './appI18n.ts';

View file

@ -0,0 +1,54 @@
{
"wb.menu.label": "Settings and more",
"wb.menu.accountsRow": "Settings and more…",
"wb.menu.newColumn": "New deck column",
"wb.menu.theme": "Theme",
"wb.menu.moreAppearance": "More in Appearance…",
"wb.menu.moreLanguages": "More languages…",
"wb.menu.zoom": "Zoom",
"wb.menu.zoomIn": "Zoom in",
"wb.menu.zoomOut": "Zoom out",
"wb.menu.zoomReset": "Reset zoom",
"wb.menu.zoomNone": "This tab has no page to zoom",
"wb.menu.zoomChip": "Zoom {percent}. Click to reset.",
"wb.menu.saveLayout": "Save layout…",
"wb.menu.noWorkspaces": "No saved workspaces yet",
"wb.menu.shortcuts": "Keyboard shortcuts…",
"wb.menu.palette": "Command palette",
"wb.menu.developer": "Developer",
"wb.menu.pluginsFolder": "Open plugins folder",
"wb.menu.about": "About {product}",
"wb.menu.section": "{section}…",
"wb.menu.find": "Find in page…",
"wb.menu.findField": "Find in page",
"wb.menu.findHint": "Finds what this page has loaded so far",
"wb.menu.findCount": "{index}/{count}",
"wb.menu.findTotal": "{count, plural, one {# match} other {# matches}}",
"wb.menu.findNone": "No matches",
"wb.menu.findNext": "Next match",
"wb.menu.findPrevious": "Previous match",
"wb.menu.findClose": "Close find bar",
"wb.menu.updateCheck": "Check for updates",
"wb.menu.updateChecking": "Checking…",
"wb.menu.updateUpToDate": "Up to date",
"wb.menu.updateUpToDateVersion": "Up to date · {version}",
"wb.menu.updateDownloading": "Downloading {version}…",
"wb.menu.updateInstalling": "Installing {version}…",
"wb.menu.updateRestart": "Restart to update",
"wb.menu.updateFailed": "Could not check",
"wb.menu.updateFailedHint": "The update server did not answer. Nothing is wrong with the app; it checks again later on its own.",
"wb.menu.safe": "Safe mode",
"wb.menu.safeRestart": "Restart in safe mode…",
"wb.menu.safeQuestion": "Restart the tabs in safe mode?",
"wb.menu.safeExplain": "Every tab loads again with plugins, themes, custom CSS and page features off, for this run only. Your setup is back the next time you start the app.",
"wb.menu.safeConfirm": "Restart tabs in safe mode",
"wb.menu.safeLeave": "Leave safe mode",
"wb.menu.safeLeaveShort": "Leave",
"wb.menu.safeChip": "Safe mode is on: plugins, themes, custom CSS and page features are off for this run. Click to leave; the tabs load again with your setup.",
"wb.menu.report": "Report a problem…",
"wb.menu.reportTitle": "Report a problem",
"wb.menu.reportLede": "This is everything the report contains: versions and what is switched on. No account, no address, nothing from the pages you have open. Copy it, then paste it into your report.",
"wb.menu.reportOpen": "Open the issue page",
"wb.menu.reportNoPage": "This app has no public issue page yet. Copy the text and send it to the developer.",
"wb.menu.strings": "Languages"
}

View file

@ -0,0 +1,468 @@
// Pure model of the app menu (the titlebar's "Settings and more": AppMenu.tsx), unit-tested under
// node: which rows an app gets (its `ShellSite.menu` groups, the built-in rows and what gates
// them), how the keyboard moves through them, the language list, the zoom steps and how a shortcut
// is written. No React, no Tauri.
//
// The menu's new words live in menuMessages.en.json (`wb.menu.*`) and are read through the
// framework i18n with that English as the fallback (`menuText`), so they work before the catalogs
// have them. Words the panel already has (section names, the mode question) are reused.
import { formatMessage } from '../../../runtime/src/i18n.ts';
import type { UpdateStatus } from '../updateModel.ts';
import EN from './menuMessages.en.json' with { type: 'json' };
import { tx, type Params } from './i18n.ts';
import type { IconName } from './icons.tsx';
/** The menu's English (`wb.menu.*`), for the catalogs. */
export const MENU_MESSAGES: Readonly<Record<string, string>> = EN;
type MenuKey = keyof typeof EN;
/** A menu message's name: its key without the `wb.menu.` prefix. */
export type MenuWord = MenuKey extends `wb.menu.${infer Name}` ? Name : never;
/** A menu message in the active language; English from menuMessages.en.json until a catalog has it. */
export function menuText(name: MenuWord, params?: Params): string {
const key = `wb.menu.${name}`;
return tx(key, params, '') || formatMessage(MENU_MESSAGES[key] ?? key, params ?? {});
}
// ---------------------------------------------------------------------------------------------
// What the app configures (`ShellSite.menu`)
/** The rows the frame brings. Each shows only when the app serves what it needs (`builtinAvailable`). */
export const MENU_BUILTINS = [
'new-tab', 'split-right', 'split-down', 'new-column',
'language', 'theme', 'mode',
'zoom',
'plugins', 'store', 'strings', 'workspaces',
'find', 'shortcuts', 'palette',
'developer', 'updates', 'safe-mode', 'report', 'about', 'settings',
] as const;
export type BuiltinMenuItem = typeof MENU_BUILTINS[number];
/** A row of the app's own. */
export type MenuItemSpec = {
/** Unique in the menu (never a built-in's name). */
id: string;
label(): string;
icon?: IconName;
/** Its keys, written like `Ctrl+Shift+D` (shown as the platform writes them; the app handles the keys). */
shortcut?: string;
/** Quiet text at the end of the row instead of a shortcut (a count, a version). */
hint?(): string;
/** Leave the row out while this is false. */
when?(): boolean;
/** A toggle: the row is a checkbox showing this state; `run` flips it. */
checked?(): boolean;
run?(): void | Promise<void>;
/** A submenu instead of an action (its rows may have submenus of their own). */
submenu?(): MenuItemSpec[];
/** Starts a new group (a rule above this row) inside a submenu. */
separated?: boolean;
/** The menu stays open after `run` (a toggle someone may flip back). */
keepOpen?: boolean;
};
export type MenuEntry = BuiltinMenuItem | MenuItemSpec;
/** Ordered groups; a rule is drawn between two groups. */
export type MenuGroups = ReadonlyArray<ReadonlyArray<MenuEntry>>;
/** One language of the app (a row of its `languages.json`). */
export type MenuLanguage = { code: string; name: string; englishName: string; dir: 'ltr' | 'rtl'; tier: 'supported' | 'community' };
/** The app's language state (frame/language.ts `createLanguage`), as the panel's picker takes it. */
export type MenuLanguages = {
list: readonly MenuLanguage[];
state(): { preference: string; siteLang: string | null; locale: string };
subscribe(listener: () => void): () => void;
set(preference: string): Promise<void>;
};
/** The app's modes (Basic / Advanced / Power User): the panel's `menuModes()` gives this. */
export type MenuModes = {
list(): ReadonlyArray<{ id: string; label: string }>;
/** The mode in use (null: none chosen yet). */
current(): Promise<string | null>;
/** How many of the owner's own changes choosing `to` would replace (0: nothing to ask). */
changes(to: string): Promise<number>;
/** Applies `to`, keeping the owner's own changes or not. */
apply(to: string, keep: boolean): Promise<void>;
/** How the features relate to the mode in use (omit: the menu never says "custom"). */
status?(): Promise<MenuModeStatus>;
/** Applies the mode in use again as it is now: exactly what `status()` listed. */
reapply?(): Promise<void>;
/** The "new features" note was looked at; it is not shown again. */
seen?(): Promise<void>;
};
/**
* A mode is a starting point. `custom`: the features are no longer what the mode starts from;
* `on` / `off`: the names of what applying it again would turn on and off; `added`: how many of
* those the mode gained in an update since it was applied.
*/
export type MenuModeStatus = { custom: boolean; on: string[]; off: string[]; added: number };
/** Lines an app adds to the "Report a problem" summary (reportModel.ts): ids only, never anything about the person. */
export type ReportDetails = ReadonlyArray<{ label: string; values: readonly string[] }>;
/** `ShellSite.menu`: the app menu's rows and what the built-in ones need from the app. */
export type ShellMenu = {
/** The rows, in order. A string is a built-in row, an object one of the app's. Default: `DEFAULT_MENU`. */
groups?: MenuGroups;
/** The Language submenu; omit for an app in one language. */
languages?: MenuLanguages;
/** The Mode submenu; omit for an app without modes. */
modes?: MenuModes;
/** The app's version, shown on the Updates row. */
version?(): Promise<string>;
/**
* "Report a problem": the project's new-issue page (https; opened bare in the system browser, the
* summary is never put in the URL) and lines the app adds to the summary (a fixed English label
* and ids: what paused itself, which areas are on). Without `issueUrl` the dialog still shows and
* copies the summary; its button is off and says there is no public page yet.
*/
report?: { issueUrl?: string; details?(): ReportDetails | Promise<ReportDetails> };
/** Opens the app's shortcuts sheet ("Keyboard shortcuts…"); without one the row opens the command palette. */
shortcuts?(): void;
};
/** The menu an app gets without saying anything: every built-in row it can serve. */
export const DEFAULT_MENU: MenuGroups = [
['new-tab', 'split-right', 'split-down', 'new-column'],
['language', 'theme', 'mode'],
['zoom'],
['plugins', 'store', 'strings', 'workspaces'],
['find', 'shortcuts', 'palette'],
['developer', 'updates', 'safe-mode', 'report', 'about', 'settings'],
];
const entryId = (entry: MenuEntry) => (typeof entry === 'string' ? entry : entry.id);
/** `groups` with the app's `items` put next to the row `anchor` (after it, or before). Without that row they form a last group. */
export function menuWith(groups: MenuGroups, anchor: string, items: readonly MenuEntry[], where: 'after' | 'before' = 'after'): MenuGroups {
let placed = false;
const out = groups.map(group => {
const at = group.findIndex(entry => entryId(entry) === anchor);
if (at < 0 || placed) return group;
placed = true;
const index = where === 'after' ? at + 1 : at;
return [...group.slice(0, index), ...items, ...group.slice(index)];
});
return placed ? out : [...out, items];
}
/** `groups` without the rows named. */
export function menuWithout(groups: MenuGroups, ...ids: string[]): MenuGroups {
return groups.map(group => group.filter(entry => !ids.includes(entryId(entry))));
}
/** What the app serves, as far as the built-in rows care. */
export type MenuEnv = {
/** Decks of site columns (`site.deck`). */
decks: boolean;
/** `menu.languages`. */
languages: boolean;
/** `site.themes`. */
themes: boolean;
/** `menu.modes` with at least one mode. */
modes: boolean;
/** `features`: native page zoom (`tab_zoom`), find in page (`tab_find`), the Store, workspaces, developer mode, the updater. */
zoom: boolean;
find: boolean;
/** `features.safeMode`: safe mode for one run (`safe_mode_get/set`, the host's own). */
safeMode: boolean;
store: boolean;
/** `features.strings`: the panel has the Languages section (string packs). */
strings: boolean;
workspaces: boolean;
developer: boolean;
updates: boolean;
};
/** Whether the app can serve a built-in row: a row that would do nothing is never shown. */
export function builtinAvailable(id: BuiltinMenuItem, env: MenuEnv): boolean {
switch (id) {
case 'new-column': return env.decks;
case 'language': return env.languages;
case 'theme': return env.themes;
case 'mode': return env.modes;
case 'zoom': return env.zoom;
case 'find': return env.find;
case 'safe-mode': return env.safeMode;
case 'store': return env.store;
case 'strings': return env.strings;
case 'workspaces': return env.workspaces;
case 'developer': return env.developer;
case 'updates': return env.updates;
default: return true;
}
}
const isBuiltin = (id: string): id is BuiltinMenuItem => (MENU_BUILTINS as readonly string[]).includes(id);
/**
* The entries the menu shows, group by group: built-in rows the app cannot serve and rows whose
* `when()` says no are left out, a row listed twice shows once, a group left empty goes (so no
* rule is ever doubled), and an unknown name is ignored.
*/
export function planMenu(groups: MenuGroups, env: MenuEnv): MenuEntry[][] {
const seen = new Set<string>();
const out: MenuEntry[][] = [];
for (const group of groups) {
const kept: MenuEntry[] = [];
for (const entry of group) {
const id = entryId(entry);
if (seen.has(id)) continue;
if (typeof entry === 'string') {
if (!isBuiltin(entry) || !builtinAvailable(entry, env)) continue;
} else if (isBuiltin(id) || (entry.when && !entry.when())) {
continue;
}
seen.add(id);
kept.push(entry);
}
if (kept.length) out.push(kept);
}
return out;
}
// ---------------------------------------------------------------------------------------------
// Rows as the menu draws them
export type MenuItemRow = {
kind: 'item';
id: string;
label: string;
icon?: IconName;
shortcut?: string;
hint?: string;
disabled?: boolean;
/** A choice among its neighbours (radio) or a toggle (checkbox), with `checked`. */
check?: 'radio' | 'checkbox';
checked?: boolean;
/** Opens a submenu (its rows come from the menu, by this row's id). */
submenu?: boolean;
keepOpen?: boolean;
/** The label's own language and direction (a language's native name). */
lang?: string;
dir?: 'ltr' | 'rtl';
/** The row's tooltip (a plain sentence that does not fit the row). */
title?: string;
/** A theme's colors, drawn as three dots (`ThemeAdapter.dots`). */
swatch?: { page: string; bg: string; border: string; text: string; accent: string };
run?(): unknown;
};
export type MenuRow =
| MenuItemRow
| { kind: 'separator' }
/** Words that are not a choice: a question above its answers, an empty list, an error. */
| { kind: 'note'; id: string; title: string; text?: string; tone?: 'error' }
/** The zoom row: − 100% + and a reset, in one line. */
| { kind: 'zoom'; id: 'zoom' };
/** Groups of rows as one list with a rule between two groups. */
export function joinGroups(groups: ReadonlyArray<readonly MenuRow[]>): MenuRow[] {
const out: MenuRow[] = [];
for (const group of groups) {
if (!group.length) continue;
if (out.length) out.push({ kind: 'separator' });
out.push(...group);
}
return out;
}
/** The app's own entries as rows (`submenu` rows are looked up again when they open). */
export function specRows(specs: readonly MenuItemSpec[]): MenuRow[] {
const out: MenuRow[] = [];
for (const spec of specs) {
if (spec.when && !spec.when()) continue;
if (spec.separated && out.length) out.push({ kind: 'separator' });
const checked = spec.checked?.();
out.push({
kind: 'item', id: spec.id, label: spec.label(), icon: spec.icon, shortcut: spec.shortcut, hint: spec.hint?.(),
check: checked === undefined ? undefined : 'checkbox', checked, submenu: !!spec.submenu, keepOpen: spec.keepOpen, run: spec.run,
});
}
return out;
}
/** The app's entry with this id, anywhere in its groups or their submenus. */
export function findSpec(groups: MenuGroups, id: string): MenuItemSpec | null {
const walk = (specs: readonly MenuItemSpec[], depth: number): MenuItemSpec | null => {
for (const spec of specs) {
if (spec.id === id) return spec;
const inner = depth < 3 && spec.submenu ? walk(spec.submenu(), depth + 1) : null;
if (inner) return inner;
}
return null;
};
return walk(groups.flat().filter((entry): entry is MenuItemSpec => typeof entry !== 'string'), 0);
}
// ---------------------------------------------------------------------------------------------
// Keyboard
/** Arrow keys, Home and End over `count` stops; wraps around. -1 (nothing focused) enters at an end. */
export function moveStop(index: number, key: string, count: number): number {
if (count <= 0) return -1;
if (key === 'Home') return 0;
if (key === 'End') return count - 1;
if (key === 'ArrowDown') return index < 0 ? 0 : (index + 1) % count;
if (key === 'ArrowUp') return index < 0 ? count - 1 : (index - 1 + count) % count;
return index;
}
const fold = (text: string) => text.normalize('NFKD').replace(/\p{M}/gu, '').toLocaleLowerCase();
/**
* Type-ahead: the next stop after `from` whose label starts with what was typed (accents and case
* ignored). One letter typed again cycles through the labels that start with it. -1: none.
*/
export function typeahead(labels: readonly string[], from: number, typed: string): number {
const text = fold(typed);
if (!text || !labels.length) return -1;
const chars = [...text];
const repeat = chars.length > 1 && chars.every(char => char === chars[0]);
const needle = repeat ? chars[0]! : text;
// While a word is being typed the focused row may keep matching; a repeated letter moves on.
const start = chars.length > 1 && !repeat ? Math.max(0, from) : from + 1;
for (let step = 0; step < labels.length; step += 1) {
const index = (start + step + labels.length) % labels.length;
if (fold(labels[index]!).startsWith(needle)) return index;
}
return -1;
}
/** The keys that open and close a submenu: they follow the reading direction. */
export function submenuKeys(rtl: boolean): { open: string; close: string } {
return rtl ? { open: 'ArrowLeft', close: 'ArrowRight' } : { open: 'ArrowRight', close: 'ArrowLeft' };
}
/**
* The left edge of a submenu `width` wide beside its menu (`parent`), in a window `viewport` wide.
* The menu hangs at one edge of the window (under its button at the end, under the logo at the
* start): the submenu opens toward the middle, else on the other side, else over the menu, and
* always stays `edge` pixels inside the window.
*/
export function submenuLeft(parent: { left: number; right: number }, width: number, viewport: number, edge = 8): number {
const overlap = 3;
const before = parent.left - width + overlap;
const after = parent.right - overlap;
const fits = (x: number) => x >= edge && x + width <= viewport - edge;
const first = (parent.left + parent.right) / 2 > viewport / 2 ? before : after;
const second = first === before ? after : before;
if (fits(first)) return first;
if (fits(second)) return second;
return Math.max(edge, Math.min(first, viewport - width - edge));
}
/** A shortcut as the platform writes it: `Ctrl+Shift+T` on Windows and Linux, `⇧⌘T` on macOS. */
export function shortcutText(shortcut: string, mac: boolean): string {
const parts = shortcut.split('+').map(part => part.trim()).filter(Boolean);
if (!mac) return parts.join('+');
const symbols: Record<string, string> = { ctrl: '⌘', cmd: '⌘', shift: '⇧', alt: '⌥' };
const order = ['alt', 'shift', 'ctrl', 'cmd'];
const mods = parts.filter(part => part.toLowerCase() in symbols).sort((a, b) => order.indexOf(a.toLowerCase()) - order.indexOf(b.toLowerCase()));
const keys = parts.filter(part => !(part.toLowerCase() in symbols));
return `${mods.map(part => symbols[part.toLowerCase()]).join('')}${keys.join('')}`;
}
// ---------------------------------------------------------------------------------------------
// Language
/**
* The Language submenu: follow the site, follow the system, then the supported languages by their
* own names (the one chosen is checked; a community language in use is listed too, so the check is
* never missing), then the way to the full list in Settings.
*/
export function languageRows(
list: readonly MenuLanguage[],
state: { preference: string; siteLang: string | null; locale: string },
words: { site: string; system: string; more: string },
): MenuRow[] {
const named = (code: string | null) => (code ? list.find(language => language.code === code)?.name : undefined);
const automatic: MenuRow[] = [
{ kind: 'item', id: 'lang:site', label: words.site, check: 'radio', checked: state.preference === 'site', hint: state.preference === 'site' ? named(state.locale) : named(state.siteLang) },
{ kind: 'item', id: 'lang:system', label: words.system, check: 'radio', checked: state.preference === 'system', hint: state.preference === 'system' ? named(state.locale) : undefined },
];
const shown = list.filter(language => language.tier !== 'community' || language.code === state.preference);
const languages: MenuRow[] = shown.map(language => ({
kind: 'item', id: `lang:${language.code}`, label: language.name, check: 'radio', checked: state.preference === language.code,
hint: language.name === language.englishName ? undefined : language.englishName, lang: language.code, dir: language.dir,
}));
return joinGroups([automatic, languages, [{ kind: 'item', id: 'lang:more', label: words.more }]]);
}
/** The preference a Language row stands for (`lang:tr` → `tr`), or null for "More languages…". */
export function languageChoice(id: string): string | null {
const code = id.startsWith('lang:') ? id.slice(5) : '';
return code && code !== 'more' ? code : null;
}
// ---------------------------------------------------------------------------------------------
// Zoom
/** Page zoom limits, as native code clamps them (waybetter-host `zoom.rs`). */
export const ZOOM_MIN = 0.25;
export const ZOOM_MAX = 5;
/** The steps − and + move through (a browser's). */
export const ZOOM_STEPS = [0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5] as const;
/** The next step up (`1`) or down (`-1`) from `factor`, or 100% (`0`). Stays inside the limits. */
export function zoomStep(factor: number, direction: 1 | -1 | 0): number {
if (direction === 0 || !Number.isFinite(factor)) return 1;
const near = 0.005;
if (direction > 0) return ZOOM_STEPS.find(step => step > factor + near) ?? ZOOM_MAX;
return [...ZOOM_STEPS].reverse().find(step => step < factor - near) ?? ZOOM_MIN;
}
// ---------------------------------------------------------------------------------------------
// Updates
/** The Updates row: what it says and what choosing it does. */
export type UpdateRow = {
label: string;
/** Quiet text at the end of the row: the state, or the version while nothing is happening. */
hint?: string;
/** A plain sentence for the row's tooltip (why a check did not get through). */
title?: string;
/** `check`: ask the updater now. `restart`: install the downloaded update. `open`: the Updates section. `wait`: nothing, a step is running. */
action: 'check' | 'restart' | 'open' | 'wait';
};
/**
* The Updates row for the updater's status. `asked`: the owner asked for a check in this menu;
* only then does a check that did not get through say so (the timer's own failures stay quiet),
* and it says it calmly: a short state, never the error text.
*/
export function updateRow(status: UpdateStatus, asked: boolean, version: string): UpdateRow {
const check = menuText('updateCheck');
const quiet = version || undefined;
switch (status.state) {
case 'ready': return { label: menuText('updateRestart'), hint: status.version || quiet, action: 'restart' };
case 'installing': return { label: check, hint: menuText('updateInstalling', { version: status.version }), action: 'wait' };
case 'downloading': return { label: check, hint: menuText('updateDownloading', { version: status.version }), action: 'wait' };
case 'checking': return { label: check, hint: menuText('updateChecking'), action: 'wait' };
case 'problem': return { label: tx('wb.update.problemLabel'), hint: quiet, action: 'open' };
case 'upToDate': return { label: check, hint: version ? menuText('updateUpToDateVersion', { version }) : menuText('updateUpToDate'), action: 'check' };
case 'error': return asked ? { label: check, hint: menuText('updateFailed'), title: menuText('updateFailedHint'), action: 'check' } : { label: check, hint: quiet, action: 'check' };
default: return { label: check, hint: quiet, action: 'check' };
}
}
// ---------------------------------------------------------------------------------------------
// Find in page
/**
* What the find bar says about a search: "3/17" (the active match of the total), the total alone
* while no match is active, "No matches" for none. `number` writes a number in the active language.
*/
export function findLabel(counts: { count: number; index: number }, number: (value: number) => string = String): string {
if (counts.count <= 0) return menuText('findNone');
if (counts.index < 0 || counts.index >= counts.count) return menuText('findTotal', { count: counts.count });
return menuText('findCount', { index: number(counts.index + 1), count: number(counts.count) });
}
/** Whole percent of a factor (1.1 → 110). */
export const zoomPercent = (factor: number) => Math.round(factor * 100);

View file

@ -6,6 +6,7 @@
import { rankItems } from '../palette.ts';
import { t } from './i18n.ts';
import type { IconName } from './icons.tsx';
import { menuText } from './menuModel.ts';
import type { PaletteSite } from './site.ts';
export { fuzzyScore, moveSelection } from '../palette.ts';
@ -27,7 +28,11 @@ export type PaletteAction =
| { type: 'plugin-command'; tab: string; command: string }
/** Workspaces: restore one, or save the current layout under a name. */
| { type: 'workspace'; id: string }
| { type: 'workspace-save' };
| { type: 'workspace-save' }
/** Opens the app menu (the titlebar's "Settings and more"). */
| { type: 'menu' }
/** Opens the find bar of the tab in front. */
| { type: 'find' };
/** The frame's groups; the app's items are grouped under its product name, plugin commands under the plugin's. */
export type PaletteGroup = 'Tabs' | 'Deck' | 'Workspaces' | 'Profiles';
@ -61,7 +66,7 @@ export type PaletteContext = {
};
/** What the palette knows about the app: its site items, its name and which frame features it has. */
export type PaletteSetup = { site: PaletteSite; product: string; decks: boolean; media: boolean; workspaces?: boolean };
export type PaletteSetup = { site: PaletteSite; product: string; decks: boolean; media: boolean; workspaces?: boolean; find?: boolean };
/** A plugin command as the palette lists it: the tab's report plus the plugin's display name. */
export type PluginCommandItem = { id: string; title: string; keywords: string; plugin: string };
@ -143,6 +148,10 @@ export function buildItems(context: PaletteContext, query: string, setup: Palett
items.push({ id: `panel:${section.id}`, group: setup.product, label: section.label(), keywords: section.keywords, icon: section.icon, action: { type: 'panel', section: section.id } });
}
if (setup.media) items.push({ id: 'media', group: setup.product, label: t('wb.palette.media'), hint: 'Ctrl+Shift+G', keywords: 'photos images screenshots attach paste media', icon: 'image', action: { type: 'media' } });
// Find in the page of the tab in front (the shell's find bar; nothing is sent anywhere).
if (setup.find !== false) items.push({ id: 'find', group: setup.product, label: menuText('find'), hint: 'Ctrl+F', keywords: 'find search page text match', icon: 'search', action: { type: 'find' } });
// The app menu (the titlebar's "Settings and more"): language, theme, mode, zoom and the rest.
items.push({ id: 'app-menu', group: setup.product, label: menuText('label'), hint: 'Alt+F', keywords: 'menu more settings language theme mode zoom options preferences', icon: 'settings', action: { type: 'menu' } });
// Plugin commands, grouped under each plugin's name; they run in the focused site tab.
if (context.commands) {
const { tab } = context.commands;

View file

@ -9,8 +9,18 @@ import { isWeb, shell } from './state.ts';
type Reported = { id: string; title: string; keywords: string };
/** Dispatched on `window` when a tab's reported commands changed. */
export const COMMANDS_CHANGED = 'wb-tab-commands';
const byTab = new Map<string, Reported[]>();
let names: Record<string, string> = {};
/** Owners that are not plugin files: an app's area plugins, by the owner id their commands carry. */
let owners: Record<string, string> = {};
/** Names for command owners the Plugins list does not know (createPanel: the feature table's areas). */
export function setCommandOwnerNames(value: Record<string, string>) {
owners = { ...value };
}
/** The last web tab that was active (the palette may be opened from the app's panel). */
let lastWebTab: string | null = null;
@ -19,6 +29,8 @@ export function installPluginCommands(): () => void {
if (!payload || typeof payload.id !== 'string') return;
if (Array.isArray(payload.commands) && payload.commands.length) byTab.set(payload.id, payload.commands);
else byTab.delete(payload.id);
// The panel's area cards show what a tab says about its features (a paused one).
window.dispatchEvent(new CustomEvent(COMMANDS_CHANGED));
});
void refreshPluginNames();
return () => { void off.then(dispose => dispose(), () => {}); };
@ -45,7 +57,7 @@ export function focusedCommands(): { tab: string; items: PluginCommandItem[] } |
if (!tab) return undefined;
const reported = byTab.get(tab);
if (!reported?.length) return undefined;
return { tab, items: pluginCommandItems(reported, names) };
return { tab, items: pluginCommandItems(reported, { ...owners, ...names }) };
}
export function runPluginCommand(tab: string, command: string) {

View file

@ -0,0 +1,130 @@
// "Report a problem": the diagnostic summary, as a pure model (unit-tested under node). It is a
// short plain text in English (the people who read reports do) built from a fixed set of facts
// about the app, never about the person: versions, the system, the language, the mode, the ids of
// what is switched on, what paused itself, safe mode. It has no field for an account, a handle, an
// address, a tab, a file path or anything of the site's, and every value must be made of the
// characters an id or a version is made of, or it is left out (never trimmed into shape), so
// nothing of that kind can ride along in a value either. The text is shown to the owner exactly as it would be shared and is
// never sent anywhere by the app (no request, and nothing is put in a URL).
/** The framework's version (kept in step with packages/waybetter/package.json by a test). */
export const FRAMEWORK_VERSION = '0.6.0';
/** Everything a report may say. */
export type ReportInfo = {
/** The app's name and version ("wayBetter for X", "1.3.2"). */
product: string;
appVersion: string;
/** "Windows 11 (x64)", "macOS", "Linux (x86_64)". */
system: string;
/** "WebView2 141.0.3537.71", "WebKit 605.1.15". */
webview: string;
/** The catalog in use and how it was chosen (`site`, `system` or a language tag). */
language: string;
languageChoice: string;
/** The mode in use (its id), when the app has modes. */
mode?: string | null;
/** The theme's id and the icon pack it uses, when the app has themes. */
theme?: string;
iconPack?: string;
/** File names of the plugins that are switched on (null: could not be read). */
plugins: readonly string[] | null;
/** Lines the app adds: a fixed English label and ids (what paused itself, which areas are on). */
details?: ReadonlyArray<{ label: string; values: readonly string[] }>;
safeMode: boolean;
};
const MAX_ITEMS = 60;
const ID = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;
/** An id or a version as it is, or nothing: anything that is not made of id characters is left out, never trimmed into shape. */
export function reportValue(value: unknown): string {
const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value : '';
return ID.test(text) ? text : '';
}
/** A plugin's file name: the name itself (never where the file is), or nothing. */
export function reportFileName(value: unknown): string {
return typeof value === 'string' ? reportValue(value.split(/[\\/]/).pop()) : '';
}
/** A language tag (`tr`, `zh-Hant`) or one of the automatic choices; anything else is left out. */
function languageValue(value: unknown): string {
return typeof value === 'string' && (/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8}){0,3}$/.test(value) || ['site', 'system', 'fixed'].includes(value)) ? value : '';
}
/** What `systemFromUserAgent` and `webviewFromUserAgent` write, and nothing else. */
const SYSTEM = /^(Windows|macOS|Linux)( \d+(\.\d+)?| 10 or 11)?( \([A-Za-z0-9_]{1,12}\))?$/;
const WEBVIEW = /^(WebView2|Chromium|WebKit) [0-9.]{1,24}$/;
/** The app's name and its labels are its own constants: letters, digits and spaces. */
const NAME = /^[A-Za-z][A-Za-z0-9 ]{0,39}$/;
function list(values: readonly unknown[] | null | undefined, clean: (value: unknown) => string): string {
if (!values) return 'unknown';
const kept = values.map(clean).filter(Boolean);
const left = values.length - kept.length;
const shown = kept.slice(0, MAX_ITEMS);
const more = kept.length - shown.length + left;
if (!shown.length) return more ? `${more} not shown` : 'none';
return `${shown.join(', ')}${more ? `, and ${more} more` : ''}`;
}
/** The report's text: one fact per line. */
export function buildReport(info: ReportInfo): string {
const lines = [
`${NAME.test(info.product) ? info.product : 'App'} ${reportValue(info.appVersion) || 'unknown version'}`,
`Framework: wayBetter ${FRAMEWORK_VERSION}`,
`System: ${SYSTEM.test(info.system) ? info.system : 'unknown'}`,
`Webview: ${WEBVIEW.test(info.webview) ? info.webview : 'unknown'}`,
`Language: ${languageValue(info.language) || 'unknown'} (chosen: ${languageValue(info.languageChoice) || 'unknown'})`,
];
if (info.mode !== undefined) lines.push(`Mode: ${info.mode === null ? 'none chosen' : reportValue(info.mode) || 'unknown'}`);
if (info.theme !== undefined) lines.push(`Theme: ${reportValue(info.theme) || 'unknown'}`);
if (info.iconPack !== undefined) lines.push(`Icon pack: ${info.iconPack === '' ? "the site's own" : reportValue(info.iconPack) || 'unknown'}`);
lines.push(`Plugins on: ${list(info.plugins, reportFileName)}`);
for (const detail of (info.details ?? []).slice(0, 12)) {
if (NAME.test(detail.label)) lines.push(`${detail.label}: ${list(detail.values, reportValue)}`);
}
lines.push(`Safe mode: ${info.safeMode ? 'yes' : 'no'}`);
return lines.join('\n');
}
/**
* The webview engine and its version from a user agent string. Chromium reduces the version in the
* user agent ("154.0.0.0"); the full one comes from the engine's brand list when it gives one.
*/
export function webviewFromUserAgent(userAgent: string, brands: ReadonlyArray<{ brand?: string; version?: string }> = []): string {
const full = brands.find(entry => /WebView2|Microsoft Edge/.test(entry.brand ?? '') && /^[\d.]+$/.test(entry.version ?? ''));
const edge = /\bEdg\/([\d.]+)/.exec(userAgent);
if (edge) return `WebView2 ${full?.version ?? edge[1]}`;
const chrome = /\bChrom(?:e|ium)\/([\d.]+)/.exec(userAgent);
if (chrome) return `Chromium ${chrome[1]}`;
const webkit = /\bAppleWebKit\/([\d.]+)/.exec(userAgent);
if (webkit) return `WebKit ${webkit[1]}`;
return 'unknown';
}
/**
* The operating system from a user agent string, refined by what the engine says when asked
* (`platformVersion`: on Windows a major of 13 or more is Windows 11; `architecture`). Coarse on
* purpose: a family and a version, nothing that names a machine.
*/
export function systemFromUserAgent(userAgent: string, hints: { platformVersion?: string; architecture?: string; bitness?: string } = {}): string {
const arch = hints.architecture ? `${hints.architecture}${hints.bitness === '64' && hints.architecture === 'x86' ? '_64' : ''}` : '';
if (/Windows NT/.test(userAgent)) {
const major = Number.parseInt(hints.platformVersion ?? '', 10);
const version = Number.isFinite(major) && major > 0 ? (major >= 13 ? '11' : '10') : /Windows NT 10\.0/.test(userAgent) ? '10 or 11' : '';
const bits = arch || (/Win64|x64|WOW64/.test(userAgent) ? 'x64' : /ARM64/i.test(userAgent) ? 'arm64' : '');
return `Windows${version ? ` ${version}` : ''}${bits ? ` (${bits})` : ''}`;
}
if (/Macintosh|Mac OS X/.test(userAgent)) {
const version = (hints.platformVersion ?? '').split('.').slice(0, 2).join('.');
return `macOS${/^\d+(\.\d+)?$/.test(version) && version !== '0' ? ` ${version}` : ''}${arch ? ` (${arch})` : ''}`;
}
if (/Linux|X11/.test(userAgent)) {
const machine = /Linux (x86_64|aarch64|armv\w+|i686)/.exec(userAgent)?.[1] ?? arch;
return `Linux${machine ? ` (${machine})` : ''}`;
}
return 'unknown';
}

View file

@ -0,0 +1,36 @@
// Safe mode, as the shell knows it. Native code owns the flag (waybetter-host `safe.rs`: memory
// only, for this run; site tabs get the tab bridge and nothing of the app's page layers). The
// shell reads it at start (`safe_mode_get`), switches it from the app menu and the titlebar chip
// (`safe_mode_set`, which rebuilds every tab), hears a switch as the `safe-mode` event, shows it in
// the titlebar for as long as it is on and drops its own chrome theme meanwhile (themeStore.ts).
import { invoke, listen } from './bridge.ts';
export const safe = { active: false };
function note(active: unknown) {
const next = active === true;
if (typeof document !== 'undefined') {
if (next) document.documentElement.dataset.safe = 'on'; else delete document.documentElement.dataset.safe;
}
if (safe.active === next) return;
safe.active = next;
window.dispatchEvent(new CustomEvent('bt-safe'));
}
/** Switches safe mode for this run; every tab is rebuilt with or without the app's page layers. */
export async function setSafeMode(on: boolean): Promise<void> {
const state = await invoke<{ active?: boolean }>('safe_mode_set', { on });
note(state?.active);
}
/** Reads the flag and follows its changes (Shell.tsx, once). Returns a cleanup. */
export function installSafeMode(): () => void {
let disposed = false;
let unlisten: (() => void) | undefined;
invoke<{ active?: boolean }>('safe_mode_get').then(state => { if (!disposed) note(state?.active); }).catch(() => {});
listen<{ active?: boolean }>('safe-mode', ({ payload }) => note(payload?.active))
.then(dispose => { if (disposed) dispose(); else unlisten = dispose; })
.catch(() => {});
return () => { disposed = true; unlisten?.(); };
}

View file

@ -32,9 +32,11 @@
--bt-t1: 120ms; --bt-t2: 180ms; --bt-t3: 320ms;
--bt-titlebar-h: 44px; --bt-toolbar-h: 48px; --bt-resize-border: 5px;
/* Room the titlebar-hosted tab strip leaves for the logo (left) and caption buttons + drag spacer + account switcher (right). */
--bt-tb-left: 50px; --bt-tb-right: calc(138px + 48px + 184px + var(--bt-tb-extra, 0px));
/* --bt-tb-menu: the app menu button (30px and its 8px margin). */
--bt-tb-menu: 38px;
--bt-tb-left: 50px; --bt-tb-right: calc(138px + 48px + 184px + var(--bt-tb-menu) + var(--bt-tb-extra, 0px));
}
html[data-os=macos] { --bt-tb-left: calc(78px + 50px); --bt-tb-right: calc(48px + 184px + var(--bt-tb-extra, 0px)); }
html[data-os=macos] { --bt-tb-left: calc(78px + 50px); --bt-tb-right: calc(48px + 184px + var(--bt-tb-menu) + var(--bt-tb-extra, 0px)); }
html, body, #root { height: 100%; margin: 0; overflow: hidden; background: var(--bt-ground); color: var(--bt-text); font: 400 13px/1.3 var(--bt-ui); -webkit-font-smoothing: antialiased; }
.bt-shell {
/* Legacy names used by the tab strip and menus. */
@ -89,12 +91,11 @@ html, body, #root { height: 100%; margin: 0; overflow: hidden; background: var(-
pointer events only on its own controls; everything else falls through to the tabs and their
drag region. With no tabs the titlebar itself is the drag region again. */
.bt-titlebar { z-index: 2; pointer-events: none; }
.bt-titlebar > :not(.bt-titlebar-drag):not(.bt-titlebar-spacer):not(.bt-titlebar-logo) { pointer-events: auto; }
.bt-titlebar > :not(.bt-titlebar-drag):not(.bt-titlebar-spacer) { pointer-events: auto; }
.bt-shell--empty .bt-titlebar > * { pointer-events: auto; }
/* Above the dock, so it must not paint: the tab strips hosted in the titlebar row show through it. */
.bt-shell:not(.bt-shell--empty) .bt-titlebar { background: transparent; }
html[data-os=macos] .bt-titlebar { padding-left: 78px; } /* rtl-ok: traffic lights; the titlebar stays LTR */
.bt-titlebar-logo { width: 20px; height: 20px; margin: 12px 14px 12px 16px; flex: 0 0 20px; -webkit-user-drag: none; }
.bt-titlebar-spacer { flex: 1; min-width: 48px; }
.bt-captions { display: flex; }
.bt-caption { width: 46px; height: 44px; display: grid; place-items: center; padding: 0; background: transparent; border: 0; color: var(--bt-text-2); cursor: default; transition: background-color var(--bt-t1) var(--bt-ease), color var(--bt-t1) var(--bt-ease); }
@ -106,8 +107,8 @@ html[data-os=macos] .bt-titlebar { padding-left: 78px; } /* rtl-ok: traffic ligh
.bt-grip { position: fixed; z-index: 50; }
/* Update chip: a quiet brush-edged pill left of the account switcher, only while an update is actionable. */
html[data-update] { --bt-tb-right: calc(138px + 48px + 184px + 184px + var(--bt-tb-extra, 0px)); }
html[data-os=macos][data-update] { --bt-tb-right: calc(48px + 184px + 184px + var(--bt-tb-extra, 0px)); }
html[data-update] { --bt-tb-right: calc(138px + 48px + 184px + 184px + var(--bt-tb-menu) + var(--bt-tb-extra, 0px)); }
html[data-os=macos][data-update] { --bt-tb-right: calc(48px + 184px + 184px + var(--bt-tb-menu) + var(--bt-tb-extra, 0px)); }
.bt-update-chip {
align-self: center; display: inline-flex; align-items: center; gap: 8px; height: 28px; margin-right: 8px; padding: 0 12px 0 10px; /* rtl-ok: titlebar */
border: 1px solid transparent; border-radius: 14px; color: var(--bt-text); font: 500 12px/1 var(--bt-ui); white-space: nowrap; cursor: pointer;

Some files were not shown because too many files have changed in this diff Show more